code
stringlengths
1
1.72M
language
stringclasses
1 value
from blog.models import MiniPost, ResultSet, StaticPage, Project, FileInfo from django.core.paginator import ObjectPaginator, InvalidPage from google.appengine.api import datastore_errors from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.blobstore import BlobInfo from google.appengine.ext.db import Model from google.appengine.ext.webapp import template from google.appengine.ext.webapp import util from pyamf import amf3 from pyamf.remoting.gateway.google import WebAppGateway import logging import os import pyamf AMF_NAMESPACE = "org.flexspeedup.blog.models" PAGE_SIZE = 10 FILE_SERVE_PATH = '/assets/' def echo(data): return 'PyAMF says: ' + data def save_static_page(page, page_name): """saves / updates a static page in the datastore""" new_page = StaticPage.get_or_insert(page_name) new_page.body = page.body new_page.title = page.title new_page.put() return new_page def get_static_page(page_name): """retrieves a StaticPage by key_name""" return StaticPage.get_by_key_name(page_name) def save_post(post): post.put() return post def create_post(post): return save_post( MiniPost( body = post.body, title = post.title, category = post.category, ) ) def delete_post(post): post.delete() def get_posts(page, page_size=None, category=None): query = MiniPost.all().order('-date') if category: query = query.filter('category =', category) return paginate_query(query, page, page_size) def get_files(page, page_size=None): query = BlobInfo.all().order('-filename') resultSet = paginate_query(query, page, page_size) files = [] for item in resultSet.items: file = FileInfo() file.filename = item.filename file.uri = FILE_SERVE_PATH + str(item.key()) files.append(file) resultSet.items = files return resultSet def get_projects(page, page_size=None): query = Project.all().order('-date') return paginate_query(query, page, page_size) def get_all_projects(): return Project.all().order('-date') def create_project(project): return save_project( Project( title = project.title, imageFilename = project.imageFilename, imageUri = project.imageUri, thumbnailFilename = project.thumbnailFilename, thumbnailUri = project.thumbnailUri, ) ) def save_project(project): project.put() return project def delete_project(project): project.delete() def paginate_query(query, page, page_size=None): paginator = ObjectPaginator(query, page_size or PAGE_SIZE) paginator_page = page - 1 resultSet = ResultSet() resultSet.hasNextPage = paginator.has_next_page(paginator_page) resultSet.hasPreviousPage = paginator.has_previous_page(paginator_page) if resultSet.hasNextPage: resultSet.nextPage = page + 1 if resultSet.hasPreviousPage: resultSet.previousPage = page - 1 resultSet.itemCountPerPage = PAGE_SIZE resultSet.totalItemCount = paginator.hits resultSet.pageCount = paginator.pages resultSet.currentPage = page resultSet.items = paginator.get_page(paginator_page) return resultSet def logout(): return users.create_logout_url('/admin') def get_current_user(): """returns the current authenticated user""" return users.get_current_user().nickname() def main(): debug = True logging.getLogger().setLevel(logging.DEBUG) pyamf.register_class(MiniPost, '%s.MiniPost' % AMF_NAMESPACE) pyamf.register_class(ResultSet, '%s.ResultSet' % AMF_NAMESPACE) pyamf.register_class(StaticPage, '%s.StaticPage' % AMF_NAMESPACE) pyamf.register_class(Project, '%s.Project' % AMF_NAMESPACE) pyamf.register_class(FileInfo, '%s.FileInfo' % AMF_NAMESPACE) services = { 'services.echo' : echo, 'services.savePost' : save_post, 'services.createPost' : create_post, 'services.getPosts' : get_posts, 'services.logout' : logout, 'services.getCurrentUser' : get_current_user, 'services.deletePost': delete_post, 'services.saveStaticPage' : save_static_page, 'services.getStaticPage' : get_static_page, 'services.getProjects' : get_projects, 'services.getFiles' : get_files, 'services.saveProject' : save_project, 'services.createProject' : create_project, 'services.deleteProject' : delete_project, 'services.getAllProjects' : get_all_projects, } gateway = WebAppGateway(services, logger = logging, debug = debug) paths = [ ('/gateway', gateway), ] application = webapp.WSGIApplication(paths, debug = debug) util.run_wsgi_app(application) if __name__ == '__main__': main()
Python
import os class FlexView: def __init__(self, title, flex_app_name, settings_url=None, secure_dir = None, player_version='10.0.0', width=None, height=None ): self.title = title self.flex_app_name = flex_app_name self.player_version = player_version self.width = width or '100%' self.height = height or '100%' self.settings_url = settings_url or 'runtime/settings.xml' self.secure_dir = secure_dir def path(self): return os.path.join(os.path.dirname(__file__), 'views/flex.html') def template_values(self): return { 'title' : self.title, 'flex_app_name' : self.flex_app_name, 'player_version' : self.player_version, 'width' : self.width, 'height' : self.height, 'settings_url': self.settings_url, 'secure_dir' : self.secure_dir, }
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Local Shared Object implementation. Local Shared Object (LSO), sometimes known as Adobe Flash cookies, is a cookie-like data entity used by the Adobe Flash Player and Gnash. The players allow web content to read and write LSO data to the computer's local drive on a per-domain basis. @see: U{Local Shared Object on WikiPedia (external) <http://en.wikipedia.org/wiki/Local_Shared_Object>} @see: U{Local Shared Object envelope (external) <http://osflash.org/documentation/amf/envelopes/sharedobject>} @since: 0.1.0 """ import pyamf from pyamf import util #: Magic Number - 2 bytes HEADER_VERSION = '\x00\xbf' #: Marker - 10 bytes HEADER_SIGNATURE = 'TCSO\x00\x04\x00\x00\x00\x00' #: Padding - 4 bytes PADDING_BYTE = '\x00' def decode(stream, strict=True): """ Decodes a SOL stream. C{strict} mode ensures that the sol stream is as spec compatible as possible. @param strict: Ensure that the SOL stream is as spec compatible as possible. @type strict: C{bool} @return: A C{tuple} containing the C{root_name} and a C{dict} of name, value pairs. @rtype: C{tuple} @raise DecodeError: Unknown SOL version in header. @raise DecodeError: Inconsistent stream header length. @raise DecodeError: Invalid signature. @raise DecodeError: Invalid padding read. @raise DecodeError: Missing padding byte. """ if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) # read the version version = stream.read(2) if version != HEADER_VERSION: raise pyamf.DecodeError('Unknown SOL version in header') # read the length length = stream.read_ulong() if strict and stream.remaining() != length: raise pyamf.DecodeError('Inconsistent stream header length') # read the signature signature = stream.read(10) if signature != HEADER_SIGNATURE: raise pyamf.DecodeError('Invalid signature') length = stream.read_ushort() root_name = stream.read_utf8_string(length) # read padding if stream.read(3) != PADDING_BYTE * 3: raise pyamf.DecodeError('Invalid padding read') decoder = pyamf.get_decoder(stream.read_uchar()) decoder.stream = stream values = {} while 1: if stream.at_eof(): break name = decoder.readString() value = decoder.readElement() # read the padding if stream.read(1) != PADDING_BYTE: raise pyamf.DecodeError('Missing padding byte') values[name] = value return (root_name, values) def encode(name, values, strict=True, encoding=pyamf.AMF0): """ Produces a SharedObject encoded stream based on the name and values. @param name: The root name of the SharedObject. @type name: C{basestring} @param values: A C{dict} of name value pairs to be encoded in the stream. @type values: C{dict} @param strict: Ensure that the SOL stream is as spec compatible as possible. @type strict: C{bool} @return: A SharedObject encoded stream. @rtype: L{BufferedByteStream<pyamf.util.BufferedByteStream>} """ encoder = pyamf.get_encoder(encoding) encoder.stream = stream = util.BufferedByteStream() # write the header stream.write(HEADER_VERSION) if strict is True: length_pos = stream.tell() stream.write_ulong(0) # write the signature stream.write(HEADER_SIGNATURE) # write the root name if not isinstance(name, unicode): name = unicode(name) stream.write_ushort(len(name)) stream.write_utf8_string(name) # write the padding stream.write(PADDING_BYTE * 3) stream.write_uchar(encoding) for n, v in values.iteritems(): encoder.writeString(n, writeType=False) encoder.writeElement(v) # write the padding stream.write(PADDING_BYTE) if strict: stream.seek(length_pos) stream.write_ulong(stream.remaining() - 4) stream.seek(0) return stream def load(name_or_file): """ Loads a sol file and returns a L{SOL} object. @param name_or_file: Name of file, or file-object. @type name_or_file: C{str} or C{StringIO} @raise ValueError: Readable stream expected. """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'rb') opened = True elif not hasattr(f, 'read'): raise ValueError('Readable stream expected') name, values = decode(f.read()) s = SOL(name) for n, v in values.iteritems(): s[n] = v if opened is True: f.close() return s def save(sol, name_or_file, encoding=pyamf.AMF0): """ Writes a L{SOL} object to C{name_or_file}. @param sol: @type sol: @param name_or_file: Name of file, or file-object. @type name_or_file: C{str} or C{StringIO} @param encoding: AMF encoding type. @type encoding: C{int} @raise ValueError: Writable stream expected. """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'wb+') opened = True elif not hasattr(f, 'write'): raise ValueError('Writable stream expected') f.write(encode(sol.name, sol, encoding=encoding).getvalue()) if opened: f.close() class SOL(dict): """ Local Shared Object class, allows easy manipulation of the internals of a C{sol} file. """ def __init__(self, name): self.name = name def save(self, name_or_file, encoding=pyamf.AMF0): save(self, name_or_file, encoding) def __repr__(self): return '<%s %s %s at 0x%x>' % (self.__class__.__name__, self.name, dict.__repr__(self), id(self)) LSO = SOL
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF0 implementation. C{AMF0} supports the basic data types used for the NetConnection, NetStream, LocalConnection, SharedObjects and other classes in the Adobe Flash Player. @see: U{Official AMF0 Specification in English (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/amf0_spec_121207.pdf>} @see: U{Official AMF0 Specification in Japanese (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/JP_amf0_spec_121207.pdf>} @see: U{AMF documentation on OSFlash (external) <http://osflash.org/documentation/amf>} @since: 0.1 """ import datetime import types import copy import pyamf from pyamf import util #: Represented as 9 bytes: 1 byte for C{0×00} and 8 bytes a double #: representing the value of the number. TYPE_NUMBER = '\x00' #: Represented as 2 bytes: 1 byte for C{0×01} and a second, C{0×00} #: for C{False}, C{0×01} for C{True}. TYPE_BOOL = '\x01' #: Represented as 3 bytes + len(String): 1 byte C{0×02}, then a UTF8 string, #: including the top two bytes representing string length as a C{int}. TYPE_STRING = '\x02' #: Represented as 1 byte, C{0×03}, then pairs of UTF8 string, the key, and #: an AMF element, ended by three bytes, C{0×00} C{0×00} C{0×09}. TYPE_OBJECT = '\x03' #: MovieClip does not seem to be supported by Remoting. #: It may be used by other AMF clients such as SharedObjects. TYPE_MOVIECLIP = '\x04' #: 1 single byte, C{0×05} indicates null. TYPE_NULL = '\x05' #: 1 single byte, C{0×06} indicates null. TYPE_UNDEFINED = '\x06' #: When an ActionScript object refers to itself, such C{this.self = this}, #: or when objects are repeated within the same scope (for example, as the #: two parameters of the same function called), a code of C{0×07} and an #: C{int}, the reference number, are written. TYPE_REFERENCE = '\x07' #: A MixedArray is indicated by code C{0×08}, then a Long representing the #: highest numeric index in the array, or 0 if there are none or they are #: all negative. After that follow the elements in key : value pairs. TYPE_MIXEDARRAY = '\x08' #: @see: L{TYPE_OBJECT} TYPE_OBJECTTERM = '\x09' #: An array is indicated by C{0x0A}, then a Long for array length, then the #: array elements themselves. Arrays are always sparse; values for #: inexistant keys are set to null (C{0×06}) to maintain sparsity. TYPE_ARRAY = '\x0A' #: Date is represented as C{00x0B}, then a double, then an C{int}. The double #: represents the number of milliseconds since 01/01/1970. The C{int} represents #: the timezone offset in minutes between GMT. Note for the latter than values #: greater than 720 (12 hours) are represented as M{2^16} - the value. Thus GMT+1 #: is 60 while GMT-5 is 65236. TYPE_DATE = '\x0B' #: LongString is reserved for strings larger then M{2^16} characters long. It #: is represented as C{00x0C} then a LongUTF. TYPE_LONGSTRING = '\x0C' #: Trying to send values which don’t make sense, such as prototypes, functions, #: built-in objects, etc. will be indicated by a single C{00x0D} byte. TYPE_UNSUPPORTED = '\x0D' #: Remoting Server -> Client only. #: @see: L{RecordSet} #: @see: U{RecordSet structure on OSFlash (external) #: <http://osflash.org/documentation/amf/recordset>} TYPE_RECORDSET = '\x0E' #: The XML element is indicated by C{00x0F} and followed by a LongUTF containing #: the string representation of the XML object. The receiving gateway may which #: to wrap this string inside a language-specific standard XML object, or simply #: pass as a string. TYPE_XML = '\x0F' #: A typed object is indicated by C{0×10}, then a UTF string indicating class #: name, and then the same structure as a normal C{0×03} Object. The receiving #: gateway may use a mapping scheme, or send back as a vanilla object or #: associative array. TYPE_TYPEDOBJECT = '\x10' #: An AMF message sent from an AVM+ client such as the Flash Player 9 may break #: out into L{AMF3<pyamf.amf3>} mode. In this case the next byte will be the #: AMF3 type code and the data will be in AMF3 format until the decoded object #: reaches it’s logical conclusion (for example, an object has no more keys). TYPE_AMF3 = '\x11' class Context(pyamf.BaseContext): """ I hold the AMF0 context for en/decoding streams. AMF0 object references start at index 1. @ivar amf3_objs: A list of objects that have been decoded in L{AMF3<pyamf.amf3>}. @type amf3_objs: L{util.IndexedCollection} """ def __init__(self, **kwargs): self.amf3_objs = [] pyamf.BaseContext.__init__(self, **kwargs) def clear(self): """ Clears the context. """ pyamf.BaseContext.clear(self) self.amf3_objs = [] if hasattr(self, 'amf3_context'): self.amf3_context.clear() def hasAMF3ObjectReference(self, obj): """ Gets a reference for an object. @raise ReferenceError: Unknown AMF3 object reference. """ return obj in self.amf3_objs o = self.amf3_objs.getReferenceTo(obj) if o is None and self.exceptions: raise pyamf.ReferenceError( 'Unknown AMF3 reference for (%r)' % (obj,)) return o def addAMF3Object(self, obj): """ Adds an AMF3 reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. """ return self.amf3_objs.append(obj) def __copy__(self): cpy = self.__class__(exceptions=self.exceptions) cpy.amf3_objs = copy.copy(self.amf3_objs) return cpy class Decoder(pyamf.BaseDecoder): """ Decodes an AMF0 stream. """ context_class = Context # XXX nick: Do we need to support TYPE_MOVIECLIP here? type_map = { TYPE_NUMBER: 'readNumber', TYPE_BOOL: 'readBoolean', TYPE_STRING: 'readString', TYPE_OBJECT: 'readObject', TYPE_NULL: 'readNull', TYPE_UNDEFINED: 'readUndefined', TYPE_REFERENCE: 'readReference', TYPE_MIXEDARRAY: 'readMixedArray', TYPE_ARRAY: 'readList', TYPE_DATE: 'readDate', TYPE_LONGSTRING: 'readLongString', # TODO: do we need a special value here? TYPE_UNSUPPORTED:'readNull', TYPE_XML: 'readXML', TYPE_TYPEDOBJECT:'readTypedObject', TYPE_AMF3: 'readAMF3' } def readNumber(self): """ Reads a ActionScript C{Number} value. In ActionScript 1 and 2 the C{NumberASTypes} type represents all numbers, both floats and integers. @rtype: C{int} or C{float} """ return _check_for_int(self.stream.read_double()) def readBoolean(self): """ Reads a ActionScript C{Boolean} value. @rtype: C{bool} @return: Boolean. """ return bool(self.stream.read_uchar()) def readNull(self): """ Reads a ActionScript C{null} value. @return: C{None} @rtype: C{None} """ return None def readUndefined(self): """ Reads an ActionScript C{undefined} value. @return: L{Undefined<pyamf.Undefined>} """ return pyamf.Undefined def readMixedArray(self): """ Read mixed array. @rtype: C{dict} @return: C{dict} read from the stream """ len = self.stream.read_ulong() obj = pyamf.MixedArray() self.context.addObject(obj) self._readObject(obj) ikeys = [] for key in obj.keys(): try: ikey = int(key) ikeys.append((key, ikey)) obj[ikey] = obj[key] del obj[key] except ValueError: # XXX: do we want to ignore this? pass ikeys.sort() return obj def readList(self): """ Read a C{list} from the data stream. @rtype: C{list} @return: C{list} """ obj = [] self.context.addObject(obj) len = self.stream.read_ulong() for i in xrange(len): obj.append(self.readElement()) return obj def readTypedObject(self): """ Reads an ActionScript object from the stream and attempts to 'cast' it. @see: L{load_class<pyamf.load_class>} """ classname = self.readString() alias = None try: alias = pyamf.get_class_alias(classname) ret = alias.createInstance(codec=self) except pyamf.UnknownClassAlias: if self.strict: raise ret = pyamf.TypedObject(classname) self.context.addObject(ret) self._readObject(ret, alias) return ret def readAMF3(self): """ Read AMF3 elements from the data stream. @rtype: C{mixed} @return: The AMF3 element read from the stream """ if not hasattr(self.context, 'amf3_context'): self.context.amf3_context = pyamf.get_context(pyamf.AMF3, exceptions=False) if not hasattr(self.context, 'amf3_decoder'): self.context.amf3_decoder = pyamf.get_decoder( pyamf.AMF3, self.stream, self.context.amf3_context) decoder = self.context.amf3_decoder element = decoder.readElement() self.context.addAMF3Object(element) return element def readString(self): """ Reads a string from the data stream. @rtype: C{str} @return: string """ len = self.stream.read_ushort() return self.stream.read_utf8_string(len) def _readObject(self, obj, alias=None): obj_attrs = dict() key = self.readString().encode('utf8') while self.stream.peek() != TYPE_OBJECTTERM: obj_attrs[key] = self.readElement() key = self.readString().encode('utf8') # discard the end marker (TYPE_OBJECTTERM) self.stream.read(1) if alias: alias.applyAttributes(obj, obj_attrs, codec=self) else: util.set_attrs(obj, obj_attrs) def readObject(self): """ Reads an object from the data stream. @rtype: L{ASObject<pyamf.ASObject>} """ obj = pyamf.ASObject() self.context.addObject(obj) self._readObject(obj) return obj def readReference(self): """ Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference. """ idx = self.stream.read_ushort() o = self.context.getObject(idx) if o is None: raise pyamf.ReferenceError('Unknown reference %d' % (idx,)) return o def readDate(self): """ Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z1 Z2 T7} to C{T0} form a 64 bit Big Endian number that specifies the number of nanoseconds that have passed since 1/1/1970 0:00 to the specified time. This format is UTC 1970. C{Z1} and C{Z0} for a 16 bit Big Endian number indicating the indicated time's timezone in minutes. """ ms = self.stream.read_double() / 1000.0 tz = self.stream.read_short() # Timezones are ignored d = util.get_datetime(ms) if self.timezone_offset: d = d + self.timezone_offset self.context.addObject(d) return d def readLongString(self): """ Read UTF8 string. """ len = self.stream.read_ulong() return self.stream.read_utf8_string(len) def readXML(self): """ Read XML. """ data = self.readLongString() xml = util.ET.fromstring(data) self.context.addObject(xml) return xml class Encoder(pyamf.BaseEncoder): """ Encodes an AMF0 stream. @ivar use_amf3: A flag to determine whether this encoder knows about AMF3. @type use_amf3: C{bool} """ context_class = Context type_map = [ ((types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType, types.GeneratorType, types.ModuleType, types.LambdaType, types.MethodType), "writeFunc"), ((types.NoneType,), "writeNull"), ((bool,), "writeBoolean"), ((int,long,float), "writeNumber"), ((types.StringTypes,), "writeString"), ((pyamf.ASObject,), "writeObject"), ((pyamf.MixedArray,), "writeMixedArray"), ((types.ListType, types.TupleType,), "writeArray"), ((datetime.date, datetime.datetime, datetime.time), "writeDate"), ((util.is_ET_element,), "writeXML"), ((lambda x: x is pyamf.Undefined,), "writeUndefined"), ((types.ClassType, types.TypeType), "writeClass"), ((types.InstanceType,types.ObjectType,), "writeObject"), ] def __init__(self, *args, **kwargs): self.use_amf3 = kwargs.pop('use_amf3', False) pyamf.BaseEncoder.__init__(self, *args, **kwargs) def writeType(self, t): """ Writes the type to the stream. @type t: C{str} @param t: ActionScript type. @raise pyamf.EncodeError: AMF0 type is not recognized. """ self.stream.write(t) def writeUndefined(self, data): """ Writes the L{undefined<TYPE_UNDEFINED>} data type to the stream. @param data: The C{undefined} data to be encoded to the AMF0 data stream. @type data: C{undefined} data """ self.writeType(TYPE_UNDEFINED) def writeClass(self, *args, **kwargs): """ Classes cannot be serialised. """ raise pyamf.EncodeError("Class objects cannot be serialised") def writeFunc(self, *args, **kwargs): """ Functions cannot be serialised. """ raise pyamf.EncodeError("Callables cannot be serialised") def writeUnsupported(self, data): """ Writes L{unsupported<TYPE_UNSUPPORTED>} data type to the stream. @param data: The C{unsupported} data to be encoded to the AMF0 data stream. @type data: C{unsupported} data """ self.writeType(TYPE_UNSUPPORTED) def _writeElementFunc(self, data): """ Gets a function based on the type of data. @see: L{pyamf.BaseEncoder._writeElementFunc} """ # There is a very specific use case that we must check for. # In the context there is an array of amf3_objs that contain # references to objects that are to be encoded in amf3. if self.use_amf3 and self.context.hasAMF3ObjectReference(data): return self.writeAMF3 return pyamf.BaseEncoder._writeElementFunc(self, data) def writeElement(self, data): """ Writes the data. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. @raise EncodeError: Cannot find encoder func. """ func = self._writeElementFunc(data) if func is None: raise pyamf.EncodeError("Cannot find encoder func for %r" % (data,)) func(data) def writeNull(self, n): """ Write null type to data stream. @type n: C{None} @param n: Is ignored. """ self.writeType(TYPE_NULL) def writeArray(self, a): """ Write array to the stream. @type a: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param a: The array data to be encoded to the AMF0 data stream. """ alias = self.context.getClassAlias(a.__class__) if alias.external: # a is a subclassed list with a registered alias - push to the # correct method self.writeObject(a) return if self.writeReference(a) is not None: return self.context.addObject(a) self.writeType(TYPE_ARRAY) self.stream.write_ulong(len(a)) for data in a: self.writeElement(data) def writeNumber(self, n): """ Write number to the data stream. @type n: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param n: The number data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_NUMBER) self.stream.write_double(float(n)) def writeBoolean(self, b): """ Write boolean to the data stream. @type b: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param b: The boolean data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_BOOL) if b: self.stream.write_uchar(1) else: self.stream.write_uchar(0) def writeString(self, s, writeType=True): """ Write string to the data stream. @type s: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param s: The string data to be encoded to the AMF0 data stream. @type writeType: C{bool} @param writeType: Write data type. """ t = type(s) if t is str: pass elif isinstance(s, unicode): s = s.encode('utf8') elif not isinstance(s, basestring): s = unicode(s).encode('utf8') l = len(s) if writeType: if l > 0xffff: self.writeType(TYPE_LONGSTRING) else: self.writeType(TYPE_STRING) if l > 0xffff: self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s) def writeReference(self, o): """ Write reference to the data stream. @type o: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param o: The reference data to be encoded to the AMF0 data stream. """ idx = self.context.getObjectReference(o) if idx is None: return None self.writeType(TYPE_REFERENCE) self.stream.write_ushort(idx) return idx def _writeDict(self, o): """ Write C{dict} to the data stream. @type o: C{iterable} @param o: The C{dict} data to be encoded to the AMF0 data stream. """ for key, val in o.iteritems(): self.writeString(key, False) self.writeElement(val) def writeMixedArray(self, o): """ Write mixed array to the data stream. @type o: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param o: The mixed array data to be encoded to the AMF0 data stream. """ if self.writeReference(o) is not None: return self.context.addObject(o) self.writeType(TYPE_MIXEDARRAY) # TODO: optimise this # work out the highest integer index try: # list comprehensions to save the day max_index = max([y[0] for y in o.items() if isinstance(y[0], (int, long))]) if max_index < 0: max_index = 0 except ValueError: max_index = 0 self.stream.write_ulong(max_index) self._writeDict(o) self._writeEndObject() def _writeEndObject(self): self.stream.write('\x00\x00') self.writeType(TYPE_OBJECTTERM) def writeObject(self, o): """ Write object to the stream. @type o: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param o: The object data to be encoded to the AMF0 data stream. """ if self.use_amf3: self.writeAMF3(o) return if self.writeReference(o) is not None: return self.context.addObject(o) alias = self.context.getClassAlias(o.__class__) alias.compile() if alias.amf3: self.writeAMF3(o) return if alias.anonymous: self.writeType(TYPE_OBJECT) else: self.writeType(TYPE_TYPEDOBJECT) self.writeString(alias.alias, False) sa, da = alias.getEncodableAttributes(o, codec=self) if sa: for key in alias.static_attrs: self.writeString(key, False) self.writeElement(sa[key]) if da: for key, value in da.iteritems(): self.writeString(key, False) self.writeElement(value) self._writeEndObject() def writeDate(self, d): """ Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream. """ if isinstance(d, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF0 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (d,)) # According to the Red5 implementation of AMF0, dates references are # created, but not used. if self.timezone_offset is not None: d -= self.timezone_offset secs = util.get_timestamp(d) tz = 0 self.writeType(TYPE_DATE) self.stream.write_double(secs * 1000.0) self.stream.write_short(tz) def writeXML(self, e): """ Write XML to the data stream. @type e: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param e: The XML data to be encoded to the AMF0 data stream. """ if self.use_amf3 is True: self.writeAMF3(e) return self.writeType(TYPE_XML) data = util.ET.tostring(e, 'utf-8') self.stream.write_ulong(len(data)) self.stream.write(data) def writeAMF3(self, data): """ Writes an element to the datastream in L{AMF3<pyamf.amf3>} format. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. """ if not hasattr(self.context, 'amf3_context'): self.context.amf3_context = pyamf.get_context(pyamf.AMF3, exceptions=False) if not hasattr(self.context, 'amf3_encoder'): self.context.amf3_encoder = pyamf.get_encoder( pyamf.AMF3, self.stream, self.context.amf3_context) self.context.addAMF3Object(data) encoder = self.context.amf3_encoder self.writeType(TYPE_AMF3) encoder.writeElement(data) def decode(*args, **kwargs): """ A helper function to decode an AMF0 datastream. """ decoder = Decoder(*args, **kwargs) while 1: try: yield decoder.readElement() except pyamf.EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element into the AMF0 format. @type element: C{mixed} @keyword element: The element to encode @type context: L{Context<pyamf.amf0.Context>} @keyword context: AMF0 C{Context} to use for the encoding. This holds previously referenced objects etc. @rtype: C{StringIO} @return: The encoded stream. """ encoder = Encoder(**kwargs) for element in args: encoder.writeElement(element) return encoder.stream class RecordSet(object): """ I represent the C{RecordSet} class used in Adobe Flash Remoting to hold (amongst other things) SQL records. @ivar columns: The columns to send. @type columns: List of strings. @ivar items: The C{RecordSet} data. @type items: List of lists, the order of the data corresponds to the order of the columns. @ivar service: Service linked to the C{RecordSet}. @type service: @ivar id: The id of the C{RecordSet}. @type id: C{str} @see: U{RecordSet on OSFlash (external) <http://osflash.org/documentation/amf/recordset>} """ class __amf__: alias = 'RecordSet' static = ('serverInfo',) dynamic = False def __init__(self, columns=[], items=[], service=None, id=None): self.columns = columns self.items = items self.service = service self.id = id def _get_server_info(self): ret = pyamf.ASObject(totalCount=len(self.items), cursor=1, version=1, initialData=self.items, columnNames=self.columns) if self.service is not None: ret.update({'serviceName': str(self.service['name'])}) if self.id is not None: ret.update({'id':str(self.id)}) return ret def _set_server_info(self, val): self.columns = val['columnNames'] self.items = val['initialData'] try: # TODO nick: find relevant service and link in here. self.service = dict(name=val['serviceName']) except KeyError: self.service = None try: self.id = val['id'] except KeyError: self.id = None serverInfo = property(_get_server_info, _set_server_info) def __repr__(self): ret = '<%s.%s object' % (self.__module__, self.__class__.__name__) if self.id is not None: ret += ' id=%s' % self.id if self.service is not None: ret += ' service=%s' % self.service ret += ' at 0x%x>' % id(self) return ret pyamf.register_class(RecordSet) def _check_for_int(x): """ This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. """ try: y = int(x) except (OverflowError, ValueError): pass else: # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x: return y return x # check for some Python 2.3 problems with floats try: float('nan') except ValueError: pass else: if float('nan') == 0: def check_nan(func): def f2(x): if str(x).lower().find('nan') >= 0: return x return f2.func(x) f2.func = func return f2 _check_for_int = check_nan(_check_for_int)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF0 Remoting support. @since: 0.1.0 """ import traceback import sys from pyamf import remoting from pyamf.remoting import gateway class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def authenticateRequest(self, request, service_request, *args, **kwargs): """ Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} """ username = password = None if 'Credentials' in request.headers: cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs) def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return remoting.Response(build_fault(cls, e, tb, self.gateway.debug), status=remoting.STATUS_ERROR) def _getBody(self, request, response, service_request, **kwargs): if 'DescribeService' in request.headers: return service_request.service.description return self.gateway.callServiceRequest(service_request, *request.body, **kwargs) def __call__(self, request, *args, **kwargs): """ Processes an AMF0 request. @param request: The request to be processed. @type request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>} """ response = remoting.Response(None) try: service_request = self.gateway.getServiceRequest(request, request.target) except gateway.UnknownServiceError: return self.buildErrorResponse(request) # we have a valid service, now attempt authentication try: authd = self.authenticateRequest(request, service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) if not authd: # authentication failed response.status = remoting.STATUS_ERROR response.body = remoting.ErrorFault(code='AuthenticationError', description='Authentication failed') return response # authentication succeeded, now fire the preprocessor (if there is one) try: self.gateway.preprocessRequest(service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) try: response.body = self._getBody(request, response, service_request, *args, **kwargs) return response except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) def build_fault(cls, e, tb, include_traceback=False): """ Builds a L{ErrorFault<pyamf.remoting.ErrorFault>} object based on the last exception raised. If include_traceback is C{False} then the traceback will not be added to the L{remoting.ErrorFault}. """ if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ details = None if include_traceback: details = str(traceback.format_exception(cls, e, tb)).replace("\\n", '') return remoting.ErrorFault(code=code, description=str(e), details=details)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Remoting client implementation. @since: 0.1.0 """ import httplib import urlparse import pyamf from pyamf import remoting #: Default AMF client type. #: @see: L{ClientTypes<pyamf.ClientTypes>} DEFAULT_CLIENT_TYPE = pyamf.ClientTypes.Flash6 #: Default user agent is C{PyAMF/x.x.x}. DEFAULT_USER_AGENT = 'PyAMF/%s' % '.'.join(map(lambda x: str(x), pyamf.__version__)) HTTP_OK = 200 def convert_args(args): if args == (tuple(),): return [] else: return [x for x in args] class ServiceMethodProxy(object): """ Serves as a proxy for calling a service method. @ivar service: The parent service. @type service: L{ServiceProxy} @ivar name: The name of the method. @type name: C{str} or C{None} @see: L{ServiceProxy.__getattr__} """ def __init__(self, service, name): self.service = service self.name = name def __call__(self, *args): """ Inform the proxied service that this function has been called. """ return self.service._call(self, *args) def __str__(self): """ Returns the full service name, including the method name if there is one. """ service_name = str(self.service) if self.name is not None: service_name = '%s.%s' % (service_name, self.name) return service_name class ServiceProxy(object): """ Serves as a service object proxy for RPC calls. Generates L{ServiceMethodProxy} objects for method calls. @see: L{RequestWrapper} for more info. @ivar _gw: The parent gateway @type _gw: L{RemotingService} @ivar _name: The name of the service @type _name: C{str} @ivar _auto_execute: If set to C{True}, when a service method is called, the AMF request is immediately sent to the remote gateway and a response is returned. If set to C{False}, a L{RequestWrapper} is returned, waiting for the underlying gateway to fire the L{execute<RemotingService.execute>} method. """ def __init__(self, gw, name, auto_execute=True): self._gw = gw self._name = name self._auto_execute = auto_execute def __getattr__(self, name): return ServiceMethodProxy(self, name) def _call(self, method_proxy, *args): """ Executed when a L{ServiceMethodProxy} is called. Adds a request to the underlying gateway. If C{_auto_execute} is set to C{True}, then the request is immediately called on the remote gateway. """ request = self._gw.addRequest(method_proxy, *args) if self._auto_execute: response = self._gw.execute_single(request) # XXX nick: What to do about Fault objects here? return response.body return request def __call__(self, *args): """ This allows services to be 'called' without a method name. """ return self._call(ServiceMethodProxy(self, None), *args) def __str__(self): """ Returns a string representation of the name of the service. """ return self._name class RequestWrapper(object): """ A container object that wraps a service method request. @ivar gw: The underlying gateway. @type gw: L{RemotingService} @ivar id: The id of the request. @type id: C{str} @ivar service: The service proxy. @type service: L{ServiceProxy} @ivar args: The args used to invoke the call. @type args: C{list} """ def __init__(self, gw, id_, service, *args): self.gw = gw self.id = id_ self.service = service self.args = args def __str__(self): return str(self.id) def setResponse(self, response): """ A response has been received by the gateway """ # XXX nick: What to do about Fault objects here? self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException() def _get_result(self): """ Returns the result of the called remote request. If the request has not yet been called, an C{AttributeError} exception is raised. """ if not hasattr(self, '_result'): raise AttributeError("'RequestWrapper' object has no attribute 'result'") return self._result def _set_result(self, result): self._result = result result = property(_get_result, _set_result) class RemotingService(object): """ Acts as a client for AMF calls. @ivar url: The url of the remote gateway. Accepts C{http} or C{https} as valid schemes. @type url: C{str} @ivar requests: The list of pending requests to process. @type requests: C{list} @ivar request_number: A unique identifier for tracking the number of requests. @ivar amf_version: The AMF version to use. See L{ENCODING_TYPES<pyamf.ENCODING_TYPES>}. @type amf_version: C{int} @ivar referer: The referer, or HTTP referer, identifies the address of the client. Ignored by default. @type referer: C{str} @ivar client_type: The client type. See L{ClientTypes<pyamf.ClientTypes>}. @type client_type: C{int} @ivar user_agent: Contains information about the user agent (client) originating the request. See L{DEFAULT_USER_AGENT}. @type user_agent: C{str} @ivar connection: The underlying connection to the remoting server. @type connection: C{httplib.HTTPConnection} or C{httplib.HTTPSConnection} @ivar headers: A list of persistent headers to send with each request. @type headers: L{HeaderCollection<pyamf.remoting.HeaderCollection>} @ivar http_headers: A dict of HTTP headers to apply to the underlying HTTP connection. @type http_headers: L{dict} @ivar strict: Whether to use strict AMF en/decoding or not. @type strict: C{bool} """ def __init__(self, url, amf_version=pyamf.AMF0, client_type=DEFAULT_CLIENT_TYPE, referer=None, user_agent=DEFAULT_USER_AGENT, strict=False, logger=None): self.logger = logger self.original_url = url self.requests = [] self.request_number = 1 self.user_agent = user_agent self.referer = referer self.amf_version = amf_version self.client_type = client_type self.headers = remoting.HeaderCollection() self.http_headers = {} self.strict = strict self._setUrl(url) def _setUrl(self, url): """ @param url: Gateway URL. @type url: C{str} @raise ValueError: Unknown scheme. """ self.url = urlparse.urlparse(url) self._root_url = urlparse.urlunparse(['', ''] + list(self.url[2:])) port = None hostname = None if hasattr(self.url, 'port'): if self.url.port is not None: port = self.url.port else: if ':' not in self.url[1]: hostname = self.url[1] port = None else: sp = self.url[1].split(':') hostname, port = sp[0], sp[1] port = int(port) if hostname is None: if hasattr(self.url, 'hostname'): hostname = self.url.hostname if self.url[0] == 'http': if port is None: port = httplib.HTTP_PORT self.connection = httplib.HTTPConnection(hostname, port) elif self.url[0] == 'https': if port is None: port = httplib.HTTPS_PORT self.connection = httplib.HTTPSConnection(hostname, port) else: raise ValueError('Unknown scheme') location = '%s://%s:%s%s' % (self.url[0], hostname, port, self.url[2]) if self.logger: self.logger.info('Connecting to %s' % location) self.logger.debug('Referer: %s' % self.referer) self.logger.debug('User-Agent: %s' % self.user_agent) def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. @type name: C{str} @param must_understand: Default is C{False}. @type must_understand: C{bool} """ self.headers[name] = value self.headers.set_required(name, must_understand) def addHTTPHeader(self, name, value): """ Adds a header to the underlying HTTP connection. """ self.http_headers[name] = value def removeHTTPHeader(self, name): """ Deletes an HTTP header. """ del self.http_headers[name] def getService(self, name, auto_execute=True): """ Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @param auto_execute: Default is C{True}. @type auto_execute: C{bool} @raise TypeError: C{string} type required for C{name}. @rtype: L{ServiceProxy} """ if not isinstance(name, basestring): raise TypeError('string type required') return ServiceProxy(self, name, auto_execute) def getRequest(self, id_): """ Gets a request based on the id. @raise LookupError: Request not found. """ for request in self.requests: if request.id == id_: return request raise LookupError("Request %s not found" % id_) def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r' % (wrapper.service, args)) return wrapper def removeRequest(self, service, *args): """ Removes a request from the pending request list. @raise LookupError: Request not found. """ if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s' % ( self.requests[self.requests.index(service)])) del self.requests[self.requests.index(service)] return for request in self.requests: if request.service == service and request.args == args: if self.logger: self.logger.debug('Removing request: %s' % ( self.requests[self.requests.index(request)])) del self.requests[self.requests.index(request)] return raise LookupError("Request not found") def getAMFRequest(self, requests): """ Builds an AMF request L{Envelope<pyamf.remoting.Envelope>} from a supplied list of requests. @param requests: List of requests @type requests: C{list} @rtype: L{Envelope<pyamf.remoting.Envelope>} """ envelope = remoting.Envelope(self.amf_version, self.client_type) if self.logger: self.logger.debug('AMF version: %s' % self.amf_version) self.logger.debug('Client type: %s' % self.client_type) for request in requests: service = request.service args = list(request.args) envelope[request.id] = remoting.Request(str(service), args) envelope.headers = self.headers return envelope def _get_execute_headers(self): headers = self.http_headers.copy() headers.update({ 'Content-Type': remoting.CONTENT_TYPE, 'User-Agent': self.user_agent }) if self.referer is not None: headers['Referer'] = self.referer return headers def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. @param request: @type request: @rtype: """ if self.logger: self.logger.debug('Executing single request: %s' % request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) if self.logger: self.logger.debug('Sending POST request to %s' % self._root_url) self.connection.request('POST', self._root_url, body.getvalue(), self._get_execute_headers() ) envelope = self._getResponse() self.removeRequest(request) return envelope[request.id] def execute(self): """ Builds, sends and handles the responses to all requests listed in C{self.requests}. """ body = remoting.encode(self.getAMFRequest(self.requests), strict=self.strict) if self.logger: self.logger.debug('Sending POST request to %s' % self._root_url) self.connection.request('POST', self._root_url, body.getvalue(), self._get_execute_headers() ) envelope = self._getResponse() for response in envelope: request = self.getRequest(response[0]) response = response[1] request.setResponse(response) self.removeRequest(request) def _getResponse(self): """ Gets and handles the HTTP response from the remote gateway. @raise RemotingError: HTTP Gateway reported error status. @raise RemotingError: Incorrect MIME type received. """ if self.logger: self.logger.debug('Waiting for response...') http_response = self.connection.getresponse() if self.logger: self.logger.debug('Got response status: %s' % http_response.status) self.logger.debug('Content-Type: %s' % http_response.getheader('Content-Type')) if http_response.status != HTTP_OK: if self.logger: self.logger.debug('Body: %s' % http_response.read()) if hasattr(httplib, 'responses'): raise remoting.RemotingError("HTTP Gateway reported status %d %s" % ( http_response.status, httplib.responses[http_response.status])) raise remoting.RemotingError("HTTP Gateway reported status %d" % ( http_response.status,)) content_type = http_response.getheader('Content-Type') if content_type != remoting.CONTENT_TYPE: if self.logger: self.logger.debug('Body = %s' % http_response.read()) raise remoting.RemotingError("Incorrect MIME type received. (got: %s)" % content_type) content_length = http_response.getheader('Content-Length') bytes = '' if self.logger: self.logger.debug('Content-Length: %s' % content_length) self.logger.debug('Server: %s' % http_response.getheader('Server')) if content_length in (None, ''): bytes = http_response.read() else: bytes = http_response.read(int(content_length)) if self.logger: self.logger.debug('Read %d bytes for the response' % len(bytes)) response = remoting.decode(bytes, strict=self.strict) if self.logger: self.logger.debug('Response: %s' % response) if remoting.APPEND_TO_GATEWAY_URL in response.headers: self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL] self._setUrl(self.original_url) elif remoting.REPLACE_GATEWAY_URL in response.headers: self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL] self._setUrl(self.original_url) if remoting.REQUEST_PERSISTENT_HEADER in response.headers: data = response.headers[remoting.REQUEST_PERSISTENT_HEADER] for k, v in data.iteritems(): self.headers[k] = v http_response.close() return response def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=unicode(username), password=unicode(password)), True)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF3 RemoteObject support. @see: U{RemoteObject on LiveDocs <http://livedocs.adobe.com/flex/3/langref/mx/rpc/remoting/RemoteObject.html>} @since: 0.1.0 """ import calendar import time import uuid import sys import pyamf from pyamf import remoting from pyamf.flex import messaging class BaseServerError(pyamf.BaseError): """ Base server error. """ class ServerCallFailed(BaseServerError): """ A catchall error. """ _amf_code = 'Server.Call.Failed' def generate_random_id(): return str(uuid.uuid4()) def generate_acknowledgement(request=None): ack = messaging.AcknowledgeMessage() ack.messageId = generate_random_id() ack.clientId = generate_random_id() ack.timestamp = calendar.timegm(time.gmtime()) if request: ack.correlationId = request.messageId return ack def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ detail = '' rootCause = None if include_traceback: detail = [] rootCause = e for x in traceback.format_exception(cls, e, tb): detail.append(x.replace("\\n", '')) return messaging.ErrorMessage(messageId=generate_random_id(), clientId=generate_random_id(), timestamp=calendar.timegm(time.gmtime()), correlationId = request.messageId, faultCode=code, faultString=str(e), faultDetail=str(detail), extendedData=detail, rootCause=rootCause) class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return generate_error(request, cls, e, tb, self.gateway.debug) def _getBody(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown request. """ if isinstance(ro_request, messaging.CommandMessage): return self._processCommandMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.RemotingMessage): return self._processRemotingMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.AsyncMessage): return self._processAsyncMessage(amf_request, ro_request, **kwargs) else: raise ServerCallFailed("Unknown request: %s" % ro_request) def _processCommandMessage(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown Command operation. @raise ServerCallFailed: Authorization is not supported in RemoteObject. """ ro_response = generate_acknowledgement(ro_request) if ro_request.operation == messaging.CommandMessage.PING_OPERATION: ro_response.body = True return remoting.Response(ro_response) elif ro_request.operation == messaging.CommandMessage.LOGIN_OPERATION: raise ServerCallFailed("Authorization is not supported in RemoteObject") elif ro_request.operation == messaging.CommandMessage.DISCONNECT_OPERATION: return remoting.Response(ro_response) else: raise ServerCallFailed("Unknown Command operation %s" % ro_request.operation) def _processAsyncMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) ro_response.body = True return remoting.Response(ro_response) def _processRemotingMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) service_name = ro_request.operation if hasattr(ro_request, 'destination') and ro_request.destination: service_name = '%s.%s' % (ro_request.destination, service_name) service_request = self.gateway.getServiceRequest(amf_request, service_name) # fire the preprocessor (if there is one) self.gateway.preprocessRequest(service_request, *ro_request.body, **kwargs) ro_response.body = self.gateway.callServiceRequest(service_request, *ro_request.body, **kwargs) return remoting.Response(ro_response) def __call__(self, amf_request, **kwargs): """ Processes an AMF3 Remote Object request. @param amf_request: The request to be processed. @type amf_request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>} """ ro_request = amf_request.body[0] try: return self._getBody(amf_request, ro_request, **kwargs) except (KeyboardInterrupt, SystemExit): raise except: return remoting.Response(self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF Remoting support. A Remoting request from the client consists of a short preamble, headers, and bodies. The preamble contains basic information about the nature of the request. Headers can be used to request debugging information, send authentication info, tag transactions, etc. Bodies contain actual Remoting requests and responses. A single Remoting envelope can contain several requests; Remoting supports batching out of the box. Client headers and bodies need not be responded to in a one-to-one manner. That is, a body or header may not require a response. Debug information is requested by a header but sent back as a body object. The response index is essential for the Adobe Flash Player to understand the response therefore. @see: U{Remoting Envelope on OSFlash (external) <http://osflash.org/documentation/amf/envelopes/remoting>} @see: U{Remoting Headers on OSFlash (external) <http://osflash.org/amf/envelopes/remoting/headers>} @see: U{Remoting Debug Headers on OSFlash (external) <http://osflash.org/documentation/amf/envelopes/remoting/debuginfo>} @since: 0.1.0 """ import pyamf from pyamf import util __all__ = ['Envelope', 'Request', 'Response', 'decode', 'encode'] #: Succesful call. STATUS_OK = 0 #: Reserved for runtime errors. STATUS_ERROR = 1 #: Debug information. STATUS_DEBUG = 2 #: List of available status response codes. STATUS_CODES = { STATUS_OK: '/onResult', STATUS_ERROR: '/onStatus', STATUS_DEBUG: '/onDebugEvents' } #: AMF mimetype. CONTENT_TYPE = 'application/x-amf' ERROR_CALL_FAILED, = range(1) ERROR_CODES = { ERROR_CALL_FAILED: 'Server.Call.Failed' } APPEND_TO_GATEWAY_URL = 'AppendToGatewayUrl' REPLACE_GATEWAY_URL = 'ReplaceGatewayUrl' REQUEST_PERSISTENT_HEADER = 'RequestPersistentHeader' class RemotingError(pyamf.BaseError): """ Generic remoting error class. """ class RemotingCallFailed(RemotingError): """ Raised if C{Server.Call.Failed} received. """ pyamf.add_error_class(RemotingCallFailed, ERROR_CODES[ERROR_CALL_FAILED]) class HeaderCollection(dict): """ Collection of AMF message headers. """ def __init__(self, raw_headers={}): self.required = [] for (k, ig, v) in raw_headers: self[k] = v if ig: self.required.append(k) def is_required(self, idx): """ @raise KeyError: Unknown header found. """ if not idx in self: raise KeyError("Unknown header %s" % str(idx)) return idx in self.required def set_required(self, idx, value=True): """ @raise KeyError: Unknown header found. """ if not idx in self: raise KeyError("Unknown header %s" % str(idx)) if not idx in self.required: self.required.append(idx) def __len__(self): return len(self.keys()) class Envelope(object): """ I wrap an entire request, encapsulating headers and bodies. There can be more than one request in a single transaction. @ivar amfVersion: AMF encoding version. See L{pyamf.ENCODING_TYPES} @type amfVersion: C{int} or C{None} @ivar clientType: Client type. See L{ClientTypes<pyamf.ClientTypes>} @type clientType: C{int} or C{None} @ivar headers: AMF headers, a list of name, value pairs. Global to each request. @type headers: L{HeaderCollection} @ivar bodies: A list of requests/response messages @type bodies: L{list} containing tuples of the key of the request and the instance of the L{Message} """ def __init__(self, amfVersion=None, clientType=None): self.amfVersion = amfVersion self.clientType = clientType self.headers = HeaderCollection() self.bodies = [] def __repr__(self): r = "<Envelope amfVersion=%s clientType=%s>\n" % ( self.amfVersion, self.clientType) for h in self.headers: r += " " + repr(h) + "\n" for request in iter(self): r += " " + repr(request) + "\n" r += "</Envelope>" return r def __setitem__(self, name, value): if not isinstance(value, Message): raise TypeError("Message instance expected") idx = 0 found = False for body in self.bodies: if name == body[0]: self.bodies[idx] = (name, value) found = True idx = idx + 1 if not found: self.bodies.append((name, value)) value.envelope = self def __getitem__(self, name): for body in self.bodies: if name == body[0]: return body[1] raise KeyError("'%r'" % (name,)) def __iter__(self): for body in self.bodies: yield body[0], body[1] raise StopIteration def __len__(self): return len(self.bodies) def iteritems(self): for body in self.bodies: yield body raise StopIteration def keys(self): return [body[0] for body in self.bodies] def items(self): return self.bodies def __contains__(self, name): for body in self.bodies: if name == body[0]: return True return False def __eq__(self, other): if isinstance(other, Envelope): return (self.amfVersion == other.amfVersion and self.clientType == other.clientType and self.headers == other.headers and self.bodies == other.bodies) if hasattr(other, 'keys') and hasattr(other, 'items'): keys, o_keys = self.keys(), other.keys() if len(o_keys) != len(keys): return False for k in o_keys: if k not in keys: return False keys.remove(k) for k, v in other.items(): if self[k] != v: return False return True class Message(object): """ I represent a singular request/response, containing a collection of headers and one body of data. I am used to iterate over all requests in the L{Envelope}. @ivar envelope: The parent envelope of this AMF Message. @type envelope: L{Envelope} @ivar body: The body of the message. @type body: C{mixed} @ivar headers: The message headers. @type headers: C{dict} """ def __init__(self, envelope, body): self.envelope = envelope self.body = body def _get_headers(self): return self.envelope.headers headers = property(_get_headers) class Request(Message): """ An AMF Request payload. @ivar target: The target of the request @type target: C{basestring} """ def __init__(self, target, body=[], envelope=None): Message.__init__(self, envelope, body) self.target = target def __repr__(self): return "<%s target=%s>%s</%s>" % ( type(self).__name__, repr(self.target), repr(self.body), type(self).__name__) class Response(Message): """ An AMF Response. @ivar status: The status of the message. Default is L{STATUS_OK}. @type status: Member of L{STATUS_CODES}. """ def __init__(self, body, status=STATUS_OK, envelope=None): Message.__init__(self, envelope, body) self.status = status def __repr__(self): return "<%s status=%s>%s</%s>" % ( type(self).__name__, _get_status(self.status), repr(self.body), type(self).__name__ ) class BaseFault(object): """ I represent a C{Fault} message (C{mx.rpc.Fault}). @ivar level: The level of the fault. @type level: C{str} @ivar code: A simple code describing the fault. @type code: C{str} @ivar details: Any extra details of the fault. @type details: C{str} @ivar description: Text description of the fault. @type description: C{str} @see: U{mx.rpc.Fault on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/rpc/Fault.html>} """ level = None class __amf__: static = ('level', 'code', 'type', 'details', 'description') def __init__(self, *args, **kwargs): self.code = kwargs.get('code', '') self.type = kwargs.get('type', '') self.details = kwargs.get('details', '') self.description = kwargs.get('description', '') def __repr__(self): x = '%s level=%s' % (self.__class__.__name__, self.level) if self.code not in ('', None): x += ' code=%s' % repr(self.code) if self.type not in ('', None): x += ' type=%s' % repr(self.type) if self.description not in ('', None): x += ' description=%s' % repr(self.description) if self.details not in ('', None): x += '\nTraceback:\n%s' % (repr(self.details),) return x def raiseException(self): """ Raises an exception based on the fault object. There is no traceback available. """ raise get_exception_from_fault(self), self.description, None class ErrorFault(BaseFault): """ I represent an error level fault. """ level = 'error' def _read_header(stream, decoder, strict=False): """ Read AMF L{Message} header. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param stream: AMF data. @type decoder: L{amf0.Decoder<pyamf.amf0.Decoder>} @param decoder: AMF decoder instance @type strict: C{bool} @param strict: Use strict decoding policy. Default is C{False}. @raise DecodeError: The data that was read from the stream does not match the header length. @rtype: C{tuple} @return: - Name of the header. - A C{bool} determining if understanding this header is required. - Value of the header. """ name_len = stream.read_ushort() name = stream.read_utf8_string(name_len) required = bool(stream.read_uchar()) data_len = stream.read_ulong() pos = stream.tell() data = decoder.readElement() if strict and pos + data_len != stream.tell(): raise pyamf.DecodeError( "Data read from stream does not match header length") return (name, required, data) def _write_header(name, header, required, stream, encoder, strict=False): """ Write AMF message header. @type name: C{str} @param name: Name of the header. @type header: @param header: Raw header data. @type required: L{bool} @param required: Required header. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param stream: AMF data. @type encoder: L{amf0.Encoder<pyamf.amf0.Encoder>} or L{amf3.Encoder<pyamf.amf3.Encoder>} @param encoder: AMF encoder instance. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. """ stream.write_ushort(len(name)) stream.write_utf8_string(name) stream.write_uchar(required) write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() encoder.writeElement(header) new_pos = stream.tell() if strict: stream.seek(write_pos) stream.write_ulong(new_pos - old_pos) stream.seek(new_pos) def _read_body(stream, decoder, strict=False, logger=None): """ Read AMF message body. @param stream: AMF data. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param decoder: AMF decoder instance. @type decoder: L{amf0.Decoder<pyamf.amf0.Decoder>} @param strict: Use strict decoding policy. Default is C{False}. @type strict: C{bool} @raise DecodeError: Data read from stream does not match body length. @param logger: Used to log interesting events whilst reading a remoting body. @type logger: A L{logging.Logger} instance or C{None}. @rtype: C{tuple} @return: A C{tuple} containing: - ID of the request - L{Request} or L{Response} """ def _read_args(): """ @raise pyamf.DecodeError: Array type required for request body. """ if stream.read(1) != '\x0a': raise pyamf.DecodeError("Array type required for request body") x = stream.read_ulong() return [decoder.readElement() for i in xrange(x)] target = stream.read_utf8_string(stream.read_ushort()) response = stream.read_utf8_string(stream.read_ushort()) status = STATUS_OK is_request = True for code, s in STATUS_CODES.iteritems(): if not target.endswith(s): continue is_request = False status = code target = target[:0 - len(s)] if logger: logger.debug('Remoting target: %r' % (target,)) data_len = stream.read_ulong() pos = stream.tell() if is_request: data = _read_args() else: data = decoder.readElement() if strict and pos + data_len != stream.tell(): raise pyamf.DecodeError("Data read from stream does not match body " "length (%d != %d)" % (pos + data_len, stream.tell(),)) if is_request: return response, Request(target, body=data) if status == STATUS_ERROR and isinstance(data, pyamf.ASObject): data = get_fault(data) return target, Response(data, status) def _write_body(name, message, stream, encoder, strict=False): """ Write AMF message body. @param name: The name of the request. @type name: C{basestring} @param message: The AMF payload. @type message: L{Request} or L{Response} @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @type encoder: L{amf0.Encoder<pyamf.amf0.Encoder>} @param encoder: Encoder to use. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. @raise TypeError: Unknown message type for C{message}. """ def _encode_body(message): if isinstance(message, Response): encoder.writeElement(message.body) return stream.write('\x0a') stream.write_ulong(len(message.body)) for x in message.body: encoder.writeElement(x) if not isinstance(message, (Request, Response)): raise TypeError("Unknown message type") target = None if isinstance(message, Request): target = unicode(message.target) else: target = u"%s%s" % (name, _get_status(message.status)) target = target.encode('utf8') stream.write_ushort(len(target)) stream.write_utf8_string(target) response = 'null' if isinstance(message, Request): response = name stream.write_ushort(len(response)) stream.write_utf8_string(response) if not strict: stream.write_ulong(0) _encode_body(message) return write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() _encode_body(message) new_pos = stream.tell() stream.seek(write_pos) stream.write_ulong(new_pos - old_pos) stream.seek(new_pos) def _get_status(status): """ Get status code. @type status: C{str} @raise ValueError: The status code is unknown. @return: Status code. @see: L{STATUS_CODES} """ if status not in STATUS_CODES.keys(): # TODO print that status code.. raise ValueError("Unknown status code") return STATUS_CODES[status] def get_fault_class(level, **kwargs): if level == 'error': return ErrorFault return BaseFault def get_fault(data): try: level = data['level'] del data['level'] except KeyError: level = 'error' e = {} for x, y in data.iteritems(): if isinstance(x, unicode): e[str(x)] = y else: e[x] = y return get_fault_class(level, **e)(**e) def decode(stream, context=None, strict=False, logger=None, timezone_offset=None): """ Decodes the incoming stream as a remoting message. @param stream: AMF data. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param context: Context. @type context: L{amf0.Context<pyamf.amf0.Context>} or L{amf3.Context<pyamf.amf3.Context>} @param strict: Enforce strict decoding. Default is C{False}. @type strict: C{bool} @param logger: Used to log interesting events whilst decoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @raise DecodeError: Malformed stream. @raise RuntimeError: Decoder is unable to fully consume the stream buffer. @return: Message envelope. @rtype: L{Envelope} """ if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) if logger is not None: logger.debug('remoting.decode start') msg = Envelope() msg.amfVersion = stream.read_uchar() # see http://osflash.org/documentation/amf/envelopes/remoting#preamble # why we are doing this... if msg.amfVersion > 0x09: raise pyamf.DecodeError("Malformed stream (amfVersion=%d)" % msg.amfVersion) if context is None: context = pyamf.get_context(pyamf.AMF0, exceptions=False) decoder = pyamf.get_decoder(pyamf.AMF0, stream, context=context, strict=strict, timezone_offset=timezone_offset) msg.clientType = stream.read_uchar() header_count = stream.read_ushort() for i in xrange(header_count): name, required, data = _read_header(stream, decoder, strict) msg.headers[name] = data if required: msg.headers.set_required(name) body_count = stream.read_short() for i in range(body_count): context.clear() target, payload = _read_body(stream, decoder, strict, logger) msg[target] = payload if strict and stream.remaining() > 0: raise RuntimeError("Unable to fully consume the buffer") if logger is not None: logger.debug('remoting.decode end') return msg def encode(msg, context=None, strict=False, logger=None, timezone_offset=None): """ Encodes AMF stream and returns file object. @type msg: L{Envelope} @param msg: The message to encode. @type strict: C{bool} @param strict: Determines whether encoding should be strict. Specifically header/body lengths will be written correctly, instead of the default 0. Default is C{False}. Introduced in 0.4. @param logger: Used to log interesting events whilst encoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @rtype: C{StringIO} @return: File object. """ stream = util.BufferedByteStream() if context is None: context = pyamf.get_context(pyamf.AMF0, exceptions=False) encoder = pyamf.get_encoder(pyamf.AMF0, stream, context=context, timezone_offset=timezone_offset, strict=strict) if msg.clientType == pyamf.ClientTypes.Flash9: encoder.use_amf3 = True stream.write_uchar(msg.amfVersion) stream.write_uchar(msg.clientType) stream.write_short(len(msg.headers)) for name, header in msg.headers.iteritems(): _write_header( name, header, int(msg.headers.is_required(name)), stream, encoder, strict) stream.write_short(len(msg)) for name, message in msg.iteritems(): encoder.context.clear() _write_body(name, message, stream, encoder, strict) stream.seek(0) return stream def get_exception_from_fault(fault): """ @raise RemotingError: Default exception from fault. """ # XXX nick: threading problems here? try: return pyamf.ERROR_CLASS_MAP[fault.code] except KeyError: # default to RemotingError return RemotingError pyamf.register_class(ErrorFault)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Gateway for Google App Engine. This gateway allows you to expose functions in Google App Engine web applications to AMF clients and servers. @see: U{Google App Engine homepage (external) <http://code.google.com/appengine>} @since: 0.3.1 """ import sys import os.path try: sys.path.remove(os.path.dirname(os.path.abspath(__file__))) except ValueError: pass google = __import__('google.appengine.ext.webapp') webapp = google.appengine.ext.webapp from pyamf import remoting from pyamf.remoting import gateway __all__ = ['WebAppGateway'] class WebAppGateway(webapp.RequestHandler, gateway.BaseGateway): """ Google App Engine Remoting Gateway. """ __name__ = None def __init__(self, *args, **kwargs): gateway.BaseGateway.__init__(self, *args, **kwargs) def getResponse(self, request): """ Processes the AMF request, returning an AMF response. @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: self.request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=self.request) return response def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.error(405) self.response.out.write("405 Method Not Allowed\n\n" "To access this PyAMF gateway you must use POST requests " "(%s received)" % self.request.method) def post(self): body = self.request.body_file.read() stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(body, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ("400 Bad Request\n\nThe request body was unable to " "be successfully decoded.") if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(400) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(request) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(500) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be encoded." if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(500) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return response = stream.getvalue() self.response.headers['Content-Type'] = remoting.CONTENT_TYPE self.response.headers['Content-Length'] = str(len(response)) self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) def __call__(self, *args, **kwargs): return self
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Gateway for the Django framework. This gateway allows you to expose functions in Django to AMF clients and servers. @see: U{Django homepage (external)<http://djangoproject.com>} @since: 0.1.0 """ django = __import__('django.http') http = django.http conf = __import__('django.conf') conf = conf.conf import pyamf from pyamf import remoting from pyamf.remoting import gateway __all__ = ['DjangoGateway'] class DjangoGateway(gateway.BaseGateway): """ An instance of this class is suitable as a Django view. An example usage would be through C{urlconf}:: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gateway/', 'yourproject.yourapp.gateway.gw_instance'), ) where C{yourproject.yourapp.gateway.gw_instance} refers to an instance of this class. @ivar expose_request: The standard Django view always has the request object as the first parameter. To disable this functionality, set this to C{False}. @type expose_request: C{bool} """ def __init__(self, *args, **kwargs): kwargs['expose_request'] = kwargs.get('expose_request', True) try: tz = conf.settings.AMF_TIME_OFFSET except AttributeError: tz = None try: debug = conf.settings.DEBUG except AttributeError: debug = False kwargs['timezone_offset'] = kwargs.get('timezone_offset', tz) kwargs['debug'] = kwargs.get('debug', debug) gateway.BaseGateway.__init__(self, *args, **kwargs) def getResponse(self, http_request, request): """ Processes the AMF request, returning an AMF response. @param http_request: The underlying HTTP Request. @type http_request: C{HTTPRequest<django.core.http.HTTPRequest>} @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: http_request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=http_request) return response def __call__(self, http_request): """ Processes and dispatches the request. @param http_request: The C{HTTPRequest} object. @type http_request: C{HTTPRequest} @return: The response to the request. @rtype: C{HTTPResponse} """ if http_request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(http_request.raw_post_data, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (pyamf.DecodeError, IOError): fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseBadRequest(mimetype='text/plain', content=response) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ('500 Internal Server Error\n\n' 'An unexpected error occurred.') if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(http_request, request) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ("500 Internal Server Error\n\nThe request was " "unable to be encoded.") if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) buf = stream.getvalue() http_response = http.HttpResponse(mimetype=remoting.CONTENT_TYPE) http_response['Server'] = gateway.SERVER_NAME http_response['Content-Length'] = str(len(buf)) http_response.write(buf) return http_response
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Twisted server implementation. This gateway allows you to expose functions in Twisted to AMF clients and servers. @see: U{Twisted homepage (external)<http://twistedmatrix.com>} @since: 0.1.0 """ import sys import os.path try: sys.path.remove('') except ValueError: pass try: sys.path.remove(os.path.dirname(os.path.abspath(__file__))) except ValueError: pass twisted = __import__('twisted') __import__('twisted.internet.defer') __import__('twisted.internet.threads') __import__('twisted.web.resource') __import__('twisted.web.server') defer = twisted.internet.defer threads = twisted.internet.threads resource = twisted.web.resource server = twisted.web.server from pyamf import remoting from pyamf.remoting import gateway, amf0, amf3 __all__ = ['TwistedGateway'] class AMF0RequestProcessor(amf0.RequestProcessor): """ A Twisted friendly implementation of L{amf0.RequestProcessor<pyamf.remoting.amf0.RequestProcessor>} """ def __call__(self, request, *args, **kwargs): """ Calls the underlying service method. @return: A C{Deferred} that will contain the AMF L{Response}. @rtype: C{twisted.internet.defer.Deferred} """ try: service_request = self.gateway.getServiceRequest( request, request.target) except gateway.UnknownServiceError: return defer.succeed(self.buildErrorResponse(request)) response = remoting.Response(None) deferred_response = defer.Deferred() def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) deferred_response.callback(self.buildErrorResponse( request, (failure.type, failure.value, failure.tb))) def response_cb(result): if self.gateway.logger: self.gateway.logger.debug("AMF Response: %s" % (result,)) response.body = result deferred_response.callback(response) def preprocess_cb(result): d = defer.maybeDeferred(self._getBody, request, response, service_request, **kwargs) d.addCallback(response_cb).addErrback(eb) def auth_cb(result): if result is not True: response.status = remoting.STATUS_ERROR response.body = remoting.ErrorFault(code='AuthenticationError', description='Authentication failed') deferred_response.callback(response) return d = defer.maybeDeferred(self.gateway.preprocessRequest, service_request, *args, **kwargs) d.addCallback(preprocess_cb).addErrback(eb) # we have a valid service, now attempt authentication d = defer.maybeDeferred(self.authenticateRequest, request, service_request, **kwargs) d.addCallback(auth_cb).addErrback(eb) return deferred_response class AMF3RequestProcessor(amf3.RequestProcessor): """ A Twisted friendly implementation of L{amf3.RequestProcessor<pyamf.remoting.amf3.RequestProcessor>} """ def _processRemotingMessage(self, amf_request, ro_request, **kwargs): ro_response = amf3.generate_acknowledgement(ro_request) amf_response = remoting.Response(ro_response, status=remoting.STATUS_OK) try: service_name = ro_request.operation if hasattr(ro_request, 'destination') and ro_request.destination: service_name = '%s.%s' % (ro_request.destination, service_name) service_request = self.gateway.getServiceRequest(amf_request, service_name) except gateway.UnknownServiceError: return defer.succeed(remoting.Response( self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR)) deferred_response = defer.Deferred() def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) ro_response = self.buildErrorResponse(ro_request, (failure.type, failure.value, failure.tb)) deferred_response.callback(remoting.Response(ro_response, status=remoting.STATUS_ERROR)) def response_cb(result): ro_response.body = result res = remoting.Response(ro_response) if self.gateway.logger: self.gateway.logger.debug("AMF Response: %r" % (res,)) deferred_response.callback(res) def process_cb(result): d = defer.maybeDeferred(self.gateway.callServiceRequest, service_request, *ro_request.body, **kwargs) d.addCallback(response_cb).addErrback(eb) d = defer.maybeDeferred(self.gateway.preprocessRequest, service_request, *ro_request.body, **kwargs) d.addCallback(process_cb).addErrback(eb) return deferred_response def __call__(self, amf_request, **kwargs): """ Calls the underlying service method. @return: A C{deferred} that will contain the AMF L{Response}. @rtype: C{Deferred<twisted.internet.defer.Deferred>} """ deferred_response = defer.Deferred() ro_request = amf_request.body[0] def cb(amf_response): deferred_response.callback(amf_response) def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) deferred_response.callback(self.buildErrorResponse(ro_request, (failure.type, failure.value, failure.tb))) d = defer.maybeDeferred(self._getBody, amf_request, ro_request, **kwargs) d.addCallback(cb).addErrback(eb) return deferred_response class TwistedGateway(gateway.BaseGateway, resource.Resource): """ Twisted Remoting gateway for C{twisted.web}. @ivar expose_request: Forces the underlying HTTP request to be the first argument to any service call. @type expose_request: C{bool} """ allowedMethods = ('POST',) def __init__(self, *args, **kwargs): if 'expose_request' not in kwargs: kwargs['expose_request'] = True gateway.BaseGateway.__init__(self, *args, **kwargs) resource.Resource.__init__(self) def _finaliseRequest(self, request, status, content, mimetype='text/plain'): """ Finalises the request. @param request: The HTTP Request. @type request: C{http.Request} @param status: The HTTP status code. @type status: C{int} @param content: The content of the response. @type content: C{str} @param mimetype: The MIME type of the request. @type mimetype: C{str} """ request.setResponseCode(status) request.setHeader("Content-Type", mimetype) request.setHeader("Content-Length", str(len(content))) request.setHeader("Server", gateway.SERVER_NAME) request.write(content) request.finish() def render_POST(self, request): """ Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} """ def handleDecodeError(failure): """ Return HTTP 400 Bad Request. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(request, 400, body) request.content.seek(0, 0) timezone_offset = self._get_timezone_offset() d = threads.deferToThread(remoting.decode, request.content.read(), strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) def cb(amf_request): if self.logger: self.logger.debug("AMF Request: %r" % amf_request) x = self.getResponse(request, amf_request) x.addCallback(self.sendResponse, request) # Process the request d.addCallback(cb).addErrback(handleDecodeError) return server.NOT_DONE_YET def sendResponse(self, amf_response, request): def cb(result): self._finaliseRequest(request, 200, result.getvalue(), remoting.CONTENT_TYPE) def eb(failure): """ Return 500 Internal Server Error. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "500 Internal Server Error\n\nThere was an error encoding " \ "the response." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(request, 500, body) timezone_offset = self._get_timezone_offset() d = threads.deferToThread(remoting.encode, amf_response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) d.addCallback(cb).addErrback(eb) def getProcessor(self, request): """ Determines the request processor, based on the request. @param request: The AMF message. @type request: L{Request<pyamf.remoting.Request>} """ if request.target == 'null': return AMF3RequestProcessor(self) return AMF0RequestProcessor(self) def getResponse(self, http_request, amf_request): """ Processes the AMF request, returning an AMF L{Response}. @param http_request: The underlying HTTP Request @type http_request: C{twisted.web.http.Request} @param amf_request: The AMF Request. @type amf_request: L{Envelope<pyamf.remoting.Envelope>} """ response = remoting.Envelope(amf_request.amfVersion, amf_request.clientType) dl = [] def cb(body, name): response[name] = body for name, message in amf_request: processor = self.getProcessor(message) http_request.amf_request = message d = defer.maybeDeferred( processor, message, http_request=http_request) dl.append(d.addCallback(cb, name)) def cb2(result): return response def eb(failure): """ Return 500 Internal Server Error. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "500 Internal Server Error\n\nThe request was unable to " \ "be successfully processed." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(http_request, 500, body) d = defer.DeferredList(dl) return d.addCallback(cb2).addErrback(eb) def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: C{Deferred}. @rtype: C{twisted.internet.defer.Deferred} """ authenticator = self.getAuthenticator(service_request) if self.logger: self.logger.debug('Authenticator expands to: %r' % authenticator) if authenticator is None: return defer.succeed(True) args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return defer.maybeDeferred(authenticator, *args) def preprocessRequest(self, service_request, *args, **kwargs): """ Preprocesses a request. """ processor = self.getPreprocessor(service_request) if self.logger: self.logger.debug('Preprocessor expands to: %r' % processor) if processor is None: return args = (service_request,) + args if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return defer.maybeDeferred(processor, *args)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Remoting server implementations. @since: 0.1.0 """ import sys import types import datetime import pyamf from pyamf import remoting, util try: from platform import python_implementation impl = python_implementation() except ImportError: impl = 'Python' SERVER_NAME = 'PyAMF/%s %s/%s' % ( '.'.join(map(lambda x: str(x), pyamf.__version__)), impl, '.'.join(map(lambda x: str(x), sys.version_info[0:3])) ) class BaseServiceError(pyamf.BaseError): """ Base service error. """ class UnknownServiceError(BaseServiceError): """ Client made a request for an unknown service. """ _amf_code = 'Service.ResourceNotFound' class UnknownServiceMethodError(BaseServiceError): """ Client made a request for an unknown method. """ _amf_code = 'Service.MethodNotFound' class InvalidServiceMethodError(BaseServiceError): """ Client made a request for an invalid methodname. """ _amf_code = 'Service.MethodInvalid' class ServiceWrapper(object): """ Wraps a supplied service with extra functionality. @ivar service: The original service. @type service: C{callable} @ivar description: A description of the service. @type description: C{str} """ def __init__(self, service, description=None, authenticator=None, expose_request=None, preprocessor=None): self.service = service self.description = description self.authenticator = authenticator self.expose_request = expose_request self.preprocessor = preprocessor def __cmp__(self, other): if isinstance(other, ServiceWrapper): return cmp(self.__dict__, other.__dict__) return cmp(self.service, other) def _get_service_func(self, method, params): """ @raise InvalidServiceMethodError: Calls to private methods are not allowed. @raise UnknownServiceMethodError: Unknown method. @raise InvalidServiceMethodError: Service method must be callable. """ service = None if isinstance(self.service, (type, types.ClassType)): service = self.service() else: service = self.service if method is not None: method = str(method) if method.startswith('_'): raise InvalidServiceMethodError( "Calls to private methods are not allowed") try: func = getattr(service, method) except AttributeError: raise UnknownServiceMethodError( "Unknown method %s" % str(method)) if not callable(func): raise InvalidServiceMethodError( "Service method %s must be callable" % str(method)) return func if not callable(service): raise UnknownServiceMethodError( "Unknown method %s" % str(self.service)) return service def __call__(self, method, params): """ Executes the service. If the service is a class, it will be instantiated. @param method: The method to call on the service. @type method: C{None} or C{mixed} @param params: The params to pass to the service. @type params: C{list} or C{tuple} @return: The result of the execution. @rtype: C{mixed} """ func = self._get_service_func(method, params) return func(*params) def getMethods(self): """ Gets a C{dict} of valid method callables for the underlying service object. """ callables = {} for name in dir(self.service): method = getattr(self.service, name) if name.startswith('_') or not callable(method): continue callables[name] = method return callables def getAuthenticator(self, service_request=None): if service_request == None: return self.authenticator methods = self.getMethods() if service_request.method is None: if hasattr(self.service, '_pyamf_authenticator'): return self.service._pyamf_authenticator if service_request.method not in methods: return self.authenticator method = methods[service_request.method] if hasattr(method, '_pyamf_authenticator'): return method._pyamf_authenticator return self.authenticator def mustExposeRequest(self, service_request=None): if service_request == None: return self.expose_request methods = self.getMethods() if service_request.method is None: if hasattr(self.service, '_pyamf_expose_request'): return self.service._pyamf_expose_request return self.expose_request if service_request.method not in methods: return self.expose_request method = methods[service_request.method] if hasattr(method, '_pyamf_expose_request'): return method._pyamf_expose_request return self.expose_request def getPreprocessor(self, service_request=None): if service_request == None: return self.preprocessor methods = self.getMethods() if service_request.method is None: if hasattr(self.service, '_pyamf_preprocessor'): return self.service._pyamf_preprocessor if service_request.method not in methods: return self.preprocessor method = methods[service_request.method] if hasattr(method, '_pyamf_preprocessor'): return method._pyamf_preprocessor return self.preprocessor class ServiceRequest(object): """ Remoting service request. @ivar request: The request to service. @type request: L{Envelope<pyamf.remoting.Envelope>} @ivar service: Facilitates the request. @type service: L{ServiceWrapper} @ivar method: The method to call on the service. A value of C{None} means that the service will be called directly. @type method: C{None} or C{str} """ def __init__(self, amf_request, service, method): self.request = amf_request self.service = service self.method = method def __call__(self, *args): return self.service(self.method, args) class ServiceCollection(dict): """ I hold a collection of services, mapping names to objects. """ def __contains__(self, value): if isinstance(value, basestring): return value in self.keys() return value in self.values() class BaseGateway(object): """ Generic Remoting gateway. @ivar services: A map of service names to callables. @type services: L{ServiceCollection} @ivar authenticator: A callable that will check the credentials of the request before allowing access to the service. Will return a C{bool} value. @type authenticator: C{Callable} or C{None} @ivar preprocessor: Called before the actual service method is invoked. Useful for setting up sessions etc. @type preprocessor: C{Callable} or C{None} @ivar logger: A logging instance. @ivar strict: Defines whether the gateway should use strict en/decoding. @type strict: C{bool} @ivar timezone_offset: A L{datetime.timedelta} between UTC and the timezone to be encoded. Most dates should be handled as UTC to avoid confusion but for older legacy systems this is not an option. Supplying an int as this will be interpretted in seconds. @ivar debug: Provides debugging information when an error occurs. Use only in non production settings. @type debug: C{bool} """ _request_class = ServiceRequest def __init__(self, services={}, **kwargs): if not hasattr(services, 'iteritems'): raise TypeError("dict type required for services") self.services = ServiceCollection() self.authenticator = kwargs.pop('authenticator', None) self.preprocessor = kwargs.pop('preprocessor', None) self.expose_request = kwargs.pop('expose_request', False) self.strict = kwargs.pop('strict', False) self.logger = kwargs.pop('logger', None) self.timezone_offset = kwargs.pop('timezone_offset', None) self.debug = kwargs.pop('debug', False) if kwargs: raise TypeError('Unknown kwargs: %r' % (kwargs,)) for name, service in services.iteritems(): self.addService(service, name) def addService(self, service, name=None, description=None, authenticator=None, expose_request=None, preprocessor=None): """ Adds a service to the gateway. @param service: The service to add to the gateway. @type service: C{callable}, class instance, or a module @param name: The name of the service. @type name: C{str} @raise pyamf.remoting.RemotingError: Service already exists. @raise TypeError: C{service} cannot be a scalar value. @raise TypeError: C{service} must be C{callable} or a module. """ if isinstance(service, (int, long, float, basestring)): raise TypeError("Service cannot be a scalar value") allowed_types = (types.ModuleType, types.FunctionType, types.DictType, types.MethodType, types.InstanceType, types.ObjectType) if not callable(service) and not isinstance(service, allowed_types): raise TypeError("Service must be a callable, module, or an object") if name is None: # TODO: include the module in the name if isinstance(service, (type, types.ClassType)): name = service.__name__ elif isinstance(service, types.FunctionType): name = service.func_name elif isinstance(service, types.ModuleType): name = service.__name__ else: name = str(service) if name in self.services: raise remoting.RemotingError("Service %s already exists" % name) self.services[name] = ServiceWrapper(service, description, authenticator, expose_request, preprocessor) def _get_timezone_offset(self): if self.timezone_offset is None: return None if isinstance(self.timezone_offset, datetime.timedelta): return self.timezone_offset return datetime.timedelta(seconds=self.timezone_offset) def removeService(self, service): """ Removes a service from the gateway. @param service: The service to remove from the gateway. @type service: C{callable} or a class instance @raise NameError: Service not found. """ if service not in self.services: raise NameError("Service %s not found" % str(service)) for name, wrapper in self.services.iteritems(): if isinstance(service, basestring) and service == name: del self.services[name] return elif isinstance(service, ServiceWrapper) and wrapper == service: del self.services[name] return elif isinstance(service, (type, types.ClassType, types.FunctionType)) and wrapper.service == service: del self.services[name] return # shouldn't ever get here raise RuntimeError("Something went wrong ...") def getServiceRequest(self, request, target): """ Returns a service based on the message. @raise UnknownServiceError: Unknown service. @param request: The AMF request. @type request: L{Request<pyamf.remoting.Request>} @rtype: L{ServiceRequest} """ try: return self._request_class( request.envelope, self.services[target], None) except KeyError: pass try: sp = target.split('.') name, meth = '.'.join(sp[:-1]), sp[-1] return self._request_class( request.envelope, self.services[name], meth) except (ValueError, KeyError): pass raise UnknownServiceError("Unknown service %s" % target) def getProcessor(self, request): """ Returns request processor. @param request: The AMF message. @type request: L{Request<remoting.Request>} """ if request.target == 'null': from pyamf.remoting import amf3 return amf3.RequestProcessor(self) else: from pyamf.remoting import amf0 return amf0.RequestProcessor(self) def getResponse(self, amf_request): """ Returns the response to the request. Any implementing gateway must define this function. @param amf_request: The AMF request. @type amf_request: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF response. @rtype: L{Envelope<pyamf.remoting.Envelope>} """ raise NotImplementedError def mustExposeRequest(self, service_request): """ Decides whether the underlying http request should be exposed as the first argument to the method call. This is granular, looking at the service method first, then at the service level and finally checking the gateway. @rtype: C{bool} """ expose_request = service_request.service.mustExposeRequest(service_request) if expose_request is None: if self.expose_request is None: return False return self.expose_request return expose_request def getAuthenticator(self, service_request): """ Gets an authenticator callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global authenticator function for the gateway. Returns C{None} if one could not be found. """ auth = service_request.service.getAuthenticator(service_request) if auth is None: return self.authenticator return auth def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool} """ authenticator = self.getAuthenticator(service_request) if authenticator is None: return True args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return authenticator(*args) == True def getPreprocessor(self, service_request): """ Gets a preprocessor callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global preprocessor function for the gateway. Returns C{None} if one could not be found. """ preproc = service_request.service.getPreprocessor(service_request) if preproc is None: return self.preprocessor return preproc def preprocessRequest(self, service_request, *args, **kwargs): """ Preprocesses a request. """ processor = self.getPreprocessor(service_request) if processor is None: return args = (service_request,) + args if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return processor(*args) def callServiceRequest(self, service_request, *args, **kwargs): """ Executes the service_request call """ if self.mustExposeRequest(service_request): http_request = kwargs.get('http_request', None) args = (http_request,) + args return service_request(*args) def authenticate(func, c, expose_request=False): """ A decorator that facilitates authentication per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the authenticating callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and authenticator must be callable. """ if not callable(func): raise TypeError('func must be callable') if not callable(c): raise TypeError('Authenticator must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if expose_request is True: c = globals()['expose_request'](c) setattr(attr, '_pyamf_authenticator', c) return func def expose_request(func): """ A decorator that adds an expose_request flag to the underlying callable. @raise TypeError: C{func} must be callable. """ if not callable(func): raise TypeError("func must be callable") if isinstance(func, types.UnboundMethodType): setattr(func.im_func, '_pyamf_expose_request', True) else: setattr(func, '_pyamf_expose_request', True) return func def preprocess(func, c, expose_request=False): """ A decorator that facilitates preprocessing per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the preprocessing callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and preprocessor must be callable. """ if not callable(func): raise TypeError('func must be callable') if not callable(c): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if expose_request is True: c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func def format_exception(): import traceback f = util.StringIO() traceback.print_exc(file=f) return f.getvalue()
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ WSGI server implementation. The Python Web Server Gateway Interface (WSGI) is a simple and universal interface between web servers and web applications or frameworks. The WSGI interface has two sides: the "server" or "gateway" side, and the "application" or "framework" side. The server side invokes a callable object (usually a function or a method) that is provided by the application side. Additionally WSGI provides middlewares; a WSGI middleware implements both sides of the API, so that it can be inserted "between" a WSGI server and a WSGI application -- the middleware will act as an application from the server's point of view, and as a server from the application's point of view. @see: U{WSGI homepage (external)<http://wsgi.org>} @see: U{PEP-333 (external)<http://www.python.org/peps/pep-0333.html>} @since: 0.1.0 """ import pyamf from pyamf import remoting from pyamf.remoting import gateway __all__ = ['WSGIGateway'] class WSGIGateway(gateway.BaseGateway): """ WSGI Remoting Gateway. """ def getResponse(self, request, environ): """ Processes the AMF request, returning an AMF response. @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: processor = self.getProcessor(message) environ['pyamf.request'] = message response[name] = processor(message, http_request=environ) return response def badRequestMethod(self, environ, start_response): """ Return HTTP 400 Bad Request. """ response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ['REQUEST_METHOD'] start_response('400 Bad Request', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] def __call__(self, environ, start_response): """ @rtype: C{StringIO} @return: File-like object. """ if environ['REQUEST_METHOD'] != 'POST': return self.badRequestMethod(environ, start_response) body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])) stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(body, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (pyamf.DecodeError, IOError): if self.logger: self.logger.exception(gateway.format_exception()) response = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('400 Bad Request', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] except (KeyboardInterrupt, SystemExit): raise except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nAn unexpected error " \ "occurred whilst decoding." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(request, environ) except (KeyboardInterrupt, SystemExit): raise except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, timezone_offset=timezone_offset) except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nThe request was " \ "unable to be encoded." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] response = stream.getvalue() start_response('200 OK', [ ('Content-Type', remoting.CONTENT_TYPE), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response]
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Flex Data Management Service implementation. This module contains the message classes used with Flex Data Management Service. @since: 0.1.0 """ import pyamf from pyamf.flex.messaging import AsyncMessage, AcknowledgeMessage, ErrorMessage __all__ = [ 'DataMessage', 'SequencedMessage', 'PagedMessage', 'DataErrorMessage' ] class DataMessage(AsyncMessage): """ I am used to transport an operation that occured on a managed object or collection. This class of message is transmitted between clients subscribed to a remote destination as well as between server nodes within a cluster. The payload of this message describes all of the relevant details of the operation. This information is used to replicate updates and detect conflicts. @see: U{DataMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/data/messages/DataMessage.html>} """ def __init__(self): AsyncMessage.__init__(self) #: Provides access to the identity map which defines the #: unique identity of the item affected by this DataMessage #: (relevant for create/update/delete but not fill operations). self.identity = None #: Provides access to the operation/command of this DataMessage. #: #: Operations indicate how the remote destination should process #: this message. self.operation = None class SequencedMessage(AcknowledgeMessage): """ Response to L{DataMessage} requests. @see: U{SequencedMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/data/messages/SequencedMessage.html>} """ def __init__(self): AcknowledgeMessage.__init__(self) #: Provides access to the sequence id for this message. #: #: The sequence id is a unique identifier for a sequence #: within a remote destination. This value is only unique for #: the endpoint and destination contacted. self.sequenceId = None #: self.sequenceProxies = None #: Provides access to the sequence size for this message. #: #: The sequence size indicates how many items reside in the #: remote sequence. self.sequenceSize = None #: self.dataMessage = None class PagedMessage(SequencedMessage): """ This messsage provides information about a partial sequence result. @see: U{PagedMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/data/messages/PagedMessage.html>} """ def __init__(self): SequencedMessage.__init__(self) #: Provides access to the number of total pages in a sequence #: based on the current page size. self.pageCount = None #: Provides access to the index of the current page in a sequence. self.pageIndex = None class DataErrorMessage(ErrorMessage): """ Special cases of ErrorMessage will be sent when a data conflict occurs. This message provides the conflict information in addition to the L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} information. @see: U{DataErrorMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/data/messages/DataErrorMessage.html>} """ def __init__(self): ErrorMessage.__init__(self) #: The client oringinated message which caused the conflict. self.cause = None #: An array of properties that were found to be conflicting #: between the client and server objects. self.propertyNames = None #: The value that the server had for the object with the #: conflicting properties. self.serverObject = None #: Namespace for C{flex.data} messages. MESSAGES_NS = 'flex.data.messages' pyamf.register_package(globals(), MESSAGES_NS)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Flex Messaging implementation. This module contains the message classes used with Flex Data Services. @see: U{RemoteObject on OSFlash (external) <http://osflash.org/documentation/amf3#remoteobject>} @since: 0.1 """ import uuid import pyamf.util from pyamf import amf3 __all__ = [ 'RemotingMessage', 'CommandMessage', 'AcknowledgeMessage', 'ErrorMessage' ] NAMESPACE = 'flex.messaging.messages' SMALL_FLAG_MORE = 0x80 class AbstractMessage(object): """ Abstract base class for all Flex messages. Messages have two customizable sections; headers and data. The headers property provides access to specialized meta information for a specific message instance. The data property contains the instance specific data that needs to be delivered and processed by the decoder. @see: U{AbstractMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/AbstractMessage.html>} @ivar body: Specific data that needs to be delivered to the remote destination. @type body: C{mixed} @ivar clientId: Indicates which client sent the message. @type clientId: C{str} @ivar destination: Message destination. @type destination: C{str} @ivar headers: Message headers. Core header names start with DS. @type headers: C{dict} @ivar messageId: Unique Message ID. @type messageId: C{str} @ivar timeToLive: How long the message should be considered valid and deliverable. @type timeToLive: C{int} @ivar timestamp: Timestamp when the message was generated. @type timestamp: C{int} """ class __amf__: amf3 = True static = ('body', 'clientId', 'destination', 'headers', 'messageId', 'timestamp', 'timeToLive') dynamic = False #: Each message pushed from the server will contain this header identifying #: the client that will receive the message. DESTINATION_CLIENT_ID_HEADER = "DSDstClientId" #: Messages are tagged with the endpoint id for the channel they are sent #: over. ENDPOINT_HEADER = "DSEndpoint" #: Messages that need to set remote credentials for a destination carry the #: C{Base64} encoded credentials in this header. REMOTE_CREDENTIALS_HEADER = "DSRemoteCredentials" #: The request timeout value is set on outbound messages by services or #: channels and the value controls how long the responder will wait for an #: acknowledgement, result or fault response for the message before timing #: out the request. REQUEST_TIMEOUT_HEADER = "DSRequestTimeout" SMALL_ATTRIBUTE_FLAGS = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40] SMALL_ATTRIBUTES = dict(zip( SMALL_ATTRIBUTE_FLAGS, __amf__.static )) SMALL_UUID_FLAGS = [0x01, 0x02] SMALL_UUIDS = dict(zip( SMALL_UUID_FLAGS, ['clientId', 'messageId'] )) def __init__(self, *args, **kwargs): self.body = kwargs.get('body', None) self.clientId = kwargs.get('clientId', None) self.destination = kwargs.get('destination', None) self.headers = kwargs.get('headers', {}) self.messageId = kwargs.get('messageId', None) self.timestamp = kwargs.get('timestamp', None) self.timeToLive = kwargs.get('timeToLive', None) def __repr__(self): m = '<%s ' % self.__class__.__name__ for k in self.__dict__: m += ' %s=%r' % (k, getattr(self, k)) return m + " />" def decodeSmallAttribute(self, attr, input): """ @since: 0.5 """ obj = input.readObject() if attr in ['timestamp', 'timeToLive']: return pyamf.util.get_datetime(obj / 1000.0) return obj def encodeSmallAttribute(self, attr): """ @since: 0.5 """ obj = getattr(self, attr) if not obj: return obj if attr in ['timestamp', 'timeToLive']: return pyamf.util.get_timestamp(obj) * 1000.0 elif attr in ['clientId', 'messageId']: if isinstance(obj, uuid.UUID): return None return obj def __readamf__(self, input): flags = read_flags(input) if len(flags) > 2: raise pyamf.DecodeError('Expected <=2 (got %d) flags for the ' 'AbstractMessage portion of the small message for %r' % ( len(flags), self.__class__)) for index, byte in enumerate(flags): if index == 0: for flag in self.SMALL_ATTRIBUTE_FLAGS: if flag & byte: attr = self.SMALL_ATTRIBUTES[flag] setattr(self, attr, self.decodeSmallAttribute(attr, input)) elif index == 1: for flag in self.SMALL_UUID_FLAGS: if flag & byte: attr = self.SMALL_UUIDS[flag] setattr(self, attr, decode_uuid(input.readObject())) def __writeamf__(self, output): flag_attrs = [] uuid_attrs = [] byte = 0 for flag in self.SMALL_ATTRIBUTE_FLAGS: value = self.encodeSmallAttribute(self.SMALL_ATTRIBUTES[flag]) if value: byte |= flag flag_attrs.append(value) flags = byte byte = 0 for flag in self.SMALL_UUID_FLAGS: attr = self.SMALL_UUIDS[flag] value = getattr(self, attr) if not value: continue byte |= flag uuid_attrs.append(amf3.ByteArray(value.bytes)) if not byte: output.writeUnsignedByte(flags) else: output.writeUnsignedByte(flags | SMALL_FLAG_MORE) output.writeUnsignedByte(byte) [output.writeObject(attr) for attr in flag_attrs] [output.writeObject(attr) for attr in uuid_attrs] def getSmallMessage(self): """ Return a ISmallMessage representation of this object. If one is not available, L{NotImplementedError} will be raised. @since: 0.5 """ raise NotImplementedError class AsyncMessage(AbstractMessage): """ I am the base class for all asynchronous Flex messages. @see: U{AsyncMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/AsyncMessage.html>} @ivar correlationId: Correlation id of the message. @type correlationId: C{str} """ #: Messages that were sent with a defined subtopic property indicate their #: target subtopic in this header. SUBTOPIC_HEADER = "DSSubtopic" class __amf__: static = ('correlationId',) def __init__(self, *args, **kwargs): AbstractMessage.__init__(self, *args, **kwargs) self.correlationId = kwargs.get('correlationId', None) def __readamf__(self, input): AbstractMessage.__readamf__(self, input) flags = read_flags(input) if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'AsyncMessage portion of the small message for %r' % ( len(flags), self.__class__)) byte = flags[0] if byte & 0x01: self.correlationId = input.readObject() if byte & 0x02: self.correlationId = decode_uuid(input.readObject()) def __writeamf__(self, output): AbstractMessage.__writeamf__(self, output) if not isinstance(self.correlationId, uuid.UUID): output.writeUnsignedByte(0x01) output.writeObject(self.correlationId) else: output.writeUnsignedByte(0x02) output.writeObject(pyamf.amf3.ByteArray(self.correlationId.bytes)) def getSmallMessage(self): """ Return a ISmallMessage representation of this async message. @since: 0.5 """ return AsyncMessageExt(**self.__dict__) class AcknowledgeMessage(AsyncMessage): """ I acknowledge the receipt of a message that was sent previously. Every message sent within the messaging system must receive an acknowledgement. @see: U{AcknowledgeMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/AcknowledgeMessage.html>} """ #: Used to indicate that the acknowledgement is for a message that #: generated an error. ERROR_HINT_HEADER = "DSErrorHint" def __readamf__(self, input): AsyncMessage.__readamf__(self, input) flags = read_flags(input) if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'AcknowledgeMessage portion of the small message for %r' % ( len(flags), self.__class__)) def __writeamf__(self, output): AsyncMessage.__writeamf__(self, output) output.writeUnsignedByte(0) def getSmallMessage(self): """ Return a ISmallMessage representation of this acknowledge message. @since: 0.5 """ return AcknowledgeMessageExt(**self.__dict__) class CommandMessage(AsyncMessage): """ Provides a mechanism for sending commands related to publish/subscribe messaging, ping, and cluster operations. @see: U{CommandMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/CommandMessage.html>} @ivar operation: The command @type operation: C{int} @ivar messageRefType: hmm, not sure about this one. @type messageRefType: C{str} """ #: The server message type for authentication commands. AUTHENTICATION_MESSAGE_REF_TYPE = "flex.messaging.messages.AuthenticationMessage" #: This is used to test connectivity over the current channel to the remote #: endpoint. PING_OPERATION = 5 #: This is used by a remote destination to sync missed or cached messages #: back to a client as a result of a client issued poll command. SYNC_OPERATION = 4 #: This is used to request a list of failover endpoint URIs for the remote #: destination based on cluster membership. CLUSTER_REQUEST_OPERATION = 7 #: This is used to send credentials to the endpoint so that the user can be #: logged in over the current channel. The credentials need to be C{Base64} #: encoded and stored in the body of the message. LOGIN_OPERATION = 8 #: This is used to log the user out of the current channel, and will #: invalidate the server session if the channel is HTTP based. LOGOUT_OPERATION = 9 #: This is used to poll a remote destination for pending, undelivered #: messages. POLL_OPERATION = 2 #: Subscribe commands issued by a consumer pass the consumer's C{selector} #: expression in this header. SELECTOR_HEADER = "DSSelector" #: This is used to indicate that the client's session with a remote #: destination has timed out. SESSION_INVALIDATE_OPERATION = 10 #: This is used to subscribe to a remote destination. SUBSCRIBE_OPERATION = 0 #: This is the default operation for new L{CommandMessage} instances. UNKNOWN_OPERATION = 1000 #: This is used to unsubscribe from a remote destination. UNSUBSCRIBE_OPERATION = 1 #: This operation is used to indicate that a channel has disconnected. DISCONNECT_OPERATION = 12 class __amf__: static = ('operation',) def __init__(self, *args, **kwargs): AsyncMessage.__init__(self, *args, **kwargs) self.operation = kwargs.get('operation', None) #: Remote destination belonging to a specific service, based upon #: whether this message type matches the message type the service #: handles. self.messageRefType = kwargs.get('messageRefType', None) def __readamf__(self, input): AsyncMessage.__readamf__(self, input) flags = read_flags(input) if not flags: return if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'CommandMessage portion of the small message for %r' % ( len(flags), self.__class__)) byte = flags[0] if byte & 0x01: self.operation = input.readObject() def __writeamf__(self, output): AsyncMessage.__writeamf__(self, output) if self.operation: output.writeUnsignedByte(0x01) output.writeObject(self.operation) else: output.writeUnsignedByte(0) def getSmallMessage(self): """ Return a ISmallMessage representation of this command message. @since: 0.5 """ return CommandMessageExt(**self.__dict__) class ErrorMessage(AcknowledgeMessage): """ I am the Flex error message to be returned to the client. This class is used to report errors within the messaging system. @see: U{ErrorMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/ErrorMessage.html>} """ #: If a message may not have been delivered, the faultCode will contain #: this constant. MESSAGE_DELIVERY_IN_DOUBT = "Client.Error.DeliveryInDoubt" #: Header name for the retryable hint header. #: #: This is used to indicate that the operation that generated the error may #: be retryable rather than fatal. RETRYABLE_HINT_HEADER = "DSRetryableErrorHint" class __amf__: static = ('extendedData', 'faultCode', 'faultDetail', 'faultString', 'rootCause') def __init__(self, *args, **kwargs): AcknowledgeMessage.__init__(self, *args, **kwargs) #: Extended data that the remote destination has chosen to associate #: with this error to facilitate custom error processing on the client. self.extendedData = kwargs.get('extendedData', {}) #: Fault code for the error. self.faultCode = kwargs.get('faultCode', None) #: Detailed description of what caused the error. self.faultDetail = kwargs.get('faultDetail', None) #: A simple description of the error. self.faultString = kwargs.get('faultString', None) #: Should a traceback exist for the error, this property contains the #: message. self.rootCause = kwargs.get('rootCause', {}) def getSmallMessage(self): """ Return a ISmallMessage representation of this error message. @since: 0.5 """ raise NotImplementedError class RemotingMessage(AbstractMessage): """ I am used to send RPC requests to a remote endpoint. @see: U{RemotingMessage on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/messaging/messages/RemotingMessage.html>} """ class __amf__: static = ('operation', 'source') def __init__(self, *args, **kwargs): AbstractMessage.__init__(self, *args, **kwargs) #: Name of the remote method/operation that should be called. self.operation = kwargs.get('operation', None) #: Name of the service to be called including package name. #: This property is provided for backwards compatibility. self.source = kwargs.get('source', None) class AcknowledgeMessageExt(AcknowledgeMessage): """ An L{AcknowledgeMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True class CommandMessageExt(CommandMessage): """ A L{CommandMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True class AsyncMessageExt(AsyncMessage): """ A L{AsyncMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True def read_flags(input): """ @since: 0.5 """ flags = [] done = False while not done: byte = input.readUnsignedByte() if not byte & SMALL_FLAG_MORE: done = True else: byte = byte ^ SMALL_FLAG_MORE flags.append(byte) return flags def decode_uuid(obj): """ Decode a L{ByteArray} contents to a C{uuid.UUID} instance. @since: 0.5 """ return uuid.UUID(bytes=str(obj)) pyamf.register_package(globals(), package=NAMESPACE) pyamf.register_class(AcknowledgeMessageExt, 'DSK') pyamf.register_class(CommandMessageExt, 'DSC') pyamf.register_class(AsyncMessageExt, 'DSA')
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Compatibility classes/functions for Flex. @note: Not available in ActionScript 1.0 and 2.0. @see: U{Flex on Wikipedia (external) <http://en.wikipedia.org/wiki/Adobe_Flex>} @since: 0.1.0 """ import pyamf __all__ = ['ArrayCollection', 'ObjectProxy'] class ArrayCollection(list): """ I represent the ActionScript 3 based class C{flex.messaging.io.ArrayCollection} used in the Flex framework. The C{ArrayCollection} class is a wrapper class that exposes an Array as a collection that can be accessed and manipulated using the methods and properties of the C{ICollectionView} or C{IList} interfaces in the Flex framework. @see: U{ArrayCollection on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/collections/ArrayCollection.html>} @note: This class does not implement the RemoteObject part of the documentation. @ivar length: [read-only] The number of items in this collection. Introduced in 0.4. @type length: C{int} """ class __amf__: external = True amf3 = True exclude = ('length',) def __init__(self, source=None): if source is not None: if isinstance(source, dict): raise TypeError('Cannot convert dicts to ArrayCollection') if hasattr(source, '__iter__'): self.extend(source) def __repr__(self): return "<flex.messaging.io.ArrayCollection %s>" % list.__repr__(self) def __readamf__(self, input): data = input.readObject() if hasattr(data, 'source'): data = data.source else: if not hasattr(data, '__iter__'): raise pyamf.DecodeError('Unable to read a list when decoding ' 'ArrayCollection') self.extend(data) def __writeamf__(self, output): output.encoder.writeList( list(self), use_references=True, use_proxies=False) def _get_length(self): return len(self) def _set_length(self, length): raise RuntimeError("Property length is read-only") length = property(_get_length, _set_length) def addItem(self, item): """ Adds the specified item to the end of the list. @param item: The object to add to the collection. @type item: C{mixed}. @since: 0.4 """ self.append(item) def addItemAt(self, item, index): """ Adds the item at the specified index. @param item: The object to add to the collection. @type item: C{mixed}. @param index: The index at which to place the item. @raise IndexError: If index is less than 0 or greater than the length of the list. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError self.insert(index, item) def getItemAt(self, index, prefetch=0): """ Gets the item at the specified index. @param index: The index in the list from which to retrieve the item. @type index: C{int} @param prefetch: This param is ignored and is only here as part of the interface. @raise IndexError: if C{index < 0} or C{index >= length} @return: The item at index C{index}. @rtype: C{mixed}. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError return self.__getitem__(index) def getItemIndex(self, item): """ Returns the index of the item if it is in the list such that C{getItemAt(index) == item}. @param item: The item to find. @type item: C{mixed}. @return: The index of the item or -1 if the item is not in the list. @rtype: C{int} @since: 0.4 """ try: return self.index(item) except ValueError: return -1 def removeAll(self): """ Removes all items from the list. @since: 0.4 """ while len(self) > 0: self.pop() def removeItemAt(self, index): """ Removes the item at the specified index and returns it. Any items that were after this index are now one index earlier. @param index: The index from which to remove the item. @return: The item that was removed. @rtype: C{mixed}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError x = self[index] del self[index] return x def setItemAt(self, item, index): """ Places the item at the specified index. If an item was already at that index the new item will replace it and it will be returned. @param item: The new item to be placed at the specified index. @type item: C{mixed}. @param index: The index at which to place the item. @type index: C{int} @return: The item that was replaced, or C{None}. @rtype: C{mixed} or C{None}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError tmp = self.__getitem__(index) self.__setitem__(index, item) return tmp def toArray(self): """ Returns an Array that is populated in the same order as the C{IList} implementation. @return: The array. @rtype: C{list} """ return self class ObjectProxy(object): """ I represent the ActionScript 3 based class C{flex.messaging.io.ObjectProxy} used in the Flex framework. Flex's C{ObjectProxy} class allows an anonymous, dynamic ActionScript Object to be bindable and report change events. @see: U{ObjectProxy on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/mx/utils/ObjectProxy.html>} """ class __amf__: external = True amf3 = True def __init__(self, object=None): if object is None: self._amf_object = pyamf.ASObject() else: self._amf_object = object def __repr__(self): return "<flex.messaging.io.ObjectProxy %s>" % self._amf_object def __getattr__(self, name): if name == '_amf_object': return self.__dict__['_amf_object'] return getattr(self.__dict__['_amf_object'], name) def __setattr__(self, name, value): if name == '_amf_object': self.__dict__['_amf_object'] = value else: setattr(self._amf_object, name, value) def __readamf__(self, input): self._amf_object = input.readObject() def __writeamf__(self, output): output.writeObject(self._amf_object, use_proxies=False) def unproxy_object(obj): """ Returns the unproxied version of the object. """ if isinstance(obj, ArrayCollection): return list(obj) elif isinstance(obj, ObjectProxy): return obj._amf_object return obj pyamf.register_package(globals(), package='flex.messaging.io')
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF3 implementation. C{AMF3} is the default serialization for U{ActionScript<http://en.wikipedia.org/wiki/ActionScript>} 3.0 and provides various advantages over L{AMF0<pyamf.amf0>}, which is used for ActionScript 1.0 and 2.0. It adds support for sending C{int} and C{uint} objects as integers and supports data types that are available only in ActionScript 3.0, such as L{ByteArray} and L{ArrayCollection}. @see: U{Official AMF3 Specification in English (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/amf3_spec_05_05_08.pdf>} @see: U{Official AMF3 Specification in Japanese (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/JP_amf3_spec_121207.pdf>} @see: U{AMF3 documentation on OSFlash (external) <http://osflash.org/documentation/amf3>} @since: 0.1 """ import types import datetime import zlib import pyamf from pyamf import util from pyamf.flex import ObjectProxy, ArrayCollection #: If True encode/decode lists/tuples to L{ArrayCollections<ArrayCollection>} #: and dicts to L{ObjectProxy} use_proxies_default = False try: set() except NameError: from sets import Set as set #: The undefined type is represented by the undefined type marker. No further #: information is encoded for this value. TYPE_UNDEFINED = '\x00' #: The null type is represented by the null type marker. No further #: information is encoded for this value. TYPE_NULL = '\x01' #: The false type is represented by the false type marker and is used to #: encode a Boolean value of C{false}. No further information is encoded for #: this value. TYPE_BOOL_FALSE = '\x02' #: The true type is represented by the true type marker and is used to encode #: a Boolean value of C{true}. No further information is encoded for this #: value. TYPE_BOOL_TRUE = '\x03' #: In AMF 3 integers are serialized using a variable length signed 29-bit #: integer. #: @see: U{Parsing Integers on OSFlash (external) #: <http://osflash.org/documentation/amf3/parsing_integers>} TYPE_INTEGER = '\x04' #: This type is used to encode an ActionScript Number or an ActionScript #: C{int} of value greater than or equal to 2^28 or an ActionScript uint of #: value greater than or equal to 2^29. The encoded value is is always an 8 #: byte IEEE-754 double precision floating point value in network byte order #: (sign bit in low memory). The AMF 3 number type is encoded in the same #: manner as the AMF 0 L{Number<pyamf.amf0.TYPE_NUMBER>} type. TYPE_NUMBER = '\x05' #: ActionScript String values are represented using a single string type in #: AMF 3 - the concept of string and long string types from AMF 0 is not used. #: Strings can be sent as a reference to a previously occurring String by #: using an index to the implicit string reference table. Strings are encoding #: using UTF-8 - however the header may either describe a string literal or a #: string reference. TYPE_STRING = '\x06' #: ActionScript 3.0 introduced a new XML type however the legacy C{XMLDocument} #: type from ActionScript 1.0 and 2.0.is retained in the language as #: C{flash.xml.XMLDocument}. Similar to AMF 0, the structure of an #: C{XMLDocument} needs to be flattened into a string representation for #: serialization. As with other strings in AMF, the content is encoded in #: UTF-8. XMLDocuments can be sent as a reference to a previously occurring #: C{XMLDocument} instance by using an index to the implicit object reference #: table. #: @see: U{OSFlash documentation (external) #: <http://osflash.org/documentation/amf3#x07_-_xml_legacy_flash.xml.xmldocument_class>} TYPE_XML = '\x07' #: In AMF 3 an ActionScript Date is serialized simply as the number of #: milliseconds elapsed since the epoch of midnight, 1st Jan 1970 in the #: UTC time zone. Local time zone information is not sent. TYPE_DATE = '\x08' #: ActionScript Arrays are described based on the nature of their indices, #: i.e. their type and how they are positioned in the Array. TYPE_ARRAY = '\x09' #: A single AMF 3 type handles ActionScript Objects and custom user classes. TYPE_OBJECT = '\x0A' #: ActionScript 3.0 introduces a new top-level XML class that supports #: U{E4X<http://en.wikipedia.org/wiki/E4X>} syntax. #: For serialization purposes the XML type needs to be flattened into a #: string representation. As with other strings in AMF, the content is #: encoded using UTF-8. TYPE_XMLSTRING = '\x0B' #: ActionScript 3.0 introduces the L{ByteArray} type to hold an Array #: of bytes. AMF 3 serializes this type using a variable length encoding #: 29-bit integer for the byte-length prefix followed by the raw bytes #: of the L{ByteArray}. #: @see: U{Parsing ByteArrays on OSFlash (external) #: <http://osflash.org/documentation/amf3/parsing_byte_arrays>} TYPE_BYTEARRAY = '\x0C' #: Reference bit. REFERENCE_BIT = 0x01 #: The maximum that can be represented by an signed 29 bit integer. MAX_29B_INT = 0x0FFFFFFF #: The minimum that can be represented by an signed 29 bit integer. MIN_29B_INT = -0x10000000 ENCODED_INT_CACHE = {} class ObjectEncoding: """ AMF object encodings. """ #: Property list encoding. #: The remaining integer-data represents the number of class members that #: exist. The property names are read as string-data. The values are then #: read as AMF3-data. STATIC = 0x00 #: Externalizable object. #: What follows is the value of the "inner" object, including type code. #: This value appears for objects that implement IExternalizable, such as #: L{ArrayCollection} and L{ObjectProxy}. EXTERNAL = 0x01 #: Name-value encoding. #: The property names and values are encoded as string-data followed by #: AMF3-data until there is an empty string property name. If there is a #: class-def reference there are no property names and the number of values #: is equal to the number of properties in the class-def. DYNAMIC = 0x02 #: Proxy object. PROXY = 0x03 class DataOutput(object): """ I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. I provide a set of methods for writing binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataInput} class, which reads binary data. @see: U{IDataOutput on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/flash/utils/IDataOutput.html>} """ def __init__(self, encoder): """ @param encoder: Encoder containing the stream. @type encoder: L{amf3.Encoder<pyamf.amf3.Encoder>} """ self.encoder = encoder self.stream = encoder.stream def writeBoolean(self, value): """ Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value found. """ if isinstance(value, bool): if value is True: self.stream.write_uchar(1) else: self.stream.write_uchar(0) else: raise ValueError("Non-boolean value found") def writeByte(self, value): """ Writes a byte. @type value: C{int} """ self.stream.write_char(value) def writeUnsignedByte(self, value): """ Writes an unsigned byte. @type value: C{int} @since: 0.5 """ return self.stream.write_uchar(value) def writeDouble(self, value): """ Writes an IEEE 754 double-precision (64-bit) floating point number. @type value: C{number} """ self.stream.write_double(value) def writeFloat(self, value): """ Writes an IEEE 754 single-precision (32-bit) floating point number. @type value: C{float} """ self.stream.write_float(value) def writeInt(self, value): """ Writes a 32-bit signed integer. @type value: C{int} """ self.stream.write_long(value) def writeMultiByte(self, value, charset): """ Writes a multibyte string to the datastream using the specified character set. @type value: C{str} @param value: The string value to be written. @type charset: C{str} @param charset: The string denoting the character set to use. Possible character set strings include C{shift-jis}, C{cn-gb}, C{iso-8859-1} and others. @see: U{Supported character sets on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/charset-codes.html>} """ self.stream.write(unicode(value).encode(charset)) def writeObject(self, value, use_references=True, use_proxies=None): """ Writes an object to data stream in AMF serialized format. @param value: The object to be serialized. @type use_references: C{bool} @param use_references: """ self.encoder.writeElement(value, use_references, use_proxies) def writeShort(self, value): """ Writes a 16-bit integer. @type value: C{int} @param value: A byte value as an integer. """ self.stream.write_short(value) def writeUnsignedShort(self, value): """ Writes a 16-bit unsigned integer. @type value: C{int} @param value: A byte value as an integer. @since: 0.5 """ self.stream.write_ushort(value) def writeUnsignedInt(self, value): """ Writes a 32-bit unsigned integer. @type value: C{int} @param value: A byte value as an unsigned integer. """ self.stream.write_ulong(value) def writeUTF(self, value): """ Writes a UTF-8 string to the data stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string. @type value: C{str} @param value: The string value to be written. """ if not isinstance(value, unicode): value = unicode(value, 'utf8') buf = util.BufferedByteStream() buf.write_utf8_string(value) bytes = buf.getvalue() self.stream.write_ushort(len(bytes)) self.stream.write(bytes) def writeUTFBytes(self, value): """ Writes a UTF-8 string. Similar to L{writeUTF}, but does not prefix the string with a 16-bit length word. @type value: C{str} @param value: The string value to be written. """ val = None if isinstance(value, unicode): val = value else: val = unicode(value, 'utf8') self.stream.write_utf8_string(val) class DataInput(object): """ I provide a set of methods for reading binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataOutput} class, which writes binary data. @see: U{IDataInput on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/flash/utils/IDataInput.html>} """ def __init__(self, decoder): """ @param decoder: AMF3 decoder containing the stream. @type decoder: L{amf3.Decoder<pyamf.amf3.Decoder>} """ assert isinstance(decoder, Decoder) self.decoder = decoder self.stream = decoder.stream def readBoolean(self): """ Read C{Boolean}. @raise ValueError: Error reading Boolean. @rtype: C{bool} @return: A Boolean value, C{True} if the byte is nonzero, C{False} otherwise. """ byte = self.stream.read(1) if byte == '\x00': return False elif byte == '\x01': return True else: raise ValueError("Error reading boolean") def readByte(self): """ Reads a signed byte. @rtype: C{int} @return: The returned value is in the range -128 to 127. """ return self.stream.read_char() def readDouble(self): """ Reads an IEEE 754 double-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 double-precision floating point number. """ return self.stream.read_double() def readFloat(self): """ Reads an IEEE 754 single-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 single-precision floating point number. """ return self.stream.read_float() def readInt(self): """ Reads a signed 32-bit integer from the data stream. @rtype: C{int} @return: The returned value is in the range -2147483648 to 2147483647. """ return self.stream.read_long() def readMultiByte(self, length, charset): """ Reads a multibyte string of specified length from the data stream using the specified character set. @type length: C{int} @param length: The number of bytes from the data stream to read. @type charset: C{str} @param charset: The string denoting the character set to use. @rtype: C{str} @return: UTF-8 encoded string. """ #FIXME nick: how to work out the code point byte size (on the fly)? bytes = self.stream.read(length) return unicode(bytes, charset) def readObject(self): """ Reads an object from the data stream. @return: The deserialized object. """ return self.decoder.readElement() def readShort(self): """ Reads a signed 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range -32768 to 32767. """ return self.stream.read_short() def readUnsignedByte(self): """ Reads an unsigned byte from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 255. """ return self.stream.read_uchar() def readUnsignedInt(self): """ Reads an unsigned 32-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 4294967295. """ return self.stream.read_ulong() def readUnsignedShort(self): """ Reads an unsigned 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 65535. """ return self.stream.read_ushort() def readUTF(self): """ Reads a UTF-8 string from the data stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters. """ length = self.stream.read_ushort() return self.stream.read_utf8_string(length) def readUTFBytes(self, length): """ Reads a sequence of C{length} UTF-8 bytes from the data stream and returns a string. @type length: C{int} @param length: The number of bytes from the data stream to read. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters of specified C{length}. """ return self.readMultiByte(length, 'utf-8') class ByteArray(util.BufferedByteStream, DataInput, DataOutput): """ I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. Supports C{zlib} compression. Possible uses of the C{ByteArray} class: - Creating a custom protocol to connect to a client. - Writing your own AMF/Remoting packet. - Optimizing the size of your data by using custom data types. @see: U{ByteArray on Livedocs (external) <http://livedocs.adobe.com/flex/201/langref/flash/utils/ByteArray.html>} """ class __amf__: amf3 = True def __init__(self, *args, **kwargs): self.context = kwargs.pop('context', Context()) util.BufferedByteStream.__init__(self, *args, **kwargs) DataInput.__init__(self, Decoder(self, self.context)) DataOutput.__init__(self, Encoder(self, self.context)) self.compressed = False def __cmp__(self, other): if isinstance(other, ByteArray): return cmp(self.getvalue(), other.getvalue()) return cmp(self.getvalue(), other) def __str__(self): buf = self.getvalue() if self.compressed: buf = zlib.compress(buf) #FIXME nick: hacked buf = buf[0] + '\xda' + buf[2:] return buf def compress(self): """ Forces compression of the underlying stream. """ self.compressed = True class ClassDefinition(object): """ """ def __init__(self, alias): self.alias = alias self.reference = None alias.compile() self.attr_len = 0 if alias.static_attrs: self.attr_len = len(alias.static_attrs) self.encoding = ObjectEncoding.DYNAMIC if alias.external: self.encoding = ObjectEncoding.EXTERNAL elif not alias.dynamic: if alias.static_attrs == alias.encodable_properties: self.encoding = ObjectEncoding.STATIC def __repr__(self): return '<%s.ClassDefinition reference=%r encoding=%r alias=%r at 0x%x>' % ( self.__class__.__module__, self.reference, self.encoding, self.alias, id(self)) class Context(pyamf.BaseContext): """ I hold the AMF3 context for en/decoding streams. @ivar strings: A list of string references. @type strings: C{list} @ivar classes: A list of L{ClassDefinition}. @type classes: C{list} @ivar legacy_xml: A list of legacy encoded XML documents. @type legacy_xml: C{list} """ def __init__(self, exceptions=True): self.strings = util.IndexedCollection(use_hash=True, exceptions=False) self.classes = {} self.class_ref = {} self.legacy_xml = util.IndexedCollection(exceptions=False) self.object_aliases = util.IndexedMap(exceptions=False) # Maps one object to another self.class_idx = 0 pyamf.BaseContext.__init__(self, exceptions=exceptions) def clear(self): """ Clears the context. """ pyamf.BaseContext.clear(self) self.strings.clear() self.classes = {} self.class_ref = {} self.legacy_xml.clear() self.object_aliases.clear() self.class_idx = 0 def setObjectAlias(self, obj, alias): """ Maps an object to an aliased object. @since: 0.4 """ self.object_aliases.map(obj, alias) def getObjectAlias(self, obj): """ Get an alias of an object. @since: 0.4 @raise pyamf.ReferenceError: Unknown object alias. @raise pyamf.ReferenceError: Unknown mapped alias. """ ref = self.object_aliases.getReferenceTo(obj) if ref is None: if self.exceptions is False: return None raise pyamf.ReferenceError('Unknown object alias for %r' % (obj,)) mapped = self.object_aliases.getMappedByReference(ref) if mapped is None: if self.exceptions is False: return None raise pyamf.ReferenceError('Unknown mapped alias for %r' % (obj,)) return mapped def getString(self, ref): """ Gets a string based on a reference C{ref}. @param ref: The reference index. @type ref: C{str} @raise pyamf.ReferenceError: The referenced string could not be found. @rtype: C{str} @return: The referenced string. """ i = self.strings.getByReference(ref) if i is None and self.exceptions: raise pyamf.ReferenceError("String reference %r not found" % (ref,)) return i def getStringReference(self, s): """ Return string reference. @type s: C{str} @param s: The referenced string. @raise pyamf.ReferenceError: The string reference could not be found. @return: The reference index to the string. @rtype: C{int} """ i = self.strings.getReferenceTo(s) if i is None and self.exceptions: raise pyamf.ReferenceError("Reference for string %r not found" % (s,)) return i def addString(self, s): """ Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. @raise pyamf.ReferenceError: Trying to store a reference to an empty string. """ if not isinstance(s, basestring): raise TypeError if len(s) == 0: if not self.exceptions: return None # do not store empty string references raise pyamf.ReferenceError("Cannot store a reference to an empty string") return self.strings.append(s) def getClassByReference(self, ref): """ Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. """ try: return self.class_ref[ref] except KeyError: if not self.exceptions: return None raise pyamf.ReferenceError("Class reference %r not found" % ( ref,)) def getClass(self, klass): """ Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. """ try: return self.classes[klass] except KeyError: if not self.exceptions: return None raise pyamf.ReferenceError("Class alias for %r not found" % ( klass,)) def addClass(self, alias, klass): """ Creates a reference to C{class_def}. @param alias: C{ClassDefinition} instance. """ ref = self.class_idx self.class_ref[ref] = alias cd = self.classes[klass] = alias cd.reference = ref self.class_idx += 1 return ref def getLegacyXML(self, ref): """ Return the legacy XML reference. This is the C{flash.xml.XMLDocument} class in ActionScript 3.0 and the top-level C{XML} class in ActionScript 1.0 and 2.0. @type ref: C{int} @param ref: The reference index. @raise pyamf.ReferenceError: The legacy XML reference could not be found. @return: Instance of L{ET<util.ET>} """ i = self.legacy_xml.getByReference(ref) if i is None: if not self.exceptions: return None raise pyamf.ReferenceError("Legacy XML reference %r not found" % (ref,)) return i def getLegacyXMLReference(self, doc): """ Return legacy XML reference. @type doc: L{ET<util.ET>} @param doc: The XML document to reference. @raise pyamf.ReferenceError: The reference could not be found. @return: The reference to C{doc}. @rtype: C{int} """ i = self.legacy_xml.getReferenceTo(doc) if i is None: if not self.exceptions: return None raise pyamf.ReferenceError("Reference for document %r not found" % (doc,)) return i def addLegacyXML(self, doc): """ Creates a reference to C{doc}. If C{doc} is already referenced that index will be returned. Otherwise a new index will be created. @type doc: L{ET<util.ET>} @param doc: The XML document to reference. @rtype: C{int} @return: The reference to C{doc}. """ return self.legacy_xml.append(doc) def __copy__(self): return self.__class__(exceptions=self.exceptions) class Decoder(pyamf.BaseDecoder): """ Decodes an AMF3 data stream. """ context_class = Context type_map = { TYPE_UNDEFINED: 'readUndefined', TYPE_NULL: 'readNull', TYPE_BOOL_FALSE: 'readBoolFalse', TYPE_BOOL_TRUE: 'readBoolTrue', TYPE_INTEGER: 'readSignedInteger', TYPE_NUMBER: 'readNumber', TYPE_STRING: 'readString', TYPE_XML: 'readXML', TYPE_DATE: 'readDate', TYPE_ARRAY: 'readArray', TYPE_OBJECT: 'readObject', TYPE_XMLSTRING: 'readXMLString', TYPE_BYTEARRAY: 'readByteArray', } def __init__(self, *args, **kwargs): self.use_proxies = kwargs.pop('use_proxies', use_proxies_default) pyamf.BaseDecoder.__init__(self, *args, **kwargs) def readUndefined(self): """ Read undefined. """ return pyamf.Undefined def readNull(self): """ Read null. @return: C{None} @rtype: C{None} """ return None def readBoolFalse(self): """ Returns C{False}. @return: C{False} @rtype: C{bool} """ return False def readBoolTrue(self): """ Returns C{True}. @return: C{True} @rtype: C{bool} """ return True def readNumber(self): """ Read number. """ return self.stream.read_double() def readUnsignedInteger(self): """ Reads and returns an unsigned integer from the stream. """ return self.readInteger(False) def readSignedInteger(self): """ Reads and returns a signed integer from the stream. """ return self.readInteger(True) def readInteger(self, signed=False): """ Reads and returns an integer from the stream. @type signed: C{bool} @see: U{Parsing integers on OSFlash <http://osflash.org/amf3/parsing_integers>} for the AMF3 integer data format. """ return decode_int(self.stream, signed) def readString(self, use_references=True): """ Reads and returns a string from the stream. @type use_references: C{bool} """ def readLength(): x = self.readUnsignedInteger() return (x >> 1, x & REFERENCE_BIT == 0) length, is_reference = readLength() if use_references and is_reference: return self.context.getString(length) if length == 0: return u'' result = self.stream.read_utf8_string(length) if len(result) != 0 and use_references: self.context.addString(result) return result def readDate(self): """ Read date from the stream. The timezone is ignored as the date is always in UTC. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) ms = self.stream.read_double() result = util.get_datetime(ms / 1000.0) if self.timezone_offset is not None: result += self.timezone_offset self.context.addObject(result) return result def readArray(self): """ Reads an array from the stream. @warning: There is a very specific problem with AMF3 where the first three bytes of an encoded empty C{dict} will mirror that of an encoded C{{'': 1, '2': 2}} @see: U{Docuverse blog (external) <http://www.docuverse.com/blog/donpark/2007/05/14/flash-9-amf3-bug>} """ size = self.readUnsignedInteger() if size & REFERENCE_BIT == 0: return self.context.getObject(size >> 1) size >>= 1 key = self.readString().encode('utf8') if key == '': # integer indexes only -> python list result = [] self.context.addObject(result) for i in xrange(size): result.append(self.readElement()) return result result = pyamf.MixedArray() self.context.addObject(result) while key != "": result[key] = self.readElement() key = self.readString().encode('utf8') for i in xrange(size): el = self.readElement() result[i] = el return result def _getClassDefinition(self, ref): """ Reads class definition from the stream. """ is_ref = ref & REFERENCE_BIT == 0 ref >>= 1 if is_ref: class_def = self.context.getClassByReference(ref) return class_def, class_def.alias name = self.readString() alias = None if name == '': name = pyamf.ASObject try: alias = pyamf.get_class_alias(name) except pyamf.UnknownClassAlias: if self.strict: raise alias = pyamf.TypedObjectClassAlias(pyamf.TypedObject, name) class_def = ClassDefinition(alias) class_def.encoding = ref & 0x03 class_def.attr_len = ref >> 2 class_def.static_properties = [] if class_def.attr_len > 0: for i in xrange(class_def.attr_len): key = self.readString().encode('utf8') class_def.static_properties.append(key) self.context.addClass(class_def, alias.klass) return class_def, alias def readObject(self, use_proxies=None): """ Reads an object from the stream. @raise pyamf.EncodeError: Decoding an object in amf3 tagged as amf0 only is not allowed. @raise pyamf.DecodeError: Unknown object encoding. """ if use_proxies is None: use_proxies = self.use_proxies def readStatic(class_def, obj): for attr in class_def.static_properties: obj[attr] = self.readElement() def readDynamic(class_def, obj): attr = self.readString().encode('utf8') while attr != '': obj[attr] = self.readElement() attr = self.readString().encode('utf8') ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: obj = self.context.getObject(ref >> 1) if use_proxies is True: obj = self.readProxyObject(obj) return obj ref >>= 1 class_def, alias = self._getClassDefinition(ref) obj = alias.createInstance(codec=self) obj_attrs = dict() self.context.addObject(obj) if class_def.encoding in (ObjectEncoding.EXTERNAL, ObjectEncoding.PROXY): obj.__readamf__(DataInput(self)) elif class_def.encoding == ObjectEncoding.DYNAMIC: readStatic(class_def, obj_attrs) readDynamic(class_def, obj_attrs) elif class_def.encoding == ObjectEncoding.STATIC: readStatic(class_def, obj_attrs) else: raise pyamf.DecodeError("Unknown object encoding") alias.applyAttributes(obj, obj_attrs, codec=self) if use_proxies is True: obj = self.readProxyObject(obj) return obj def readProxyObject(self, proxy): """ Return the source object of a proxied object. @since: 0.4 """ if isinstance(proxy, ArrayCollection): return list(proxy) elif isinstance(proxy, ObjectProxy): return proxy._amf_object return proxy def _readXML(self, legacy=False): """ Reads an object from the stream. @type legacy: C{bool} @param legacy: The read XML is in 'legacy' format. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) xmlstring = self.stream.read(ref >> 1) x = util.ET.fromstring(xmlstring) self.context.addObject(x) if legacy is True: self.context.addLegacyXML(x) return x def readXMLString(self): """ Reads a string from the data stream and converts it into an XML Tree. @return: The XML Document. @rtype: L{ET<util.ET>} """ return self._readXML() def readXML(self): """ Read a legacy XML Document from the stream. @return: The XML Document. @rtype: L{ET<util.ET>} """ return self._readXML(True) def readByteArray(self): """ Reads a string of data from the stream. Detects if the L{ByteArray} was compressed using C{zlib}. @see: L{ByteArray} @note: This is not supported in ActionScript 1.0 and 2.0. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) buffer = self.stream.read(ref >> 1) try: buffer = zlib.decompress(buffer) compressed = True except zlib.error: compressed = False obj = ByteArray(buffer, context=self.context) obj.compressed = compressed self.context.addObject(obj) return obj class Encoder(pyamf.BaseEncoder): """ Encodes an AMF3 data stream. """ context_class = Context type_map = [ ((types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType, types.GeneratorType, types.ModuleType, types.LambdaType, types.MethodType), "writeFunc"), ((bool,), "writeBoolean"), ((types.NoneType,), "writeNull"), ((int,long), "writeInteger"), ((float,), "writeNumber"), (types.StringTypes, "writeString"), ((ByteArray,), "writeByteArray"), ((datetime.date, datetime.datetime, datetime.time), "writeDate"), ((util.is_ET_element,), "writeXML"), ((pyamf.UndefinedType,), "writeUndefined"), ((types.ClassType, types.TypeType), "writeClass"), ((types.InstanceType, types.ObjectType,), "writeInstance"), ] def __init__(self, *args, **kwargs): self.use_proxies = kwargs.pop('use_proxies', use_proxies_default) self.string_references = kwargs.pop('string_references', True) pyamf.BaseEncoder.__init__(self, *args, **kwargs) def writeElement(self, data, use_references=True, use_proxies=None): """ Writes the data. @param data: The data to be encoded to the AMF3 data stream. @type data: C{mixed} @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Cannot find encoder func for C{data}. """ func = self._writeElementFunc(data) if func is None: raise pyamf.EncodeError("Unknown type %r" % (data,)) func(data, use_references=use_references, use_proxies=use_proxies) def writeClass(self, *args, **kwargs): """ Classes cannot be serialised. """ raise pyamf.EncodeError("Class objects cannot be serialised") def writeUndefined(self, *args, **kwargs): """ Writes an C{pyamf.Undefined} value to the stream. """ self.stream.write(TYPE_UNDEFINED) def writeNull(self, *args, **kwargs): """ Writes a C{null} value to the stream. """ self.stream.write(TYPE_NULL) def writeBoolean(self, n, **kwargs): """ Writes a Boolean to the stream. """ t = TYPE_BOOL_TRUE if not n: t = TYPE_BOOL_FALSE self.stream.write(t) def _writeInteger(self, n): """ AMF3 integers are encoded. @param n: The integer data to be encoded to the AMF3 data stream. @type n: integer data @see: U{Parsing Integers on OSFlash <http://osflash.org/documentation/amf3/parsing_integers>} for more info. """ try: self.stream.write(ENCODED_INT_CACHE[n]) except KeyError: ENCODED_INT_CACHE[n] = encode_int(n) self.stream.write(ENCODED_INT_CACHE[n]) def writeInteger(self, n, **kwargs): """ Writes an integer to the stream. @type n: integer data @param n: The integer data to be encoded to the AMF3 data stream. @type use_references: C{bool} @kwarg use_references: Default is C{True}. """ if n < MIN_29B_INT or n > MAX_29B_INT: self.writeNumber(float(n)) return self.stream.write(TYPE_INTEGER) self.stream.write(encode_int(n)) def writeNumber(self, n, **kwargs): """ Writes a float to the stream. @type n: C{float} """ self.stream.write(TYPE_NUMBER) self.stream.write_double(n) def _writeString(self, n, **kwargs): """ Writes a raw string to the stream. @type n: C{str} or C{unicode} @param n: The string data to be encoded to the AMF3 data stream. """ if n == '': self.stream.write_uchar(REFERENCE_BIT) return t = type(n) if t is str: bytes = n elif t is unicode: bytes = n.encode('utf8') else: bytes = unicode(n).encode('utf8') n = bytes if self.string_references: ref = self.context.getStringReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addString(n) self._writeInteger((len(bytes) << 1) | REFERENCE_BIT) self.stream.write(bytes) def writeString(self, n, writeType=True, **kwargs): """ Writes a string to the stream. If C{n} is not a unicode string, an attempt will be made to convert it. @type n: C{basestring} @param n: The string data to be encoded to the AMF3 data stream. """ if writeType: self.stream.write(TYPE_STRING) self._writeString(n, **kwargs) def writeDate(self, n, use_references=True, **kwargs): """ Writes a C{datetime} instance to the stream. @type n: L{datetime} @param n: The C{Date} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ if isinstance(n, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF3 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (n,)) self.stream.write(TYPE_DATE) if use_references is True: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self.stream.write_uchar(REFERENCE_BIT) if self.timezone_offset is not None: n -= self.timezone_offset ms = util.get_timestamp(n) self.stream.write_double(ms * 1000.0) def writeList(self, n, use_references=True, use_proxies=None): """ Writes a C{tuple}, C{set} or C{list} to the stream. @type n: One of C{__builtin__.tuple}, C{__builtin__.set} or C{__builtin__.list} @param n: The C{list} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ # Encode lists as ArrayCollections if use_proxies is None: use_proxies = self.use_proxies if use_proxies: ref_obj = self.context.getObjectAlias(n) if ref_obj is None: proxy = ArrayCollection(n) self.context.setObjectAlias(n, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_ARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self._writeInteger((len(n) << 1) | REFERENCE_BIT) self.stream.write_uchar(0x01) [self.writeElement(x) for x in n] def writeDict(self, n, use_references=True, use_proxies=None): """ Writes a C{dict} to the stream. @type n: C{__builtin__.dict} @param n: The C{dict} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. @raise ValueError: Non C{int}/C{str} key value found in the C{dict} @raise EncodeError: C{dict} contains empty string keys. """ # Design bug in AMF3 that cannot read/write empty key strings # http://www.docuverse.com/blog/donpark/2007/05/14/flash-9-amf3-bug # for more info if '' in n: raise pyamf.EncodeError("dicts cannot contain empty string keys") if use_proxies is None: use_proxies = self.use_proxies if use_proxies is True: ref_obj = self.context.getObjectAlias(n) if ref_obj is None: proxy = ObjectProxy(pyamf.ASObject(n)) self.context.setObjectAlias(n, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_ARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) # The AMF3 spec demands that all str based indicies be listed first keys = n.keys() int_keys = [] str_keys = [] for x in keys: if isinstance(x, (int, long)): int_keys.append(x) elif isinstance(x, (str, unicode)): str_keys.append(x) else: raise ValueError("Non int/str key value found in dict") # Make sure the integer keys are within range l = len(int_keys) for x in int_keys: if l < x <= 0: # treat as a string key str_keys.append(x) del int_keys[int_keys.index(x)] int_keys.sort() # If integer keys don't start at 0, they will be treated as strings if len(int_keys) > 0 and int_keys[0] != 0: for x in int_keys: str_keys.append(str(x)) del int_keys[int_keys.index(x)] self._writeInteger(len(int_keys) << 1 | REFERENCE_BIT) for x in str_keys: self._writeString(x) self.writeElement(n[x]) self.stream.write_uchar(0x01) for k in int_keys: self.writeElement(n[k]) def writeInstance(self, obj, **kwargs): """ Read class definition. @param obj: The class instance to be encoded. """ kls = obj.__class__ if kls is pyamf.MixedArray: f = self._write_elem_func_cache[kls] = self.writeDict elif kls in (list, set, tuple): f = self._write_elem_func_cache[kls] = self.writeList else: f = self._write_elem_func_cache[kls] = self.writeObject f(obj, **kwargs) def writeObject(self, obj, use_references=True, use_proxies=None): """ Writes an object to the stream. @param obj: The object data to be encoded to the AMF3 data stream. @type obj: object data @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Encoding an object in amf3 tagged as amf0 only. """ if use_proxies is None: use_proxies = self.use_proxies if use_proxies is True and obj.__class__ is dict: ref_obj = self.context.getObjectAlias(obj) if ref_obj is None: proxy = ObjectProxy(obj) self.context.setObjectAlias(obj, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_OBJECT) if use_references: ref = self.context.getObjectReference(obj) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(obj) # object is not referenced, serialise it kls = obj.__class__ definition = self.context.getClass(kls) alias = None class_ref = False # if the class definition is a reference if definition: class_ref = True alias = definition.alias if alias.anonymous and definition.reference is not None: class_ref = True else: try: alias = pyamf.get_class_alias(kls) except pyamf.UnknownClassAlias: alias_klass = util.get_class_alias(kls) meta = util.get_class_meta(kls) alias = alias_klass(kls, defer=True, **meta) definition = ClassDefinition(alias) self.context.addClass(definition, alias.klass) if class_ref: self.stream.write(definition.reference) else: ref = 0 if definition.encoding != ObjectEncoding.EXTERNAL: ref += definition.attr_len << 4 final_reference = encode_int(ref | definition.encoding << 2 | REFERENCE_BIT << 1 | REFERENCE_BIT) self.stream.write(final_reference) definition.reference = encode_int( definition.reference << 2 | REFERENCE_BIT) if alias.anonymous: self.stream.write_uchar(0x01) else: self._writeString(alias.alias) # work out what the final reference for the class will be. # this is okay because the next time an object of the same # class is encoded, class_ref will be True and never get here # again. if alias.external: obj.__writeamf__(DataOutput(self)) return sa, da = alias.getEncodableAttributes(obj, codec=self) if sa: if not class_ref: [self._writeString(attr) for attr in alias.static_attrs] [self.writeElement(sa[attr]) for attr in alias.static_attrs] if definition.encoding == ObjectEncoding.STATIC: return if definition.encoding == ObjectEncoding.DYNAMIC: if da: for attr, value in da.iteritems(): self._writeString(attr) self.writeElement(value) self.stream.write_uchar(0x01) def writeByteArray(self, n, use_references=True, **kwargs): """ Writes a L{ByteArray} to the data stream. @param n: The L{ByteArray} data to be encoded to the AMF3 data stream. @type n: L{ByteArray} @param use_references: Default is C{True}. @type use_references: C{bool} """ self.stream.write(TYPE_BYTEARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) buf = str(n) l = len(buf) self._writeInteger(l << 1 | REFERENCE_BIT) self.stream.write(buf) def writeXML(self, n, use_references=True, use_proxies=None): """ Writes a XML string to the data stream. @type n: L{ET<util.ET>} @param n: The XML Document to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ i = self.context.getLegacyXMLReference(n) if i is None: is_legacy = True else: is_legacy = False if is_legacy is True: self.stream.write(TYPE_XMLSTRING) else: self.stream.write(TYPE_XML) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self._writeString(util.ET.tostring(n, 'utf-8')) def decode(stream, context=None, strict=False): """ A helper function to decode an AMF3 datastream. @type stream: L{BufferedByteStream<util.BufferedByteStream>} @param stream: AMF3 data. @type context: L{Context} @param context: Context. """ decoder = Decoder(stream, context, strict) while 1: try: yield decoder.readElement() except pyamf.EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element into AMF3 format. @type args: List of args to encode. @keyword context: Any initial context to use. @type context: L{Context} @return: C{StringIO} type object containing the encoded AMF3 data. @rtype: L{BufferedByteStream<pyamf.util.BufferedByteStream>} """ context = kwargs.get('context', None) buf = util.BufferedByteStream() encoder = Encoder(buf, context) for element in args: encoder.writeElement(element) return buf def encode_int(n): """ Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range. """ if n < MIN_29B_INT or n > MAX_29B_INT: raise OverflowError("Out of range") if n < 0: n += 0x20000000 bytes = '' real_value = None if n > 0x1fffff: real_value = n n >>= 1 bytes += chr(0x80 | ((n >> 21) & 0xff)) if n > 0x3fff: bytes += chr(0x80 | ((n >> 14) & 0xff)) if n > 0x7f: bytes += chr(0x80 | ((n >> 7) & 0xff)) if real_value is not None: n = real_value if n > 0x1fffff: bytes += chr(n & 0xff) else: bytes += chr(n & 0x7f) return bytes def decode_int(stream, signed=False): """ Decode C{int}. """ n = result = 0 b = stream.read_uchar() while b & 0x80 != 0 and n < 3: result <<= 7 result |= b & 0x7f b = stream.read_uchar() n += 1 if n < 3: result <<= 7 result |= b else: result <<= 8 result |= b if result & 0x10000000 != 0: if signed: result -= 0x20000000 else: result <<= 1 result += 1 return result try: from cpyamf.amf3 import encode_int, decode_int except ImportError: pass pyamf.register_class(ByteArray) for x in range(0, 20): ENCODED_INT_CACHE[x] = encode_int(x) del x
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Remoting tests. @since: 0.1.0 """
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ File included to make the directory a Python package. The test_*.py files are special in this directory in that they refer to the top level module names of the adapter to test. An attempt will be made to import that module but ignored if it fails (not available on the system). """
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Test utilities. @since: 0.1.0 """ import unittest import copy import pyamf from pyamf.util import BufferedByteStream PosInf = 1e300000 NegInf = -1e300000 NaN = PosInf / PosInf class ClassicSpam: def __readamf__(self, input): pass def __writeamf__(self, output): pass class Spam(object): """ A generic object to use for object encoding. """ def __init__(self, d={}): self.__dict__.update(d) def __readamf__(self, input): pass def __writeamf__(self, output): pass class ClassCacheClearingTestCase(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self._class_cache = pyamf.CLASS_CACHE.copy() self._class_loaders = copy.copy(pyamf.CLASS_LOADERS) def tearDown(self): unittest.TestCase.tearDown(self) pyamf.CLASS_CACHE = self._class_cache pyamf.CLASS_LOADERS = self._class_loaders class EncoderTester(object): """ A helper object that takes some input, runs over the encoder and checks the output. """ def __init__(self, encoder, data): self.encoder = encoder self.buf = encoder.stream self.data = data def getval(self): t = self.buf.getvalue() self.buf.truncate(0) return t def run(self, testcase): for n in self.data: s = n[1:] n = n[0] self.encoder.writeElement(n) if isinstance(s, basestring): testcase.assertEqual(self.getval(), s) elif isinstance(s, (tuple, list)): val = self.getval() if not check_buffer(val, s): testcase.fail('%r != %r' % (val, s)) class DecoderTester(object): """ A helper object that takes some input, runs over the decoder and checks the output. """ def __init__(self, decoder, data): self.decoder = decoder self.buf = decoder.stream self.data = data def run(self, testcase): for n, s in self.data: self.buf.truncate(0) self.buf.write(s) self.buf.seek(0) testcase.assertEqual(self.decoder.readElement(), n) if self.buf.remaining() != 0: from pyamf.util import hexdump print hexdump(self.buf.getvalue()) # make sure that the entire buffer was consumed testcase.assertEqual(self.buf.remaining(), 0) def isNaN(val): return str(float(val)) == str(NaN) def isPosInf(val): return str(float(val)) == str(PosInf) def isNegInf(val): return str(float(val)) == str(NegInf) def check_buffer(buf, parts, inner=False): assert isinstance(parts, (tuple, list)) orig = buf parts = [p for p in parts] for part in parts: if inner is False: if isinstance(part, (tuple, list)): buf = check_buffer(buf, part, inner=True) else: if not buf.startswith(part): return False buf = buf[len(part):] else: for k in parts[:]: for p in parts[:]: if isinstance(p, (tuple, list)): buf = check_buffer(buf, p, inner=True) else: if buf.startswith(p): parts.remove(p) buf = buf[len(p):] return buf return len(buf) == 0 def assert_buffer(testcase, val, s): if not check_buffer(val, s): testcase.fail('%r != %r' % (val, s)) def replace_dict(src, dest): for name in dest.keys(): if name not in src: del dest[name] continue if dest[name] is not src[name]: dest[name] = src[name] class BaseCodecMixIn(object): amf_version = pyamf.AMF0 def setUp(self): self.context = pyamf.get_context(self.amf_version) self.stream = BufferedByteStream() class BaseDecoderMixIn(BaseCodecMixIn): def setUp(self): BaseCodecMixIn.setUp(self) self.decoder = pyamf.get_decoder( self.amf_version, data=self.stream, context=self.context) class BaseEncoderMixIn(BaseCodecMixIn): def setUp(self): BaseCodecMixIn.setUp(self) self.encoder = pyamf.get_encoder( self.amf_version, stream=self.stream, context=self.context) class NullFileDescriptor(object): def write(self, *args, **kwargs): pass def get_fqcn(klass): return '%s.%s' % (klass.__module__, klass.__name__)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Unit tests. @since: 0.1.0 """ import unittest # some Python 2.3 unittest compatibility fixes if not hasattr(unittest.TestCase, 'assertTrue'): unittest.TestCase.assertTrue = unittest.TestCase.failUnless if not hasattr(unittest.TestCase, 'assertFalse'): unittest.TestCase.assertFalse = unittest.TestCase.failIf mod_base = 'pyamf.tests' def suite(): import os.path from glob import glob suite = unittest.TestSuite() for testcase in glob(os.path.join(os.path.dirname(__file__), 'test_*.py')): mod_name = os.path.basename(testcase).split('.')[0] full_name = '%s.%s' % (mod_base, mod_name) mod = __import__(full_name) for part in full_name.split('.')[1:]: mod = getattr(mod, part) suite.addTest(mod.suite()) return suite def main(): unittest.main(defaultTest='suite') if __name__ == '__main__': main()
Python
spam = 'eggs'
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Unit tests for Remoting gateways. @since: 0.1.0 """
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE for details. """ SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)<http://www.sqlalchemy.org>} @since: 0.4 """ from sqlalchemy.orm import collections import pyamf from pyamf.adapters import util pyamf.add_type(collections.InstrumentedList, util.to_list) pyamf.add_type(collections.InstrumentedDict, util.to_dict) pyamf.add_type(collections.InstrumentedSet, util.to_set)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ collections adapter module. @since: 0.5 """ import collections import pyamf from pyamf.adapters import util if hasattr(collections, 'deque'): pyamf.add_type(collections.deque, util.to_list) if hasattr(collections, 'defaultdict'): pyamf.add_type(collections.defaultdict, util.to_dict)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Adapter for the C{decimal} module. @since: 0.4 """ import decimal import pyamf def convert_Decimal(x, encoder): """ Called when an instance of L{decimal.Decimal} is about to be encoded to an AMF stream. @param x: The L{decimal.Decimal} instance to encode. @param encoder: The L{pyamf.BaseEncoder} instance about to perform the operation. @return: If the encoder is in 'strict' mode then C{x} will be converted to a float. Otherwise an L{pyamf.EncodeError} with a friendly message is raised. """ if encoder is not None and isinstance(encoder, pyamf.BaseEncoder): if encoder.strict is False: return float(x) raise pyamf.EncodeError('Unable to encode decimal.Decimal instances as ' 'there is no way to guarantee exact conversion. Use strict=False to ' 'convert to a float.') if hasattr(decimal, 'Decimal'): pyamf.add_type(decimal.Decimal, convert_Decimal)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.db.models} adapter module. @see: U{Django Project<http://www.djangoproject.com>} @since: 0.4.1 """ from django.db.models.base import Model from django.db.models import fields from django.db.models.fields import related, files import datetime import pyamf from pyamf.util import imports class DjangoReferenceCollection(dict): """ This helper class holds a dict of klass to pk/objects loaded from the underlying db. @since: 0.5 """ def _getClass(self, klass): if klass not in self.keys(): self[klass] = {} return self[klass] def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then L{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of L{klass}. """ d = self._getClass(klass) return d[key] def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ d = self._getClass(klass) d[key] = obj class DjangoClassAlias(pyamf.ClassAlias): """ """ def getCustomProperties(self): self.fields = {} self.relations = {} self.columns = [] self.meta = self.klass._meta for x in self.meta.local_fields: if isinstance(x, files.FileField): self.readonly_attrs.update([x.name]) if not isinstance(x, related.ForeignKey): self.fields[x.name] = x else: self.relations[x.name] = x self.columns.append(x.attname) for k, v in self.klass.__dict__.iteritems(): if isinstance(v, related.ReverseManyRelatedObjectsDescriptor): self.fields[k] = v.field parent_fields = [] for field in self.meta.parents.values(): parent_fields.append(field.attname) del self.relations[field.name] self.exclude_attrs.update(parent_fields) props = self.fields.keys() self.static_attrs.update(props) self.encodable_properties.update(props) self.decodable_properties.update(props) def _compile_base_class(self, klass): if klass is Model: return pyamf.ClassAlias._compile_base_class(self, klass) def _encodeValue(self, field, value): if value is fields.NOT_PROVIDED: return pyamf.Undefined if value is None: return value # deal with dates .. if isinstance(field, fields.DateTimeField): return value elif isinstance(field, fields.DateField): return datetime.datetime(value.year, value.month, value.day, 0, 0, 0) elif isinstance(field, fields.TimeField): return datetime.datetime(1970, 1, 1, value.hour, value.minute, value.second, value.microsecond) elif isinstance(value, files.FieldFile): return value.name return value def _decodeValue(self, field, value): if value is pyamf.Undefined: return fields.NOT_PROVIDED if isinstance(field, fields.AutoField) and value == 0: return None elif isinstance(field, fields.DateTimeField): # deal with dates return value elif isinstance(field, fields.DateField): if not value: return None return datetime.date(value.year, value.month, value.day) elif isinstance(field, fields.TimeField): if not value: return None return datetime.time(value.hour, value.minute, value.second, value.microsecond) return value def getEncodableAttributes(self, obj, **kwargs): sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) for name, prop in self.fields.iteritems(): if name not in sa: continue if isinstance(prop, related.ManyToManyField): sa[name] = [x for x in getattr(obj, name).all()] else: sa[name] = self._encodeValue(prop, getattr(obj, name)) if not da: da = {} keys = da.keys() for key in keys: if key.startswith('_'): del da[key] elif key in self.columns: del da[key] for name, relation in self.relations.iteritems(): if '_%s_cache' % name in obj.__dict__: da[name] = getattr(obj, name) else: da[name] = pyamf.Undefined if not da: da = None return sa, da def getDecodableAttributes(self, obj, attrs, **kwargs): attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, **kwargs) for n in self.decodable_properties: f = self.fields[n] attrs[f.attname] = self._decodeValue(f, attrs[n]) # primary key of django object must always be set first for # relationships with other model objects to work properly # and dict.iteritems() does not guarantee order # # django also forces the use only one attribute as primary key, so # our obj._meta.pk.attname check is sufficient) try: setattr(obj, obj._meta.pk.attname, attrs[obj._meta.pk.attname]) del attrs[obj._meta.pk.attname] except KeyError: pass return attrs def getDjangoObjects(context): """ Returns a reference to the C{django_objects} on the context. If it doesn't exist then it is created. @param context: The context to load the C{django_objects} index from. @type context: Instance of L{pyamf.BaseContext} @return: The C{django_objects} index reference. @rtype: Instance of L{DjangoReferenceCollection} @since: 0.5 """ if not hasattr(context, 'django_objects'): context.django_objects = DjangoReferenceCollection() return context.django_objects def writeDjangoObject(self, obj, *args, **kwargs): """ The Django ORM creates new instances of objects for each db request. This is a problem for PyAMF as it uses the id(obj) of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the effort should be made to attempt to resolve references for a given object graph. We create a new map on the encoder context object which contains a dict of C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We use the primary key to do the reference checking. @since: 0.5 """ if not isinstance(obj, Model): self.writeNonDjangoObject(obj, *args, **kwargs) return context = self.context kls = obj.__class__ s = obj.pk django_objects = getDjangoObjects(context) try: referenced_object = django_objects.getClassKey(kls, s) except KeyError: referenced_object = obj django_objects.addClassKey(kls, s, obj) self.writeNonDjangoObject(referenced_object, *args, **kwargs) def install_django_reference_model_hook(mod): """ Called when L{pyamf.amf0} or L{pyamf.amf3} are imported. Attaches the L{writeDjangoObject} method to the C{Encoder} class in that module. @param mod: The module imported. @since: 0.4.1 """ if not hasattr(mod.Encoder, 'writeNonDjangoObject'): mod.Encoder.writeNonDjangoObject = mod.Encoder.writeObject mod.Encoder.writeObject = writeDjangoObject # initialise the module here: hook into pyamf pyamf.register_alias_type(DjangoClassAlias, Model) # hook the L{writeDjangobject} method to the Encoder class on import imports.when_imported('pyamf.amf0', install_django_reference_model_hook) imports.when_imported('pyamf.amf3', install_django_reference_model_hook)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Google App Engine adapter module. Sets up basic type mapping and class mappings for using the Datastore API in Google App Engine. @see: U{Datastore API on Google App Engine (external) <http://code.google.com/appengine/docs/datastore>} @since: 0.3.1 """ from google.appengine.ext import db from google.appengine.ext.db import polymodel import datetime import pyamf from pyamf.util import imports from pyamf.adapters import util class ModelStub(object): """ This class represents a L{db.Model} or L{db.Expando} class as the typed object is being read from the AMF stream. Once the attributes have been read from the stream and through the magic of Python, the instance of this class will be converted into the correct type. @ivar klass: The referenced class either L{db.Model} or L{db.Expando}. This is used so we can proxy some of the method calls during decoding. @type klass: L{db.Model} or L{db.Expando} @see: L{DataStoreClassAlias.applyAttributes} """ def __init__(self, klass): self.klass = klass def properties(self): return self.klass.properties() def dynamic_properties(self): return [] class GAEReferenceCollection(dict): """ This helper class holds a dict of klass to key/objects loaded from the Datastore. @since: 0.4.1 """ def _getClass(self, klass): if not issubclass(klass, (db.Model, db.Expando)): raise TypeError('expected db.Model/db.Expando class, got %s' % (klass,)) if klass not in self.keys(): self[klass] = {} return self[klass] def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then L{KeyError} is raised. @param klass: The class of the instance. @param key: The key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of L{klass}. """ if not isinstance(key, basestring): raise TypeError('basestring type expected for test, got %s' % (repr(key),)) d = self._getClass(klass) return d[key] def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ if not isinstance(key, basestring): raise TypeError('basestring type expected for test, got %s' % (repr(key),)) d = self._getClass(klass) d[key] = obj class DataStoreClassAlias(pyamf.ClassAlias): """ This class contains all the business logic to interact with Google's Datastore API's. Any L{db.Model} or L{db.Expando} classes will use this class alias for encoding/decoding. We also add a number of indexes to the encoder context to aggressively decrease the number of Datastore API's that we need to complete. """ # The name of the attribute used to represent the key KEY_ATTR = '_key' def _compile_base_class(self, klass): if klass in (db.Model, polymodel.PolyModel): return pyamf.ClassAlias._compile_base_class(self, klass) def getCustomProperties(self): props = [self.KEY_ATTR] self.reference_properties = {} self.properties = {} reverse_props = [] for name, prop in self.klass.properties().iteritems(): self.properties[name] = prop props.append(name) if isinstance(prop, db.ReferenceProperty): self.reference_properties[name] = prop if issubclass(self.klass, polymodel.PolyModel): del self.properties['_class'] props.remove('_class') # check if the property is a defined as a collection_name. These types # of properties are read-only and the datastore freaks out if you # attempt to meddle with it. We delete the attribute entirely .. for name, value in self.klass.__dict__.iteritems(): if isinstance(value, db._ReverseReferenceProperty): reverse_props.append(name) self.static_attrs.update(props) self.encodable_properties.update(self.properties.keys()) self.decodable_properties.update(self.properties.keys()) self.readonly_attrs.update(reverse_props) if not self.reference_properties: self.reference_properties = None if not self.properties: self.properties = None def getEncodableAttributes(self, obj, codec=None): sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, codec=codec) sa[self.KEY_ATTR] = str(obj.key()) if obj.is_saved() else None gae_objects = getGAEObjects(codec.context) if codec else None if self.reference_properties and gae_objects: for name, prop in self.reference_properties.iteritems(): klass = prop.reference_class key = prop.get_value_for_datastore(obj) if not key: continue key = str(key) try: sa[name] = gae_objects.getClassKey(klass, key) except KeyError: ref_obj = getattr(obj, name) gae_objects.addClassKey(klass, key, ref_obj) sa[name] = ref_obj if da: for k, v in da.copy().iteritems(): if k.startswith('_'): del da[k] if not da: da = {} for attr in obj.dynamic_properties(): da[attr] = getattr(obj, attr) if not da: da = None return sa, da def createInstance(self, codec=None): return ModelStub(self.klass) def getDecodableAttributes(self, obj, attrs, codec=None): try: key = attrs[self.KEY_ATTR] except KeyError: key = attrs[self.KEY_ATTR] = None attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, codec=codec) del attrs[self.KEY_ATTR] new_obj = None # attempt to load the object from the datastore if KEY_ATTR exists. if key and codec: new_obj = loadInstanceFromDatastore(self.klass, key, codec) # clean up the stub if isinstance(obj, ModelStub) and hasattr(obj, 'klass'): del obj.klass if new_obj: obj.__dict__ = new_obj.__dict__.copy() obj.__class__ = self.klass apply_init = True if self.properties: for k in [k for k in attrs.keys() if k in self.properties.keys()]: prop = self.properties[k] v = attrs[k] if isinstance(prop, db.FloatProperty) and isinstance(v, (int, long)): attrs[k] = float(v) elif isinstance(prop, db.ListProperty) and v is None: attrs[k] = [] elif isinstance(v, datetime.datetime): # Date/Time Property fields expect specific types of data # whereas PyAMF only decodes into datetime.datetime objects. if isinstance(prop, db.DateProperty): attrs[k] = v.date() elif isinstance(prop, db.TimeProperty): attrs[k] = v.time() if new_obj is None and isinstance(v, ModelStub) and prop.required and k in self.reference_properties: apply_init = False del attrs[k] # If the object does not exist in the datastore, we must fire the # class constructor. This sets internal attributes that pyamf has # no business messing with .. if new_obj is None and apply_init is True: obj.__init__(**attrs) return attrs def getGAEObjects(context): """ Returns a reference to the C{gae_objects} on the context. If it doesn't exist then it is created. @param context: The context to load the C{gae_objects} index from. @type context: Instance of L{pyamf.BaseContext} @return: The C{gae_objects} index reference. @rtype: Instance of L{GAEReferenceCollection} @since: 0.4.1 """ if not hasattr(context, 'gae_objects'): context.gae_objects = GAEReferenceCollection() return context.gae_objects def loadInstanceFromDatastore(klass, key, codec=None): """ Attempt to load an instance from the datastore, based on C{klass} and C{key}. We create an index on the codec's context (if it exists) so we can check that first before accessing the datastore. @param klass: The class that will be loaded from the datastore. @type klass: Sub-class of L{db.Model} or L{db.Expando} @param key: The key which is used to uniquely identify the instance in the datastore. @type key: C{str} @param codec: The codec to reference the C{gae_objects} index. If supplied,The codec must have have a context attribute. @type codec: Instance of L{pyamf.BaseEncoder} or L{pyamf.BaseDecoder} @return: The loaded instance from the datastore. @rtype: Instance of C{klass}. @since: 0.4.1 """ if not issubclass(klass, (db.Model, db.Expando)): raise TypeError('expected db.Model/db.Expando class, got %s' % (klass,)) if not isinstance(key, basestring): raise TypeError('string expected for key, got %s', (repr(key),)) key = str(key) if codec is None: return klass.get(key) gae_objects = getGAEObjects(codec.context) try: return gae_objects.getClassKey(klass, key) except KeyError: pass obj = klass.get(key) gae_objects.addClassKey(klass, key, obj) return obj def writeGAEObject(self, object, *args, **kwargs): """ The GAE Datastore creates new instances of objects for each get request. This is a problem for PyAMF as it uses the id(obj) of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the effort should be made to attempt to resolve references for a given object graph. We create a new map on the encoder context object which contains a dict of C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We use the datastore key to do the reference checking. @since: 0.4.1 """ if not (isinstance(object, db.Model) and object.is_saved()): self.writeNonGAEObject(object, *args, **kwargs) return context = self.context kls = object.__class__ s = str(object.key()) gae_objects = getGAEObjects(context) try: referenced_object = gae_objects.getClassKey(kls, s) except KeyError: referenced_object = object gae_objects.addClassKey(kls, s, object) self.writeNonGAEObject(referenced_object, *args, **kwargs) def install_gae_reference_model_hook(mod): """ Called when L{pyamf.amf0} or L{pyamf.amf3} are imported. Attaches the L{writeGAEObject} method to the C{Encoder} class in that module. @param mod: The module imported. @since: 0.4.1 """ if not hasattr(mod.Encoder, 'writeNonGAEObject'): mod.Encoder.writeNonGAEObject = mod.Encoder.writeObject mod.Encoder.writeObject = writeGAEObject # initialise the module here: hook into pyamf pyamf.add_type(db.Query, util.to_list) pyamf.register_alias_type(DataStoreClassAlias, db.Model, db.Expando) # hook the L{writeGAEObject} method to the Encoder class on import imports.when_imported('pyamf.amf0', install_gae_reference_model_hook) imports.when_imported('pyamf.amf3', install_gae_reference_model_hook)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Adapter for the stdlib C{sets} module. @since: 0.4 """ import sets import pyamf from pyamf.adapters import util if hasattr(sets, 'ImmutableSet'): pyamf.add_type(sets.ImmutableSet, util.to_tuple) if hasattr(sets, 'Set'): pyamf.add_type(sets.Set, util.to_tuple)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Useful helpers for adapters. @since: 0.4 """ import __builtin__ if not hasattr(__builtin__, 'set'): from sets import Set as set def to_list(obj, encoder): """ Converts an arbitrary object C{obj} to a list. @rtype: L{list} """ return list(obj) def to_dict(obj, encoder): """ Converts an arbitrary object C{obj} to a dict. @rtype: L{dict} """ return dict(obj) def to_set(obj, encoder): """ Converts an arbitrary object C{obj} to a set. @rtype: L{set} """ return set(obj) def to_tuple(x, encoder): """ Converts an arbitrary object C{obj} to a tuple. @rtype: L{tuple} """ return tuple(x) def to_string(x, encoder): """ Converts an arbitrary object C{obj} to a string. @rtype: L{tuple} @since: 0.5 """ return str(x)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.utils.translation} adapter module. @see: U{Django Project<http://www.djangoproject.com>} @since: 0.4.2 """ from django.utils.translation import ugettext_lazy import pyamf def convert_lazy(l, encoder=None): if l.__class__._delegate_unicode: return unicode(l) if l.__class__._delegate_str: return str(l) raise ValueError('Don\'t know how to convert lazy value %s' % (repr(l),)) pyamf.add_type(type(ugettext_lazy('foo')), convert_lazy)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ `array` adapter module. Will convert all array.array instances to a python list before encoding. All type information is lost (but degrades nicely). @since: 0.5 """ import array import pyamf from pyamf.adapters import util if hasattr(array, 'array'): pyamf.add_type(array.ArrayType, util.to_list)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Django query adapter module. Sets up basic type mapping and class mappings for a Django models. @see: U{Django Project<http://www.djangoproject.com>} @since: 0.1b """ from django.db.models import query import pyamf from pyamf.adapters import util pyamf.add_type(query.QuerySet, util.to_list)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ The adapter package provides additional functionality for other Python packages. This includes registering classes, setting up type maps etc. @since: 0.1.0 """ import os.path import glob from pyamf.util import imports class PackageImporter(object): """ Package importer used for lazy module loading. """ def __init__(self, name): self.name = name def __call__(self, mod): __import__('%s.%s' % ('pyamf.adapters', self.name)) adapters_registered = False def register_adapters(): global adapters_registered if adapters_registered is True: return try: import pkg_resources packageDir = pkg_resources.resource_filename('pyamf', 'adapters') except: packageDir = os.path.dirname(__file__) for f in glob.glob(os.path.join(packageDir, '*.py')): mod = os.path.basename(f).split(os.path.extsep, 1)[0] if mod == '__init__' or not mod.startswith('_'): continue try: register_adapter(mod[1:].replace('_', '.'), PackageImporter(mod)) except ImportError: pass adapters_registered = True def register_adapter(mod, func): """ Registers a callable to be executed when a module is imported. If the module already exists then the callable will be executed immediately. You can register the same module multiple times, the callables will be executed in the order they were registered. The root module must exist (i.e. be importable) otherwise an C{ImportError} will be thrown. @param mod: The fully qualified module string, as used in the imports statement. E.g. 'foo.bar.baz'. The string must map to a module otherwise the callable will not fire. @type mod: C{str} @param func: The function to call when C{mod} is imported. This function must take one arg, the newly imported C{module} object. @type func: callable @raise TypeError: C{func} must be callable """ if not callable(func): raise TypeError('func must be callable') imports.when_imported(str(mod), func)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE for details. """ SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)<http://www.sqlalchemy.org>} @since: 0.4 """ from sqlalchemy import orm, __version__ try: from sqlalchemy.orm import class_mapper except ImportError: from sqlalchemy.orm.util import class_mapper import pyamf UnmappedInstanceError = None try: class_mapper(dict) except Exception, e: UnmappedInstanceError = e.__class__ class SaMappedClassAlias(pyamf.ClassAlias): KEY_ATTR = 'sa_key' LAZY_ATTR = 'sa_lazy' EXCLUDED_ATTRS = [ '_entity_name', '_instance_key', '_sa_adapter', '_sa_appender', '_sa_class_manager', '_sa_initiator', '_sa_instance_state', '_sa_instrumented', '_sa_iterator', '_sa_remover', '_sa_session_id', '_state' ] STATE_ATTR = '_sa_instance_state' if __version__.startswith('0.4'): STATE_ATTR = '_state' def getCustomProperties(self): self.mapper = class_mapper(self.klass) self.exclude_attrs.update(self.EXCLUDED_ATTRS) self.properties = [] for prop in self.mapper.iterate_properties: self.properties.append(prop.key) self.encodable_properties.update(self.properties) self.decodable_properties.update(self.properties) self.static_attrs.update(self.properties) def getEncodableAttributes(self, obj, **kwargs): """ Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}. """ sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not da: da = {} lazy_attrs = [] # primary_key_from_instance actually changes obj.__dict__ if # primary key properties do not already exist in obj.__dict__ da[self.KEY_ATTR] = self.mapper.primary_key_from_instance(obj) for attr in self.properties: if attr not in obj.__dict__: lazy_attrs.append(attr) da[self.LAZY_ATTR] = lazy_attrs return sa, da def getDecodableAttributes(self, obj, attrs, **kwargs): """ """ attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, **kwargs) # Delete lazy-loaded attrs. # # Doing it this way ensures that lazy-loaded attributes are not # attached to the object, even if there is a default value specified # in the __init__ method. # # This is the correct behavior, because SQLAlchemy ignores __init__. # So, an object retreived from a DB with SQLAlchemy will not have a # lazy-loaded value, even if __init__ specifies a default value. if self.LAZY_ATTR in attrs: obj_state = None if hasattr(orm.attributes, 'instance_state'): obj_state = orm.attributes.instance_state(obj) for lazy_attr in attrs[self.LAZY_ATTR]: if lazy_attr in obj.__dict__: # Delete directly from the dict, so # SA callbacks are not triggered. del obj.__dict__[lazy_attr] # Delete from committed_state so SA thinks this attribute was # never modified. # # If the attribute was set in the __init__ method, # SA will think it is modified and will try to update # it in the database. if obj_state is not None: if lazy_attr in obj_state.committed_state: del obj_state.committed_state[lazy_attr] if lazy_attr in obj_state.dict: del obj_state.dict[lazy_attr] if lazy_attr in attrs: del attrs[lazy_attr] del attrs[self.LAZY_ATTR] if self.KEY_ATTR in attrs: del attrs[self.KEY_ATTR] return attrs def is_class_sa_mapped(klass): """ @rtype: C{bool} """ if not isinstance(klass, type): klass = type(klass) try: class_mapper(klass) except UnmappedInstanceError: return False return True pyamf.register_alias_type(SaMappedClassAlias, is_class_sa_mapped)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.db.models.fields} adapter module. @see: U{Django Project<http://www.djangoproject.com>} @since: 0.4 """ from django.db.models import fields import pyamf def convert_NOT_PROVIDED(x, encoder): """ @rtype: L{Undefined<pyamf.Undefined>} """ return pyamf.Undefined pyamf.add_type(lambda x: x is fields.NOT_PROVIDED, convert_NOT_PROVIDED)
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ B{PyAMF} provides B{A}ction B{M}essage B{F}ormat (U{AMF<http://en.wikipedia.org/wiki/Action_Message_Format>}) support for Python that is compatible with the Adobe U{Flash Player<http://en.wikipedia.org/wiki/Flash_Player>}. @copyright: Copyright (c) 2007-2009 The PyAMF Project. All Rights Reserved. @contact: U{users@pyamf.org<mailto:users@pyamf.org>} @see: U{http://pyamf.org} @since: October 2007 @version: 0.5.1 @status: Production/Stable """ import types import inspect from pyamf import util from pyamf.adapters import register_adapters try: set except NameError: from sets import Set as set __all__ = [ 'register_class', 'register_class_loader', 'encode', 'decode', '__version__' ] #: PyAMF version number. __version__ = (0, 5, 1) #: Class mapping support. CLASS_CACHE = {} #: Class loaders. CLASS_LOADERS = [] #: Custom type map. TYPE_MAP = {} #: Maps error classes to string codes. ERROR_CLASS_MAP = {} #: Alias mapping support ALIAS_TYPES = {} #: Specifies that objects are serialized using AMF for ActionScript 1.0 #: and 2.0 that were introduced in the Adobe Flash Player 6. AMF0 = 0 #: Specifies that objects are serialized using AMF for ActionScript 3.0 #: that was introduced in the Adobe Flash Player 9. AMF3 = 3 #: Supported AMF encoding types. ENCODING_TYPES = (AMF0, AMF3) #: Default encoding DEFAULT_ENCODING = AMF0 class ClientTypes: """ Typecodes used to identify AMF clients and servers. @see: U{Adobe Flash Player on WikiPedia (external) <http://en.wikipedia.org/wiki/Flash_Player>} @see: U{Adobe Flash Media Server on WikiPedia (external) <http://en.wikipedia.org/wiki/Adobe_Flash_Media_Server>} """ #: Specifies a Adobe Flash Player 6.0 - 8.0 client. Flash6 = 0 #: Specifies a Adobe FlashCom / Flash Media Server client. FlashCom = 1 #: Specifies a Adobe Flash Player 9.0 client or newer. Flash9 = 3 #: List of AMF client typecodes. CLIENT_TYPES = [] for x in ClientTypes.__dict__: if not x.startswith('_'): CLIENT_TYPES.append(ClientTypes.__dict__[x]) del x class UndefinedType(object): def __repr__(self): return 'pyamf.Undefined' #: Represents the C{undefined} value in a Adobe Flash Player client. Undefined = UndefinedType() class BaseError(Exception): """ Base AMF Error. All AMF related errors should be subclassed from this class. """ class DecodeError(BaseError): """ Raised if there is an error in decoding an AMF data stream. """ class EOStream(BaseError): """ Raised if the data stream has come to a natural end. """ class ReferenceError(BaseError): """ Raised if an AMF data stream refers to a non-existent object or string reference. """ class EncodeError(BaseError): """ Raised if the element could not be encoded to the stream. @bug: See U{Docuverse blog (external) <http://www.docuverse.com/blog/donpark/2007/05/14/flash-9-amf3-bug>} for more info about the empty key string array bug. """ class ClassAliasError(BaseError): """ Generic error for anything class alias related. """ class UnknownClassAlias(ClassAliasError): """ Raised if the AMF stream specifies an Actionscript class that does not have a Python class alias. @see: L{register_class} """ class BaseContext(object): """ I hold the AMF context for en/decoding streams. @ivar objects: An indexed collection of referencable objects encountered during en/decoding. @type objects: L{util.IndexedCollection} @ivar class_aliases: A L{dict} of C{class} to L{ClassAlias} @ivar exceptions: If C{True} then reference errors will be propagated. @type exceptions: C{bool} """ def __init__(self, exceptions=True): self.objects = util.IndexedCollection(exceptions=False) self.clear() self.exceptions = exceptions def clear(self): """ Completely clears the context. """ self.objects.clear() self.class_aliases = {} def getObject(self, ref): """ Gets an object based on a reference. @raise ReferenceError: Unknown object reference, if L{exceptions} is C{True}, otherwise C{None} will be returned. """ o = self.objects.getByReference(ref) if o is None and self.exceptions: raise ReferenceError("Unknown object reference %r" % (ref,)) return o def getObjectReference(self, obj): """ Gets a reference for an object. @raise ReferenceError: Object not a valid reference, """ o = self.objects.getReferenceTo(obj) if o is None and self.exceptions: raise ReferenceError("Object %r not a valid reference" % (obj,)) return o def addObject(self, obj): """ Adds a reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. """ return self.objects.append(obj) def getClassAlias(self, klass): """ Gets a class alias based on the supplied C{klass}. """ try: return self.class_aliases[klass] except KeyError: pass try: self.class_aliases[klass] = get_class_alias(klass) except UnknownClassAlias: # no alias has been found yet .. check subclasses alias = util.get_class_alias(klass) self.class_aliases[klass] = alias(klass) return self.class_aliases[klass] def __copy__(self): raise NotImplementedError class ASObject(dict): """ This class represents a Flash Actionscript Object (typed or untyped). I supply a C{__builtin__.dict} interface to support C{get}/C{setattr} calls. @raise AttributeError: Unknown attribute. """ class __amf__: dynamic = True def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) def __getattr__(self, k): try: return self[k] except KeyError: raise AttributeError('Unknown attribute \'%s\'' % (k,)) def __setattr__(self, k, v): self[k] = v def __repr__(self): return dict.__repr__(self) def __hash__(self): return id(self) class MixedArray(dict): """ Used to be able to specify the C{mixedarray} type. """ class ClassAlias(object): """ Class alias. Provides class/instance meta data to the En/Decoder to allow fine grain control and some performance increases. """ def __init__(self, klass, alias=None, **kwargs): if not isinstance(klass, (type, types.ClassType)): raise TypeError('klass must be a class type, got %r' % type(klass)) self.checkClass(klass) self.klass = klass self.alias = alias self.static_attrs = kwargs.get('static_attrs', None) self.exclude_attrs = kwargs.get('exclude_attrs', None) self.readonly_attrs = kwargs.get('readonly_attrs', None) self.proxy_attrs = kwargs.get('proxy_attrs', None) self.amf3 = kwargs.get('amf3', None) self.external = kwargs.get('external', None) self.dynamic = kwargs.get('dynamic', None) self._compiled = False self.anonymous = False self.sealed = None if self.alias is None: self.anonymous = True # we don't set this to None because AMF3 untyped objects have a # class name of '' self.alias = '' else: if self.alias == '': raise ValueError('Cannot set class alias as \'\'') if not kwargs.get('defer', False): self.compile() def _checkExternal(self): if not hasattr(self.klass, '__readamf__'): raise AttributeError("An externalised class was specified, but" " no __readamf__ attribute was found for %r" % (self.klass,)) if not hasattr(self.klass, '__writeamf__'): raise AttributeError("An externalised class was specified, but" " no __writeamf__ attribute was found for %r" % (self.klass,)) if not isinstance(self.klass.__readamf__, types.UnboundMethodType): raise TypeError("%s.__readamf__ must be callable" % ( self.klass.__name__,)) if not isinstance(self.klass.__writeamf__, types.UnboundMethodType): raise TypeError("%s.__writeamf__ must be callable" % ( self.klass.__name__,)) def compile(self): """ This compiles the alias into a form that can be of most benefit to the en/decoder. """ if self._compiled: return self.decodable_properties = set() self.encodable_properties = set() self.inherited_dynamic = None self.inherited_sealed = None self.exclude_attrs = set(self.exclude_attrs or []) self.readonly_attrs = set(self.readonly_attrs or []) self.static_attrs = set(self.static_attrs or []) self.proxy_attrs = set(self.proxy_attrs or []) if self.external: self._checkExternal() self._finalise_compile() # this class is external so no more compiling is necessary return self.sealed = util.is_class_sealed(self.klass) if hasattr(self.klass, '__slots__'): self.decodable_properties.update(self.klass.__slots__) self.encodable_properties.update(self.klass.__slots__) for k, v in self.klass.__dict__.iteritems(): if not isinstance(v, property): continue if v.fget: self.encodable_properties.update([k]) if v.fset: self.decodable_properties.update([k]) else: self.readonly_attrs.update([k]) mro = inspect.getmro(self.klass)[1:] try: self._compile_base_class(mro[0]) except IndexError: pass self.getCustomProperties() self._finalise_compile() def _compile_base_class(self, klass): if klass is object: return try: alias = get_class_alias(klass) except UnknownClassAlias: alias = register_class(klass) alias.compile() if alias.exclude_attrs: self.exclude_attrs.update(alias.exclude_attrs) if alias.readonly_attrs: self.readonly_attrs.update(alias.readonly_attrs) if alias.static_attrs: self.static_attrs.update(alias.static_attrs) if alias.proxy_attrs: self.proxy_attrs.update(alias.proxy_attrs) if alias.encodable_properties: self.encodable_properties.update(alias.encodable_properties) if alias.decodable_properties: self.decodable_properties.update(alias.decodable_properties) if self.amf3 is None and alias.amf3: self.amf3 = alias.amf3 if self.dynamic is None and alias.dynamic is not None: self.inherited_dynamic = alias.dynamic if alias.sealed is not None: self.inherited_sealed = alias.sealed def _finalise_compile(self): if self.dynamic is None: self.dynamic = True if self.inherited_dynamic is not None: if self.inherited_dynamic is False and not self.sealed and self.inherited_sealed: self.dynamic = True else: self.dynamic = self.inherited_dynamic if self.sealed: self.dynamic = False if self.amf3 is None: self.amf3 = False if self.external is None: self.external = False if not self.static_attrs: self.static_attrs = None else: self.encodable_properties.update(self.static_attrs) self.decodable_properties.update(self.static_attrs) if self.static_attrs is not None: if self.exclude_attrs: self.static_attrs.difference_update(self.exclude_attrs) self.static_attrs = list(self.static_attrs) self.static_attrs.sort() if not self.exclude_attrs: self.exclude_attrs = None else: self.encodable_properties.difference_update(self.exclude_attrs) self.decodable_properties.difference_update(self.exclude_attrs) if self.exclude_attrs is not None: self.exclude_attrs = list(self.exclude_attrs) self.exclude_attrs.sort() if not self.readonly_attrs: self.readonly_attrs = None else: self.decodable_properties.difference_update(self.readonly_attrs) if self.readonly_attrs is not None: self.readonly_attrs = list(self.readonly_attrs) self.readonly_attrs.sort() if not self.proxy_attrs: self.proxy_attrs = None else: if not self.amf3: raise ClassAliasError('amf3 = True must be specified for ' 'classes with proxied attributes. Attribute = %r, ' 'Class = %r' % (self.proxy_attrs, self.klass,)) self.proxy_attrs = list(self.proxy_attrs) self.proxy_attrs.sort() if len(self.decodable_properties) == 0: self.decodable_properties = None else: self.decodable_properties = list(self.decodable_properties) self.decodable_properties.sort() if len(self.encodable_properties) == 0: self.encodable_properties = None else: self.encodable_properties = list(self.encodable_properties) self.encodable_properties.sort() self.non_static_encodable_properties = None if self.encodable_properties: self.non_static_encodable_properties = set(self.encodable_properties) if self.static_attrs: self.non_static_encodable_properties.difference_update(self.static_attrs) self.shortcut_encode = True if self.encodable_properties or self.static_attrs or self.exclude_attrs: self.shortcut_encode = False self._compiled = True def is_compiled(self): return self._compiled def __str__(self): return self.alias def __repr__(self): return '<ClassAlias alias=%s class=%s @ 0x%x>' % ( self.alias, self.klass, id(self)) def __eq__(self, other): if isinstance(other, basestring): return self.alias == other elif isinstance(other, self.__class__): return self.klass == other.klass elif isinstance(other, (type, types.ClassType)): return self.klass == other else: return False def __hash__(self): return id(self) def checkClass(self, klass): """ This function is used to check if the class being aliased fits certain criteria. The default is to check that the C{__init__} constructor does not pass in arguments. @since: 0.4 @raise TypeError: C{__init__} doesn't support additional arguments """ # Check that the constructor of the class doesn't require any additonal # arguments. if not (hasattr(klass, '__init__') and hasattr(klass.__init__, 'im_func')): return klass_func = klass.__init__.im_func # built-in classes don't have func_code if hasattr(klass_func, 'func_code') and ( klass_func.func_code.co_argcount - len(klass_func.func_defaults or []) > 1): args = list(klass_func.func_code.co_varnames) values = list(klass_func.func_defaults or []) if not values: sign = "%s.__init__(%s)" % (klass.__name__, ", ".join(args)) else: named_args = zip(args[len(args) - len(values):], values) sign = "%s.%s.__init__(%s, %s)" % ( klass.__module__, klass.__name__, ", ".join(args[:0-len(values)]), ", ".join(map(lambda x: "%s=%s" % x, named_args))) raise TypeError("__init__ doesn't support additional arguments: %s" % sign) def getEncodableAttributes(self, obj, codec=None): """ Returns a C{tuple} containing a dict of static and dynamic attributes for an object to encode. @param codec: An optional argument that will contain the en/decoder instance calling this function. @since: 0.5 """ if not self._compiled: self.compile() static_attrs = {} dynamic_attrs = {} if self.static_attrs: for attr in self.static_attrs: try: static_attrs[attr] = getattr(obj, attr) except AttributeError: static_attrs[attr] = Undefined if not self.dynamic: if self.non_static_encodable_properties: for attr in self.non_static_encodable_properties: dynamic_attrs[attr] = getattr(obj, attr) if not static_attrs: static_attrs = None if not dynamic_attrs: dynamic_attrs = None return static_attrs, dynamic_attrs dynamic_props = util.get_properties(obj) if not self.shortcut_encode: dynamic_props = set(dynamic_props) if self.encodable_properties: dynamic_props.update(self.encodable_properties) if self.static_attrs: dynamic_props.difference_update(self.static_attrs) if self.exclude_attrs: dynamic_props.difference_update(self.exclude_attrs) if self.klass is dict: for attr in dynamic_props: dynamic_attrs[attr] = obj[attr] else: for attr in dynamic_props: dynamic_attrs[attr] = getattr(obj, attr) if self.proxy_attrs is not None: if static_attrs: for k, v in static_attrs.copy().iteritems(): if k in self.proxy_attrs: static_attrs[k] = self.getProxiedAttribute(k, v) if dynamic_attrs: for k, v in dynamic_attrs.copy().iteritems(): if k in self.proxy_attrs: dynamic_attrs[k] = self.getProxiedAttribute(k, v) if not static_attrs: static_attrs = None if not dynamic_attrs: dynamic_attrs = None return static_attrs, dynamic_attrs def getDecodableAttributes(self, obj, attrs, codec=None): """ Returns a dictionary of attributes for C{obj} that has been filtered, based on the supplied C{attrs}. This allows for fine grain control over what will finally end up on the object or not .. @param obj: The reference object. @param attrs: The attrs dictionary that has been decoded. @param codec: An optional argument that will contain the codec instance calling this function. @return: A dictionary of attributes that can be applied to C{obj} @since: 0.5 """ if not self._compiled: self.compile() changed = False props = set(attrs.keys()) if self.static_attrs: missing_attrs = [] for p in self.static_attrs: if p not in props: missing_attrs.append(p) if missing_attrs: raise AttributeError('Static attributes %r expected ' 'when decoding %r' % (missing_attrs, self.klass)) if not self.dynamic: if not self.decodable_properties: props = set() else: props.intersection_update(self.decodable_properties) changed = True if self.readonly_attrs: props.difference_update(self.readonly_attrs) changed = True if self.exclude_attrs: props.difference_update(self.exclude_attrs) changed = True if self.proxy_attrs is not None: from pyamf import flex for k in self.proxy_attrs: try: v = attrs[k] except KeyError: continue attrs[k] = flex.unproxy_object(v) if not changed: return attrs a = {} [a.__setitem__(p, attrs[p]) for p in props] return a def getProxiedAttribute(self, attr, obj): """ Returns the proxied equivalent for C{obj}. @param attr: The attribute of the proxy request. Useful for class introspection. @type attr: C{str} @param obj: The object to proxy. @return: The proxied object or the original object if it cannot be proxied. """ # the default is to just check basic types from pyamf import flex if type(obj) is list: return flex.ArrayCollection(obj) elif type(obj) is dict: return flex.ObjectProxy(obj) return obj def applyAttributes(self, obj, attrs, codec=None): """ Applies the collection of attributes C{attrs} to aliased object C{obj}. Called when decoding reading aliased objects from an AMF byte stream. Override this to provide fine grain control of application of attributes to C{obj}. @param codec: An optional argument that will contain the en/decoder instance calling this function. """ attrs = self.getDecodableAttributes(obj, attrs, codec=codec) util.set_attrs(obj, attrs) def getCustomProperties(self): """ Overrride this to provide known static properties based on the aliased class. @since: 0.5 """ def createInstance(self, codec=None, *args, **kwargs): """ Creates an instance of the klass. @return: Instance of C{self.klass}. """ return self.klass(*args, **kwargs) class TypedObject(dict): """ This class is used when a strongly typed object is decoded but there is no registered class to apply it to. This object can only be used for 'simple' streams - i.e. not externalized data. If encountered, a L{DecodeError} will be raised. @ivar alias: The alias of the typed object. @type alias: C{unicode} @since: 0.4 """ def __init__(self, alias): dict.__init__(self) self.alias = alias def __readamf__(self, o): raise DecodeError('Unable to decode an externalised stream with ' 'class alias \'%s\'.\n\nThe class alias was found and because ' 'strict mode is False an attempt was made to decode the object ' 'automatically. To decode this stream, a registered class with ' 'the alias and a corresponding __readamf__ method will be ' 'required.' % (self.alias,)) def __writeamf__(self, o): raise EncodeError('Unable to encode an externalised stream with ' 'class alias \'%s\'.\n\nThe class alias was found and because ' 'strict mode is False an attempt was made to encode the object ' 'automatically. To encode this stream, a registered class with ' 'the alias and a corresponding __readamf__ method will be ' 'required.' % (self.alias,)) class TypedObjectClassAlias(ClassAlias): """ @since: 0.4 """ klass = TypedObject def __init__(self, klass, alias, *args, **kwargs): # klass attr is ignored ClassAlias.__init__(self, self.klass, alias) def createInstance(self, codec=None): return self.klass(self.alias) def checkClass(kls, klass): pass class ErrorAlias(ClassAlias): """ Adapts Python exception objects to Adobe Flash Player error objects. @since: 0.5 """ def getCustomProperties(self): self.exclude_attrs.update(['args']) def getEncodableAttributes(self, obj, **kwargs): sa, da = ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not da: da = {} da['message'] = str(obj) da['name'] = obj.__class__.__name__ return sa, da class BaseDecoder(object): """ Base AMF decoder. @ivar context_class: The context for the decoding. @type context_class: An instance of C{BaseDecoder.context_class} @ivar type_map: @type type_map: C{list} @ivar stream: The underlying data stream. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @ivar strict: Defines how strict the decoding should be. For the time being this relates to typed objects in the stream that do not have a registered alias. Introduced in 0.4. @type strict: C{bool} @ivar timezone_offset: The offset from UTC for any datetime objects being decoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} """ context_class = BaseContext type_map = {} def __init__(self, stream=None, context=None, strict=False, timezone_offset=None): if isinstance(stream, util.BufferedByteStream): self.stream = stream else: self.stream = util.BufferedByteStream(stream) if context is None: self.context = self.context_class() else: self.context = context self.context.exceptions = False self.strict = strict self.timezone_offset = timezone_offset def readElement(self): """ Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. """ pos = self.stream.tell() try: t = self.stream.read(1) except IOError: raise EOStream try: func = getattr(self, self.type_map[t]) except KeyError: raise DecodeError("Unsupported ActionScript type %r" % (t,)) try: return func() except IOError: self.stream.seek(pos) raise def __iter__(self): try: while 1: yield self.readElement() except EOStream: raise StopIteration class CustomTypeFunc(object): """ Custom type mappings. """ def __init__(self, encoder, func): self.encoder = encoder self.func = func def __call__(self, data, *args, **kwargs): self.encoder.writeElement(self.func(data, encoder=self.encoder)) class BaseEncoder(object): """ Base AMF encoder. @ivar type_map: A list of types -> functions. The types is a list of possible instances or functions to call (that return a C{bool}) to determine the correct function to call to encode the data. @type type_map: C{list} @ivar context_class: Holds the class that will create context objects for the implementing C{Encoder}. @type context_class: C{type} or C{types.ClassType} @ivar stream: The underlying data stream. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @ivar context: The context for the encoding. @type context: An instance of C{BaseEncoder.context_class} @ivar strict: Whether the encoder should operate in 'strict' mode. Nothing is really affected by this for the time being - its just here for flexibility. @type strict: C{bool}, default is False. @ivar timezone_offset: The offset from UTC for any datetime objects being encoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} """ context_class = BaseContext type_map = [] def __init__(self, stream=None, context=None, strict=False, timezone_offset=None): if isinstance(stream, util.BufferedByteStream): self.stream = stream else: self.stream = util.BufferedByteStream(stream) if context is None: self.context = self.context_class() else: self.context = context self.context.exceptions = False self._write_elem_func_cache = {} self.strict = strict self.timezone_offset = timezone_offset def writeFunc(self, obj, **kwargs): """ Not possible to encode functions. @raise EncodeError: Unable to encode function/methods. """ raise EncodeError("Unable to encode function/methods") def _getWriteElementFunc(self, data): """ Gets a function used to encode the data. @type data: C{mixed} @param data: Python data. @rtype: callable or C{None}. @return: The function used to encode data to the stream. """ for type_, func in TYPE_MAP.iteritems(): try: if isinstance(data, type_): return CustomTypeFunc(self, func) except TypeError: if callable(type_) and type_(data): return CustomTypeFunc(self, func) for tlist, method in self.type_map: for t in tlist: try: if isinstance(data, t): return getattr(self, method) except TypeError: if callable(t) and t(data): return getattr(self, method) return None def _writeElementFunc(self, data): """ Gets a function used to encode the data. @type data: C{mixed} @param data: Python data. @rtype: callable or C{None}. @return: The function used to encode data to the stream. """ try: key = data.__class__ except AttributeError: return self._getWriteElementFunc(data) try: return self._write_elem_func_cache[key] except KeyError: self._write_elem_func_cache[key] = self._getWriteElementFunc(data) return self._write_elem_func_cache[key] def writeElement(self, data): """ Writes the data. Overridden in subclass. @type data: C{mixed} @param data: The data to be encoded to the data stream. """ raise NotImplementedError def register_class(klass, alias=None): """ Registers a class to be used in the data streaming. @return: The registered L{ClassAlias}. """ meta = util.get_class_meta(klass) if alias is not None: meta['alias'] = alias alias_klass = util.get_class_alias(klass) x = alias_klass(klass, defer=True, **meta) if not x.anonymous: CLASS_CACHE[x.alias] = x CLASS_CACHE[klass] = x return x def unregister_class(alias): """ Deletes a class from the cache. If C{alias} is a class, the matching alias is found. @type alias: C{class} or C{str} @param alias: Alias for class to delete. @raise UnknownClassAlias: Unknown alias. """ try: x = CLASS_CACHE[alias] except KeyError: raise UnknownClassAlias('Unknown alias %r' % (alias,)) if not x.anonymous: del CLASS_CACHE[x.alias] del CLASS_CACHE[x.klass] return x def get_class_alias(klass): """ Finds the alias registered to the class. @type klass: C{object} or class object. @return: The class alias linked to C{klass}. @rtype: L{ClassAlias} @raise UnknownClassAlias: Class not found. """ if isinstance(klass, basestring): try: return CLASS_CACHE[klass] except KeyError: return load_class(klass) if not isinstance(klass, (type, types.ClassType)): if isinstance(klass, types.InstanceType): klass = klass.__class__ elif isinstance(klass, types.ObjectType): klass = type(klass) try: return CLASS_CACHE[klass] except KeyError: raise UnknownClassAlias('Unknown alias for %r' % (klass,)) def register_class_loader(loader): """ Registers a loader that is called to provide the C{Class} for a specific alias. The L{loader} is provided with one argument, the C{Class} alias. If the loader succeeds in finding a suitable class then it should return that class, otherwise it should return C{None}. @type loader: C{callable} @raise TypeError: The C{loader} is not callable. @raise ValueError: The C{loader} is already registered. """ if not callable(loader): raise TypeError("loader must be callable") if loader in CLASS_LOADERS: raise ValueError("loader has already been registered") CLASS_LOADERS.append(loader) def unregister_class_loader(loader): """ Unregisters a class loader. @type loader: C{callable} @param loader: The object to be unregistered @raise LookupError: The C{loader} was not registered. """ if loader not in CLASS_LOADERS: raise LookupError("loader not found") CLASS_LOADERS.remove(loader) def get_module(mod_name): """ Load a module based on C{mod_name}. @type mod_name: C{str} @param mod_name: The module name. @return: Module. @raise ImportError: Unable to import an empty module. """ if mod_name is '': raise ImportError("Unable to import empty module") mod = __import__(mod_name) components = mod_name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def load_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @type alias: C{str} @param alias: The class name. @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. """ alias = str(alias) # Try the CLASS_CACHE first try: return CLASS_CACHE[alias] except KeyError: pass # Check each CLASS_LOADERS in turn for loader in CLASS_LOADERS: klass = loader(alias) if klass is None: continue if isinstance(klass, (type, types.ClassType)): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[str(alias)] = klass CLASS_CACHE[klass.klass] = klass return klass else: raise TypeError("Expecting class type or ClassAlias from loader") # XXX nick: Are there security concerns for loading classes this way? mod_class = alias.split('.') if mod_class: module = '.'.join(mod_class[:-1]) klass = mod_class[-1] try: module = get_module(module) except (ImportError, AttributeError): # XXX What to do here? pass else: klass = getattr(module, klass) if isinstance(klass, (type, types.ClassType)): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[str(alias)] = klass CLASS_CACHE[klass.klass] = klass return klass.klass else: raise TypeError("Expecting class type or ClassAlias from loader") # All available methods for finding the class have been exhausted raise UnknownClassAlias("Unknown alias for %r" % (alias,)) def decode(*args, **kwargs): """ A generator function to decode a datastream. @kwarg stream: AMF data. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @type encoding: C{int} @kwarg encoding: AMF encoding type. @type context: L{AMF0 Context<pyamf.amf0.Context>} or L{AMF3 Context<pyamf.amf3.Context>} @kwarg context: Context. @return: Each element in the stream. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) decoder = _get_decoder_class(encoding)(*args, **kwargs) while 1: try: yield decoder.readElement() except EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element. @type args: C{mixed} @keyword element: Python data. @type encoding: C{int} @keyword encoding: AMF encoding type. @type context: L{amf0.Context<pyamf.amf0.Context>} or L{amf3.Context<pyamf.amf3.Context>} @keyword context: Context. @rtype: C{StringIO} @return: File-like object. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) encoder = _get_encoder_class(encoding)(**kwargs) stream = encoder.stream for el in args: encoder.writeElement(el) stream.seek(0) return stream def get_decoder(encoding, *args, **kwargs): """ Returns a subclassed instance of L{pyamf.BaseDecoder}, based on C{encoding} """ return _get_decoder_class(encoding)(*args, **kwargs) def _get_decoder_class(encoding): """ Get compatible decoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Decoder<pyamf.amf0.Decoder>} or L{amf3.Decoder<pyamf.amf3.Decoder>} @return: AMF0 or AMF3 decoder. """ if encoding == AMF0: from pyamf import amf0 return amf0.Decoder elif encoding == AMF3: from pyamf import amf3 return amf3.Decoder raise ValueError("Unknown encoding %s" % (encoding,)) def get_encoder(encoding, *args, **kwargs): """ Returns a subclassed instance of L{pyamf.BaseEncoder}, based on C{encoding} """ return _get_encoder_class(encoding)(*args, **kwargs) def _get_encoder_class(encoding): """ Get compatible encoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Encoder<pyamf.amf0.Encoder>} or L{amf3.Encoder<pyamf.amf3.Encoder>} @return: AMF0 or AMF3 encoder. """ if encoding == AMF0: from pyamf import amf0 return amf0.Encoder elif encoding == AMF3: from pyamf import amf3 return amf3.Encoder raise ValueError("Unknown encoding %s" % (encoding,)) def get_context(encoding, **kwargs): return _get_context_class(encoding)(**kwargs) def _get_context_class(encoding): """ Gets a compatible context class. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Context<pyamf.amf0.Context>} or L{amf3.Context<pyamf.amf3.Context>} @return: AMF0 or AMF3 context class. """ if encoding == AMF0: from pyamf import amf0 return amf0.Context elif encoding == AMF3: from pyamf import amf3 return amf3.Context raise ValueError("Unknown encoding %s" % (encoding,)) def blaze_loader(alias): """ Loader for BlazeDS framework compatibility classes, specifically implementing C{ISmallMessage}. @see: U{BlazeDS (external)<http://opensource.adobe.com/wiki/display/blazeds/BlazeDS>} @since: 0.5 """ if alias not in ['DSC', 'DSK']: return import pyamf.flex.messaging return CLASS_CACHE[alias] def flex_loader(alias): """ Loader for L{Flex<pyamf.flex>} framework compatibility classes. @raise UnknownClassAlias: Trying to load unknown Flex compatibility class. """ if not alias.startswith('flex.'): return try: if alias.startswith('flex.messaging.messages'): import pyamf.flex.messaging elif alias.startswith('flex.messaging.io'): import pyamf.flex elif alias.startswith('flex.data.messages'): import pyamf.flex.data return CLASS_CACHE[alias] except KeyError: raise UnknownClassAlias(alias) def add_type(type_, func=None): """ Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control of what to encode to an AMF data stream. @raise TypeError: Unable to add as a custom type (expected a class or callable). @raise KeyError: Type already exists. """ def _check_type(type_): if not (isinstance(type_, (type, types.ClassType)) or callable(type_)): raise TypeError(r'Unable to add '%r' as a custom type (expected a ' 'class or callable)' % (type_,)) if isinstance(type_, list): type_ = tuple(type_) if type_ in TYPE_MAP: raise KeyError('Type %r already exists' % (type_,)) if isinstance(type_, types.TupleType): for x in type_: _check_type(x) else: _check_type(type_) TYPE_MAP[type_] = func def get_type(type_): """ Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. """ if isinstance(type_, list): type_ = tuple(type_) for (k, v) in TYPE_MAP.iteritems(): if k == type_: return v raise KeyError("Unknown type %r" % (type_,)) def remove_type(type_): """ Removes the custom type declaration. @return: Custom type declaration. """ declaration = get_type(type_) del TYPE_MAP[type_] return declaration def add_error_class(klass, code): """ Maps an exception class to a string code. Used to map remoting C{onStatus} objects to an exception class so that an exception can be built to represent that error:: class AuthenticationError(Exception): pass An example: C{add_error_class(AuthenticationError, 'Auth.Failed')} @type code: C{str} @raise TypeError: C{klass} must be a C{class} type. @raise TypeError: Error classes must subclass the C{__builtin__.Exception} class. @raise ValueError: Code is already registered. """ if not isinstance(code, basestring): code = str(code) if not isinstance(klass, (type, types.ClassType)): raise TypeError("klass must be a class type") mro = inspect.getmro(klass) if not Exception in mro: raise TypeError('Error classes must subclass the __builtin__.Exception class') if code in ERROR_CLASS_MAP.keys(): raise ValueError('Code %s is already registered' % (code,)) ERROR_CLASS_MAP[code] = klass def remove_error_class(klass): """ Removes a class from C{ERROR_CLASS_MAP}. @raise ValueError: Code is not registered. @raise ValueError: Class is not registered. @raise TypeError: Invalid type, expected C{class} or C{string}. """ if isinstance(klass, basestring): if not klass in ERROR_CLASS_MAP.keys(): raise ValueError('Code %s is not registered' % (klass,)) elif isinstance(klass, (type, types.ClassType)): classes = ERROR_CLASS_MAP.values() if not klass in classes: raise ValueError('Class %s is not registered' % (klass,)) klass = ERROR_CLASS_MAP.keys()[classes.index(klass)] else: raise TypeError("Invalid type, expected class or string") del ERROR_CLASS_MAP[klass] def register_alias_type(klass, *args): """ This function allows you to map subclasses of L{ClassAlias} to classes listed in C{args}. When an object is read/written from/to the AMF stream, a paired L{ClassAlias} instance is created (or reused), based on the Python class of that object. L{ClassAlias} provides important metadata for the class and can also control how the equivalent Python object is created, how the attributes are applied etc. Use this function if you need to do something non-standard. @see: L{pyamf.adapters._google_appengine_ext_db.DataStoreClassAlias} for a good example. @since: 0.4 @raise RuntimeError: Type is already registered. @raise TypeError: C{klass} must be a class. @raise ValueError: New aliases must subclass L{pyamf.ClassAlias}. @raise ValueError: At least one type must be supplied. """ def check_type_registered(arg): # FIXME: Create a reverse index of registered types and do a quicker lookup for k, v in ALIAS_TYPES.iteritems(): for kl in v: if arg is kl: raise RuntimeError('%r is already registered under %r' % (arg, k)) if not isinstance(klass, (type, types.ClassType)): raise TypeError('klass must be class') if not issubclass(klass, ClassAlias): raise ValueError('New aliases must subclass pyamf.ClassAlias') if len(args) == 0: raise ValueError('At least one type must be supplied') if len(args) == 1 and callable(args[0]): c = args[0] check_type_registered(c) else: for arg in args: if not isinstance(arg, (type, types.ClassType)): raise TypeError('%r must be class' % (arg,)) check_type_registered(arg) ALIAS_TYPES[klass] = args def register_package(module=None, package=None, separator='.', ignore=[], strict=True): """ This is a helper function that takes the concept of Actionscript packages and registers all the classes in the supplied Python module under that package. It auto-aliased all classes in C{module} based on C{package}. e.g. C{mymodule.py}:: class User(object): pass class Permission(object): pass >>> import mymodule >>> pyamf.register_package(mymodule, 'com.example.app') Now all instances of C{mymodule.User} will appear in Actionscript under the alias 'com.example.app.User'. Same goes for C{mymodule.Permission} - the Actionscript alias is 'com.example.app.Permission'. The reverse is also true, any objects with the correct aliases will now be instances of the relevant Python class. This function respects the C{__all__} attribute of the module but you can have further control of what not to auto alias by populating the C{ignore} argument. This function provides the ability to register the module it is being called in, an example: >>> class Foo: ... pass ... >>> class Bar: ... pass ... >>> import pyamf >>> pyamf.register_package('foo') You can also supply a list of classes to register. An example, taking the above classes: >>> import pyamf >>> pyamf.register_package([Foo, Bar], 'foo') @param module: The Python module that will contain all the classes to auto alias. @type module: C{module} or C{dict} @param package: The base package name. e.g. 'com.example.app'. If this is C{None} then the value is inferred from module.__name__. @type package: C{str} or C{unicode} or C{None} @param separator: The separator used to append to C{package} to form the complete alias. @type separator: C{str} @param ignore: To give fine grain control over what gets aliased and what doesn't, supply a list of classes that you B{do not} want to be aliased. @type ignore: C{iterable} @param strict: If this value is C{True} then only classes that originate from C{module} will be registered, all others will be left in peace. @type strict: C{bool} @return: A collection of all the classes that were registered and their respective L{ClassAlias} objects. @since: 0.5 """ if isinstance(module, basestring): if module == '': raise TypeError('Cannot get list of classes from %r' % (module,)) package = module module = None if module is None: import inspect prev_frame = inspect.stack()[1][0] module = prev_frame.f_locals if type(module) is dict: has = lambda x: x in module.keys() get = module.__getitem__ elif type(module) is list: has = lambda x: x in module get = module.__getitem__ strict = False else: has = lambda x: hasattr(module, x) get = lambda x: getattr(module, x) if package is None: if has('__name__'): package = get('__name__') else: raise TypeError('Cannot get list of classes from %r' % (module,)) if has('__all__'): keys = get('__all__') elif hasattr(module, '__dict__'): keys = module.__dict__.keys() elif hasattr(module, 'keys'): keys = module.keys() elif isinstance(module, list): keys = range(len(module)) else: raise TypeError('Cannot get list of classes from %r' % (module,)) def check_attr(attr): if not isinstance(attr, (types.ClassType, types.TypeType)): return False if attr.__name__ in ignore: return False try: if strict and attr.__module__ != get('__name__'): return False except AttributeError: return False return True # gotta love python classes = filter(check_attr, [get(x) for x in keys]) registered = {} for klass in classes: alias = '%s%s%s' % (package, separator, klass.__name__) registered[klass] = register_class(klass, alias) return registered # init module here register_class(ASObject) register_class_loader(flex_loader) register_class_loader(blaze_loader) register_alias_type(TypedObjectClassAlias, TypedObject) register_alias_type(ErrorAlias, Exception) register_adapters()
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF Utilities. @since: 0.1.0 """ import struct import calendar import datetime import types import inspect import pyamf try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: set except NameError: from sets import Set as set #: XML types. xml_types = None ET = None #: On some Python versions retrieving a negative timestamp, like #: C{datetime.datetime.utcfromtimestamp(-31536000.0)} is broken. negative_timestamp_broken = False int_types = [int] str_types = [str] # py3k support try: int_types.append(long) except NameError: pass try: str_types.append(unicode) except NameError: pass #: Numeric types. int_types = tuple(int_types) #: String types. str_types = tuple(str_types) PosInf = 1e300000 NegInf = -1e300000 # we do this instead of float('nan') because windows throws a wobbler. NaN = PosInf / PosInf def find_xml_lib(): """ Run through a predefined order looking through the various C{ElementTree} implementations so that any type can be encoded but PyAMF will return elements as the first implementation found. We work through the C implementations first - then the pure Python versions. The downside to this is that a possible of three libraries will be loaded into memory that are not used but the libs are small (relatively) and the flexibility that this gives seems to outweigh the cost. Time will tell. @since: 0.4 """ global xml_types, ET xml_types = [] try: import xml.etree.cElementTree as cET ET = cET xml_types.append(type(cET.Element('foo'))) except ImportError: pass try: import cElementTree as cET if ET is None: ET = cET xml_types.append(type(cET.Element('foo'))) except ImportError: pass try: import xml.etree.ElementTree as pET if ET is None: ET = pET xml_types.append(pET._ElementInterface) except ImportError: pass try: import elementtree.ElementTree as pET if ET is None: ET = pET xml_types.append(pET._ElementInterface) except ImportError: pass for x in xml_types[:]: # hack for jython if x.__name__ == 'instance': xml_types.remove(x) xml_types = tuple(xml_types) return xml_types class StringIOProxy(object): """ I am a C{StringIO} type object containing byte data from the AMF stream. @see: U{ByteArray on OSFlash (external) <http://osflash.org/documentation/amf3#x0c_-_bytearray>} @see: U{Parsing ByteArrays on OSFlash (external) <http://osflash.org/documentation/amf3/parsing_byte_arrays>} """ _wrapped_class = StringIO def __init__(self, buf=None): """ @raise TypeError: Unable to coerce C{buf} to C{StringIO}. """ self._buffer = StringIOProxy._wrapped_class() if isinstance(buf, (str, unicode)): self._buffer.write(buf) elif hasattr(buf, 'getvalue'): self._buffer.write(buf.getvalue()) elif hasattr(buf, 'read') and hasattr(buf, 'seek') and hasattr(buf, 'tell'): old_pos = buf.tell() buf.seek(0) self._buffer.write(buf.read()) buf.seek(old_pos) elif buf is None: pass else: raise TypeError("Unable to coerce buf->StringIO") self._get_len() self._len_changed = False self._buffer.seek(0, 0) def getvalue(self): """ Get raw data from buffer. """ return self._buffer.getvalue() def read(self, n=-1): """ Reads C{n} bytes from the stream. """ bytes = self._buffer.read(n) return bytes def seek(self, pos, mode=0): """ Sets the file-pointer offset, measured from the beginning of this stream, at which the next write operation will occur. @param pos: @type pos: C{int} @param mode: @type mode: C{int} """ return self._buffer.seek(pos, mode) def tell(self): """ Returns the position of the stream pointer. """ return self._buffer.tell() def truncate(self, size=0): """ Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int} """ if size == 0: self._buffer = StringIOProxy._wrapped_class() self._len_changed = True return cur_pos = self.tell() self.seek(0) buf = self.read(size) self._buffer = StringIOProxy._wrapped_class() self._buffer.write(buf) self.seek(cur_pos) self._len_changed = True def write(self, s): """ Writes the content of the specified C{s} into this buffer. @param s: @type s: """ self._buffer.write(s) self._len_changed = True def _get_len(self): """ Return total number of bytes in buffer. """ if hasattr(self._buffer, 'len'): self._len = self._buffer.len return old_pos = self._buffer.tell() self._buffer.seek(0, 2) self._len = self._buffer.tell() self._buffer.seek(old_pos) def __len__(self): if not self._len_changed: return self._len self._get_len() self._len_changed = False return self._len def consume(self): """ Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. @since: 0.4 """ try: bytes = self.read() except IOError: bytes = '' self.truncate() if len(bytes) > 0: self.write(bytes) self.seek(0) class DataTypeMixIn(object): """ Provides methods for reading and writing basic data types for file-like objects. @ivar endian: Byte ordering used to represent the data. Default byte order is L{ENDIAN_NETWORK}. @type endian: C{str} """ #: Network byte order ENDIAN_NETWORK = "!" #: Native byte order ENDIAN_NATIVE = "@" #: Little endian ENDIAN_LITTLE = "<" #: Big endian ENDIAN_BIG = ">" endian = ENDIAN_NETWORK def _read(self, length): """ Reads C{length} bytes from the stream. If an attempt to read past the end of the buffer is made, L{IOError} is raised. """ bytes = self.read(length) if len(bytes) != length: self.seek(0 - len(bytes), 1) raise IOError("Tried to read %d byte(s) from the stream" % length) return bytes def _is_big_endian(self): """ Whether this system is big endian or not. @rtype: C{bool} """ if self.endian == DataTypeMixIn.ENDIAN_NATIVE: return DataTypeMixIn._system_endian == DataTypeMixIn.ENDIAN_BIG return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK) def read_uchar(self): """ Reads an C{unsigned char} from the stream. """ return struct.unpack("B", self._read(1))[0] def write_uchar(self, c): """ Writes an C{unsigned char} to the stream. @param c: Unsigned char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. """ if type(c) not in int_types: raise TypeError('expected an int (got:%r)' % (type(c),)) if not 0 <= c <= 255: raise OverflowError("Not in range, %d" % c) self.write(struct.pack("B", c)) def read_char(self): """ Reads a C{char} from the stream. """ return struct.unpack("b", self._read(1))[0] def write_char(self, c): """ Write a C{char} to the stream. @param c: char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. """ if type(c) not in int_types: raise TypeError('expected an int (got:%r)' % (type(c),)) if not -128 <= c <= 127: raise OverflowError("Not in range, %d" % c) self.write(struct.pack("b", c)) def read_ushort(self): """ Reads a 2 byte unsigned integer from the stream. """ return struct.unpack("%sH" % self.endian, self._read(2))[0] def write_ushort(self, s): """ Writes a 2 byte unsigned integer to the stream. @param s: 2 byte unsigned integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. """ if type(s) not in int_types: raise TypeError('expected an int (got:%r)' % (type(s),)) if not 0 <= s <= 65535: raise OverflowError("Not in range, %d" % s) self.write(struct.pack("%sH" % self.endian, s)) def read_short(self): """ Reads a 2 byte integer from the stream. """ return struct.unpack("%sh" % self.endian, self._read(2))[0] def write_short(self, s): """ Writes a 2 byte integer to the stream. @param s: 2 byte integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. """ if type(s) not in int_types: raise TypeError('expected an int (got:%r)' % (type(s),)) if not -32768 <= s <= 32767: raise OverflowError("Not in range, %d" % s) self.write(struct.pack("%sh" % self.endian, s)) def read_ulong(self): """ Reads a 4 byte unsigned integer from the stream. """ return struct.unpack("%sL" % self.endian, self._read(4))[0] def write_ulong(self, l): """ Writes a 4 byte unsigned integer to the stream. @param l: 4 byte unsigned integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. """ if type(l) not in int_types: raise TypeError('expected an int (got:%r)' % (type(l),)) if not 0 <= l <= 4294967295: raise OverflowError("Not in range, %d" % l) self.write(struct.pack("%sL" % self.endian, l)) def read_long(self): """ Reads a 4 byte integer from the stream. """ return struct.unpack("%sl" % self.endian, self._read(4))[0] def write_long(self, l): """ Writes a 4 byte integer to the stream. @param l: 4 byte integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. """ if type(l) not in int_types: raise TypeError('expected an int (got:%r)' % (type(l),)) if not -2147483648 <= l <= 2147483647: raise OverflowError("Not in range, %d" % l) self.write(struct.pack("%sl" % self.endian, l)) def read_24bit_uint(self): """ Reads a 24 bit unsigned integer from the stream. @since: 0.4 """ order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] n = 0 for x in order: n += (self.read_uchar() << x) return n def write_24bit_uint(self, n): """ Writes a 24 bit unsigned integer to the stream. @since: 0.4 @param n: 24 bit unsigned integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. """ if type(n) not in int_types: raise TypeError('expected an int (got:%r)' % (type(n),)) if not 0 <= n <= 0xffffff: raise OverflowError("n is out of range") order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] for x in order: self.write_uchar((n >> x) & 0xff) def read_24bit_int(self): """ Reads a 24 bit integer from the stream. @since: 0.4 """ n = self.read_24bit_uint() if n & 0x800000 != 0: # the int is signed n -= 0x1000000 return n def write_24bit_int(self, n): """ Writes a 24 bit integer to the stream. @since: 0.4 @param n: 24 bit integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. """ if type(n) not in int_types: raise TypeError('expected an int (got:%r)' % (type(n),)) if not -8388608 <= n <= 8388607: raise OverflowError("n is out of range") order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] if n < 0: n += 0x1000000 for x in order: self.write_uchar((n >> x) & 0xff) def read_double(self): """ Reads an 8 byte float from the stream. """ return struct.unpack("%sd" % self.endian, self._read(8))[0] def write_double(self, d): """ Writes an 8 byte float to the stream. @param d: 8 byte float @type d: C{float} @raise TypeError: Unexpected type for float C{d}. """ if not type(d) is float: raise TypeError('expected a float (got:%r)' % (type(d),)) self.write(struct.pack("%sd" % self.endian, d)) def read_float(self): """ Reads a 4 byte float from the stream. """ return struct.unpack("%sf" % self.endian, self._read(4))[0] def write_float(self, f): """ Writes a 4 byte float to the stream. @param f: 4 byte float @type f: C{float} @raise TypeError: Unexpected type for float C{f}. """ if type(f) is not float: raise TypeError('expected a float (got:%r)' % (type(f),)) self.write(struct.pack("%sf" % self.endian, f)) def read_utf8_string(self, length): """ Reads a UTF-8 string from the stream. @rtype: C{unicode} """ str = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0] return unicode(str, "utf8") def write_utf8_string(self, u): """ Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. """ if type(u) not in str_types: raise TypeError('expected a str (got:%r)' % (type(u),)) bytes = u.encode("utf8") self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes)) if struct.pack('@H', 1)[0] == '\x01': DataTypeMixIn._system_endian = DataTypeMixIn.ENDIAN_LITTLE else: DataTypeMixIn._system_endian = DataTypeMixIn.ENDIAN_BIG class BufferedByteStream(StringIOProxy, DataTypeMixIn): """ An extension of C{StringIO}. Features: - Raises L{IOError} if reading past end. - Allows you to C{peek()} at the next byte. @see: L{cBufferedByteStream<cpyamf.util.cBufferedByteStream>} """ def __init__(self, buf=None): """ @param buf: Initial byte stream. @type buf: C{str} or C{StringIO} instance """ StringIOProxy.__init__(self, buf=buf) self.seek(0) def read(self, length=-1): """ Reads up to the specified number of bytes from the stream into the specified byte array of specified length. @raise IOError: Attempted to read past the end of the buffer. """ if length == -1 and self.at_eof(): raise IOError('Attempted to read from the buffer but already at ' 'the end') elif length > 0 and self.tell() + length > len(self): raise IOError('Attempted to read %d bytes from the buffer but ' 'only %d remain' % (length, len(self) - self.tell())) return StringIOProxy.read(self, length) def peek(self, size=1): """ Looks C{size} bytes ahead in the stream, returning what it finds, returning the stream pointer to its initial position. @param size: Default is 1. @type size: C{int} @raise ValueError: Trying to peek backwards. @rtype: @return: Bytes. """ if size == -1: return self.peek(len(self) - self.tell()) if size < -1: raise ValueError("Cannot peek backwards") bytes = '' pos = self.tell() while not self.at_eof() and len(bytes) != size: bytes += self.read(1) self.seek(pos) return bytes def remaining(self): """ Returns number of remaining bytes. @rtype: C{number} @return: Number of remaining bytes. """ return len(self) - self.tell() def at_eof(self): """ Returns C{True} if the internal pointer is at the end of the stream. @rtype: C{bool} """ return self.tell() == len(self) def append(self, data): """ Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to the stream. @type data: C{str} or C{unicode} @raise TypeError: data is not C{str} or C{unicode} """ t = self.tell() # seek to the end of the stream self.seek(0, 2) if hasattr(data, 'getvalue'): self.write_utf8_string(data.getvalue()) else: self.write_utf8_string(data) self.seek(t) def __add__(self, other): old_pos = self.tell() old_other_pos = other.tell() new = BufferedByteStream(self) other.seek(0) new.seek(0, 2) new.write(other.read()) self.seek(old_pos) other.seek(old_other_pos) new.seek(0) return new def hexdump(data): """ Get hexadecimal representation of C{StringIO} data. @type data: @param data: @rtype: C{str} @return: Hexadecimal string. """ import string hex = ascii = buf = "" index = 0 for c in data: hex += "%02x " % ord(c) if c in string.printable and c not in string.whitespace: ascii += c else: ascii += "." if len(ascii) == 16: buf += "%04x: %s %s %s\n" % (index, hex[:24], hex[24:], ascii) hex = ascii = "" index += 16 if len(ascii): buf += "%04x: %-24s %-24s %s\n" % (index, hex[:24], hex[24:], ascii) return buf def get_timestamp(d): """ Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @param d: The date object. @return: UTC timestamp. @rtype: C{str} @note: Inspiration taken from the U{Intertwingly blog <http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. """ if isinstance(d, datetime.date) and not isinstance(d, datetime.datetime): d = datetime.datetime.combine(d, datetime.time(0, 0, 0, 0)) msec = str(d.microsecond).rjust(6).replace(' ', '0') return float('%s.%s' % (calendar.timegm(d.utctimetuple()), msec)) def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if secs < 0 and negative_timestamp_broken: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=secs) return datetime.datetime.utcfromtimestamp(secs) def get_properties(obj): """ @since: 0.5 """ if hasattr(obj, 'keys'): return set(obj.keys()) elif hasattr(obj, '__dict__'): return obj.__dict__.keys() return [] def get_attrs(obj): """ Gets a C{dict} of the attrs of an object in a predefined resolution order. @raise AttributeError: A duplicate attribute was already found in this collection, are you mixing different key types? """ if hasattr(obj, 'iteritems'): attrs = {} for k, v in obj.iteritems(): sk = str(k) if sk in attrs.keys(): raise AttributeError('A duplicate attribute (%s) was ' 'already found in this collection, are you mixing ' 'different key types?' % (sk,)) attrs[sk] = v return attrs elif hasattr(obj, '__dict__'): return obj.__dict__.copy() elif hasattr(obj, '__slots__'): attrs = {} for k in obj.__slots__: attrs[k] = getattr(obj, k) return attrs return None def set_attrs(obj, attrs): """ A generic function which applies a collection of attributes C{attrs} to object C{obj}. @param obj: An instance implementing the C{__setattr__} function @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict """ if isinstance(obj, (list, dict)): for k, v in attrs.iteritems(): obj[k] = v return for k, v in attrs.iteritems(): setattr(obj, k, v) def get_class_alias(klass): """ Returns a alias class suitable for klass. Defaults to L{pyamf.ClassAlias} """ for k, v in pyamf.ALIAS_TYPES.iteritems(): for kl in v: if isinstance(kl, types.FunctionType): if kl(klass) is True: return k elif isinstance(kl, (type, (types.ClassType, types.ObjectType))): if issubclass(klass, kl): return k return pyamf.ClassAlias def is_class_sealed(klass): """ Returns a C{boolean} whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in kls.__dict__: return False if not hasattr(kls, '__slots__'): return False return True def get_class_meta(klass): """ Returns a C{dict} containing meta data based on the supplied class, useful for class aliasing. @rtype: C{dict} @since: 0.5 """ if not isinstance(klass, (type, types.ClassType)) or klass is object: raise TypeError('klass must be a class object, got %r' % type(klass)) meta = { 'static_attrs': None, 'exclude_attrs': None, 'readonly_attrs': None, 'amf3': None, 'dynamic': None, 'alias': None, 'external': None } if not hasattr(klass, '__amf__'): return meta a = klass.__amf__ if type(a) is dict: in_func = lambda x: x in a get_func = a.__getitem__ else: in_func = lambda x: hasattr(a, x) get_func = lambda x: getattr(a, x) for prop in ['alias', 'amf3', 'dynamic', 'external']: if in_func(prop): meta[prop] = get_func(prop) for prop in ['static', 'exclude', 'readonly']: if in_func(prop): meta[prop + '_attrs'] = list(get_func(prop)) return meta class IndexedCollection(object): """ A class that provides a quick and clean way to store references and referenced objects. @note: All attributes on the instance are private. @ivar exceptions: If C{True} then L{ReferenceError<pyamf.ReferenceError>} will be raised, otherwise C{None} will be returned. """ def __init__(self, use_hash=False, exceptions=True): if use_hash is True: self.func = hash else: self.func = id self.exceptions = exceptions self.clear() def clear(self): """ Clears the index. """ self.list = [] self.dict = {} def getByReference(self, ref): """ Returns an object based on the reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. """ if not isinstance(ref, (int, long)): raise TypeError("Bad reference type") try: return self.list[ref] except IndexError: if self.exceptions is False: return None raise pyamf.ReferenceError("Reference %r not found" % (ref,)) def getReferenceTo(self, obj): """ Returns a reference to C{obj} if it is contained within this index. @raise pyamf.ReferenceError: Value not found. """ try: return self.dict[self.func(obj)] except KeyError: if self.exceptions is False: return None raise pyamf.ReferenceError("Value %r not found" % (obj,)) def append(self, obj): """ Appends C{obj} to this index. @note: Uniqueness is not checked @return: The reference to C{obj} in this index. """ h = self.func(obj) self.list.append(obj) idx = len(self.list) - 1 self.dict[h] = idx return idx def __eq__(self, other): if isinstance(other, list): return self.list == other elif isinstance(other, dict): return self.dict == other return False def __len__(self): return len(self.list) def __getitem__(self, idx): return self.getByReference(idx) def __contains__(self, obj): try: r = self.getReferenceTo(obj) except pyamf.ReferenceError: r = None return r is not None def __repr__(self): return '<%s list=%r dict=%r>' % (self.__class__.__name__, self.list, self.dict) def __iter__(self): return iter(self.list) class IndexedMap(IndexedCollection): """ Like L{IndexedCollection}, but also maps to another object. @since: 0.4 """ def __init__(self, use_hash=False, exceptions=True): IndexedCollection.__init__(self, use_hash, exceptions) def clear(self): """ Clears the index and mapping. """ IndexedCollection.clear(self) self.mapped = [] def getMappedByReference(self, ref): """ Returns the mapped object by reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. """ if not isinstance(ref, (int, long)): raise TypeError("Bad reference type.") try: return self.mapped[ref] except IndexError: if self.exceptions is False: return None raise pyamf.ReferenceError("Reference %r not found" % ref) def append(self, obj): """ Appends C{obj} to this index. @return: The reference to C{obj} in this index. """ idx = IndexedCollection.append(self, obj) diff = (idx + 1) - len(self.mapped) for i in range(0, diff): self.mapped.append(None) return idx def map(self, obj, mapped_obj): """ Maps an object. """ idx = self.append(obj) self.mapped[idx] = mapped_obj return idx def is_ET_element(obj): """ Determines if the supplied C{obj} param is a valid ElementTree element. """ return isinstance(obj, xml_types) def is_float_broken(): """ Older versions of Python (<=2.5) and the Windows platform are renowned for mixing up 'special' floats. This function determines whether this is the case. @since: 0.4 @rtype: C{bool} """ global NaN return str(NaN) != str(struct.unpack("!d", '\xff\xf8\x00\x00\x00\x00\x00\x00')[0]) def isNaN(val): """ @since: 0.5 """ return str(float(val)) == str(NaN) def isPosInf(val): """ @since: 0.5 """ return str(float(val)) == str(PosInf) def isNegInf(val): """ @since: 0.5 """ return str(float(val)) == str(NegInf) # init the module from here .. find_xml_lib() try: datetime.datetime.utcfromtimestamp(-31536000.0) except ValueError: negative_timestamp_broken = True if is_float_broken(): def read_double_workaround(self): global PosInf, NegInf, NaN """ Override the L{DataTypeMixIn.read_double} method to fix problems with doubles by using the third-party C{fpconst} library. """ bytes = self.read(8) if self._is_big_endian(): if bytes == '\xff\xf8\x00\x00\x00\x00\x00\x00': return NaN if bytes == '\xff\xf0\x00\x00\x00\x00\x00\x00': return NegInf if bytes == '\x7f\xf0\x00\x00\x00\x00\x00\x00': return PosInf else: if bytes == '\x00\x00\x00\x00\x00\x00\xf8\xff': return NaN if bytes == '\x00\x00\x00\x00\x00\x00\xf0\xff': return NegInf if bytes == '\x00\x00\x00\x00\x00\x00\xf0\x7f': return PosInf return struct.unpack("%sd" % self.endian, bytes)[0] DataTypeMixIn.read_double = read_double_workaround def write_double_workaround(self, d): """ Override the L{DataTypeMixIn.write_double} method to fix problems with doubles by using the third-party C{fpconst} library. """ if type(d) is not float: raise TypeError('expected a float (got:%r)' % (type(d),)) if isNaN(d): if self._is_big_endian(): self.write('\xff\xf8\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf8\xff') elif isNegInf(d): if self._is_big_endian(): self.write('\xff\xf0\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf0\xff') elif isPosInf(d): if self._is_big_endian(): self.write('\x7f\xf0\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf0\x7f') else: write_double_workaround.old_func(self, d) x = DataTypeMixIn.write_double DataTypeMixIn.write_double = write_double_workaround write_double_workaround.old_func = x try: from cpyamf.util import BufferedByteStream, IndexedCollection, IndexedMap class StringIOProxy(BufferedByteStream): _wrapped_class = None def __init__(self, *args, **kwargs): BufferedByteStream.__init__(self, *args, **kwargs) self._buffer = self class DataTypeMixIn(BufferedByteStream): #: Network byte order ENDIAN_NETWORK = "!" #: Native byte order ENDIAN_NATIVE = "@" #: Little endian ENDIAN_LITTLE = "<" #: Big endian ENDIAN_BIG = ">" except ImportError: pass
Python
# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Tools for doing dynamic imports. @since: 0.3 """ import sys __all__ = ['when_imported'] #: A list of callables to be executed when the module is imported. post_load_hooks = {} #: List of modules that have already been loaded. loaded_modules = [] class ModuleFinder(object): """ This is a special module finder object that executes a collection of callables when a specific module has been imported. An instance of this is placed in C{sys.meta_path}, which is consulted before C{sys.modules} - allowing us to provide this functionality. @see: L{when_imported} @since: 0.5 """ def find_module(self, name, path): """ Called when an import is made. If there are hooks waiting for this module to be imported then we stop the normal import process and manually load the module. @param name: The name of the module being imported. @param path The root path of the module (if a package). We ignore this. @return: If we want to hook this module, we return a C{loader} interface (which is this instance again). If not we return C{None} to allow the standard import process to continue. """ if name in loaded_modules or name not in post_load_hooks: return None return self def load_module(self, name): """ If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run the hooks. @param name: The name of the module to import. """ loaded_modules.append(name) parent, child = split_module(name) __import__(name, {}, {}, []) mod = sys.modules[name] run_hooks(name, mod) return mod def run_hooks(name, module): """ Run all hooks for a module. Load an unactivated "lazy" module object. """ try: for hook in post_load_hooks[name]: hook(module) finally: del post_load_hooks[name] def split_module(name): """ Splits a module name into its parent and child parts. >>> split_module('foo.bar.baz') 'foo.bar', 'baz' >>> split_module('foo') None, 'foo' """ try: splitpos = name.rindex('.') + 1 return name[:splitpos - 1], name[splitpos:] except ValueError: return None, name def when_imported(name, hook): """ Call C{hook(module)} when module named C{name} is first used. 'hook' must accept one argument: the module object named by 'name', which must be a fully qualified (i.e. absolute) module name. The hook should not raise any exceptions, or it will prevent later hooks from running. If the module has already been imported normally, 'hook(module)' is called immediately, and the module object is returned from this function. If the module has not been imported, then the hook is called when the module is first imported. """ if name in loaded_modules or name in sys.modules: hook(sys.modules[name]) return if name not in post_load_hooks: post_load_hooks[name] = [] post_load_hooks[name].append(hook) # this is required for reloading this module for obj in sys.meta_path: if obj.__class__ is ModuleFinder: break else: sys.meta_path.insert(0, ModuleFinder())
Python
# Django settings for fleq project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('FLEQ Admin', 'fleq.libresoft@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db_fleq', # 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 = 'Europe/Brussels' TIME_ZONE = '' # 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 path to the directory that holds media. # Example: "/srv/wwwmedia/media.lawrence.com/" #MEDIA_ROOT = '/srv/www/FLEQ/fleq/template/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # 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: "/srv/wwwmedia/media.lawrence.com/static/" #STATIC_ROOT = '/srv/www/FLEQ/fleq/' STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/admin/media/' # Temporary email EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'fleq.libresoft@gmail.com' EMAIL_HOST_PASSWORD = '...' EMAIL_PORT = 587 # Make this unique, and don't share it with anybody. SECRET_KEY = ')2-q1^z&u@ch0)7tq!h+6vu9xy#h1lr1v5g(41i66*f(w&lb&c' # 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.middleware.csrf.CsrfResponseMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'minidetector.Middleware', ) ROOT_URLCONF = 'fleq.urls' TEMPLATE_DIRS = ( # Put strings here, like "/srv/wwwhtml/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. 'template', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'quizbowl', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # 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, }, } } AUTH_PROFILE_MODULE = 'quizbowl.Player'
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# import tornado import tornado.web import tornado.httpserver import tornadio2 import tornadio2.router import tornadio2.server import tornadio2.conn import json from django.core.management import setup_environ import settings setup_environ(settings) from django.contrib.sessions.models import Session from django.contrib.auth.models import User from quizbowl.models import Game class UserTornado(object): def __init__(self, socket, username, room): self.socket = socket self.username = username self.room = room class FleqConnection(tornadio2.conn.SocketConnection): participants = set() def on_open(self, request): try: sessionid = str(request.cookies['sessionid']).split("=")[1] session = Session.objects.get(session_key=sessionid) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) if user.is_authenticated: create = True for person in self.participants: if person.username == user.username: # A user only must be in one room and from one device each time create = False person.socket = self person.room = None break if create: self.participants.add(UserTornado(self, user.username, None)) else: return False # The user is not authenticated, then connection is rejected return except (KeyError, Session.DoesNotExist, User.DoesNotExist): return False # Session cookie is missed, or Session/User doesn't exist, then connection is rejected def on_message(self, message): message = json.loads(message) # JOIN if message['code'] == "1": for person in self.participants: if person.username == message['user'] and person.socket == self: try: game = Game.objects.get(pk=message['room']) except Game.DoesNotExist: return if game.player1.username == person.username or game.player2.username == person.username or person.username == "FLEQBOT": person.room = message['room'] person.socket.send('{"code":"1"}') else: self.participants.remove(person) break # NEW MESSAGE elif message['code'] == "2": for person in self.participants: if person.username == message['user'] and person.socket == self: for person in self.participants: if person.room == message['room']: msg = message['message'] msg = msg.replace('<', '&lt;').replace('>', '&gt;').replace("'", "&#39;") person.socket.send('{"code": "2", "user": "' + message['user'] + '", "message": "' + msg + '"}') break def on_close(self): for person in self.participants: if person.socket == self: self.participants.remove(person) break # Create tornadio server FleqRouter = tornadio2.router.TornadioRouter(FleqConnection) # Create socket application sock_app = tornado.web.Application( FleqRouter.urls, socket_io_port = 8004, socket_io_address = '127.0.0.1' ) if __name__ == "__main__": tornadio2.server.SocketServer(sock_app, auto_start=True)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.http import HttpResponse from django.shortcuts import render_to_response from views_connect import LoginForm, RegisterForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.models import UserProfile, RecoverUser from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * from quizbowl.views_notify import notify_user import string import os def NextGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') myFutureGames = Game.objects.filter(Q(log = False), Q(player1 = request.user) | Q(player2 = request.user)).order_by('start_time') dates = [] for game in myFutureGames: if not game.start_time_committed and (datetime.datetime.now() + datetime.timedelta(minutes=120)) > game.start_time: game.start_time_committed = True game.save() if not game.start_time.date() in dates: dates.append(game.start_time.date()) # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/next-games.html' if request.mobile: template = 'mobile/next-games.html' return render_to_response(template, { 'user_me': request.user, 'myNextGames': myFutureGames, 'dates': dates, 'lang': lang, }) def SelectStartTime(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') game = Game.objects.get(id = gid) pst = Preferred_start_time.objects.get(game = game, player = request.user) if request.user != game.player1 and request.user != game.player2 and request.user.username == "FLEQBOT": return HttpResponseRedirect('/') if game.is_over(): return HttpResponseRedirect('/') if game.start_time_committed: return HttpResponseRedirect('/game-room/' + gid) now = datetime.datetime.now() g = game # Save all dates of my uncommitted games to select date and time to play myUncommittedGamesDate = [] # Contains all options to select in my next games startDate = g.round.start_date finishDate = g.round.finish_date while startDate <= finishDate: # Check to show only valid dates if startDate >= datetime.datetime.now().date(): d = {} d['gid'] = g.pk d['date'] = startDate d['dateslashed'] = str(startDate.day) + "/" + str(startDate.month) + "/" + str(startDate.year) myUncommittedGamesDate.append(d) startDate = startDate + timedelta(days=1) if request.method == "GET": hour = now.hour # Extract all dates and times selected by user to show them mySelectedGamesDate = [] # Contains all options selected by user to each game opponentSelectedGamesDate = [] # Contains all options selected by opponent to each game # Select game preferences by user mySelection = Preferred_start_time.objects.filter(Q(player = request.user), Q(game = g)) for selection in mySelection: # Extract all datetimes selected by user to show them myDateTimesSelected = Date_time.objects.filter(Q(preferred_start_time = selection)).order_by('date_time') for dateSelected in myDateTimesSelected: s = {} s['gid'] = g.pk s['date'] = dateSelected mySelectedGamesDate.append(s) # Select game preferences by opponent if g.player1 == request.user: opponent = g.player2 else: opponent = g.player1 opponentSelection = Preferred_start_time.objects.filter(Q(player = opponent), Q(game = g)) firstDateSinceNow = datetime.datetime.now() if firstDateSinceNow.hour < 22: firstDateSinceNow = datetime.datetime(now.year, now.month, now.day, now.hour + 2, 0, 0) else: firstDateSinceNow = firstDateSinceNow + datetime.timedelta(minutes=120) for selection in opponentSelection: # Extract all datetimes selected by opponent to show them myDateTimesSelected = Date_time.objects.filter(Q(preferred_start_time = selection)).order_by('date_time') for dateSelected in myDateTimesSelected: s = {} s['gid'] = g.pk s['date'] = dateSelected if dateSelected.date_time >= firstDateSinceNow: opponentSelectedGamesDate.append(s) hours = [] if hour < 6: hours = range(8,24) elif hour < 22: hour = hour + 2 while hour < 24: hours.append(hour) hour = hour + 1 template = 'pc/select-time.html' if request.mobile: template = 'mobile/select-time.html' return render_to_response(template, { 'hours': hours, 'allhours': range(8,24), 'today': now.date(), 'myUncommittedGamesDate': myUncommittedGamesDate, 'mySelectedGamesDate': mySelectedGamesDate, 'opponentSelectedGamesDate': opponentSelectedGamesDate, 'player1': game.player1.username, 'player2': game.player2.username, 'date': now, 'user_me': request.user, }) elif request.method == "POST": pst = Preferred_start_time.objects.get(player=request.user, game=game) gameDate = pst.game.start_time.date() for date in request.POST.getlist('hours'): pst = Preferred_start_time.objects.get(player=request.user, game=game) date = date.split("/") date = datetime.datetime(int(date[3]), int(date[2]), int(date[1]), int(date[0]), 0, 0) checkDate = Date_time.objects.filter(date_time = date, preferred_start_time = pst) if not checkDate: dateTime = Date_time(date_time = date, preferred_start_time = pst) dateTime.save() pst.committed = True pst.save() pst = Preferred_start_time.objects.filter(game = pst.game) if pst[0].committed and pst[1].committed: d_t1 = Date_time.objects.filter(preferred_start_time = pst[0]) d_t2 = Date_time.objects.filter(preferred_start_time = pst[1]) for d_t_player1 in d_t1: for d_t_player2 in d_t2: if d_t_player1.date_time == d_t_player2.date_time and not game.start_time_committed: game.start_time = d_t_player1.date_time game.start_time_committed = True game.save() notify_user(game.player1, 'time_commited', game) notify_user(game.player2, 'time_commited', game) return HttpResponseRedirect('/next-games') # Check if players saved the same hour to play for date in request.POST.getlist('hourselected'): checkDate = Date_time.objects.filter(date_time = date, preferred_start_time = pst) if not checkDate: dateTime = Date_time(date_time = date, preferred_start_time = pst) dateTime.save() pst.committed = True pst.save() pst = Preferred_start_time.objects.filter(game = pst.game) if pst[0].committed and pst[1].committed: d_t1 = Date_time.objects.filter(preferred_start_time = pst[0]) d_t2 = Date_time.objects.filter(preferred_start_time = pst[1]) for d_t_player1 in d_t1: for d_t_player2 in d_t2: if d_t_player1.date_time == d_t_player2.date_time and not game.start_time_committed: game.start_time = d_t_player1.date_time game.start_time_committed = True game.save() notify_user(game.player1, 'time_commited', game) notify_user(game.player2, 'time_commited', game) return HttpResponseRedirect('/next-games') return HttpResponseRedirect('/game-room/' + gid + "/select-time") def DeleteStartTime(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == "POST": game = Game.objects.get(id = gid) dateNow = datetime.datetime.now() for date in request.POST.getlist('hours'): dateSelected = Date_time.objects.get(pk = date) if dateSelected.preferred_start_time.player == request.user: dateSelected.delete() return HttpResponseRedirect('/game-room/' + gid + "/select-time") else: return HttpResponseRedirect('/') def GameRoom(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') game = Game.objects.get(id = gid) if request.user != game.player1 and request.user != game.player2 and request.user.username != "FLEQBOT": return HttpResponseRedirect('/') tournament = game.round.tournament r = game.round.round_number startDate = game.start_time player1 = game.player1 player2 = game.player2 template = 'pc/game-room.html' dico = [] if game.is_over(): if request.mobile: return HttpResponseRedirect("/") lines = "" print os.getcwd() logfile = open(os.getcwd() + '/logs/' + str(game.id), 'r') lines = logfile.readlines() for line in lines: linesplit = {} line = line.split(";", 2) linesplit['timestamp'] = line[0].split(".")[0] linesplit['user'] = line[1] linesplit['message'] = line[2].replace('&amp;','&').replace('&lt;','<').replace('&gt;','>').replace('&quot;','"').replace('&#39;',"'").split(";")[0] dico.append(linesplit) else: if request.mobile: template = 'mobile/game-room.html' # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' return render_to_response(template, { 'user_me': request.user, 'game': game, 'dico': dico, 'tournament': tournament, 'round': r, 'player1': player1, 'player2': player2, 'lang': lang, }) def WonGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # Select all won games wonGames = Game.objects.filter(Q(winner = request.user), Q(log=True)).order_by('-start_time') # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/won-games.html' if request.mobile: template = 'mobile/won-games.html' return render_to_response(template, { 'user_me': request.user, 'lang': lang, 'wonGames': wonGames, }) def LostGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # Select all won games lostGames = Game.objects.filter(Q(player1 = request.user) | Q(player2 = request.user), ~Q(winner = request.user), Q(log=True)).order_by('-start_time') # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/lost-games.html' if request.mobile: template = 'mobile/lost-games.html' return render_to_response(template, { 'user_me': request.user, 'lang': lang, 'lostGames': lostGames, })
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models import datetime def validate_future_date(date): if date <= datetime.date.today(): raise ValidationError("Only future dates are allowed") class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.name class Date_time(models.Model): date_time = models.DateTimeField() preferred_start_time = models.ForeignKey("Preferred_start_time") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return unicode(self.date_time) class Game(models.Model): start_time = models.DateTimeField('Start date and time') start_time_committed = models.BooleanField(default=False) log = models.BooleanField(default=False) player1 = models.ForeignKey(User, related_name='Player 1') score_player1 = models.PositiveIntegerField() player2 = models.ForeignKey(User, related_name='Player 2') score_player2 = models.PositiveIntegerField() winner = models.ForeignKey(User, related_name='Winner') round = models.ForeignKey("Round") # referenced model name between quotations marks ("") to avoid previous declaration requirement def is_over(self): if self.log: return True else: return False def __unicode__(self): return "Tournament '%s' - Round %s - %s vs %s" % (unicode(self.round.tournament), self.round.round_number, self.player1, self.player2) class Preferred_start_time(models.Model): committed = models.BooleanField(default=False) game = models.ForeignKey(Game) player = models.ForeignKey(User) def __unicode__(self): return "%s - %s" % (unicode(self.game), self.player) class Question(models.Model): alt_answer1 = models.CharField(max_length=120, blank=True, help_text="(optional)") alt_answer2 = models.CharField(max_length=120, blank=True, help_text="(optional)") alt_answer3 = models.CharField(max_length=120, blank=True, help_text="(optional)") answer = models.CharField(max_length=120) question = models.CharField(max_length=200, unique=True) use_phonetic = models.BooleanField(default=False, editable=False) categories = models.ManyToManyField(Category) def __unicode__(self): return self.question class Question_review(models.Model): arguments = models.TextField() resolution = models.TextField(blank=True) game = models.ForeignKey(Game) player = models.ForeignKey(User) question = models.ForeignKey(Question) def is_closed(self): if self.resolution: return True else: return False def __unicode__(self): return "%s - %s" % (unicode(self.question), unicode(self.game)) class RecoverUser(models.Model): user = models.ForeignKey(User) code = models.CharField(max_length=16, unique=True) class Round(models.Model): round_number = models.PositiveIntegerField() start_date = models.DateField('start date') finish_date = models.DateField('finish date') tournament = models.ForeignKey("Tournament") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return "%s - round %s" % (unicode(self.tournament), self.round_number) class Score(models.Model): points = models.PositiveIntegerField(default=0) questions_won = models.PositiveIntegerField(default=0) questions_lost = models.PositiveIntegerField(default=0) player = models.ForeignKey(User) tournament = models.ForeignKey("Tournament") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return "%s - %s" % (self.player, unicode(self.tournament)) class Tournament(models.Model): ROUNDS_CHOICES = ( (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), ) DAYS_PER_ROUND_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), ) sid = models.CharField(max_length=128) days_per_round = models.PositiveIntegerField(choices=DAYS_PER_ROUND_CHOICES) name = models.CharField(max_length=50, unique=True) rounds = models.PositiveIntegerField(choices=ROUNDS_CHOICES) start_date = models.DateField('start date', default=(datetime.datetime.today() + datetime.timedelta(days=10))) finish_date = models.DateField('finish date', default="2012-10-10") mail_log = models.TextField(blank=True, editable=False) admin = models.ForeignKey(User, related_name='admin', default=1) categories = models.ManyToManyField(Category) players = models.ManyToManyField(User, blank=True) optional_info = models.TextField(blank=True) only_mobile_devices = models.BooleanField(default=False) def __unicode__(self): return self.name class UserProfile(models.Model): avatar = models.ImageField(upload_to='images/avatars/', default='images/avatars/default.png') user = models.ForeignKey(User) winner_games = models.PositiveIntegerField(default=0) loser_games = models.PositiveIntegerField(default=0)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from datetime import * import datetime # Create the info to show a box def setBox(status): box = {} lang = strLang() box['message'] = lang[status] if status.count("success"): box['status'] = 'success' elif status.count("error"): box['status'] = 'error' elif status.count("info"): box['status'] = 'info' elif status.count("warning"): box['status'] = 'warning' return box def strLang(): strng = {} ### CONTACT.HTML ### strng['title_contact_with_us'] = u"Contact Us" strng['success_contact_sent'] = u"Your request has been sent successfully! As soon as posible, our team reply you." strng['error_contact_empty_subject'] = u"Subject is required!" strng['error_contact_empty_message'] = u"Message is required!" strng['error_contact_empty_email'] = u"Email is required to reply you!" ### EDIT PROFILE AND CHANGE PASSWORD ### strng['label_change_avatar'] = u"Change current avatar" strng['help_change_avatar'] = u"Leave this field empty if you want to keep your current avatar" strng['label_current_password'] = u"Current password" strng['label_new_password'] = u"New password" strng['label_new_password2'] = u"Repeat new password" strng['title_edit_profile'] = u"Edit My Profile" strng['button_edit_profile'] = u"Update My Profile" strng['button_change_password'] = u"Update My Password" strng['error_change_password_differents'] = u"New password could not be different in both fields required." strng['error_change_password_empty_field'] = u"This is field is required." strng['error_current_password_incorrect'] = u"Current password introduced is incorrect. Try again!" strng['success_edit_account'] = u"Your info has been updated successfully!" strng['success_change_password'] = u"Your password has been changed successfully!" ### GAMEINFO.HTML ### strng['vs'] = u"vs" strng['finished'] = u"Finished" strng['pending'] = u"Pending" strng['closed'] = u"Closed" strng['title_question_reviews'] = u"Question Reviews" strng['title_my_question_reviews'] = u"My Question Reviews" strng['error_title_game_no_exists'] = u"Oops!" strng['error_game_info'] = u"Sorry! You haven't got permission to see the info of this game." strng['error_game_no_exists'] = u"Sorry! The game selected doesn't exist in our database." strng['error_tournament_info_no_exists'] = u"Error! Tournament info doesn't exist in the system!" strng['error_no_tournament_score'] = u"Error! Tournament scores doesn't exist in the system!" strng['error_question_reviews_no_exists'] = u"Error! Don't exist question reviews!" strng['error_question_no_exists'] = u"Error! Question #ID selected doesn't exist! Try again!" ### LOADQUESTIONS.HTML ### strng['title_load_questions'] = u"Load File Questions" strng['button_load_questions'] = u"Load File" strng['success_load_questions'] = u"Questions loaded successfully!" ### LOGIN.HTML ### # Register an account strng['button_register'] = u"Register" strng['label_password2'] = u"Repeat password" strng['success_register_account'] = u"Your account has been successfully registered! Login now." strng['error_register_username_exists'] = u"Exists in our database. Choose other." strng['error_register_email_exists'] = u"Exists in our database. Choose other." strng['error_register_first_name_required'] = u"First name is required." strng['error_register_last_name_required'] = u"Last name is required." strng['error_register_passwords_differents'] = u"Password could not be different in both fields." strng['error_register_before_join_tournament'] = u"Before join to the Tournament selected, you have to register an account. It's free!" strng['error_register_before_show_tournament'] = u"Do you want to see all info about Tournaments? Only you have to register an account. It's free!" # Login an account strng['title_login'] = u"Are You Registered?" strng['button_login'] = u"Login" strng['button_recover_account'] = u"Forgot Password?" strng['error_login_password_required'] = u"Password is required." strng['error_login_username_required'] = u"Username is required." strng['error_login_failed'] = u"Login failed!" ### LOSTGAMES.HTML WONGAMES.HTML ### strng['title_lost_games'] = u"Lost Games" strng['title_won_games'] = u"Won Games" strng['table_date'] = u"DATE" strng['table_tournament'] = u"TOURNAMENT" strng['table_round'] = u"ROUND" strng['table_vs'] = u"VS" ### MYNEXTGAMES.HTML ### strng['title_my_next_games'] = u"My Next Games" strng['round'] = u"Round" strng['dates_times_play'] = u"Select all dates and time using ctrl+click that you have available to play" strng['error_no_next_games'] = u"Sorry! You haven't any game active now!" strng['error_datetime_selected_before'] = u"Sorry! One or more dates or times selected are past and you can't play a game in past times! No date and time has been saved. Try again selecting valid dates and times." date2hours = datetime.datetime.now() + timedelta(hours = 2) strng['error_datetime_selected_too_soon'] = u"Sorry! One or more times selected to play today are too soon. To facilitate that your opponent can see the game schedule, you can't select to play too soon. If you want to play today, choose any time that is about 2 hours from the current time. " + "<br />" + "<center>(<u>Select hours to play today from: " + str(date2hours.hour) + ":00h</u>)</center>" strng['success_datetime_selected'] = u"Date and times saved successfully! You can select more dates and times to play this game." strng['success_datetime_committed'] = u"Date and times saved successfully! Date and time of game has been set with the preferences of your oponent. Show details of game to see when you have to play this game." strng['datetime_selected_players'] = u"Date and time selected by players" strng['button_select_datetime'] = u"Save date and times to play" strng['button_delete_datetimes'] = u"Remove date(s)" ### MYQUESTIONREVIEWS.HTML ### strng['title_my_admin_question_reviews'] = u"My Tournament's Question Reviews" ### MYTOURNAMENTS.HTML ### strng['title_my_active_tournaments'] = u"My Active Tournaments" strng['title_my_active_admin_tournaments'] = u"My Active Admin Tournaments" strng['title_my_finished_tournaments'] = u" My Finished Tournaments" strng['tournament_categories'] = u"Categories selected" strng['tournament_start_date'] = u"Start date" strng['tournament_finish_date'] = u"Finish date" strng['error_no_active_tournaments'] = u"Sorry! You haven't any Tournament active now." strng['error_no_admin_active_tournaments'] = u"Sorry! You haven't any Tournament with admin permissions active now." strng['error_no_won_games'] = u"Sorry! You haven't won any Game." strng['error_no_lost_games'] = u"Sorry! You haven't lost any Game." ### NEWTOURNAMENT.HTML ### strng['title_new_tournament'] = u"Create New Tournament" strng['button_new_tournament'] = u"Create New Tournament" strng['success_create_new_tournament'] = u"Tournament created successfully!" strng['error_new_tournament_name_exists'] = u"Exists in our database. Choose other." ### NEWQUESTIONREVIEW.HTML ### strng['title_new_question_review'] = u"New Question Review" strng['label_question_id'] = u"Question #ID" strng['label_arguments'] = u"Your arguments" strng['button_new_question_review'] = u"Send Question Review" ### PLAY.HTML ### strng['title_play'] = u"Play Now With Webchat Freenode" ### PROFILE.HTML ### strng['title_profile_hi'] = u"Hi" strng['profile_last_login'] = u"Last login" ### QUESTIONREVIEW.HTML ### strng['title_question_reviews'] = u"Question Review" strng['warning_waiting_resolution'] = u"Waiting a resolution by admin" strng['arguments'] = u"Arguments" strng['resolution'] = u"Resolution" strng['button_save_question_review_resolution'] = u"Add resolution and close review" strng['error_question_review_no_exists'] = u"Sorry! This question review doesn't exists in our database!" strng['success_resolution'] = u"Your resolution has been saved successfully!" ### RECOVERUSER.HTML ### strng['label_recover_username'] = u"Write your username registered" strng['label_recover_email'] = u"Write your email registered" strng['title_recover_account'] = u"Recover Account" strng['title_recover_account_new_password'] = u"Change My Password" strng['button_recover_account'] = u"Recover Account" strng['button_recover_account_new_password'] = u"Set my new Password" strng['success_recover_account_email_sent'] = u"A message has been sent to verify your email and can recover your account." strng['error_recover_account'] = u"One or more errors. Try again" strng['error_unknown_code'] = u"ERROR! Code used to recover an account is wrong." strng['error_recover_user_unknown'] = u"This username doesn't exist in our database." strng['error_recover_email_unknown'] = u"This email doesn't exist in our database." strng['error_recover_user_email_differents'] = u"The username and password you enter do not match both for any user. Try again." ### TOURNAMENTINFO.HTML ### strng['title_info'] = u"Info" strng['title_table'] = u"Tournament Table" strng['title_tournament_games'] = u"Tournament Games" strng['number_rounds'] = u"Number of Rounds" strng['remember'] = u"Remember!" strng['joined_tournament'] = u"You joined to play this Tournament!" strng['button_join'] = u"Join to this Tournament Now" strng['warning_you_tournament_admin'] = u"You're the admin of this Tournament" strng['warning_only_admin'] = u"Only visible for admin tournament or admin system." strng['warning_only_players'] = u"Only visible for players." strng['error_you_tournament_admin'] = u"You're the admin of this Tournament" strng['error_tournament_no_games'] = u"Sorry! This Tournament hasn't any games!" ### TOURNAMENTS.HTML ### # Next Tournaments strng['success_join_tournament'] = u"You have been joined successfully!" strng['info_join_tournaments'] = u"We've seen that you haven't joined any Tournament. Do you want to play? Select one in <u>Next Tournaments</u> section!" strng['info_new_tournament'] = u"We've seen that you haven't joined any Tournament and you haven't create anyone. Create a Tournament in this section or join a Tournament to play in <u><a href='/tournaments'>Next Tournaments</a></u> section! " strng['error_join_tournament'] = u"Error! You can't join to this Tournament" strng['error_join_tournament_admin'] = u"Error! You can't join to this Tournament: admin's tournament can't play!" strng['error_join_tournament_joined'] = u"Error! You can't join to this Tournament: you have joined it before!" strng['error_join_tournament_expired'] = u"Error! You can't join to this Tournament: join period expired!" strng['error_tournament_no_exists'] = u"Error! Tournament selected doesn't exists!" strng['error_no_next_tournaments'] = u"Sorry! System hasn't got any next Tournament." strng['error_no_active_tournaments'] = u"Sorry! System hasn't got any active Tournament." strng['title_next_tournaments'] = u"Next Tournaments" strng['title_active_tournaments'] = u"Active Tournaments" strng['title_finished_tournaments'] = u"Last Finished Tournaments" strng['join'] = u"Join" strng['tournament_started_date'] = u"Started date" strng['tournament_finished_date'] = u"Finished date" ### SIDEBAR ### strng['title_sidebar_my_active_tournaments'] = u"My Active Tournaments" strng['title_sidebar_my_admin_tournaments'] = u"My Admin Tournaments" strng['title_sidebar_today_games'] = u"Today Games" strng['title_sidebar_next_games'] = u"Next Games" strng['committed'] = u"Committed!" strng['uncommitted'] = u"Uncommitted!" strng['error_sidebar_no_active_tournaments'] = u"No active tournaments." strng['error_sidebar_no_admin_active_tournaments'] = u"No admin active tournaments." return strng
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.mail import send_mail from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from quizbowl.models import Category, User from datetime import * import datetime # Sends and email to the user to notify an update in the Tournament def notify_user(user, case, instance): subject = "" message = "" from_email = "fleq.libresoft@gmail.com" to_email = user.email if case == 'new_tournament': tournament = instance subject += "Nuevo torneo" message += "Enhorabuena, " + user.username + ":\n\n" message += "El torneo '" + unicode(tournament) + "', en el que estabas inscrito, acaba de dar comienzo.\n" message += "Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener los detalles de la primera partida." message += "\n\n\n" elif case == 'time_commited': game = instance tournament = game.round.tournament subject += u"Confirmación fecha y hora de partida" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que, atendiendo a las preferencias de los jugadores, la partida de la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(tournament) + u"' a la que estás convocado se celebrará el día " + game.start_time.strftime("%d/%m/%Y") + " a las " + game.start_time.strftime("%H:%M%Z") + " horas.\n" message += u"Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'hurry_up': game = instance tournament = game.round.tournament subject += "Partida a punto de comenzar" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que la partida en la que participas perteneciente a la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(game.round.tournament) + u"' empezará en unos minutos (" + game.start_time.strftime("%H:%M%Z") + ")." message += "\n\n\n" elif case == 'new_review': question_review = instance tournament = question_review.game.round.tournament subject += u"Nueva revisión de pregunta" message += "Estimado " + user.username + ":\n\n" message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que el usuario " message += question_review.player.username + u" ha solicitado la revisión de una pregunta realizada en una de las partidas de dicho torneo.\n" message += u"Por favor, revisa tu perfil de usuario (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'review_closed': question_review = instance tournament = question_review.game.round.tournament subject += u"Revisión de pregunta atendida" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la revisión de pregunta que solicitaste en referencia a la partida de la ronda " message += str(question_review.game.round.round_number) + " del torneo '" + unicode(tournament) + "' ha sido resuelta.\n" message += u"Por favor, revisa los detalles de esa partida (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'tournament_canceled': tournament = instance c = Category.objects.filter(tournament=tournament) subject += "Torneo cancelado" message += "Estimado " + user.username + ":\n\n" if user == tournament.admin: message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que este ha sido cancelado por ser " message += u"el número de participantes inferior al mínimo (2).\n\n" message += u"A continuación se detallan las características del torneo cancelado:\n\n" message += "\t- Nombre: " + unicode(tournament) + "\n" message += "\t- Fecha de comienzo: " + tournament.start_date.strftime("%d/%m/%Y") + "\n" message += u"\t- Número de rondas: " + str(tournament.rounds) + "\n" message += u"\t- Duración de cada ronda (días): " + str(tournament.days_per_round) + "\n" message += u"\t- Categoría(s): " for category in list(c): message += unicode(category) + ", " message = message[:-2] message += "\n\n\n" else: message += "Te informamos que el torneo '" + unicode(tournament) + "' al que estabas inscrito, ha sido cancelado. " message += u"Por favor, ponte en contacto con el administrador del torneo para obtener más información.\n" message += "Sentimos las molestias que hayamos podido ocasionarte." message += "\n\n\n" elif case == 'new_game': round = instance tournament = round.tournament subject += "Nueva ronda de partidas" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la ronda número " + str(round.round_number) + " del torneo '" + unicode(tournament) + "' ha dado comienzo.\n" message += u"Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener los detalles de la partida que jugarás en esta ronda y elegir tu hora de preferencia." message += "\n\n\n" elif case == 'meditation_round': round = instance tournament = round.tournament subject = u"Ronda de reflexión" message += "Estimado " + user.username + ":\n\n" message += u"Debido a limitaciones relacionadas con la lógica del juego, te informamos que no podrás enfrentarte a ningún " message += "jugador durante la ronda " + str(round.round_number) + " del torneo '" + unicode(tournament) + u"' al que estás inscrito.\n" message += u"Como compensación, tu puntación en el torneo ha sido incrementada 1 punto, igual que si hubieses ganado la partida correspondiente a la ronda.\n\n" message += u"Sentimos las molestias que hayamos podido ocasionarte y deseamos que aproveches de la mejor manera posible esta ronda de reflexión." message += "\n\n\n" elif case == 'tournament_over': tournament = instance subject += "Torneo finalizado" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que el torneo '" + unicode(tournament) + "' ha finalizado.\n" message += u"Puedes consultar la tabla de clasificación de jugadores en la página del torneo (http://trivial.libresoft.es)." message += "\n\n\n" elif case == 'recover_user': recover = instance subject += u"Recuperación de cuenta de usuario" message += "Estimado " + user.username + ":\n\n" message += u"Has solicitado recuperar tu cuenta de usuario porque no recuerdas tu contraseña. Para hacerlo, accede a través del siguiente enlace:\n\n" message += "http://pfc-jgonzalez.libresoft.es/recover-account/" + recover.code + "\n\n" message += u"Desde él, podrás introducir una nueva contraseña que modificará a la que tenías anteriormente." message += "\n\n\n" message += "Atentamente,\n\n\tFLEQ (Free LibreSoft Educational Quizbowl)" send_mail(subject, message, from_email, [to_email]) log = "Date: " + str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S %Z")) + "\n" log += "Subject: " + subject + "\n" log += "To: " + to_email + "\n" log += "Message:\n" + message + "\n" log += "\n\n" if case != 'recover_user': tournament.mail_log += log tournament.save() def contactEmail(info): to_email = "fleq.libresoft@gmail.com" from_email = info['userEmail'] try: user = User.objects.get(email=info['userEmail']) except: user = "" # First, send an email to Administrator subject = "[FLEQ CONTACT FORM]" + " " + info['subject'] message = "----------- INFO USER -----------\n" if user: message += "User: " + user.username + "\n" message += "Name: " + unicode(user.first_name) + " " + unicode(user.last_name) + "\n" message += "Email contact: " + user.email + "\n" else: message += "User: anonymous" + "\n" message += "Email contact: " + info['userEmail'] + "\n" message += "----------- END INFO USER -----------\n\n" message += info['message'] send_mail(subject, message, from_email, [to_email]) # After that, send an email to User subject = "[FLEQ CONTACT SUCCESSFULL]" + " " + info['subject'] message = "Thanks for your message!\n\n" message += "Our team have received your request and soon will contact you with our reply. We'll try to be as fast as we can...\n\n" message += u"\tThanks to contact with FLEQ Project (Free LibreSoft Educational Quizbowl - http://pfc-jgonzalez.libresoft.es)." send_mail(subject, message, to_email, [from_email])
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core.files import File from django.core.mail import send_mail from django.db.models import Q from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, Round, Score, Tournament from datetime import * from quizbowl.views_notify import notify_user import datetime import os import sys def myTodayGames(request): dateNow = datetime.datetime.now().date() timeNow = datetime.datetime.now().time() # Check if I have to play today a game myNextGames = Game.objects.filter(Q(log__isnull = False), Q(start_time__gte = dateNow), Q(player1 = request.user) | Q(player2 = request.user)).order_by('-start_time') todayGames = [] for game in myNextGames: if game.start_time.date() == dateNow and game.start_time.time() > timeNow: todayGames.append(game) return todayGames def myNextGames(request): dateNow = datetime.datetime.now().date() timeNow = datetime.datetime.now().time() # Check if I have to play today a game myNextGames = Game.objects.filter(Q(log__isnull = False), Q(start_time__gte = dateNow), Q(player1 = request.user) | Q(player2 = request.user)).order_by('-start_time') nextGames = [] for game in myNextGames: if game.start_time.date() > dateNow: nextGames.append(game) return nextGames # Shows active Tournaments of user (player tournament) def myActiveTournaments(request): # Select all Tournaments and Games of user with status player dateNow = datetime.datetime.now() myActiveTournaments = Tournament.objects.filter(players = request.user).filter(Q(finish_date__gte = dateNow)).order_by('-start_date') return myActiveTournaments # Shows active admin Tournaments of user def myAdminTournaments(request): # Select all Tournaments and Games of user with status player dateNow = datetime.datetime.now() myActiveAdminTournaments = Tournament.objects.filter(admin = request.user).filter(Q(finish_date__gte = dateNow)).order_by('-start_date') return myActiveAdminTournaments def myPastTournaments(request): # Select all Tournaments finished dateNow = datetime.datetime.now() myFinishedTournaments = Tournament.objects.filter(Q(players = request.user)).filter(finish_date__lt = dateNow).order_by('-start_date') return myFinishedTournaments def myAdminPendingQuestionReviews(user): # Pending Question Reviews allMyAdminTournaments = Tournament.objects.filter(admin = user) pendingQuestionReviews = 0 # All reviews in my Tournaments for tournament in allMyAdminTournaments: questionReviews = Question_review.objects.filter(game__round__tournament = tournament, resolution__exact = '') pendingQuestionReviews += len(questionReviews) allMyTournaments = Tournament.objects.filter(Q(players = user)) # All reviews in my Tournaments for tournament in allMyTournaments: questionReviews = Question_review.objects.filter(game__round__tournament = tournament, resolution__exact = '', player = user) pendingQuestionReviews += len(questionReviews) return pendingQuestionReviews
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core.files import File from django.core.mail import send_mail from django.db.models import Q from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, Round, Score, Tournament import datetime import os import sys class Date_timeForm(forms.Form): TIME_CHOICES = ( (10, '10:00'), (16, '16:00'), (22, '22:00'), ) times = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(), choices=TIME_CHOICES, label="Choose one start time at least:") class NewQuestion_reviewForm(forms.Form): question_number = forms.IntegerField() arguments = forms.CharField(widget=forms.Textarea) class Question_reviewForm(ModelForm): class Meta: model = Question_review fields = ('game', 'question', 'arguments', 'resolution') class UserForm(ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') widgets = { 'password': forms.PasswordInput(), } def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user def validate_password(value): if value != "el campo password": raise ValidationError(u"Las contraseñas introducidas no coinciden") # Sends and email to the user to notify an update in the Tournament def notify_user(user, case, instance): subject = "" message = "" from_email = "fleqproject@gmail.com" to_email = user.email if case == 'new_tournament': tournament = instance subject += "Nuevo torneo" message += "Enhorabuena, " + user.username + ":\n\n" message += "El torneo '" + unicode(tournament) + "', en el que estabas inscrito, acaba de dar comienzo.\n" message += "Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener los detalles de la primera partida." message += "\n\n\n" elif case == 'time_commited': game = instance tournament = game.round.tournament subject += u"Confirmación fecha y hora de partida" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que, atendiendo a las preferencias de los jugadores, la partida de la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(tournament) + u"' a la que estás convocado se celebrará el día " + game.start_time.strftime("%d/%m/%Y") + " a las " + game.start_time.strftime("%H:%M%Z") + " horas.\n" message += u"Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'hurry_up': game = instance tournament = game.round.tournament subject += "Partida a punto de comenzar" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que la partida en la que participas perteneciente a la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(game.round.tournament) + u"' empezará en unos minutos (" + game.start_time.strftime("%H:%M%Z") + ")." message += "\n\n\n" elif case == 'new_review': question_review = instance tournament = question_review.game.round.tournament subject += u"Nueva revisión de pregunta" message += "Estimado " + user.username + ":\n\n" message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que el usuario " message += question_review.player.username + u" ha solicitado la revisión de una pregunta realizada en una de las partidas de dicho torneo.\n" message += u"Por favor, revisa tu perfil de usuario (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'review_closed': question_review = instance tournament = question_review.game.round.tournament subject += u"Revisión de pregunta atendida" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la revisión de pregunta que solicitaste en referencia a la partida de la ronda " message += str(question_review.game.round.round_number) + " del torneo '" + unicode(tournament) + "' ha sido resuelta.\n" message += u"Por favor, revisa los detalles de esa partida (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'tournament_canceled': tournament = instance c = Category.objects.filter(tournament=tournament) subject += "Torneo cancelado" message += "Estimado " + user.username + ":\n\n" if user == tournament.admin: message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que este ha sido cancelado por ser " message += u"el número de participantes inferior al mínimo (2).\n\n" message += u"A continuación se detallan las características del torneo cancelado:\n\n" message += "\t- Nombre: " + unicode(tournament) + "\n" message += "\t- Fecha de comienzo: " + tournament.start_date.strftime("%d/%m/%Y") + "\n" message += u"\t- Número de rondas: " + str(tournament.rounds) + "\n" message += u"\t- Duración de cada ronda (días): " + str(tournament.days_per_round) + "\n" message += u"\t- Categoría(s): " for category in list(c): message += unicode(category) + ", " message = message[:-2] message += "\n\n\n" else: message += "Te informamos que el torneo '" + unicode(tournament) + "' al que estabas inscrito, ha sido cancelado. " message += u"Por favor, ponte en contacto con el administrador del torneo para obtener más información.\n" message += "Sentimos las molestias que hayamos podido ocasionarte." message += "\n\n\n" elif case == 'new_game': round = instance tournament = round.tournament subject += "Nueva ronda de partidas" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la ronda número " + str(round.round_number) + " del torneo '" + unicode(tournament) + "' ha dado comienzo.\n" message += u"Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener los detalles de la partida que jugarás en esta ronda y elegir tu hora de preferencia." message += "\n\n\n" elif case == 'meditation_round': round = instance tournament = round.tournament subject = u"Ronda de reflexión" message += "Estimado " + user.username + ":\n\n" message += u"Debido a limitaciones relacionadas con la lógica del juego, te informamos que no podrás enfrentarte a ningún " message += "jugador durante la ronda " + str(round.round_number) + " del torneo '" + unicode(tournament) + u"' al que estás inscrito.\n" message += u"Como compensación, tu puntación en el torneo ha sido incrementada 1 punto, igual que si hubieses ganado la partida correspondiente a la ronda.\n\n" message += u"Sentimos las molestias que hayamos podido ocasionarte y deseamos que aproveches de la mejor manera posible esta ronda de reflexión." message += "\n\n\n" elif case == 'tournament_over': tournament = instance subject += "Torneo finalizado" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que el torneo '" + unicode(tournament) + "' ha finalizado.\n" message += u"Puedes consultar la tabla de clasificación de jugadores en la página del torneo (http://trivial.libresoft.es)." message += "\n\n\n" message += "Atentamente,\n\n\tFLEQ (Free LibreSoft Educational Quizbowl)" send_mail(subject, message, from_email, [to_email]) log = "Date: " + str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S %Z")) + "\n" log += "Subject: " + subject + "\n" log += "To: " + to_email + "\n" log += "Message:\n" + message + "\n" log += "\n\n" tournament.mail_log += log tournament.save() def games_history(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" if not request.user.is_staff: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) for tournament in Tournament.objects.filter(admin = request.user): response += "<strong><u>Tournament: </u>" + unicode(tournament) + "</strong>" "<br>" for round in Round.objects.filter(tournament = tournament): response += "<strong>Round " + str(round.round_number) + "</strong>" "<br>" for game in Game.objects.filter(round = round): response += "<a href='/games/" + str(game.id) + "/'>(" + game.player1.username + " vs " + game.player2.username + ")</a>" "<br>" response += "<br>" response += "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) @csrf_exempt def new_question_review(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" g = Game.objects.get(id = gid) if request.user != g.player1 and request.user != g.player2: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) if request.method == 'POST': # If the form has been submitted... form = NewQuestion_reviewForm(request.POST) # A form bound to the POST data if form.is_valid(): q = Question.objects.get(id = form.cleaned_data['question_number']) qr = Question_review(arguments = form.cleaned_data['arguments'], game = g, question = q, player = request.user) qr.save() notify_user(qr.game.round.tournament.admin, 'new_review', qr) return HttpResponseRedirect('/games/' + str(g.id) + '/') # Redirect after POST else: form = NewQuestion_reviewForm() # An unbound form return render_to_response('blank_form.html', { 'form': form, }) @csrf_exempt def question_review(request, question_review_id): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" qr = Question_review.objects.get(id = question_review_id) if request.user != qr.player and request.user != qr.game.round.tournament.admin: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) if request.user == qr.player: response += "<strong>Reviewed question: </strong>" + qr.question.question + "<br>" response += "<strong>Your review aguments:</strong>" "<br>" response += qr.arguments + "<br>" response += "<strong>Game admin's resolution:</strong>" "<br>" response += qr.resolution + "<br>" else: if request.method == 'POST': # If the form has been submitted... form = Question_reviewForm(request.POST) # A form bound to the POST data if form.is_valid(): qr.resolution = form.cleaned_data['resolution'] qr.save() notify_user(qr.player, 'review_closed', qr) return HttpResponseRedirect('/accounts/profile/') # Redirect after POST else: form = Question_reviewForm(instance = qr) # An unbound form form.fields['game'].widget.attrs['readonly'] = True form.fields['question'].widget.attrs['readonly'] = True form.fields['arguments'].widget.attrs['readonly'] = True return render_to_response('blank_form.html', { 'form': form, }) response += "<br>" "<br>" response += "<a href='/games/" + str(qr.game.id) + '/' + "'>Go to game site</a>" return HttpResponse(response)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.http import HttpResponse from django.shortcuts import render_to_response from views_connect import LoginForm, RegisterForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.models import UserProfile, RecoverUser from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * from quizbowl.views_notify import notify_user import string import os def NextGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') myFutureGames = Game.objects.filter(Q(log = False), Q(player1 = request.user) | Q(player2 = request.user)).order_by('start_time') dates = [] for game in myFutureGames: if not game.start_time_committed and (datetime.datetime.now() + datetime.timedelta(minutes=120)) > game.start_time: game.start_time_committed = True game.save() if not game.start_time.date() in dates: dates.append(game.start_time.date()) # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/next-games.html' if request.mobile: template = 'mobile/next-games.html' return render_to_response(template, { 'user_me': request.user, 'myNextGames': myFutureGames, 'dates': dates, 'lang': lang, }) def SelectStartTime(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') game = Game.objects.get(id = gid) pst = Preferred_start_time.objects.get(game = game, player = request.user) if request.user != game.player1 and request.user != game.player2 and request.user.username == "FLEQBOT": return HttpResponseRedirect('/') if game.is_over(): return HttpResponseRedirect('/') if game.start_time_committed: return HttpResponseRedirect('/game-room/' + gid) now = datetime.datetime.now() g = game # Save all dates of my uncommitted games to select date and time to play myUncommittedGamesDate = [] # Contains all options to select in my next games startDate = g.round.start_date finishDate = g.round.finish_date while startDate <= finishDate: # Check to show only valid dates if startDate >= datetime.datetime.now().date(): d = {} d['gid'] = g.pk d['date'] = startDate d['dateslashed'] = str(startDate.day) + "/" + str(startDate.month) + "/" + str(startDate.year) myUncommittedGamesDate.append(d) startDate = startDate + timedelta(days=1) if request.method == "GET": hour = now.hour # Extract all dates and times selected by user to show them mySelectedGamesDate = [] # Contains all options selected by user to each game opponentSelectedGamesDate = [] # Contains all options selected by opponent to each game # Select game preferences by user mySelection = Preferred_start_time.objects.filter(Q(player = request.user), Q(game = g)) for selection in mySelection: # Extract all datetimes selected by user to show them myDateTimesSelected = Date_time.objects.filter(Q(preferred_start_time = selection)).order_by('date_time') for dateSelected in myDateTimesSelected: s = {} s['gid'] = g.pk s['date'] = dateSelected mySelectedGamesDate.append(s) # Select game preferences by opponent if g.player1 == request.user: opponent = g.player2 else: opponent = g.player1 opponentSelection = Preferred_start_time.objects.filter(Q(player = opponent), Q(game = g)) firstDateSinceNow = datetime.datetime.now() if firstDateSinceNow.hour < 22: firstDateSinceNow = datetime.datetime(now.year, now.month, now.day, now.hour + 2, 0, 0) else: firstDateSinceNow = firstDateSinceNow + datetime.timedelta(minutes=120) for selection in opponentSelection: # Extract all datetimes selected by opponent to show them myDateTimesSelected = Date_time.objects.filter(Q(preferred_start_time = selection)).order_by('date_time') for dateSelected in myDateTimesSelected: s = {} s['gid'] = g.pk s['date'] = dateSelected if dateSelected.date_time >= firstDateSinceNow: opponentSelectedGamesDate.append(s) hours = [] if hour < 6: hours = range(8,24) elif hour < 22: hour = hour + 2 while hour < 24: hours.append(hour) hour = hour + 1 template = 'pc/select-time.html' if request.mobile: template = 'mobile/select-time.html' return render_to_response(template, { 'hours': hours, 'allhours': range(8,24), 'today': now.date(), 'myUncommittedGamesDate': myUncommittedGamesDate, 'mySelectedGamesDate': mySelectedGamesDate, 'opponentSelectedGamesDate': opponentSelectedGamesDate, 'player1': game.player1.username, 'player2': game.player2.username, 'date': now, 'user_me': request.user, }) elif request.method == "POST": pst = Preferred_start_time.objects.get(player=request.user, game=game) gameDate = pst.game.start_time.date() for date in request.POST.getlist('hours'): pst = Preferred_start_time.objects.get(player=request.user, game=game) date = date.split("/") date = datetime.datetime(int(date[3]), int(date[2]), int(date[1]), int(date[0]), 0, 0) checkDate = Date_time.objects.filter(date_time = date, preferred_start_time = pst) if not checkDate: dateTime = Date_time(date_time = date, preferred_start_time = pst) dateTime.save() pst.committed = True pst.save() pst = Preferred_start_time.objects.filter(game = pst.game) if pst[0].committed and pst[1].committed: d_t1 = Date_time.objects.filter(preferred_start_time = pst[0]) d_t2 = Date_time.objects.filter(preferred_start_time = pst[1]) for d_t_player1 in d_t1: for d_t_player2 in d_t2: if d_t_player1.date_time == d_t_player2.date_time and not game.start_time_committed: game.start_time = d_t_player1.date_time game.start_time_committed = True game.save() notify_user(game.player1, 'time_commited', game) notify_user(game.player2, 'time_commited', game) return HttpResponseRedirect('/next-games') # Check if players saved the same hour to play for date in request.POST.getlist('hourselected'): checkDate = Date_time.objects.filter(date_time = date, preferred_start_time = pst) if not checkDate: dateTime = Date_time(date_time = date, preferred_start_time = pst) dateTime.save() pst.committed = True pst.save() pst = Preferred_start_time.objects.filter(game = pst.game) if pst[0].committed and pst[1].committed: d_t1 = Date_time.objects.filter(preferred_start_time = pst[0]) d_t2 = Date_time.objects.filter(preferred_start_time = pst[1]) for d_t_player1 in d_t1: for d_t_player2 in d_t2: if d_t_player1.date_time == d_t_player2.date_time and not game.start_time_committed: game.start_time = d_t_player1.date_time game.start_time_committed = True game.save() notify_user(game.player1, 'time_commited', game) notify_user(game.player2, 'time_commited', game) return HttpResponseRedirect('/next-games') return HttpResponseRedirect('/game-room/' + gid + "/select-time") def DeleteStartTime(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == "POST": game = Game.objects.get(id = gid) dateNow = datetime.datetime.now() for date in request.POST.getlist('hours'): dateSelected = Date_time.objects.get(pk = date) if dateSelected.preferred_start_time.player == request.user: dateSelected.delete() return HttpResponseRedirect('/game-room/' + gid + "/select-time") else: return HttpResponseRedirect('/') def GameRoom(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') game = Game.objects.get(id = gid) if request.user != game.player1 and request.user != game.player2 and request.user.username != "FLEQBOT": return HttpResponseRedirect('/') tournament = game.round.tournament r = game.round.round_number startDate = game.start_time player1 = game.player1 player2 = game.player2 template = 'pc/game-room.html' dico = [] if game.is_over(): if request.mobile: return HttpResponseRedirect("/") lines = "" print os.getcwd() logfile = open(os.getcwd() + '/logs/' + str(game.id), 'r') lines = logfile.readlines() for line in lines: linesplit = {} line = line.split(";", 2) linesplit['timestamp'] = line[0].split(".")[0] linesplit['user'] = line[1] linesplit['message'] = line[2].replace('&amp;','&').replace('&lt;','<').replace('&gt;','>').replace('&quot;','"').replace('&#39;',"'").split(";")[0] dico.append(linesplit) else: if request.mobile: template = 'mobile/game-room.html' # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' return render_to_response(template, { 'user_me': request.user, 'game': game, 'dico': dico, 'tournament': tournament, 'round': r, 'player1': player1, 'player2': player2, 'lang': lang, }) def WonGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # Select all won games wonGames = Game.objects.filter(Q(winner = request.user), Q(log=True)).order_by('-start_time') # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/won-games.html' if request.mobile: template = 'mobile/won-games.html' return render_to_response(template, { 'user_me': request.user, 'lang': lang, 'wonGames': wonGames, }) def LostGames(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # Select all won games lostGames = Game.objects.filter(Q(player1 = request.user) | Q(player2 = request.user), ~Q(winner = request.user), Q(log=True)).order_by('-start_time') # Load strings language to template mynextgames.html try: lang = strLang() except: lang = '' template = 'pc/lost-games.html' if request.mobile: template = 'mobile/lost-games.html' return render_to_response(template, { 'user_me': request.user, 'lang': lang, 'lostGames': lostGames, })
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from datetime import * import datetime # Create the info to show a box def setBox(status): box = {} lang = strLang() box['message'] = lang[status] if status.count("success"): box['status'] = 'success' elif status.count("error"): box['status'] = 'error' elif status.count("info"): box['status'] = 'info' elif status.count("warning"): box['status'] = 'warning' return box def strLang(): strng = {} ### CONTACT.HTML ### strng['title_contact_with_us'] = u"Contact Us" strng['success_contact_sent'] = u"Your request has been sent successfully! As soon as posible, our team reply you." strng['error_contact_empty_subject'] = u"Subject is required!" strng['error_contact_empty_message'] = u"Message is required!" strng['error_contact_empty_email'] = u"Email is required to reply you!" ### EDIT PROFILE AND CHANGE PASSWORD ### strng['label_change_avatar'] = u"Change current avatar" strng['help_change_avatar'] = u"Leave this field empty if you want to keep your current avatar" strng['label_current_password'] = u"Current password" strng['label_new_password'] = u"New password" strng['label_new_password2'] = u"Repeat new password" strng['title_edit_profile'] = u"Edit My Profile" strng['button_edit_profile'] = u"Update My Profile" strng['button_change_password'] = u"Update My Password" strng['error_change_password_differents'] = u"New password could not be different in both fields required." strng['error_change_password_empty_field'] = u"This is field is required." strng['error_current_password_incorrect'] = u"Current password introduced is incorrect. Try again!" strng['success_edit_account'] = u"Your info has been updated successfully!" strng['success_change_password'] = u"Your password has been changed successfully!" ### GAMEINFO.HTML ### strng['vs'] = u"vs" strng['finished'] = u"Finished" strng['pending'] = u"Pending" strng['closed'] = u"Closed" strng['title_question_reviews'] = u"Question Reviews" strng['title_my_question_reviews'] = u"My Question Reviews" strng['error_title_game_no_exists'] = u"Oops!" strng['error_game_info'] = u"Sorry! You haven't got permission to see the info of this game." strng['error_game_no_exists'] = u"Sorry! The game selected doesn't exist in our database." strng['error_tournament_info_no_exists'] = u"Error! Tournament info doesn't exist in the system!" strng['error_no_tournament_score'] = u"Error! Tournament scores doesn't exist in the system!" strng['error_question_reviews_no_exists'] = u"Error! Don't exist question reviews!" strng['error_question_no_exists'] = u"Error! Question #ID selected doesn't exist! Try again!" ### LOADQUESTIONS.HTML ### strng['title_load_questions'] = u"Load File Questions" strng['button_load_questions'] = u"Load File" strng['success_load_questions'] = u"Questions loaded successfully!" ### LOGIN.HTML ### # Register an account strng['button_register'] = u"Register" strng['label_password2'] = u"Repeat password" strng['success_register_account'] = u"Your account has been successfully registered! Login now." strng['error_register_username_exists'] = u"Exists in our database. Choose other." strng['error_register_email_exists'] = u"Exists in our database. Choose other." strng['error_register_first_name_required'] = u"First name is required." strng['error_register_last_name_required'] = u"Last name is required." strng['error_register_passwords_differents'] = u"Password could not be different in both fields." strng['error_register_before_join_tournament'] = u"Before join to the Tournament selected, you have to register an account. It's free!" strng['error_register_before_show_tournament'] = u"Do you want to see all info about Tournaments? Only you have to register an account. It's free!" # Login an account strng['title_login'] = u"Are You Registered?" strng['button_login'] = u"Login" strng['button_recover_account'] = u"Forgot Password?" strng['error_login_password_required'] = u"Password is required." strng['error_login_username_required'] = u"Username is required." strng['error_login_failed'] = u"Login failed!" ### LOSTGAMES.HTML WONGAMES.HTML ### strng['title_lost_games'] = u"Lost Games" strng['title_won_games'] = u"Won Games" strng['table_date'] = u"DATE" strng['table_tournament'] = u"TOURNAMENT" strng['table_round'] = u"ROUND" strng['table_vs'] = u"VS" ### MYNEXTGAMES.HTML ### strng['title_my_next_games'] = u"My Next Games" strng['round'] = u"Round" strng['dates_times_play'] = u"Select all dates and time using ctrl+click that you have available to play" strng['error_no_next_games'] = u"Sorry! You haven't any game active now!" strng['error_datetime_selected_before'] = u"Sorry! One or more dates or times selected are past and you can't play a game in past times! No date and time has been saved. Try again selecting valid dates and times." date2hours = datetime.datetime.now() + timedelta(hours = 2) strng['error_datetime_selected_too_soon'] = u"Sorry! One or more times selected to play today are too soon. To facilitate that your opponent can see the game schedule, you can't select to play too soon. If you want to play today, choose any time that is about 2 hours from the current time. " + "<br />" + "<center>(<u>Select hours to play today from: " + str(date2hours.hour) + ":00h</u>)</center>" strng['success_datetime_selected'] = u"Date and times saved successfully! You can select more dates and times to play this game." strng['success_datetime_committed'] = u"Date and times saved successfully! Date and time of game has been set with the preferences of your oponent. Show details of game to see when you have to play this game." strng['datetime_selected_players'] = u"Date and time selected by players" strng['button_select_datetime'] = u"Save date and times to play" strng['button_delete_datetimes'] = u"Remove date(s)" ### MYQUESTIONREVIEWS.HTML ### strng['title_my_admin_question_reviews'] = u"My Tournament's Question Reviews" ### MYTOURNAMENTS.HTML ### strng['title_my_active_tournaments'] = u"My Active Tournaments" strng['title_my_active_admin_tournaments'] = u"My Active Admin Tournaments" strng['title_my_finished_tournaments'] = u" My Finished Tournaments" strng['tournament_categories'] = u"Categories selected" strng['tournament_start_date'] = u"Start date" strng['tournament_finish_date'] = u"Finish date" strng['error_no_active_tournaments'] = u"Sorry! You haven't any Tournament active now." strng['error_no_admin_active_tournaments'] = u"Sorry! You haven't any Tournament with admin permissions active now." strng['error_no_won_games'] = u"Sorry! You haven't won any Game." strng['error_no_lost_games'] = u"Sorry! You haven't lost any Game." ### NEWTOURNAMENT.HTML ### strng['title_new_tournament'] = u"Create New Tournament" strng['button_new_tournament'] = u"Create New Tournament" strng['success_create_new_tournament'] = u"Tournament created successfully!" strng['error_new_tournament_name_exists'] = u"Exists in our database. Choose other." ### NEWQUESTIONREVIEW.HTML ### strng['title_new_question_review'] = u"New Question Review" strng['label_question_id'] = u"Question #ID" strng['label_arguments'] = u"Your arguments" strng['button_new_question_review'] = u"Send Question Review" ### PLAY.HTML ### strng['title_play'] = u"Play Now With Webchat Freenode" ### PROFILE.HTML ### strng['title_profile_hi'] = u"Hi" strng['profile_last_login'] = u"Last login" ### QUESTIONREVIEW.HTML ### strng['title_question_reviews'] = u"Question Review" strng['warning_waiting_resolution'] = u"Waiting a resolution by admin" strng['arguments'] = u"Arguments" strng['resolution'] = u"Resolution" strng['button_save_question_review_resolution'] = u"Add resolution and close review" strng['error_question_review_no_exists'] = u"Sorry! This question review doesn't exists in our database!" strng['success_resolution'] = u"Your resolution has been saved successfully!" ### RECOVERUSER.HTML ### strng['label_recover_username'] = u"Write your username registered" strng['label_recover_email'] = u"Write your email registered" strng['title_recover_account'] = u"Recover Account" strng['title_recover_account_new_password'] = u"Change My Password" strng['button_recover_account'] = u"Recover Account" strng['button_recover_account_new_password'] = u"Set my new Password" strng['success_recover_account_email_sent'] = u"A message has been sent to verify your email and can recover your account." strng['error_recover_account'] = u"One or more errors. Try again" strng['error_unknown_code'] = u"ERROR! Code used to recover an account is wrong." strng['error_recover_user_unknown'] = u"This username doesn't exist in our database." strng['error_recover_email_unknown'] = u"This email doesn't exist in our database." strng['error_recover_user_email_differents'] = u"The username and password you enter do not match both for any user. Try again." ### TOURNAMENTINFO.HTML ### strng['title_info'] = u"Info" strng['title_table'] = u"Tournament Table" strng['title_tournament_games'] = u"Tournament Games" strng['number_rounds'] = u"Number of Rounds" strng['remember'] = u"Remember!" strng['joined_tournament'] = u"You joined to play this Tournament!" strng['button_join'] = u"Join to this Tournament Now" strng['warning_you_tournament_admin'] = u"You're the admin of this Tournament" strng['warning_only_admin'] = u"Only visible for admin tournament or admin system." strng['warning_only_players'] = u"Only visible for players." strng['error_you_tournament_admin'] = u"You're the admin of this Tournament" strng['error_tournament_no_games'] = u"Sorry! This Tournament hasn't any games!" ### TOURNAMENTS.HTML ### # Next Tournaments strng['success_join_tournament'] = u"You have been joined successfully!" strng['info_join_tournaments'] = u"We've seen that you haven't joined any Tournament. Do you want to play? Select one in <u>Next Tournaments</u> section!" strng['info_new_tournament'] = u"We've seen that you haven't joined any Tournament and you haven't create anyone. Create a Tournament in this section or join a Tournament to play in <u><a href='/tournaments'>Next Tournaments</a></u> section! " strng['error_join_tournament'] = u"Error! You can't join to this Tournament" strng['error_join_tournament_admin'] = u"Error! You can't join to this Tournament: admin's tournament can't play!" strng['error_join_tournament_joined'] = u"Error! You can't join to this Tournament: you have joined it before!" strng['error_join_tournament_expired'] = u"Error! You can't join to this Tournament: join period expired!" strng['error_tournament_no_exists'] = u"Error! Tournament selected doesn't exists!" strng['error_no_next_tournaments'] = u"Sorry! System hasn't got any next Tournament." strng['error_no_active_tournaments'] = u"Sorry! System hasn't got any active Tournament." strng['title_next_tournaments'] = u"Next Tournaments" strng['title_active_tournaments'] = u"Active Tournaments" strng['title_finished_tournaments'] = u"Last Finished Tournaments" strng['join'] = u"Join" strng['tournament_started_date'] = u"Started date" strng['tournament_finished_date'] = u"Finished date" ### SIDEBAR ### strng['title_sidebar_my_active_tournaments'] = u"My Active Tournaments" strng['title_sidebar_my_admin_tournaments'] = u"My Admin Tournaments" strng['title_sidebar_today_games'] = u"Today Games" strng['title_sidebar_next_games'] = u"Next Games" strng['committed'] = u"Committed!" strng['uncommitted'] = u"Uncommitted!" strng['error_sidebar_no_active_tournaments'] = u"No active tournaments." strng['error_sidebar_no_admin_active_tournaments'] = u"No admin active tournaments." return strng
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.mail import send_mail from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from quizbowl.models import Category, User from datetime import * import datetime # Sends and email to the user to notify an update in the Tournament def notify_user(user, case, instance): subject = "" message = "" from_email = "fleq.libresoft@gmail.com" to_email = user.email if case == 'new_tournament': tournament = instance subject += "Nuevo torneo" message += "Enhorabuena, " + user.username + ":\n\n" message += "El torneo '" + unicode(tournament) + "', en el que estabas inscrito, acaba de dar comienzo.\n" message += "Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener los detalles de la primera partida." message += "\n\n\n" elif case == 'time_commited': game = instance tournament = game.round.tournament subject += u"Confirmación fecha y hora de partida" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que, atendiendo a las preferencias de los jugadores, la partida de la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(tournament) + u"' a la que estás convocado se celebrará el día " + game.start_time.strftime("%d/%m/%Y") + " a las " + game.start_time.strftime("%H:%M%Z") + " horas.\n" message += u"Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'hurry_up': game = instance tournament = game.round.tournament subject += "Partida a punto de comenzar" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que la partida en la que participas perteneciente a la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(game.round.tournament) + u"' empezará en unos minutos (" + game.start_time.strftime("%H:%M%Z") + ")." message += "\n\n\n" elif case == 'new_review': question_review = instance tournament = question_review.game.round.tournament subject += u"Nueva revisión de pregunta" message += "Estimado " + user.username + ":\n\n" message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que el usuario " message += question_review.player.username + u" ha solicitado la revisión de una pregunta realizada en una de las partidas de dicho torneo.\n" message += u"Por favor, revisa tu perfil de usuario (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'review_closed': question_review = instance tournament = question_review.game.round.tournament subject += u"Revisión de pregunta atendida" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la revisión de pregunta que solicitaste en referencia a la partida de la ronda " message += str(question_review.game.round.round_number) + " del torneo '" + unicode(tournament) + "' ha sido resuelta.\n" message += u"Por favor, revisa los detalles de esa partida (http://pfc-jgonzalez.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'tournament_canceled': tournament = instance c = Category.objects.filter(tournament=tournament) subject += "Torneo cancelado" message += "Estimado " + user.username + ":\n\n" if user == tournament.admin: message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que este ha sido cancelado por ser " message += u"el número de participantes inferior al mínimo (2).\n\n" message += u"A continuación se detallan las características del torneo cancelado:\n\n" message += "\t- Nombre: " + unicode(tournament) + "\n" message += "\t- Fecha de comienzo: " + tournament.start_date.strftime("%d/%m/%Y") + "\n" message += u"\t- Número de rondas: " + str(tournament.rounds) + "\n" message += u"\t- Duración de cada ronda (días): " + str(tournament.days_per_round) + "\n" message += u"\t- Categoría(s): " for category in list(c): message += unicode(category) + ", " message = message[:-2] message += "\n\n\n" else: message += "Te informamos que el torneo '" + unicode(tournament) + "' al que estabas inscrito, ha sido cancelado. " message += u"Por favor, ponte en contacto con el administrador del torneo para obtener más información.\n" message += "Sentimos las molestias que hayamos podido ocasionarte." message += "\n\n\n" elif case == 'new_game': round = instance tournament = round.tournament subject += "Nueva ronda de partidas" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la ronda número " + str(round.round_number) + " del torneo '" + unicode(tournament) + "' ha dado comienzo.\n" message += u"Por favor, revisa tu perfil de jugador (http://pfc-jgonzalez.libresoft.es) para obtener los detalles de la partida que jugarás en esta ronda y elegir tu hora de preferencia." message += "\n\n\n" elif case == 'meditation_round': round = instance tournament = round.tournament subject = u"Ronda de reflexión" message += "Estimado " + user.username + ":\n\n" message += u"Debido a limitaciones relacionadas con la lógica del juego, te informamos que no podrás enfrentarte a ningún " message += "jugador durante la ronda " + str(round.round_number) + " del torneo '" + unicode(tournament) + u"' al que estás inscrito.\n" message += u"Como compensación, tu puntación en el torneo ha sido incrementada 1 punto, igual que si hubieses ganado la partida correspondiente a la ronda.\n\n" message += u"Sentimos las molestias que hayamos podido ocasionarte y deseamos que aproveches de la mejor manera posible esta ronda de reflexión." message += "\n\n\n" elif case == 'tournament_over': tournament = instance subject += "Torneo finalizado" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que el torneo '" + unicode(tournament) + "' ha finalizado.\n" message += u"Puedes consultar la tabla de clasificación de jugadores en la página del torneo (http://trivial.libresoft.es)." message += "\n\n\n" elif case == 'recover_user': recover = instance subject += u"Recuperación de cuenta de usuario" message += "Estimado " + user.username + ":\n\n" message += u"Has solicitado recuperar tu cuenta de usuario porque no recuerdas tu contraseña. Para hacerlo, accede a través del siguiente enlace:\n\n" message += "http://pfc-jgonzalez.libresoft.es/recover-account/" + recover.code + "\n\n" message += u"Desde él, podrás introducir una nueva contraseña que modificará a la que tenías anteriormente." message += "\n\n\n" message += "Atentamente,\n\n\tFLEQ (Free LibreSoft Educational Quizbowl)" send_mail(subject, message, from_email, [to_email]) log = "Date: " + str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S %Z")) + "\n" log += "Subject: " + subject + "\n" log += "To: " + to_email + "\n" log += "Message:\n" + message + "\n" log += "\n\n" if case != 'recover_user': tournament.mail_log += log tournament.save() def contactEmail(info): to_email = "fleq.libresoft@gmail.com" from_email = info['userEmail'] try: user = User.objects.get(email=info['userEmail']) except: user = "" # First, send an email to Administrator subject = "[FLEQ CONTACT FORM]" + " " + info['subject'] message = "----------- INFO USER -----------\n" if user: message += "User: " + user.username + "\n" message += "Name: " + unicode(user.first_name) + " " + unicode(user.last_name) + "\n" message += "Email contact: " + user.email + "\n" else: message += "User: anonymous" + "\n" message += "Email contact: " + info['userEmail'] + "\n" message += "----------- END INFO USER -----------\n\n" message += info['message'] send_mail(subject, message, from_email, [to_email]) # After that, send an email to User subject = "[FLEQ CONTACT SUCCESSFULL]" + " " + info['subject'] message = "Thanks for your message!\n\n" message += "Our team have received your request and soon will contact you with our reply. We'll try to be as fast as we can...\n\n" message += u"\tThanks to contact with FLEQ Project (Free LibreSoft Educational Quizbowl - http://pfc-jgonzalez.libresoft.es)." send_mail(subject, message, to_email, [from_email])
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.forms.widgets import CheckboxSelectMultiple from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt import datetime from quizbowl.models import Category, Question, Tournament, UserProfile from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * # Create sid of new Tournament import re import unicodedata class TournamentForm(ModelForm): class Meta: model = Tournament fields = ('name', 'categories', 'start_date', 'only_mobile_devices', 'days_per_round', 'rounds', 'optional_info') widgets = { 'start_date': SelectDateWidget(), 'categories': CheckboxSelectMultiple, } def clean_name(self): name = self.cleaned_data.get('name') try: tournament = Tournament.objects.get(name=name) except Tournament.DoesNotExist: return name raise forms.ValidationError(strLang()['error_new_tournament_name_exists']) def NewTournament(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/register') elif not request.user.is_superuser and not request.user.has_perm('quizbowl.add_tournament'): return HttpResponseRedirect('/my-tournaments') if request.user.has_perm('quizbowl.add_tournament'): admin_user = True else: admin_user = False # Load strings language to template newtournament.html try: lang = strLang() except: lang = '' # Info about user user_me = UserProfile.objects.get(user=request.user) if request.method == 'POST': # If the form has been submitted... form = TournamentForm(request.POST) # A form bound to the POST data if form.is_valid(): t = form.save() t.admin = request.user # Generate sid name sid = t.name.lower() sid = sid.replace(" ", "") # Remove accents sid = ''.join((c for c in unicodedata.normalize('NFD', sid) if unicodedata.category(c) != 'Mn')) # Remove special chars sid = re.sub(r"\W+", "", sid) # Check if this sid exists or similars ts = Tournament.objects.filter(sid__startswith=sid) if len(ts) > 0: sid = sid + '-' + str(len(ts)) t.sid = sid t.finish_date = t.start_date + datetime.timedelta((t.rounds * t.days_per_round) -1) t.save() return HttpResponseRedirect('/next-tournaments') else: return render_to_response('pc/new-tournament.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) else: form = TournamentForm(initial={'start_date': (datetime.date.today() + datetime.timedelta(days=1))}) return render_to_response('pc/new-tournament.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) class LoadQuestionsForm(forms.Form): questions_file = forms.FileField() # Function called by loadQuestions(request) that extracts and saves all questions received in a file def loadQuestionsFile(questionsFile): count = 0 for line in questionsFile: fields = line.rstrip('\n').split(';') fields = fields[:-1] # ommits the last empty string q = Question(use_phonetic = 0, question = fields[1], answer = fields[2]) try: q.alt_answer1 = fields[3] q.alt_answer2 = fields[4] q.alt_answer3 = fields[5] except IndexError: # none or not all alt_answers were provided pass try: q.save() count = count + 1 print str(count) + " " + line except db.utils.IntegrityError: # question already exists q = Question.objects.get(question = fields[1]) for category in fields[0].split(','): category = category.lower() try: c = Category.objects.get(name = category) except Category.DoesNotExist: c = Category(name = category) c.save() q.categories.add(c) q.save() # Handle files loaded in admin panel to save them in the system #@csrf_exempt def LoadQuestions(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') if not request.user.is_superuser: return HttpResponseRedirect('/') # Load strings language to template loadquestions.html try: lang = strLang() except: lang = '' if request.method == 'POST': print "POST" form = LoadQuestionsForm(request.POST, request.FILES) # Load strings language to template loadquestions.html if form.is_valid(): loadQuestionsFile(request.FILES['questions_file']) return HttpResponseRedirect('/load-questions?status=success_load_questions') else: return render_to_response('pc/load-questions.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) else: # Must we show a notification user? try: if request.GET['status']: box = setBox(request.GET['status']) return render_to_response('pc/load-questions.html', { 'box': box, 'user_me': request.user, 'lang': lang, }) except: box = '' form = LoadQuestionsForm() return render_to_response('pc/load-questions.html', { 'form': form, 'box': box, 'user_me': request.user, 'lang': lang, })
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.http import HttpResponse from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.models import UserProfile, RecoverUser from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * from quizbowl.views_notify import notify_user def Welcome(request): if request.mobile: return render_to_response('mobile/welcome.html', {}) return render_to_response('pc/welcome.html', {}) # Login to the app def Home(request): if request.user.is_authenticated(): nextGames = len(Game.objects.filter(Q(log = False), Q(start_time__gte = datetime.datetime.now()), Q(player1 = request.user) | Q(player2 = request.user))) wonGames = len(Game.objects.filter(Q(winner = request.user), Q(log=True))) lostGames = len(Game.objects.filter(Q(player1 = request.user) | Q(player2 = request.user), ~Q(winner = request.user), Q(log=True))) myTournaments = len(Tournament.objects.filter(players = request.user)) activeTournaments = len(Tournament.objects.filter(start_date__lte = datetime.date.today(), finish_date__gte = datetime.date.today())) nextTournaments = len(Tournament.objects.filter(start_date__gt = datetime.date.today())) finishedTournaments = len(Tournament.objects.filter(finish_date__lt = datetime.datetime.now())) if request.mobile: return render_to_response('mobile/home.html', { 'nextGames': nextGames, 'wonGames': wonGames, 'lostGames': lostGames, 'myTournaments': myTournaments, 'activeTournaments': activeTournaments, 'nextTournaments': nextTournaments, 'finishedTournaments': finishedTournaments, }) return HttpResponseRedirect("/next-games") else: # Load strings language to template login.html try: lang = strLang() except: lang = '' if request.method == 'POST': loginForm = LoginForm(request.POST) if loginForm.is_valid(): user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) if request.mobile: return render_to_response('mobile/home.html', {}) else: return HttpResponseRedirect('/next-games') else: registerForm = RegisterForm() template = 'pc/splash.html' if request.mobile: template = 'mobile/login.html' return render_to_response(template, { 'loginForm': loginForm, 'lang': lang, }) else: if request.mobile: return render_to_response('mobile/login.html', {}) return render_to_response('pc/splash.html', {}) def Logout(request): logout(request) if request.mobile: return render_to_response('mobile/login.html', {}) return HttpResponseRedirect("/") def Signin(request): try: lang = strLang() except: lang = '' if request.method == 'POST': registerForm = RegisterForm(request.POST) if registerForm.is_valid(): user = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password']) user.is_staff = False user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] userProfile = UserProfile(user=user) user.save() userProfile.save() user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) if request.mobile: return render_to_response('mobile/welcome.html', {}) return render_to_response('pc/welcome.html', { 'user': request.user }) else: template = 'pc/signin.html' if request.mobile: template = 'mobile/signin.html' return render_to_response(template, { 'user_me': request.user, 'registerForm': registerForm, 'lang': lang, }) else: registerForm = RegisterForm() template = 'pc/signin.html' if request.mobile: template = 'mobile/signin.html' return render_to_response(template, { 'user_me': request.user, 'registerForm': registerForm, 'lang': lang, }) class RegisterForm(forms.Form): username = forms.CharField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(),max_length=100) password2 = forms.CharField(widget=forms.PasswordInput(),max_length=100,label=(strLang()['label_password2'])) email = forms.EmailField(max_length=100) def clean_username(self): username = self.cleaned_data.get('username') try: user = User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(strLang()['error_register_username_exists']) def clean_email(self): email = self.cleaned_data.get('email') try: email = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(strLang()['error_register_email_exists']) def clean_first_name(self): first_name = self.cleaned_data.get('first_name') if not first_name: raise forms.ValidationError(strLang()['error_register_first_name_required']) return first_name def clean_last_name(self): last_name = self.cleaned_data.get('last_name') if not last_name: raise forms.ValidationError(strLang()['error_register_last_name_required']) return last_name def clean(self): cleaned_data = super(RegisterForm, self).clean() password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password != password2: self._errors["password"] = self.error_class([strLang()['error_register_passwords_differents']]) self._errors["password2"] = self.error_class([strLang()['error_register_passwords_differents']]) return cleaned_data class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(),max_length=100) def clean_password(self): password = self.cleaned_data.get('password') if not password: raise forms.ValidationError(strLang()['error_login_password_required']) return password def clean_username(self): username = self.cleaned_data.get('username') if not username: raise forms.ValidationError(strLang()['error_login_username_required']) return username def clean(self): cleaned_data = super(LoginForm, self).clean() username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: if not user.is_active: raise forms.ValidationError(strLang()['error_login_failed']) else: raise forms.ValidationError(strLang()['error_login_failed']) return cleaned_data
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib import admin from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, RecoverUser, Round, Score, Tournament, UserProfile class CategoryAdmin(admin.ModelAdmin): list_display = ('pk', 'name') fields = ['name'] class DateTimeAdmin(admin.ModelAdmin): list_display = ('pk', 'date_time', 'preferred_start_time') fields = ['date_time', 'preferred_start_time'] class GameAdmin(admin.ModelAdmin): list_display = ('pk', 'start_time', 'start_time_committed', 'player1', 'player2', 'score_player1', 'score_player2', 'winner', 'round') #readonly_fields=('pk', 'log') fields = ['start_time', 'start_time_committed', 'player1', 'player2', 'score_player1', 'score_player2', 'winner', 'round', 'log'] class PreferredStartTimeAdmin(admin.ModelAdmin): list_display = ('pk', 'committed', 'game', 'player') fields = ['committed', 'game', 'player'] class QuestionAdmin(admin.ModelAdmin): list_display = ('pk', 'question', 'answer', 'alt_answer1', 'alt_answer2', 'alt_answer3', 'use_phonetic') list_filter = ['question', 'answer', 'alt_answer1', 'alt_answer2', 'alt_answer3', 'use_phonetic'] class RecoverUserAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'code') list_filter = ['user', 'code'] class TournamentAdmin(admin.ModelAdmin): list_display = ('pk', 'sid', 'name', 'start_date', 'finish_date', 'admin', 'optional_info') list_filter = ['sid', 'name', 'start_date', 'finish_date', 'admin', 'optional_info'] class UserProfileAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'winner_games', 'loser_games', 'avatar') fields = ['user', 'winner_games', 'loser_games', 'avatar'] admin.site.register(Category, CategoryAdmin) admin.site.register(Date_time, DateTimeAdmin) admin.site.register(Game, GameAdmin) admin.site.register(Preferred_start_time, PreferredStartTimeAdmin) admin.site.register(Question, QuestionAdmin) admin.site.register(UserProfile, UserProfileAdmin) admin.site.register(Question_review) admin.site.register(RecoverUser, RecoverUserAdmin) admin.site.register(Round) admin.site.register(Score) admin.site.register(Tournament, TournamentAdmin)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core.files import File from django.core.mail import send_mail from django.db.models import Q from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, Round, Score, Tournament from datetime import * from quizbowl.views_notify import notify_user import datetime import os import sys def myTodayGames(request): dateNow = datetime.datetime.now().date() timeNow = datetime.datetime.now().time() # Check if I have to play today a game myNextGames = Game.objects.filter(Q(log__isnull = False), Q(start_time__gte = dateNow), Q(player1 = request.user) | Q(player2 = request.user)).order_by('-start_time') todayGames = [] for game in myNextGames: if game.start_time.date() == dateNow and game.start_time.time() > timeNow: todayGames.append(game) return todayGames def myNextGames(request): dateNow = datetime.datetime.now().date() timeNow = datetime.datetime.now().time() # Check if I have to play today a game myNextGames = Game.objects.filter(Q(log__isnull = False), Q(start_time__gte = dateNow), Q(player1 = request.user) | Q(player2 = request.user)).order_by('-start_time') nextGames = [] for game in myNextGames: if game.start_time.date() > dateNow: nextGames.append(game) return nextGames # Shows active Tournaments of user (player tournament) def myActiveTournaments(request): # Select all Tournaments and Games of user with status player dateNow = datetime.datetime.now() myActiveTournaments = Tournament.objects.filter(players = request.user).filter(Q(finish_date__gte = dateNow)).order_by('-start_date') return myActiveTournaments # Shows active admin Tournaments of user def myAdminTournaments(request): # Select all Tournaments and Games of user with status player dateNow = datetime.datetime.now() myActiveAdminTournaments = Tournament.objects.filter(admin = request.user).filter(Q(finish_date__gte = dateNow)).order_by('-start_date') return myActiveAdminTournaments def myPastTournaments(request): # Select all Tournaments finished dateNow = datetime.datetime.now() myFinishedTournaments = Tournament.objects.filter(Q(players = request.user)).filter(finish_date__lt = dateNow).order_by('-start_date') return myFinishedTournaments def myAdminPendingQuestionReviews(user): # Pending Question Reviews allMyAdminTournaments = Tournament.objects.filter(admin = user) pendingQuestionReviews = 0 # All reviews in my Tournaments for tournament in allMyAdminTournaments: questionReviews = Question_review.objects.filter(game__round__tournament = tournament, resolution__exact = '') pendingQuestionReviews += len(questionReviews) allMyTournaments = Tournament.objects.filter(Q(players = user)) # All reviews in my Tournaments for tournament in allMyTournaments: questionReviews = Question_review.objects.filter(game__round__tournament = tournament, resolution__exact = '', player = user) pendingQuestionReviews += len(questionReviews) return pendingQuestionReviews
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models import datetime def validate_future_date(date): if date <= datetime.date.today(): raise ValidationError("Only future dates are allowed") class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.name class Date_time(models.Model): date_time = models.DateTimeField() preferred_start_time = models.ForeignKey("Preferred_start_time") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return unicode(self.date_time) class Game(models.Model): start_time = models.DateTimeField('Start date and time') start_time_committed = models.BooleanField(default=False) log = models.BooleanField(default=False) player1 = models.ForeignKey(User, related_name='Player 1') score_player1 = models.PositiveIntegerField() player2 = models.ForeignKey(User, related_name='Player 2') score_player2 = models.PositiveIntegerField() winner = models.ForeignKey(User, related_name='Winner') round = models.ForeignKey("Round") # referenced model name between quotations marks ("") to avoid previous declaration requirement def is_over(self): if self.log: return True else: return False def __unicode__(self): return "Tournament '%s' - Round %s - %s vs %s" % (unicode(self.round.tournament), self.round.round_number, self.player1, self.player2) class Preferred_start_time(models.Model): committed = models.BooleanField(default=False) game = models.ForeignKey(Game) player = models.ForeignKey(User) def __unicode__(self): return "%s - %s" % (unicode(self.game), self.player) class Question(models.Model): alt_answer1 = models.CharField(max_length=120, blank=True, help_text="(optional)") alt_answer2 = models.CharField(max_length=120, blank=True, help_text="(optional)") alt_answer3 = models.CharField(max_length=120, blank=True, help_text="(optional)") answer = models.CharField(max_length=120) question = models.CharField(max_length=200, unique=True) use_phonetic = models.BooleanField(default=False, editable=False) categories = models.ManyToManyField(Category) def __unicode__(self): return self.question class Question_review(models.Model): arguments = models.TextField() resolution = models.TextField(blank=True) game = models.ForeignKey(Game) player = models.ForeignKey(User) question = models.ForeignKey(Question) def is_closed(self): if self.resolution: return True else: return False def __unicode__(self): return "%s - %s" % (unicode(self.question), unicode(self.game)) class RecoverUser(models.Model): user = models.ForeignKey(User) code = models.CharField(max_length=16, unique=True) class Round(models.Model): round_number = models.PositiveIntegerField() start_date = models.DateField('start date') finish_date = models.DateField('finish date') tournament = models.ForeignKey("Tournament") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return "%s - round %s" % (unicode(self.tournament), self.round_number) class Score(models.Model): points = models.PositiveIntegerField(default=0) questions_won = models.PositiveIntegerField(default=0) questions_lost = models.PositiveIntegerField(default=0) player = models.ForeignKey(User) tournament = models.ForeignKey("Tournament") # referenced model name between quotations marks ("") to avoid previous declaration requirement def __unicode__(self): return "%s - %s" % (self.player, unicode(self.tournament)) class Tournament(models.Model): ROUNDS_CHOICES = ( (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), ) DAYS_PER_ROUND_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), ) sid = models.CharField(max_length=128) days_per_round = models.PositiveIntegerField(choices=DAYS_PER_ROUND_CHOICES) name = models.CharField(max_length=50, unique=True) rounds = models.PositiveIntegerField(choices=ROUNDS_CHOICES) start_date = models.DateField('start date', default=(datetime.datetime.today() + datetime.timedelta(days=10))) finish_date = models.DateField('finish date', default="2012-10-10") mail_log = models.TextField(blank=True, editable=False) admin = models.ForeignKey(User, related_name='admin', default=1) categories = models.ManyToManyField(Category) players = models.ManyToManyField(User, blank=True) optional_info = models.TextField(blank=True) only_mobile_devices = models.BooleanField(default=False) def __unicode__(self): return self.name class UserProfile(models.Model): avatar = models.ImageField(upload_to='images/avatars/', default='images/avatars/default.png') user = models.ForeignKey(User) winner_games = models.PositiveIntegerField(default=0) loser_games = models.PositiveIntegerField(default=0)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.views_language import strLang, setBox import datetime from quizbowl.models import Date_time, Game, Preferred_start_time, Question_review, Round, Score, Tournament, Question, UserProfile def MyTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') dateNow = datetime.datetime.now() myTournaments = Tournament.objects.filter(players = request.user).order_by('-start_date') tournamentCategories = [] for t in myTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/my-tournaments.html' if request.mobile: template = 'pc/my-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'myTournaments': myTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def ActiveTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') activeTournaments = Tournament.objects.filter(start_date__lte = datetime.date.today(), finish_date__gte = datetime.date.today()).order_by('-start_date') tournamentCategories = [] for t in activeTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/active-tournaments.html' if request.mobile: template = 'mobile/active-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'activeTournaments': activeTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def NextTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') nextTournaments = Tournament.objects.filter(start_date__gt = datetime.date.today()) tournamentCategories = [] for t in nextTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/next-tournaments.html' if request.mobile: template = 'mobile/next-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'nextTournaments': nextTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def FinishedTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') finishedTournaments = Tournament.objects.filter(finish_date__lt = datetime.datetime.now()).order_by('-start_date') tournamentCategories = [] for t in finishedTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/finished-tournaments.html' if request.mobile: template = 'mobile/finished-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'finishedTournaments': finishedTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def TournamentStatistics(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') tournament = Tournament.objects.get(id=gid) rounds = Round.objects.filter(tournament = tournament).order_by('round_number') # Generate Score Table by this Tournament allscores = Score.objects.filter(tournament=tournament).order_by('-points', '-questions_won', 'questions_lost', 'player') scores = [] pos = 0 for userScore in allscores: userProfile = UserProfile.objects.get(user=userScore.player) user = {} user['profile'] = userProfile user['score'] = userScore.points # Create tournament positions if pos == 0: user['pos'] = pos+1 else: if scores[pos-1]['score'] == userScore.points: user['pos'] = scores[pos-1]['pos'] else: user['pos'] = pos+1 # Initializing vars for question stats user['winner_questions'] = userScore.questions_won user['loser_questions'] = userScore.questions_lost user['winner_games'] = 0 user['loser_games'] = 0 # For each user, calculate how many games did he play gamesUser = [] for r in rounds: game = Game.objects.filter(Q(round = r), Q(player1 = userProfile.user) | Q(player2 = userProfile.user), Q(log=True)) try: #if game[0] and game[0].log: if game[0]: gamesUser.append(game) # Total points won and lost try: if game[0].winner != userScore.player and game[0].winner.username != "jgonzalez": print "LOST" user['loser_games'] += 1 elif game[0].winner.username == "FLEQBOT": user['loser_games'] += 1 elif game[0].winner == userScore.player: user['winner_games'] += 1 except: continue except: continue user['reflection_days'] = user['score'] - user['winner_games'] user['total_games'] = user['loser_games'] + user['winner_games'] # Save user stats and increment counter var scores.append(user) pos += 1 rounds = Round.objects.filter(tournament=tournament) games = Game.objects.all() join = False disjoin = False if not (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): join = True elif (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): disjoin = True # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/tournament-statistics.html' if request.mobile: template = 'mobile/tournament-statistics.html' return render_to_response(template, { 'user_me': request.user, 'tournament': tournament, 'join': join, 'disjoin': disjoin, 'scores': scores, 'rounds': rounds, 'games': games, 'lang': lang, }) def JoinTournament(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') try: tournament = Tournament.objects.get(pk=gid) except: return HttpResponseRedirect('/') # players are added automatically to not started tournament the first time they visit tournament's site if (request.user != tournament.admin) and (not request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): tournament.players.add(request.user) tournament.save() s = Score(player = request.user, tournament = tournament) s.save() return HttpResponseRedirect('/tournament/' + gid) else: return HttpResponseRedirect('/tournament/' + gid) def DisjoinTournament(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') try: tournament = Tournament.objects.get(pk=gid) except: return HttpResponseRedirect('/') # players are added automatically to not started tournament the first time they visit tournament's site if (request.user != tournament.admin) and (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): tournament.players.remove(request.user) tournament.save() Score.objects.get(player=request.user, tournament=tournament).delete() return HttpResponseRedirect('/tournament/' + gid) else: return HttpResponseRedirect('/tournament/' + gid)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.http import HttpResponse from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.models import UserProfile, RecoverUser from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * from quizbowl.views_notify import notify_user def Welcome(request): if request.mobile: return render_to_response('mobile/welcome.html', {}) return render_to_response('pc/welcome.html', {}) # Login to the app def Home(request): if request.user.is_authenticated(): nextGames = len(Game.objects.filter(Q(log = False), Q(start_time__gte = datetime.datetime.now()), Q(player1 = request.user) | Q(player2 = request.user))) wonGames = len(Game.objects.filter(Q(winner = request.user), Q(log=True))) lostGames = len(Game.objects.filter(Q(player1 = request.user) | Q(player2 = request.user), ~Q(winner = request.user), Q(log=True))) myTournaments = len(Tournament.objects.filter(players = request.user)) activeTournaments = len(Tournament.objects.filter(start_date__lte = datetime.date.today(), finish_date__gte = datetime.date.today())) nextTournaments = len(Tournament.objects.filter(start_date__gt = datetime.date.today())) finishedTournaments = len(Tournament.objects.filter(finish_date__lt = datetime.datetime.now())) if request.mobile: return render_to_response('mobile/home.html', { 'nextGames': nextGames, 'wonGames': wonGames, 'lostGames': lostGames, 'myTournaments': myTournaments, 'activeTournaments': activeTournaments, 'nextTournaments': nextTournaments, 'finishedTournaments': finishedTournaments, }) return HttpResponseRedirect("/next-games") else: # Load strings language to template login.html try: lang = strLang() except: lang = '' if request.method == 'POST': loginForm = LoginForm(request.POST) if loginForm.is_valid(): user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) if request.mobile: return render_to_response('mobile/home.html', {}) else: return HttpResponseRedirect('/next-games') else: registerForm = RegisterForm() template = 'pc/splash.html' if request.mobile: template = 'mobile/login.html' return render_to_response(template, { 'loginForm': loginForm, 'lang': lang, }) else: if request.mobile: return render_to_response('mobile/login.html', {}) return render_to_response('pc/splash.html', {}) def Logout(request): logout(request) if request.mobile: return render_to_response('mobile/login.html', {}) return HttpResponseRedirect("/") def Signin(request): try: lang = strLang() except: lang = '' if request.method == 'POST': registerForm = RegisterForm(request.POST) if registerForm.is_valid(): user = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password']) user.is_staff = False user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] userProfile = UserProfile(user=user) user.save() userProfile.save() user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) if request.mobile: return render_to_response('mobile/welcome.html', {}) return render_to_response('pc/welcome.html', { 'user': request.user }) else: template = 'pc/signin.html' if request.mobile: template = 'mobile/signin.html' return render_to_response(template, { 'user_me': request.user, 'registerForm': registerForm, 'lang': lang, }) else: registerForm = RegisterForm() template = 'pc/signin.html' if request.mobile: template = 'mobile/signin.html' return render_to_response(template, { 'user_me': request.user, 'registerForm': registerForm, 'lang': lang, }) class RegisterForm(forms.Form): username = forms.CharField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(),max_length=100) password2 = forms.CharField(widget=forms.PasswordInput(),max_length=100,label=(strLang()['label_password2'])) email = forms.EmailField(max_length=100) def clean_username(self): username = self.cleaned_data.get('username') try: user = User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(strLang()['error_register_username_exists']) def clean_email(self): email = self.cleaned_data.get('email') try: email = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(strLang()['error_register_email_exists']) def clean_first_name(self): first_name = self.cleaned_data.get('first_name') if not first_name: raise forms.ValidationError(strLang()['error_register_first_name_required']) return first_name def clean_last_name(self): last_name = self.cleaned_data.get('last_name') if not last_name: raise forms.ValidationError(strLang()['error_register_last_name_required']) return last_name def clean(self): cleaned_data = super(RegisterForm, self).clean() password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password != password2: self._errors["password"] = self.error_class([strLang()['error_register_passwords_differents']]) self._errors["password2"] = self.error_class([strLang()['error_register_passwords_differents']]) return cleaned_data class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(),max_length=100) def clean_password(self): password = self.cleaned_data.get('password') if not password: raise forms.ValidationError(strLang()['error_login_password_required']) return password def clean_username(self): username = self.cleaned_data.get('username') if not username: raise forms.ValidationError(strLang()['error_login_username_required']) return username def clean(self): cleaned_data = super(LoginForm, self).clean() username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: if not user.is_active: raise forms.ValidationError(strLang()['error_login_failed']) else: raise forms.ValidationError(strLang()['error_login_failed']) return cleaned_data
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.conf import settings from quizbowl.views_language import strLang, setBox import datetime from quizbowl.models import Date_time, Game, Preferred_start_time, Question_review, Round, Score, Tournament, Question, UserProfile def MyTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') dateNow = datetime.datetime.now() myTournaments = Tournament.objects.filter(players = request.user).order_by('-start_date') tournamentCategories = [] for t in myTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/my-tournaments.html' if request.mobile: template = 'pc/my-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'myTournaments': myTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def ActiveTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') activeTournaments = Tournament.objects.filter(start_date__lte = datetime.date.today(), finish_date__gte = datetime.date.today()).order_by('-start_date') tournamentCategories = [] for t in activeTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/active-tournaments.html' if request.mobile: template = 'mobile/active-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'activeTournaments': activeTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def NextTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') nextTournaments = Tournament.objects.filter(start_date__gt = datetime.date.today()) tournamentCategories = [] for t in nextTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/next-tournaments.html' if request.mobile: template = 'mobile/next-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'nextTournaments': nextTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def FinishedTournaments(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') finishedTournaments = Tournament.objects.filter(finish_date__lt = datetime.datetime.now()).order_by('-start_date') tournamentCategories = [] for t in finishedTournaments: categories = t.categories.all() c = {} c['tid'] = t.pk c['categories'] = categories tournamentCategories.append(c) # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/finished-tournaments.html' if request.mobile: template = 'mobile/finished-tournaments.html' return render_to_response(template, { 'user_me': request.user, 'finishedTournaments': finishedTournaments, 'tournamentCategories': tournamentCategories, 'lang': lang, }) def TournamentStatistics(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') tournament = Tournament.objects.get(id=gid) rounds = Round.objects.filter(tournament = tournament).order_by('round_number') # Generate Score Table by this Tournament allscores = Score.objects.filter(tournament=tournament).order_by('-points', '-questions_won', 'questions_lost', 'player') scores = [] pos = 0 for userScore in allscores: userProfile = UserProfile.objects.get(user=userScore.player) user = {} user['profile'] = userProfile user['score'] = userScore.points # Create tournament positions if pos == 0: user['pos'] = pos+1 else: if scores[pos-1]['score'] == userScore.points: user['pos'] = scores[pos-1]['pos'] else: user['pos'] = pos+1 # Initializing vars for question stats user['winner_questions'] = userScore.questions_won user['loser_questions'] = userScore.questions_lost user['winner_games'] = 0 user['loser_games'] = 0 # For each user, calculate how many games did he play gamesUser = [] for r in rounds: game = Game.objects.filter(Q(round = r), Q(player1 = userProfile.user) | Q(player2 = userProfile.user), Q(log=True)) try: #if game[0] and game[0].log: if game[0]: gamesUser.append(game) # Total points won and lost try: if game[0].winner != userScore.player and game[0].winner.username != "jgonzalez": print "LOST" user['loser_games'] += 1 elif game[0].winner.username == "FLEQBOT": user['loser_games'] += 1 elif game[0].winner == userScore.player: user['winner_games'] += 1 except: continue except: continue user['reflection_days'] = user['score'] - user['winner_games'] user['total_games'] = user['loser_games'] + user['winner_games'] # Save user stats and increment counter var scores.append(user) pos += 1 rounds = Round.objects.filter(tournament=tournament) games = Game.objects.all() join = False disjoin = False if not (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): join = True elif (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): disjoin = True # Load strings language to template mytournaments.html try: lang = strLang() except: lang = '' template = 'pc/tournament-statistics.html' if request.mobile: template = 'mobile/tournament-statistics.html' return render_to_response(template, { 'user_me': request.user, 'tournament': tournament, 'join': join, 'disjoin': disjoin, 'scores': scores, 'rounds': rounds, 'games': games, 'lang': lang, }) def JoinTournament(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') try: tournament = Tournament.objects.get(pk=gid) except: return HttpResponseRedirect('/') # players are added automatically to not started tournament the first time they visit tournament's site if (request.user != tournament.admin) and (not request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): tournament.players.add(request.user) tournament.save() s = Score(player = request.user, tournament = tournament) s.save() return HttpResponseRedirect('/tournament/' + gid) else: return HttpResponseRedirect('/tournament/' + gid) def DisjoinTournament(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/') try: tournament = Tournament.objects.get(pk=gid) except: return HttpResponseRedirect('/') # players are added automatically to not started tournament the first time they visit tournament's site if (request.user != tournament.admin) and (request.user in tournament.players.all()) and (datetime.date.today() < tournament.start_date): tournament.players.remove(request.user) tournament.save() Score.objects.get(player=request.user, tournament=tournament).delete() return HttpResponseRedirect('/tournament/' + gid) else: return HttpResponseRedirect('/tournament/' + gid)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.forms.widgets import CheckboxSelectMultiple from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt import datetime from quizbowl.models import Category, Question, Tournament, UserProfile from quizbowl.views_language import strLang, setBox from quizbowl.views_tournaments_api import * # Create sid of new Tournament import re import unicodedata class TournamentForm(ModelForm): class Meta: model = Tournament fields = ('name', 'categories', 'start_date', 'only_mobile_devices', 'days_per_round', 'rounds', 'optional_info') widgets = { 'start_date': SelectDateWidget(), 'categories': CheckboxSelectMultiple, } def clean_name(self): name = self.cleaned_data.get('name') try: tournament = Tournament.objects.get(name=name) except Tournament.DoesNotExist: return name raise forms.ValidationError(strLang()['error_new_tournament_name_exists']) def NewTournament(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/register') elif not request.user.is_superuser and not request.user.has_perm('quizbowl.add_tournament'): return HttpResponseRedirect('/my-tournaments') if request.user.has_perm('quizbowl.add_tournament'): admin_user = True else: admin_user = False # Load strings language to template newtournament.html try: lang = strLang() except: lang = '' # Info about user user_me = UserProfile.objects.get(user=request.user) if request.method == 'POST': # If the form has been submitted... form = TournamentForm(request.POST) # A form bound to the POST data if form.is_valid(): t = form.save() t.admin = request.user # Generate sid name sid = t.name.lower() sid = sid.replace(" ", "") # Remove accents sid = ''.join((c for c in unicodedata.normalize('NFD', sid) if unicodedata.category(c) != 'Mn')) # Remove special chars sid = re.sub(r"\W+", "", sid) # Check if this sid exists or similars ts = Tournament.objects.filter(sid__startswith=sid) if len(ts) > 0: sid = sid + '-' + str(len(ts)) t.sid = sid t.finish_date = t.start_date + datetime.timedelta((t.rounds * t.days_per_round) -1) t.save() return HttpResponseRedirect('/next-tournaments') else: return render_to_response('pc/new-tournament.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) else: form = TournamentForm(initial={'start_date': (datetime.date.today() + datetime.timedelta(days=1))}) return render_to_response('pc/new-tournament.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) class LoadQuestionsForm(forms.Form): questions_file = forms.FileField() # Function called by loadQuestions(request) that extracts and saves all questions received in a file def loadQuestionsFile(questionsFile): count = 0 for line in questionsFile: fields = line.rstrip('\n').split(';') fields = fields[:-1] # ommits the last empty string q = Question(use_phonetic = 0, question = fields[1], answer = fields[2]) try: q.alt_answer1 = fields[3] q.alt_answer2 = fields[4] q.alt_answer3 = fields[5] except IndexError: # none or not all alt_answers were provided pass try: q.save() count = count + 1 print str(count) + " " + line except db.utils.IntegrityError: # question already exists q = Question.objects.get(question = fields[1]) for category in fields[0].split(','): category = category.lower() try: c = Category.objects.get(name = category) except Category.DoesNotExist: c = Category(name = category) c.save() q.categories.add(c) q.save() # Handle files loaded in admin panel to save them in the system #@csrf_exempt def LoadQuestions(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') if not request.user.is_superuser: return HttpResponseRedirect('/') # Load strings language to template loadquestions.html try: lang = strLang() except: lang = '' if request.method == 'POST': print "POST" form = LoadQuestionsForm(request.POST, request.FILES) # Load strings language to template loadquestions.html if form.is_valid(): loadQuestionsFile(request.FILES['questions_file']) return HttpResponseRedirect('/load-questions?status=success_load_questions') else: return render_to_response('pc/load-questions.html', { 'user_me': request.user, 'form': form, 'lang': lang, }) else: # Must we show a notification user? try: if request.GET['status']: box = setBox(request.GET['status']) return render_to_response('pc/load-questions.html', { 'box': box, 'user_me': request.user, 'lang': lang, }) except: box = '' form = LoadQuestionsForm() return render_to_response('pc/load-questions.html', { 'form': form, 'box': box, 'user_me': request.user, 'lang': lang, })
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django import db, forms from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core.files import File from django.core.mail import send_mail from django.db.models import Q from django.forms import ModelForm from django.forms.extras.widgets import SelectDateWidget from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, Round, Score, Tournament import datetime import os import sys class Date_timeForm(forms.Form): TIME_CHOICES = ( (10, '10:00'), (16, '16:00'), (22, '22:00'), ) times = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(), choices=TIME_CHOICES, label="Choose one start time at least:") class NewQuestion_reviewForm(forms.Form): question_number = forms.IntegerField() arguments = forms.CharField(widget=forms.Textarea) class Question_reviewForm(ModelForm): class Meta: model = Question_review fields = ('game', 'question', 'arguments', 'resolution') class UserForm(ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') widgets = { 'password': forms.PasswordInput(), } def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user def validate_password(value): if value != "el campo password": raise ValidationError(u"Las contraseñas introducidas no coinciden") # Sends and email to the user to notify an update in the Tournament def notify_user(user, case, instance): subject = "" message = "" from_email = "fleqproject@gmail.com" to_email = user.email if case == 'new_tournament': tournament = instance subject += "Nuevo torneo" message += "Enhorabuena, " + user.username + ":\n\n" message += "El torneo '" + unicode(tournament) + "', en el que estabas inscrito, acaba de dar comienzo.\n" message += "Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener los detalles de la primera partida." message += "\n\n\n" elif case == 'time_commited': game = instance tournament = game.round.tournament subject += u"Confirmación fecha y hora de partida" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que, atendiendo a las preferencias de los jugadores, la partida de la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(tournament) + u"' a la que estás convocado se celebrará el día " + game.start_time.strftime("%d/%m/%Y") + " a las " + game.start_time.strftime("%H:%M%Z") + " horas.\n" message += u"Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'hurry_up': game = instance tournament = game.round.tournament subject += "Partida a punto de comenzar" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que la partida en la que participas perteneciente a la ronda " + str(game.round.round_number) message += " del torneo '" + unicode(game.round.tournament) + u"' empezará en unos minutos (" + game.start_time.strftime("%H:%M%Z") + ")." message += "\n\n\n" elif case == 'new_review': question_review = instance tournament = question_review.game.round.tournament subject += u"Nueva revisión de pregunta" message += "Estimado " + user.username + ":\n\n" message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que el usuario " message += question_review.player.username + u" ha solicitado la revisión de una pregunta realizada en una de las partidas de dicho torneo.\n" message += u"Por favor, revisa tu perfil de usuario (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'review_closed': question_review = instance tournament = question_review.game.round.tournament subject += u"Revisión de pregunta atendida" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la revisión de pregunta que solicitaste en referencia a la partida de la ronda " message += str(question_review.game.round.round_number) + " del torneo '" + unicode(tournament) + "' ha sido resuelta.\n" message += u"Por favor, revisa los detalles de esa partida (http://trivial.libresoft.es) para obtener más detalles." message += "\n\n\n" elif case == 'tournament_canceled': tournament = instance c = Category.objects.filter(tournament=tournament) subject += "Torneo cancelado" message += "Estimado " + user.username + ":\n\n" if user == tournament.admin: message += "Como administrador del torneo '" + unicode(tournament) + "', te informamos que este ha sido cancelado por ser " message += u"el número de participantes inferior al mínimo (2).\n\n" message += u"A continuación se detallan las características del torneo cancelado:\n\n" message += "\t- Nombre: " + unicode(tournament) + "\n" message += "\t- Fecha de comienzo: " + tournament.start_date.strftime("%d/%m/%Y") + "\n" message += u"\t- Número de rondas: " + str(tournament.rounds) + "\n" message += u"\t- Duración de cada ronda (días): " + str(tournament.days_per_round) + "\n" message += u"\t- Categoría(s): " for category in list(c): message += unicode(category) + ", " message = message[:-2] message += "\n\n\n" else: message += "Te informamos que el torneo '" + unicode(tournament) + "' al que estabas inscrito, ha sido cancelado. " message += u"Por favor, ponte en contacto con el administrador del torneo para obtener más información.\n" message += "Sentimos las molestias que hayamos podido ocasionarte." message += "\n\n\n" elif case == 'new_game': round = instance tournament = round.tournament subject += "Nueva ronda de partidas" message += "Estimado " + user.username + ":\n\n" message += u"Te informamos que la ronda número " + str(round.round_number) + " del torneo '" + unicode(tournament) + "' ha dado comienzo.\n" message += u"Por favor, revisa tu perfil de jugador (http://trivial.libresoft.es) para obtener los detalles de la partida que jugarás en esta ronda y elegir tu hora de preferencia." message += "\n\n\n" elif case == 'meditation_round': round = instance tournament = round.tournament subject = u"Ronda de reflexión" message += "Estimado " + user.username + ":\n\n" message += u"Debido a limitaciones relacionadas con la lógica del juego, te informamos que no podrás enfrentarte a ningún " message += "jugador durante la ronda " + str(round.round_number) + " del torneo '" + unicode(tournament) + u"' al que estás inscrito.\n" message += u"Como compensación, tu puntación en el torneo ha sido incrementada 1 punto, igual que si hubieses ganado la partida correspondiente a la ronda.\n\n" message += u"Sentimos las molestias que hayamos podido ocasionarte y deseamos que aproveches de la mejor manera posible esta ronda de reflexión." message += "\n\n\n" elif case == 'tournament_over': tournament = instance subject += "Torneo finalizado" message += "Estimado " + user.username + ":\n\n" message += "Te informamos que el torneo '" + unicode(tournament) + "' ha finalizado.\n" message += u"Puedes consultar la tabla de clasificación de jugadores en la página del torneo (http://trivial.libresoft.es)." message += "\n\n\n" message += "Atentamente,\n\n\tFLEQ (Free LibreSoft Educational Quizbowl)" send_mail(subject, message, from_email, [to_email]) log = "Date: " + str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S %Z")) + "\n" log += "Subject: " + subject + "\n" log += "To: " + to_email + "\n" log += "Message:\n" + message + "\n" log += "\n\n" tournament.mail_log += log tournament.save() def games_history(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" if not request.user.is_staff: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) for tournament in Tournament.objects.filter(admin = request.user): response += "<strong><u>Tournament: </u>" + unicode(tournament) + "</strong>" "<br>" for round in Round.objects.filter(tournament = tournament): response += "<strong>Round " + str(round.round_number) + "</strong>" "<br>" for game in Game.objects.filter(round = round): response += "<a href='/games/" + str(game.id) + "/'>(" + game.player1.username + " vs " + game.player2.username + ")</a>" "<br>" response += "<br>" response += "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) @csrf_exempt def new_question_review(request, gid): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" g = Game.objects.get(id = gid) if request.user != g.player1 and request.user != g.player2: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) if request.method == 'POST': # If the form has been submitted... form = NewQuestion_reviewForm(request.POST) # A form bound to the POST data if form.is_valid(): q = Question.objects.get(id = form.cleaned_data['question_number']) qr = Question_review(arguments = form.cleaned_data['arguments'], game = g, question = q, player = request.user) qr.save() notify_user(qr.game.round.tournament.admin, 'new_review', qr) return HttpResponseRedirect('/games/' + str(g.id) + '/') # Redirect after POST else: form = NewQuestion_reviewForm() # An unbound form return render_to_response('blank_form.html', { 'form': form, }) @csrf_exempt def question_review(request, question_review_id): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') response = "You're logged as " + request.user.username + " <a href='/logout'>(sign out)</a> <br>" response += "<br>" "<br>" qr = Question_review.objects.get(id = question_review_id) if request.user != qr.player and request.user != qr.game.round.tournament.admin: response += "You are not authorized to view this page <br>" response += "<br>" "<br>" response += "<a href='/accounts/profile'>Go to user profile</a>" return HttpResponse(response) if request.user == qr.player: response += "<strong>Reviewed question: </strong>" + qr.question.question + "<br>" response += "<strong>Your review aguments:</strong>" "<br>" response += qr.arguments + "<br>" response += "<strong>Game admin's resolution:</strong>" "<br>" response += qr.resolution + "<br>" else: if request.method == 'POST': # If the form has been submitted... form = Question_reviewForm(request.POST) # A form bound to the POST data if form.is_valid(): qr.resolution = form.cleaned_data['resolution'] qr.save() notify_user(qr.player, 'review_closed', qr) return HttpResponseRedirect('/accounts/profile/') # Redirect after POST else: form = Question_reviewForm(instance = qr) # An unbound form form.fields['game'].widget.attrs['readonly'] = True form.fields['question'].widget.attrs['readonly'] = True form.fields['arguments'].widget.attrs['readonly'] = True return render_to_response('blank_form.html', { 'form': form, }) response += "<br>" "<br>" response += "<a href='/games/" + str(qr.game.id) + '/' + "'>Go to game site</a>" return HttpResponse(response)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.contrib import admin from quizbowl.models import Category, Date_time, Game, Preferred_start_time, Question, Question_review, RecoverUser, Round, Score, Tournament, UserProfile class CategoryAdmin(admin.ModelAdmin): list_display = ('pk', 'name') fields = ['name'] class DateTimeAdmin(admin.ModelAdmin): list_display = ('pk', 'date_time', 'preferred_start_time') fields = ['date_time', 'preferred_start_time'] class GameAdmin(admin.ModelAdmin): list_display = ('pk', 'start_time', 'start_time_committed', 'player1', 'player2', 'score_player1', 'score_player2', 'winner', 'round') #readonly_fields=('pk', 'log') fields = ['start_time', 'start_time_committed', 'player1', 'player2', 'score_player1', 'score_player2', 'winner', 'round', 'log'] class PreferredStartTimeAdmin(admin.ModelAdmin): list_display = ('pk', 'committed', 'game', 'player') fields = ['committed', 'game', 'player'] class QuestionAdmin(admin.ModelAdmin): list_display = ('pk', 'question', 'answer', 'alt_answer1', 'alt_answer2', 'alt_answer3', 'use_phonetic') list_filter = ['question', 'answer', 'alt_answer1', 'alt_answer2', 'alt_answer3', 'use_phonetic'] class RecoverUserAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'code') list_filter = ['user', 'code'] class TournamentAdmin(admin.ModelAdmin): list_display = ('pk', 'sid', 'name', 'start_date', 'finish_date', 'admin', 'optional_info') list_filter = ['sid', 'name', 'start_date', 'finish_date', 'admin', 'optional_info'] class UserProfileAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'winner_games', 'loser_games', 'avatar') fields = ['user', 'winner_games', 'loser_games', 'avatar'] admin.site.register(Category, CategoryAdmin) admin.site.register(Date_time, DateTimeAdmin) admin.site.register(Game, GameAdmin) admin.site.register(Preferred_start_time, PreferredStartTimeAdmin) admin.site.register(Question, QuestionAdmin) admin.site.register(UserProfile, UserProfileAdmin) admin.site.register(Question_review) admin.site.register(RecoverUser, RecoverUserAdmin) admin.site.register(Round) admin.site.register(Score) admin.site.register(Tournament, TournamentAdmin)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# import tornado import tornado.web import tornado.httpserver import tornadio2 import tornadio2.router import tornadio2.server import tornadio2.conn import json from django.core.management import setup_environ import settings setup_environ(settings) from django.contrib.sessions.models import Session from django.contrib.auth.models import User from quizbowl.models import Game class UserTornado(object): def __init__(self, socket, username, room): self.socket = socket self.username = username self.room = room class FleqConnection(tornadio2.conn.SocketConnection): participants = set() def on_open(self, request): try: sessionid = str(request.cookies['sessionid']).split("=")[1] session = Session.objects.get(session_key=sessionid) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) if user.is_authenticated: create = True for person in self.participants: if person.username == user.username: # A user only must be in one room and from one device each time create = False person.socket = self person.room = None break if create: self.participants.add(UserTornado(self, user.username, None)) else: return False # The user is not authenticated, then connection is rejected return except (KeyError, Session.DoesNotExist, User.DoesNotExist): return False # Session cookie is missed, or Session/User doesn't exist, then connection is rejected def on_message(self, message): message = json.loads(message) # JOIN if message['code'] == "1": for person in self.participants: if person.username == message['user'] and person.socket == self: try: game = Game.objects.get(pk=message['room']) except Game.DoesNotExist: return if game.player1.username == person.username or game.player2.username == person.username or person.username == "FLEQBOT": person.room = message['room'] person.socket.send('{"code":"1"}') else: self.participants.remove(person) break # NEW MESSAGE elif message['code'] == "2": for person in self.participants: if person.username == message['user'] and person.socket == self: for person in self.participants: if person.room == message['room']: msg = message['message'] msg = msg.replace('<', '&lt;').replace('>', '&gt;').replace("'", "&#39;") person.socket.send('{"code": "2", "user": "' + message['user'] + '", "message": "' + msg + '"}') break def on_close(self): for person in self.participants: if person.socket == self: self.participants.remove(person) break # Create tornadio server FleqRouter = tornadio2.router.TornadioRouter(FleqConnection) # Create socket application sock_app = tornado.web.Application( FleqRouter.urls, socket_io_port = 8004, socket_io_address = '127.0.0.1' ) if __name__ == "__main__": tornadio2.server.SocketServer(sock_app, auto_start=True)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las 00:01 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Round, Score, Tournament from quizbowl.views_notify import notify_user import datetime import sys t = Tournament.objects.all() t = Tournament.objects.filter(start_date = datetime.date.today()) for tournament in t: if tournament.players.all().count() < 2: # tournaments with one or no users are deleted before starting notify_user(tournament.admin, 'tournament_canceled', tournament) if tournament.players.all().count() > 0: p = tournament.players.all() for player in p: notify_user(player, 'tournament_canceled', tournament) tournament.delete() else: p = tournament.players.all() for player in p: notify_user(player, 'new_tournament', tournament) i = 1 actual_date = tournament.start_date while True: if i <= tournament.rounds: round = Round(round_number = i, start_date = actual_date, finish_date = actual_date + datetime.timedelta(tournament.days_per_round-1), tournament = tournament) round.save() actual_date += datetime.timedelta(tournament.days_per_round) i += 1 else: break
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.management import setup_environ import settings setup_environ(settings) import os import sys import time import random import datetime from selenium import webdriver from pyvirtualdisplay import Display from selenium.webdriver.common.keys import Keys from quizbowl.models import Category, Game, Question, Score, UserProfile from quizbowl.views import notify_user from django.utils.html import escape from django.contrib.auth.models import User NUM_CORRECT = 10 QUESTIONS = 30 HOST = "http://pfc-jgonzalez.libresoft.es" game_id = sys.argv[1] # Synchronization now = datetime.datetime.now() seconds_init = int(time.mktime(now.timetuple())) seconds_start = seconds_init + 180 # Extract quiz questions game = Game.objects.get(pk=game_id) c = Category.objects.filter(tournament = game.round.tournament) q = [] for category in c: questions = list(Question.objects.filter(categories = category)) for question in questions: q.append(question) # Set up codec reload(sys) sys.setdefaultencoding("utf-8") # Hide Firefox display = Display(visible=0, size=(800, 600)) display.start() # Launch Firefox browser = webdriver.Firefox() # Log in FLEQ as FLEQBOT browser.get(HOST + "/game-room/" + game_id) elem = browser.find_element_by_name("username") elem.send_keys("FLEQBOT") elem = browser.find_element_by_name("password") elem.send_keys("F13B0t") elem = browser.find_element_by_class_name("button").send_keys(Keys.RETURN) # Go to Game window browser.get(HOST + "/game-room/" + game_id) time.sleep(5) elem = browser.find_element_by_name("message") # Start countdown now = datetime.datetime.now() seconds_now = int(time.mktime(now.timetuple())) time.sleep(30 - (seconds_now - seconds_init)) elem.send_keys('La partida empieza en 2 min 30 seg' + Keys.RETURN) time.sleep(30) elem.send_keys('Quedan 2 minutos...' + Keys.RETURN) time.sleep(30) elem.send_keys('Solo 1 min 30 seg...' + Keys.RETURN) time.sleep(30) elem.send_keys('Un minuto para el comienzo!' + Keys.RETURN) time.sleep(30) elem.send_keys('30 segundos' + Keys.RETURN) time.sleep(20) elem.send_keys('La partida entre ' + game.player1.username + " y " + game.player2.username + ' correspondiente al torneo ' + str(game.round) + ' va a empezar' + Keys.RETURN) time.sleep(5) elem.send_keys('Recordamos que es indiferente contestar en mayúsculas o en minúsculas' + Keys.RETURN) time.sleep(5) elem.send_keys('Una vez lanzada la pregunta, se dispone de 90 segundos para contestar' + Keys.RETURN) time.sleep(5) elem.send_keys('El primer jugador en conseguir ' + str(NUM_CORRECT) + ' respuestas correctas gana la partida.' + Keys.RETURN) time.sleep(5) elem.send_keys('Se dispone de un total de ' + str(QUESTIONS) + ' preguntas' + Keys.RETURN) time.sleep(5) elem.send_keys('Si se consumen sin que ningún jugador alcance ' + str(NUM_CORRECT) + ' aciertos, ganará el que más haya acertado' + Keys.RETURN) time.sleep(5) elem.send_keys('En caso de haber empate, se considerará que ambos jugadores pierden' + Keys.RETURN) time.sleep(5) elem.send_keys('SUERTE!!' + Keys.RETURN) time.sleep(3) # Select and send first question num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) QUESTIONS = QUESTIONS - 1 # Create log file logfile = open(os.getcwd() + '/logs/' + str(game_id), 'w') # Set up auxiliar variables num_msg = 0 score1 = 0 score2 = 0 game_finished = False winner = '' lap = 0 ######################################################### ## GAME LOOP ######################################################### while 1: if game_finished == False: messages = browser.find_elements_by_class_name('message') new_msg = len(messages) - num_msg num_msg = len(messages) for i in range(0, new_msg): try: line = messages[num_msg - new_msg + i].get_attribute("innerHTML") (user, message) = line.split(': ', 1) message = str(message).lower().replace('"', "&quot;").replace("'", "&#39;") logfile.write(str(datetime.datetime.now().time()) + ";" + user + ";" + message + ";\n") if (message == str(escape(q[num_question].answer)).lower() or message == str(escape(q[num_question].alt_answer1)).lower() \ or message == str(escape(q[num_question].alt_answer2)).lower() or message == str(escape(q[num_question].alt_answer3)).lower()) \ and message != "": q.remove(q[num_question]) num_question = random.randrange(len(q)) elem.send_keys('Respuesta correcta!' + Keys.RETURN) time.sleep(2) if user == game.player1.username: elem.send_keys(game.player1.username + ' ha acertado!' + Keys.RETURN) score1 = score1 + 1 elif user == game.player2.username: elem.send_keys(game.player2.username + ' ha acertado!' + Keys.RETURN) score2 = score2 + 1 time.sleep(3) elem.send_keys(game.player1.username + " " + str(score1) + ':' + str(score2) + " " + game.player2.username + Keys.RETURN) time.sleep(2) if score1 == NUM_CORRECT or score2 == NUM_CORRECT: game_finished = True break if QUESTIONS == 1: elem.send_keys("Última pregunta disponible..." + Keys.RETURN) time.sleep(3) if QUESTIONS != 0: num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) else: game_finished = True QUESTIONS = QUESTIONS - 1 lap = 0 break except: pass if lap == 90: elem.send_keys("Los 90 segundos se han cumplido sin que se haya acertado la respuesta" + Keys.RETURN) time.sleep(3) elem.send_keys("La respuesta correcta era: " + q[num_question].answer + Keys.RETURN) time.sleep(3) if QUESTIONS == 1: elem.send_keys("Última pregunta disponible..." + Keys.RETURN) time.sleep(3) if QUESTIONS != 0: q.remove(q[num_question]) num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) else: game_finished = True QUESTIONS = QUESTIONS - 1 lap = 0 time.sleep(1) lap = lap + 1 else: elem.send_keys('La partida ha terminado' + Keys.RETURN) time.sleep(3) elem.send_keys('El resultado final ha sido: ' + str(score1) + ' - ' + str(score2) + Keys.RETURN) time.sleep(3) if score1 > score2: winner = game.player1 loser = game.player2 elif score2 > score1: winner = game.player2 loser = game.player1 if score1 != score2: game.winner = winner elem.send_keys(winner.username + " ha sido el vencedor" + Keys.RETURN) time.sleep(2) elem.send_keys("ENHORABUENA!!" + Keys.RETURN) else: fleqbot = User.objects.get(username="FLEQBOT") game.winner = fleqbot elem.send_keys("Habéis empatado tras agotar el lote de preguntas disponibles para la partida" + Keys.RETURN) time.sleep(3) elem.send_keys("El sistema de puntuación aún no contempla empates, por lo que ambos habéis perdido esta partida..." + Keys.RETURN) time.sleep(3) elem.send_keys("Al empatar por lo menos habéis evitado que vuestro oponente sume una victoria, no está mal!" + Keys.RETURN) time.sleep(3) elem.send_keys("Podéis consultar la tabla del torneo para conocer la clasificación. Hasta la próxima!" + Keys.RETURN) scorepl1 = Score.objects.get(player=game.player1, tournament=game.round.tournament) scorepl2 = Score.objects.get(player=game.player2, tournament=game.round.tournament) game.score_player1 = score1 game.score_player2 = score2 scorepl1.questions_won += score1 scorepl1.questions_lost += score2 scorepl2.questions_lost += score1 scorepl2.questions_won += score2 game.save() scorepl1.save() scorepl2.save() if score2 != score1: winnerProfile = UserProfile.objects.get(user=winner) loserProfile = UserProfile.objects.get(user=loser) winnerProfile.winner_games = winnerProfile.winner_games + 1 loserProfile.loser_games = loserProfile.loser_games + 1 winnerProfile.save() loserProfile.save() if score1 > score2: scorepl1.points = scorepl1.points + 1 scorepl1.save() elif score2 > score1: scorepl2.points = scorepl2.points + 1 scorepl2.save() else: player1pf = UserProfile.objects.get(user=game.player1) player2pf = UserProfile.objects.get(user=game.player2) player1pf.loser_games = player1pf.loser_games + 1 player2pf.loser_games = player2pf.loser_games + 1 player1pf.save() player2pf.save() if game.round.round_number == game.round.tournament.rounds: if not Game.objects.filter(round = game.round): for score in Score.objects.filter(tournament = game.round.tournament): notify_user(score.player, 'tournament_over', game.round.tournament) notify_user(game.round.tournament.admin, 'tournament_over', game.round.tournament) break logfile.close() game.log = True game.save() time.sleep(2) browser.close() display.stop()
Python
#!/usr/bin/python from django.core.management import execute_manager try: import 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(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Category, Game, Question import codecs import datetime import os import random import subprocess three_minutes_ahead = datetime.datetime.now() + datetime.timedelta(minutes=3) g = Game.objects.filter(start_time__lte = three_minutes_ahead, start_time__gte = datetime.datetime.now()) for game in g: if not game.is_over(): subprocess.Popen(['python', os.getcwd() + '/fleqbot.py', str(game.id)])
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las *:30 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Game from quizbowl.views_notify import notify_user import datetime thirty_minutes_ahead = datetime.datetime.now() + datetime.timedelta(minutes=30) g = Game.objects.filter(start_time__lte = thirty_minutes_ahead, start_time__gte = datetime.datetime.now()) for game in g: if not game.log: notify_user(game.player1, 'hurry_up', game) notify_user(game.player2, 'hurry_up', game)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las 00:05 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Game, Preferred_start_time, Round, Score from quizbowl.views_notify import notify_user from random import choice import datetime import sys r = Round.objects.filter(start_date = datetime.date.today()) for round in r: s = Score.objects.filter(tournament = round.tournament.id).order_by('points', '?') scores = list(s) if len(scores)%2: # if the number of players is odd, a random player is earned with 1 point and won't play this round lucky_score = choice(scores) lucky_score.points += 1 lucky_score.save() scores.remove(lucky_score) notify_user(lucky_score.player, 'meditation_round', round) while scores: player1 = scores.pop().player player2 = scores.pop().player default_date = round.finish_date default_time = datetime.time(22,00) default_start_time = datetime.datetime.combine(default_date, default_time) game = Game(start_time = default_start_time, player1 = player1, player2 = player2, score_player1 = 0, score_player2 = 0, winner = round.tournament.admin, round = round) game.save() notify_user(player1, 'new_game', round) notify_user(player2, 'new_game', round) pst = Preferred_start_time(player = game.player1, game = game) pst.save() pst = Preferred_start_time(player = game.player2, game = game) pst.save()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.conf.urls.defaults import * import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Admin (r'^admin/', include(admin.site.urls)), (r'^admin/new-tournament/', 'quizbowl.views_admin.newTournament'), (r'^admin/load-questions/', 'quizbowl.views_admin.loadQuestions'), # Media (r'css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/css'}), (r'images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/images'}), (r'js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/js'}), # Connect url('^$', 'quizbowl.views_connect.Home'), url('^signin$', 'quizbowl.views_connect.Signin'), url('^logout$', 'quizbowl.views_connect.Logout'), url('^welcome$', 'quizbowl.views_connect.Welcome'), # Tournaments url('^my-tournaments$', 'quizbowl.views_tournaments.MyTournaments'), url('^active-tournaments$', 'quizbowl.views_tournaments.ActiveTournaments'), url('^next-tournaments$', 'quizbowl.views_tournaments.NextTournaments'), url('^finished-tournaments$', 'quizbowl.views_tournaments.FinishedTournaments'), url('^new-tournament$', 'quizbowl.views_admin.NewTournament'), url('^load-questions$', 'quizbowl.views_admin.LoadQuestions'), url('^tournament/(?P<gid>\d+)$', 'quizbowl.views_tournaments.TournamentStatistics'), url('^tournament/(?P<gid>\d+)/join$', 'quizbowl.views_tournaments.JoinTournament'), url('^tournament/(?P<gid>\d+)/disjoin$', 'quizbowl.views_tournaments.DisjoinTournament'), # Games url('^next-games$', 'quizbowl.views_games.NextGames'), url('^won-games$', 'quizbowl.views_games.WonGames'), url('^lost-games$', 'quizbowl.views_games.LostGames'), url('^game-room/(?P<gid>\d+)$', 'quizbowl.views_games.GameRoom'), url('^game-room/(?P<gid>\d+)/select-time$', 'quizbowl.views_games.SelectStartTime'), url('^game-room/(?P<gid>\d+)/delete-time$', 'quizbowl.views_games.DeleteStartTime'), ) urlpatterns += patterns('django.views.generic.simple', (r'^login/$', 'direct_to_template', {'template': 'login.html'}), )
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las *:30 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Game from quizbowl.views_notify import notify_user import datetime thirty_minutes_ahead = datetime.datetime.now() + datetime.timedelta(minutes=30) g = Game.objects.filter(start_time__lte = thirty_minutes_ahead, start_time__gte = datetime.datetime.now()) for game in g: if not game.log: notify_user(game.player1, 'hurry_up', game) notify_user(game.player2, 'hurry_up', game)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las 00:01 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Round, Score, Tournament from quizbowl.views_notify import notify_user import datetime import sys t = Tournament.objects.all() t = Tournament.objects.filter(start_date = datetime.date.today()) for tournament in t: if tournament.players.all().count() < 2: # tournaments with one or no users are deleted before starting notify_user(tournament.admin, 'tournament_canceled', tournament) if tournament.players.all().count() > 0: p = tournament.players.all() for player in p: notify_user(player, 'tournament_canceled', tournament) tournament.delete() else: p = tournament.players.all() for player in p: notify_user(player, 'new_tournament', tournament) i = 1 actual_date = tournament.start_date while True: if i <= tournament.rounds: round = Round(round_number = i, start_date = actual_date, finish_date = actual_date + datetime.timedelta(tournament.days_per_round-1), tournament = tournament) round.save() actual_date += datetime.timedelta(tournament.days_per_round) i += 1 else: break
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.conf.urls.defaults import * import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Admin (r'^admin/', include(admin.site.urls)), (r'^admin/new-tournament/', 'quizbowl.views_admin.newTournament'), (r'^admin/load-questions/', 'quizbowl.views_admin.loadQuestions'), # Media (r'css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/css'}), (r'images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/images'}), (r'js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/js'}), # Connect url('^$', 'quizbowl.views_connect.Home'), url('^signin$', 'quizbowl.views_connect.Signin'), url('^logout$', 'quizbowl.views_connect.Logout'), url('^welcome$', 'quizbowl.views_connect.Welcome'), # Tournaments url('^my-tournaments$', 'quizbowl.views_tournaments.MyTournaments'), url('^active-tournaments$', 'quizbowl.views_tournaments.ActiveTournaments'), url('^next-tournaments$', 'quizbowl.views_tournaments.NextTournaments'), url('^finished-tournaments$', 'quizbowl.views_tournaments.FinishedTournaments'), url('^new-tournament$', 'quizbowl.views_admin.NewTournament'), url('^load-questions$', 'quizbowl.views_admin.LoadQuestions'), url('^tournament/(?P<gid>\d+)$', 'quizbowl.views_tournaments.TournamentStatistics'), url('^tournament/(?P<gid>\d+)/join$', 'quizbowl.views_tournaments.JoinTournament'), url('^tournament/(?P<gid>\d+)/disjoin$', 'quizbowl.views_tournaments.DisjoinTournament'), # Games url('^next-games$', 'quizbowl.views_games.NextGames'), url('^won-games$', 'quizbowl.views_games.WonGames'), url('^lost-games$', 'quizbowl.views_games.LostGames'), url('^game-room/(?P<gid>\d+)$', 'quizbowl.views_games.GameRoom'), url('^game-room/(?P<gid>\d+)/select-time$', 'quizbowl.views_games.SelectStartTime'), url('^game-room/(?P<gid>\d+)/delete-time$', 'quizbowl.views_games.DeleteStartTime'), ) urlpatterns += patterns('django.views.generic.simple', (r'^login/$', 'direct_to_template', {'template': 'login.html'}), )
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.management import setup_environ import settings setup_environ(settings) import os import sys import time import random import datetime from selenium import webdriver from pyvirtualdisplay import Display from selenium.webdriver.common.keys import Keys from quizbowl.models import Category, Game, Question, Score, UserProfile from quizbowl.views import notify_user from django.utils.html import escape from django.contrib.auth.models import User NUM_CORRECT = 10 QUESTIONS = 30 HOST = "http://pfc-jgonzalez.libresoft.es" game_id = sys.argv[1] # Synchronization now = datetime.datetime.now() seconds_init = int(time.mktime(now.timetuple())) seconds_start = seconds_init + 180 # Extract quiz questions game = Game.objects.get(pk=game_id) c = Category.objects.filter(tournament = game.round.tournament) q = [] for category in c: questions = list(Question.objects.filter(categories = category)) for question in questions: q.append(question) # Set up codec reload(sys) sys.setdefaultencoding("utf-8") # Hide Firefox display = Display(visible=0, size=(800, 600)) display.start() # Launch Firefox browser = webdriver.Firefox() # Log in FLEQ as FLEQBOT browser.get(HOST + "/game-room/" + game_id) elem = browser.find_element_by_name("username") elem.send_keys("FLEQBOT") elem = browser.find_element_by_name("password") elem.send_keys("F13B0t") elem = browser.find_element_by_class_name("button").send_keys(Keys.RETURN) # Go to Game window browser.get(HOST + "/game-room/" + game_id) time.sleep(5) elem = browser.find_element_by_name("message") # Start countdown now = datetime.datetime.now() seconds_now = int(time.mktime(now.timetuple())) time.sleep(30 - (seconds_now - seconds_init)) elem.send_keys('La partida empieza en 2 min 30 seg' + Keys.RETURN) time.sleep(30) elem.send_keys('Quedan 2 minutos...' + Keys.RETURN) time.sleep(30) elem.send_keys('Solo 1 min 30 seg...' + Keys.RETURN) time.sleep(30) elem.send_keys('Un minuto para el comienzo!' + Keys.RETURN) time.sleep(30) elem.send_keys('30 segundos' + Keys.RETURN) time.sleep(20) elem.send_keys('La partida entre ' + game.player1.username + " y " + game.player2.username + ' correspondiente al torneo ' + str(game.round) + ' va a empezar' + Keys.RETURN) time.sleep(5) elem.send_keys('Recordamos que es indiferente contestar en mayúsculas o en minúsculas' + Keys.RETURN) time.sleep(5) elem.send_keys('Una vez lanzada la pregunta, se dispone de 90 segundos para contestar' + Keys.RETURN) time.sleep(5) elem.send_keys('El primer jugador en conseguir ' + str(NUM_CORRECT) + ' respuestas correctas gana la partida.' + Keys.RETURN) time.sleep(5) elem.send_keys('Se dispone de un total de ' + str(QUESTIONS) + ' preguntas' + Keys.RETURN) time.sleep(5) elem.send_keys('Si se consumen sin que ningún jugador alcance ' + str(NUM_CORRECT) + ' aciertos, ganará el que más haya acertado' + Keys.RETURN) time.sleep(5) elem.send_keys('En caso de haber empate, se considerará que ambos jugadores pierden' + Keys.RETURN) time.sleep(5) elem.send_keys('SUERTE!!' + Keys.RETURN) time.sleep(3) # Select and send first question num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) QUESTIONS = QUESTIONS - 1 # Create log file logfile = open(os.getcwd() + '/logs/' + str(game_id), 'w') # Set up auxiliar variables num_msg = 0 score1 = 0 score2 = 0 game_finished = False winner = '' lap = 0 ######################################################### ## GAME LOOP ######################################################### while 1: if game_finished == False: messages = browser.find_elements_by_class_name('message') new_msg = len(messages) - num_msg num_msg = len(messages) for i in range(0, new_msg): try: line = messages[num_msg - new_msg + i].get_attribute("innerHTML") (user, message) = line.split(': ', 1) message = str(message).lower().replace('"', "&quot;").replace("'", "&#39;") logfile.write(str(datetime.datetime.now().time()) + ";" + user + ";" + message + ";\n") if (message == str(escape(q[num_question].answer)).lower() or message == str(escape(q[num_question].alt_answer1)).lower() \ or message == str(escape(q[num_question].alt_answer2)).lower() or message == str(escape(q[num_question].alt_answer3)).lower()) \ and message != "": q.remove(q[num_question]) num_question = random.randrange(len(q)) elem.send_keys('Respuesta correcta!' + Keys.RETURN) time.sleep(2) if user == game.player1.username: elem.send_keys(game.player1.username + ' ha acertado!' + Keys.RETURN) score1 = score1 + 1 elif user == game.player2.username: elem.send_keys(game.player2.username + ' ha acertado!' + Keys.RETURN) score2 = score2 + 1 time.sleep(3) elem.send_keys(game.player1.username + " " + str(score1) + ':' + str(score2) + " " + game.player2.username + Keys.RETURN) time.sleep(2) if score1 == NUM_CORRECT or score2 == NUM_CORRECT: game_finished = True break if QUESTIONS == 1: elem.send_keys("Última pregunta disponible..." + Keys.RETURN) time.sleep(3) if QUESTIONS != 0: num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) else: game_finished = True QUESTIONS = QUESTIONS - 1 lap = 0 break except: pass if lap == 90: elem.send_keys("Los 90 segundos se han cumplido sin que se haya acertado la respuesta" + Keys.RETURN) time.sleep(3) elem.send_keys("La respuesta correcta era: " + q[num_question].answer + Keys.RETURN) time.sleep(3) if QUESTIONS == 1: elem.send_keys("Última pregunta disponible..." + Keys.RETURN) time.sleep(3) if QUESTIONS != 0: q.remove(q[num_question]) num_question = random.randrange(len(q)) elem.send_keys(escape(q[num_question].question) + Keys.RETURN) else: game_finished = True QUESTIONS = QUESTIONS - 1 lap = 0 time.sleep(1) lap = lap + 1 else: elem.send_keys('La partida ha terminado' + Keys.RETURN) time.sleep(3) elem.send_keys('El resultado final ha sido: ' + str(score1) + ' - ' + str(score2) + Keys.RETURN) time.sleep(3) if score1 > score2: winner = game.player1 loser = game.player2 elif score2 > score1: winner = game.player2 loser = game.player1 if score1 != score2: game.winner = winner elem.send_keys(winner.username + " ha sido el vencedor" + Keys.RETURN) time.sleep(2) elem.send_keys("ENHORABUENA!!" + Keys.RETURN) else: fleqbot = User.objects.get(username="FLEQBOT") game.winner = fleqbot elem.send_keys("Habéis empatado tras agotar el lote de preguntas disponibles para la partida" + Keys.RETURN) time.sleep(3) elem.send_keys("El sistema de puntuación aún no contempla empates, por lo que ambos habéis perdido esta partida..." + Keys.RETURN) time.sleep(3) elem.send_keys("Al empatar por lo menos habéis evitado que vuestro oponente sume una victoria, no está mal!" + Keys.RETURN) time.sleep(3) elem.send_keys("Podéis consultar la tabla del torneo para conocer la clasificación. Hasta la próxima!" + Keys.RETURN) scorepl1 = Score.objects.get(player=game.player1, tournament=game.round.tournament) scorepl2 = Score.objects.get(player=game.player2, tournament=game.round.tournament) game.score_player1 = score1 game.score_player2 = score2 scorepl1.questions_won += score1 scorepl1.questions_lost += score2 scorepl2.questions_lost += score1 scorepl2.questions_won += score2 game.save() scorepl1.save() scorepl2.save() if score2 != score1: winnerProfile = UserProfile.objects.get(user=winner) loserProfile = UserProfile.objects.get(user=loser) winnerProfile.winner_games = winnerProfile.winner_games + 1 loserProfile.loser_games = loserProfile.loser_games + 1 winnerProfile.save() loserProfile.save() if score1 > score2: scorepl1.points = scorepl1.points + 1 scorepl1.save() elif score2 > score1: scorepl2.points = scorepl2.points + 1 scorepl2.save() else: player1pf = UserProfile.objects.get(user=game.player1) player2pf = UserProfile.objects.get(user=game.player2) player1pf.loser_games = player1pf.loser_games + 1 player2pf.loser_games = player2pf.loser_games + 1 player1pf.save() player2pf.save() if game.round.round_number == game.round.tournament.rounds: if not Game.objects.filter(round = game.round): for score in Score.objects.filter(tournament = game.round.tournament): notify_user(score.player, 'tournament_over', game.round.tournament) notify_user(game.round.tournament.admin, 'tournament_over', game.round.tournament) break logfile.close() game.log = True game.save() time.sleep(2) browser.close() display.stop()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # El script se lanza a las 00:05 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Game, Preferred_start_time, Round, Score from quizbowl.views_notify import notify_user from random import choice import datetime import sys r = Round.objects.filter(start_date = datetime.date.today()) for round in r: s = Score.objects.filter(tournament = round.tournament.id).order_by('points', '?') scores = list(s) if len(scores)%2: # if the number of players is odd, a random player is earned with 1 point and won't play this round lucky_score = choice(scores) lucky_score.points += 1 lucky_score.save() scores.remove(lucky_score) notify_user(lucky_score.player, 'meditation_round', round) while scores: player1 = scores.pop().player player2 = scores.pop().player default_date = round.finish_date default_time = datetime.time(22,00) default_start_time = datetime.datetime.combine(default_date, default_time) game = Game(start_time = default_start_time, player1 = player1, player2 = player2, score_player1 = 0, score_player2 = 0, winner = round.tournament.admin, round = round) game.save() notify_user(player1, 'new_game', round) notify_user(player2, 'new_game', round) pst = Preferred_start_time(player = game.player1, game = game) pst.save() pst = Preferred_start_time(player = game.player2, game = game) pst.save()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# # # # FLEQ (Free LibreSoft Educational Quizbowl) # # A synchronous on-line competition software to improve and # # motivate learning. # # # # Copyright (C) 2012 Arturo Moral, Gregorio Robles, Félix Redondo # # & Jorge González Navarro # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # Contact authors : Arturo Moral <amoral@gmail.com> # # Gregorio Robles <grex@gsyc.urjc.es> # # Félix Redondo <felix.redondo.sierra@gmail.com> # # Jorge González Navarro <j.gonzalezna@gmail.com> # # # ############################################################################# from django.core.management import setup_environ import settings setup_environ(settings) from quizbowl.models import Category, Game, Question import codecs import datetime import os import random import subprocess three_minutes_ahead = datetime.datetime.now() + datetime.timedelta(minutes=3) g = Game.objects.filter(start_time__lte = three_minutes_ahead, start_time__gte = datetime.datetime.now()) for game in g: if not game.is_over(): subprocess.Popen(['python', os.getcwd() + '/fleqbot.py', str(game.id)])
Python
#!/usr/bin/python from django.core.management import execute_manager try: import 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(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/python import sys import time import os import string import StringIO sys.path.insert(0, "python") import libxml2 # Memory debug specific libxml2.debugMemory(1) debug = 0 verbose = 0 quiet = 1 # # the testsuite description # CONF=os.path.join(os.path.dirname(__file__), "test/relaxng/OASIS/spectest.xml") LOG="check-relaxng-test-suite.log" RES="relaxng-test-results.xml" log = open(LOG, "w") nb_schemas_tests = 0 nb_schemas_success = 0 nb_schemas_failed = 0 nb_instances_tests = 0 nb_instances_success = 0 nb_instances_failed = 0 libxml2.lineNumbersDefault(1) # # Error and warnng callbacks # def callback(ctx, str): global log log.write("%s%s" % (ctx, str)) libxml2.registerErrorHandler(callback, "") # # Resolver callback # resources = {} def resolver(URL, ID, ctxt): global resources if string.find(URL, '#') != -1: URL = URL[0:string.find(URL, '#')] if resources.has_key(URL): return(StringIO.StringIO(resources[URL])) log.write("Resolver failure: asked %s\n" % (URL)) log.write("resources: %s\n" % (resources)) return None # # Load the previous results # #results = {} #previous = {} # #try: # res = libxml2.parseFile(RES) #except: # log.write("Could not parse %s" % (RES)) # # handle a valid instance # def handle_valid(node, schema): global log global nb_instances_success global nb_instances_failed instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nFailed to parse correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 return try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) except: ret = -1 if ret != 0: log.write("\nFailed to validate correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 doc.freeDoc() # # handle an invalid instance # def handle_invalid(node, schema): global log global nb_instances_success global nb_instances_failed instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nStrange: failed to parse incorrect instance:\n-----\n") log.write(instance) log.write("\n-----\n") return try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) except: ret = -1 if ret == 0: log.write("\nFailed to detect validation problem in instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 doc.freeDoc() # # handle an incorrect test # def handle_correct(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs == None: log.write("\nFailed to compile correct schema:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: nb_schemas_success = nb_schemas_success + 1 return rngs def handle_incorrect(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs != None: log.write("\nFailed to detect schema error in:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: # log.write("\nSuccess detecting schema error in:\n-----\n") # log.write(schema) # log.write("\n-----\n") nb_schemas_success = nb_schemas_success + 1 return None # # resource handling: keep a dictionary of URL->string mappings # def handle_resource(node, dir): global resources try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name res = "" child = node.children while child != None: if child.type != 'text': res = res + child.serialize() child = child.next resources[name] = res # # dir handling: pseudo directory resources # def handle_dir(node, dir): try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, name) res = node.xpathEval('resource') for r in res: handle_resource(r, name) # # handle a testCase element # def handle_testCase(node): global nb_schemas_tests global nb_instances_tests global resources sections = node.xpathEval('string(section)') log.write("\n ======== test %d line %d section %s ==========\n" % ( nb_schemas_tests, node.lineNo(), sections)) resources = {} if debug: print "test %d line %d" % (nb_schemas_tests, node.lineNo()) dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, None) res = node.xpathEval('resource') for r in res: handle_resource(r, None) tsts = node.xpathEval('incorrect') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <incorrect> example" %(node.lineNo()) schema = handle_incorrect(tsts[0]) else: tsts = node.xpathEval('correct') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <correct> example"% (node.lineNo()) schema = handle_correct(tsts[0]) else: print "warning <testCase> line %d has no <correct> nor <incorrect> child" % (node.lineNo()) nb_schemas_tests = nb_schemas_tests + 1; valids = node.xpathEval('valid') invalids = node.xpathEval('invalid') nb_instances_tests = nb_instances_tests + len(valids) + len(invalids) if schema != None: for valid in valids: handle_valid(valid, schema) for invalid in invalids: handle_invalid(invalid, schema) # # handle a testSuite element # def handle_testSuite(node, level = 0): global nb_schemas_tests, nb_schemas_success, nb_schemas_failed global nb_instances_tests, nb_instances_success, nb_instances_failed global quiet if level >= 1: old_schemas_tests = nb_schemas_tests old_schemas_success = nb_schemas_success old_schemas_failed = nb_schemas_failed old_instances_tests = nb_instances_tests old_instances_success = nb_instances_success old_instances_failed = nb_instances_failed docs = node.xpathEval('documentation') authors = node.xpathEval('author') if docs != []: msg = "" for doc in docs: msg = msg + doc.content + " " if authors != []: msg = msg + "written by " for author in authors: msg = msg + author.content + " " if quiet == 0: print msg sections = node.xpathEval('section') if sections != [] and level <= 0: msg = "" for section in sections: msg = msg + section.content + " " if quiet == 0: print "Tests for section %s" % (msg) for test in node.xpathEval('testCase'): handle_testCase(test) for test in node.xpathEval('testSuite'): handle_testSuite(test, level + 1) if verbose and level >= 1 and sections != []: msg = "" for section in sections: msg = msg + section.content + " " print "Result of tests for section %s" % (msg) if nb_schemas_tests != old_schemas_tests: print "found %d test schemas: %d success %d failures" % ( nb_schemas_tests - old_schemas_tests, nb_schemas_success - old_schemas_success, nb_schemas_failed - old_schemas_failed) if nb_instances_tests != old_instances_tests: print "found %d test instances: %d success %d failures" % ( nb_instances_tests - old_instances_tests, nb_instances_success - old_instances_success, nb_instances_failed - old_instances_failed) # # Parse the conf file # libxml2.substituteEntitiesDefault(1); testsuite = libxml2.parseFile(CONF) libxml2.setEntityLoader(resolver) root = testsuite.getRootElement() if root.name != 'testSuite': print "%s doesn't start with a testSuite element, aborting" % (CONF) sys.exit(1) if quiet == 0: print "Running Relax NG testsuite" handle_testSuite(root) if quiet == 0: print "\nTOTAL:\n" if quiet == 0 or nb_schemas_failed != 0: print "found %d test schemas: %d success %d failures" % ( nb_schemas_tests, nb_schemas_success, nb_schemas_failed) if quiet == 0 or nb_instances_failed != 0: print "found %d test instances: %d success %d failures" % ( nb_instances_tests, nb_instances_success, nb_instances_failed) testsuite.freeDoc() # Memory debug specific libxml2.relaxNGCleanupTypes() libxml2.cleanupParser() if libxml2.debugMemory(1) == 0: if quiet == 0: print "OK" else: print "Memory leak %d bytes" % (libxml2.debugMemory(1)) libxml2.dumpMemory()
Python
#!/usr/bin/python import sys import time import os import string sys.path.insert(0, "python") import libxml2 # # the testsuite description # DIR="xinclude-test-suite" CONF="testdescr.xml" LOG="check-xinclude-test-suite.log" log = open(LOG, "w") os.chdir(DIR) test_nr = 0 test_succeed = 0 test_failed = 0 test_error = 0 # # Error and warning handlers # error_nr = 0 error_msg = '' def errorHandler(ctx, str): global error_nr global error_msg if string.find(str, "error:") >= 0: error_nr = error_nr + 1 if len(error_msg) < 300: if len(error_msg) == 0 or error_msg[-1] == '\n': error_msg = error_msg + " >>" + str else: error_msg = error_msg + str libxml2.registerErrorHandler(errorHandler, None) def testXInclude(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' print "testXInclude(%s, %s)" % (filename, id) return 1 def runTest(test, basedir): global test_nr global test_failed global test_error global test_succeed global error_msg global log fatal_error = 0 uri = test.prop('href') id = test.prop('id') type = test.prop('type') if uri == None: print "Test without ID:", uri return -1 if id == None: print "Test without URI:", id return -1 if type == None: print "Test without URI:", id return -1 if basedir != None: URI = basedir + "/" + uri else: URI = uri if os.access(URI, os.R_OK) == 0: print "Test %s missing: base %s uri %s" % (URI, basedir, uri) return -1 expected = None outputfile = None diff = None if type != 'error': output = test.xpathEval('string(output)') if output == 'No output file.': output = None if output == '': output = None if output != None: if basedir != None: output = basedir + "/" + output if os.access(output, os.R_OK) == 0: print "Result for %s missing: %s" % (id, output) output = None else: try: f = open(output) expected = f.read() outputfile = output except: print "Result for %s unreadable: %s" % (id, output) try: # print "testing %s" % (URI) doc = libxml2.parseFile(URI) except: doc = None if doc != None: res = doc.xincludeProcess() if res >= 0 and expected != None: result = doc.serialize() if result != expected: print "Result for %s differs" % (id) open("xinclude.res", "w").write(result) diff = os.popen("diff %s xinclude.res" % outputfile).read() doc.freeDoc() else: print "Failed to parse %s" % (URI) res = -1 test_nr = test_nr + 1 if type == 'success': if res > 0: test_succeed = test_succeed + 1 elif res == 0: test_failed = test_failed + 1 print "Test %s: no substitution done ???" % (id) elif res < 0: test_error = test_error + 1 print "Test %s: failed valid XInclude processing" % (id) elif type == 'error': if res > 0: test_error = test_error + 1 print "Test %s: failed to detect invalid XInclude processing" % (id) elif res == 0: test_failed = test_failed + 1 print "Test %s: Invalid but no substitution done" % (id) elif res < 0: test_succeed = test_succeed + 1 elif type == 'optional': if res > 0: test_succeed = test_succeed + 1 else: print "Test %s: failed optional test" % (id) # Log the ontext if res != 1: log.write("Test ID %s\n" % (id)) log.write(" File: %s\n" % (URI)) content = string.strip(test.content) while content[-1] == '\n': content = content[0:-1] log.write(" %s:%s\n\n" % (type, content)) if error_msg != '': log.write(" ----\n%s ----\n" % (error_msg)) error_msg = '' log.write("\n") if diff != None: log.write("diff from test %s:\n" %(id)) log.write(" -----------\n%s\n -----------\n" % (diff)); return 0 def runTestCases(case): creator = case.prop('creator') if creator != None: print "=>", creator base = case.getBase(None) basedir = case.prop('basedir') if basedir != None: base = libxml2.buildURI(basedir, base) test = case.children while test != None: if test.name == 'testcase': runTest(test, base) if test.name == 'testcases': runTestCases(test) test = test.next conf = libxml2.parseFile(CONF) if conf == None: print "Unable to load %s" % CONF sys.exit(1) testsuite = conf.getRootElement() if testsuite.name != 'testsuite': print "Expecting TESTSUITE root element: aborting" sys.exit(1) profile = testsuite.prop('PROFILE') if profile != None: print profile start = time.time() case = testsuite.children while case != None: if case.name == 'testcases': old_test_nr = test_nr old_test_succeed = test_succeed old_test_failed = test_failed old_test_error = test_error runTestCases(case) print " Ran %d tests: %d suceeded, %d failed and %d generated an error" % ( test_nr - old_test_nr, test_succeed - old_test_succeed, test_failed - old_test_failed, test_error - old_test_error) case = case.next conf.freeDoc() log.close() print "Ran %d tests: %d suceeded, %d failed and %d generated an error in %.2f s." % ( test_nr, test_succeed, test_failed, test_error, time.time() - start)
Python
#!/usr/bin/python -u import glob, os, string, sys, thread, time # import difflib import libxml2 ### # # This is a "Work in Progress" attempt at a python script to run the # various regression tests. The rationale for this is that it should be # possible to run this on most major platforms, including those (such as # Windows) which don't support gnu Make. # # The script is driven by a parameter file which defines the various tests # to be run, together with the unique settings for each of these tests. A # script for Linux is included (regressions.xml), with comments indicating # the significance of the various parameters. To run the tests under Windows, # edit regressions.xml and remove the comment around the default parameter # "<execpath>" (i.e. make it point to the location of the binary executables). # # Note that this current version requires the Python bindings for libxml2 to # have been previously installed and accessible # # See Copyright for the status of this software. # William Brack (wbrack@mmm.com.hk) # ### defaultParams = {} # will be used as a dictionary to hold the parsed params # This routine is used for comparing the expected stdout / stdin with the results. # The expected data has already been read in; the result is a file descriptor. # Within the two sets of data, lines may begin with a path string. If so, the # code "relativises" it by removing the path component. The first argument is a # list already read in by a separate thread; the second is a file descriptor. # The two 'base' arguments are to let me "relativise" the results files, allowing # the script to be run from any directory. def compFiles(res, expected, base1, base2): l1 = len(base1) exp = expected.readlines() expected.close() # the "relativisation" is done here for i in range(len(res)): j = string.find(res[i],base1) if (j == 0) or ((j == 2) and (res[i][0:2] == './')): col = string.find(res[i],':') if col > 0: start = string.rfind(res[i][:col], '/') if start > 0: res[i] = res[i][start+1:] for i in range(len(exp)): j = string.find(exp[i],base2) if (j == 0) or ((j == 2) and (exp[i][0:2] == './')): col = string.find(exp[i],':') if col > 0: start = string.rfind(exp[i][:col], '/') if start > 0: exp[i] = exp[i][start+1:] ret = 0 # ideally we would like to use difflib functions here to do a # nice comparison of the two sets. Unfortunately, during testing # (using python 2.3.3 and 2.3.4) the following code went into # a dead loop under windows. I'll pursue this later. # diff = difflib.ndiff(res, exp) # diff = list(diff) # for line in diff: # if line[:2] != ' ': # print string.strip(line) # ret = -1 # the following simple compare is fine for when the two data sets # (actual result vs. expected result) are equal, which should be true for # us. Unfortunately, if the test fails it's not nice at all. rl = len(res) el = len(exp) if el != rl: print 'Length of expected is %d, result is %d' % (el, rl) ret = -1 for i in range(min(el, rl)): if string.strip(res[i]) != string.strip(exp[i]): print '+:%s-:%s' % (res[i], exp[i]) ret = -1 if el > rl: for i in range(rl, el): print '-:%s' % exp[i] ret = -1 elif rl > el: for i in range (el, rl): print '+:%s' % res[i] ret = -1 return ret # Separate threads to handle stdout and stderr are created to run this function def readPfile(file, list, flag): data = file.readlines() # no call by reference, so I cheat for l in data: list.append(l) file.close() flag.append('ok') # This routine runs the test program (e.g. xmllint) def runOneTest(testDescription, filename, inbase, errbase): if 'execpath' in testDescription: dir = testDescription['execpath'] + '/' else: dir = '' cmd = os.path.abspath(dir + testDescription['testprog']) if 'flag' in testDescription: for f in string.split(testDescription['flag']): cmd += ' ' + f if 'stdin' not in testDescription: cmd += ' ' + inbase + filename if 'extarg' in testDescription: cmd += ' ' + testDescription['extarg'] noResult = 0 expout = None if 'resext' in testDescription: if testDescription['resext'] == 'None': noResult = 1 else: ext = '.' + testDescription['resext'] else: ext = '' if not noResult: try: fname = errbase + filename + ext expout = open(fname, 'rt') except: print "Can't open result file %s - bypassing test" % fname return noErrors = 0 if 'reserrext' in testDescription: if testDescription['reserrext'] == 'None': noErrors = 1 else: if len(testDescription['reserrext'])>0: ext = '.' + testDescription['reserrext'] else: ext = '' else: ext = '' if not noErrors: try: fname = errbase + filename + ext experr = open(fname, 'rt') except: experr = None else: experr = None pin, pout, perr = os.popen3(cmd) if 'stdin' in testDescription: infile = open(inbase + filename, 'rt') pin.writelines(infile.readlines()) infile.close() pin.close() # popen is great fun, but can lead to the old "deadly embrace", because # synchronizing the writing (by the task being run) of stdout and stderr # with respect to the reading (by this task) is basically impossible. I # tried several ways to cheat, but the only way I have found which works # is to do a *very* elementary multi-threading approach. We can only hope # that Python threads are implemented on the target system (it's okay for # Linux and Windows) th1Flag = [] # flags to show when threads finish th2Flag = [] outfile = [] # lists to contain the pipe data errfile = [] th1 = thread.start_new_thread(readPfile, (pout, outfile, th1Flag)) th2 = thread.start_new_thread(readPfile, (perr, errfile, th2Flag)) while (len(th1Flag)==0) or (len(th2Flag)==0): time.sleep(0.001) if not noResult: ret = compFiles(outfile, expout, inbase, 'test/') if ret != 0: print 'trouble with %s' % cmd else: if len(outfile) != 0: for l in outfile: print l print 'trouble with %s' % cmd if experr != None: ret = compFiles(errfile, experr, inbase, 'test/') if ret != 0: print 'trouble with %s' % cmd else: if not noErrors: if len(errfile) != 0: for l in errfile: print l print 'trouble with %s' % cmd if 'stdin' not in testDescription: pin.close() # This routine is called by the parameter decoding routine whenever the end of a # 'test' section is encountered. Depending upon file globbing, a large number of # individual tests may be run. def runTest(description): testDescription = defaultParams.copy() # set defaults testDescription.update(description) # override with current ent if 'testname' in testDescription: print "## %s" % testDescription['testname'] if not 'file' in testDescription: print "No file specified - can't run this test!" return # Set up the source and results directory paths from the decoded params dir = '' if 'srcdir' in testDescription: dir += testDescription['srcdir'] + '/' if 'srcsub' in testDescription: dir += testDescription['srcsub'] + '/' rdir = '' if 'resdir' in testDescription: rdir += testDescription['resdir'] + '/' if 'ressub' in testDescription: rdir += testDescription['ressub'] + '/' testFiles = glob.glob(os.path.abspath(dir + testDescription['file'])) if testFiles == []: print "No files result from '%s'" % testDescription['file'] return # Some test programs just don't work (yet). For now we exclude them. count = 0 excl = [] if 'exclfile' in testDescription: for f in string.split(testDescription['exclfile']): glb = glob.glob(dir + f) for g in glb: excl.append(os.path.abspath(g)) # Run the specified test program for f in testFiles: if not os.path.isdir(f): if f not in excl: count = count + 1 runOneTest(testDescription, os.path.basename(f), dir, rdir) # # The following classes are used with the xmlreader interface to interpret the # parameter file. Once a test section has been identified, runTest is called # with a dictionary containing the parsed results of the interpretation. # class testDefaults: curText = '' # accumulates text content of parameter def addToDict(self, key): txt = string.strip(self.curText) # if txt == '': # return if key not in defaultParams: defaultParams[key] = txt else: defaultParams[key] += ' ' + txt def processNode(self, reader, curClass): if reader.Depth() == 2: if reader.NodeType() == 1: self.curText = '' # clear the working variable elif reader.NodeType() == 15: if (reader.Name() != '#text') and (reader.Name() != '#comment'): self.addToDict(reader.Name()) elif reader.Depth() == 3: if reader.Name() == '#text': self.curText += reader.Value() elif reader.NodeType() == 15: # end of element print "Defaults have been set to:" for k in defaultParams.keys(): print " %s : '%s'" % (k, defaultParams[k]) curClass = rootClass() return curClass class testClass: def __init__(self): self.testParams = {} # start with an empty set of params self.curText = '' # and empty text def addToDict(self, key): data = string.strip(self.curText) if key not in self.testParams: self.testParams[key] = data else: if self.testParams[key] != '': data = ' ' + data self.testParams[key] += data def processNode(self, reader, curClass): if reader.Depth() == 2: if reader.NodeType() == 1: self.curText = '' # clear the working variable if reader.Name() not in self.testParams: self.testParams[reader.Name()] = '' elif reader.NodeType() == 15: if (reader.Name() != '#text') and (reader.Name() != '#comment'): self.addToDict(reader.Name()) elif reader.Depth() == 3: if reader.Name() == '#text': self.curText += reader.Value() elif reader.NodeType() == 15: # end of element runTest(self.testParams) curClass = rootClass() return curClass class rootClass: def processNode(self, reader, curClass): if reader.Depth() == 0: return curClass if reader.Depth() != 1: print "Unexpected junk: Level %d, type %d, name %s" % ( reader.Depth(), reader.NodeType(), reader.Name()) return curClass if reader.Name() == 'test': curClass = testClass() curClass.testParams = {} elif reader.Name() == 'defaults': curClass = testDefaults() return curClass def streamFile(filename): try: reader = libxml2.newTextReaderFilename(filename) except: print "unable to open %s" % (filename) return curClass = rootClass() ret = reader.Read() while ret == 1: curClass = curClass.processNode(reader, curClass) ret = reader.Read() if ret != 0: print "%s : failed to parse" % (filename) # OK, we're finished with all the routines. Now for the main program:- if len(sys.argv) != 2: print "Usage: maketest {filename}" sys.exit(-1) streamFile(sys.argv[1])
Python
#!/usr/bin/python -u # # generate a tester program for the API # import sys import os import string try: import libxml2 except: print "libxml2 python bindings not available, skipping testapi.c generation" sys.exit(0) if len(sys.argv) > 1: srcPref = sys.argv[1] + '/' else: srcPref = '' # # Modules we want to skip in API test # skipped_modules = [ "SAX", "xlink", "threads", "globals", "xmlmemory", "xmlversion", "xmlexports", #deprecated "DOCBparser", ] # # defines for each module # modules_defines = { "HTMLparser": "LIBXML_HTML_ENABLED", "catalog": "LIBXML_CATALOG_ENABLED", "xmlreader": "LIBXML_READER_ENABLED", "relaxng": "LIBXML_SCHEMAS_ENABLED", "schemasInternals": "LIBXML_SCHEMAS_ENABLED", "xmlschemas": "LIBXML_SCHEMAS_ENABLED", "xmlschemastypes": "LIBXML_SCHEMAS_ENABLED", "xpath": "LIBXML_XPATH_ENABLED", "xpathInternals": "LIBXML_XPATH_ENABLED", "xinclude": "LIBXML_XINCLUDE_ENABLED", "xpointer": "LIBXML_XPTR_ENABLED", "xmlregexp" : "LIBXML_REGEXP_ENABLED", "xmlautomata" : "LIBXML_AUTOMATA_ENABLED", "xmlsave" : "LIBXML_OUTPUT_ENABLED", "DOCBparser" : "LIBXML_DOCB_ENABLED", "xmlmodule" : "LIBXML_MODULES_ENABLED", "pattern" : "LIBXML_PATTERN_ENABLED", "schematron" : "LIBXML_SCHEMATRON_ENABLED", } # # defines for specific functions # function_defines = { "htmlDefaultSAXHandlerInit": "LIBXML_HTML_ENABLED", "xmlSAX2EndElement" : "LIBXML_SAX1_ENABLED", "xmlSAX2StartElement" : "LIBXML_SAX1_ENABLED", "xmlSAXDefaultVersion" : "LIBXML_SAX1_ENABLED", "UTF8Toisolat1" : "LIBXML_OUTPUT_ENABLED", "xmlCleanupPredefinedEntities": "LIBXML_LEGACY_ENABLED", "xmlInitializePredefinedEntities": "LIBXML_LEGACY_ENABLED", "xmlSetFeature": "LIBXML_LEGACY_ENABLED", "xmlGetFeature": "LIBXML_LEGACY_ENABLED", "xmlGetFeaturesList": "LIBXML_LEGACY_ENABLED", "xmlIOParseDTD": "LIBXML_VALID_ENABLED", "xmlParseDTD": "LIBXML_VALID_ENABLED", "xmlParseDoc": "LIBXML_SAX1_ENABLED", "xmlParseMemory": "LIBXML_SAX1_ENABLED", "xmlRecoverDoc": "LIBXML_SAX1_ENABLED", "xmlParseFile": "LIBXML_SAX1_ENABLED", "xmlRecoverFile": "LIBXML_SAX1_ENABLED", "xmlRecoverMemory": "LIBXML_SAX1_ENABLED", "xmlSAXParseFileWithData": "LIBXML_SAX1_ENABLED", "xmlSAXParseMemory": "LIBXML_SAX1_ENABLED", "xmlSAXUserParseMemory": "LIBXML_SAX1_ENABLED", "xmlSAXParseDoc": "LIBXML_SAX1_ENABLED", "xmlSAXParseDTD": "LIBXML_SAX1_ENABLED", "xmlSAXUserParseFile": "LIBXML_SAX1_ENABLED", "xmlParseEntity": "LIBXML_SAX1_ENABLED", "xmlParseExternalEntity": "LIBXML_SAX1_ENABLED", "xmlSAXParseMemoryWithData": "LIBXML_SAX1_ENABLED", "xmlParseBalancedChunkMemory": "LIBXML_SAX1_ENABLED", "xmlParseBalancedChunkMemoryRecover": "LIBXML_SAX1_ENABLED", "xmlSetupParserForBuffer": "LIBXML_SAX1_ENABLED", "xmlStopParser": "LIBXML_PUSH_ENABLED", "xmlAttrSerializeTxtContent": "LIBXML_OUTPUT_ENABLED", "xmlSAXParseFile": "LIBXML_SAX1_ENABLED", "xmlSAXParseEntity": "LIBXML_SAX1_ENABLED", "xmlNewTextChild": "LIBXML_TREE_ENABLED", "xmlNewDocRawNode": "LIBXML_TREE_ENABLED", "xmlNewProp": "LIBXML_TREE_ENABLED", "xmlReconciliateNs": "LIBXML_TREE_ENABLED", "xmlValidateNCName": "LIBXML_TREE_ENABLED", "xmlValidateNMToken": "LIBXML_TREE_ENABLED", "xmlValidateName": "LIBXML_TREE_ENABLED", "xmlNewChild": "LIBXML_TREE_ENABLED", "xmlValidateQName": "LIBXML_TREE_ENABLED", "xmlSprintfElementContent": "LIBXML_OUTPUT_ENABLED", "xmlValidGetPotentialChildren" : "LIBXML_VALID_ENABLED", "xmlValidGetValidElements" : "LIBXML_VALID_ENABLED", "docbDefaultSAXHandlerInit" : "LIBXML_DOCB_ENABLED", "xmlTextReaderPreservePattern" : "LIBXML_PATTERN_ENABLED", } # # Some functions really need to be skipped for the tests. # skipped_functions = [ # block on I/O "xmlFdRead", "xmlReadFd", "xmlCtxtReadFd", "htmlFdRead", "htmlReadFd", "htmlCtxtReadFd", "xmlReaderNewFd", "xmlReaderForFd", "xmlIORead", "xmlReadIO", "xmlCtxtReadIO", "htmlIORead", "htmlReadIO", "htmlCtxtReadIO", "xmlReaderNewIO", "xmlBufferDump", "xmlNanoFTPConnect", "xmlNanoFTPConnectTo", "xmlNanoHTTPMethod", "xmlNanoHTTPMethodRedir", # Complex I/O APIs "xmlCreateIOParserCtxt", "xmlParserInputBufferCreateIO", "xmlRegisterInputCallbacks", "xmlReaderForIO", "xmlOutputBufferCreateIO", "xmlRegisterOutputCallbacks", "xmlSaveToIO", "xmlIOHTTPOpenW", # library state cleanup, generate false leak informations and other # troubles, heavillyb tested otherwise. "xmlCleanupParser", "xmlRelaxNGCleanupTypes", "xmlSetListDoc", "xmlSetTreeDoc", "xmlUnlinkNode", # hard to avoid leaks in the tests "xmlStrcat", "xmlStrncat", "xmlCatalogAddLocal", "xmlNewTextWriterDoc", "xmlXPathNewValueTree", "xmlXPathWrapString", # unimplemented "xmlTextReaderReadInnerXml", "xmlTextReaderReadOuterXml", "xmlTextReaderReadString", # destructor "xmlListDelete", "xmlOutputBufferClose", "xmlNanoFTPClose", "xmlNanoHTTPClose", # deprecated "xmlCatalogGetPublic", "xmlCatalogGetSystem", "xmlEncodeEntities", "xmlNewGlobalNs", "xmlHandleEntity", "xmlNamespaceParseNCName", "xmlNamespaceParseNSDef", "xmlNamespaceParseQName", "xmlParseNamespace", "xmlParseQuotedString", "xmlParserHandleReference", "xmlScanName", "xmlDecodeEntities", # allocators "xmlMemFree", # verbosity "xmlCatalogSetDebug", "xmlShellPrintXPathError", "xmlShellPrintNode", # Internal functions, no user space should really call them "xmlParseAttribute", "xmlParseAttributeListDecl", "xmlParseName", "xmlParseNmtoken", "xmlParseEntityValue", "xmlParseAttValue", "xmlParseSystemLiteral", "xmlParsePubidLiteral", "xmlParseCharData", "xmlParseExternalID", "xmlParseComment", "xmlParsePITarget", "xmlParsePI", "xmlParseNotationDecl", "xmlParseEntityDecl", "xmlParseDefaultDecl", "xmlParseNotationType", "xmlParseEnumerationType", "xmlParseEnumeratedType", "xmlParseAttributeType", "xmlParseAttributeListDecl", "xmlParseElementMixedContentDecl", "xmlParseElementChildrenContentDecl", "xmlParseElementContentDecl", "xmlParseElementDecl", "xmlParseMarkupDecl", "xmlParseCharRef", "xmlParseEntityRef", "xmlParseReference", "xmlParsePEReference", "xmlParseDocTypeDecl", "xmlParseAttribute", "xmlParseStartTag", "xmlParseEndTag", "xmlParseCDSect", "xmlParseContent", "xmlParseElement", "xmlParseVersionNum", "xmlParseVersionInfo", "xmlParseEncName", "xmlParseEncodingDecl", "xmlParseSDDecl", "xmlParseXMLDecl", "xmlParseTextDecl", "xmlParseMisc", "xmlParseExternalSubset", "xmlParserHandlePEReference", "xmlSkipBlankChars", ] # # These functions have side effects on the global state # and hence generate errors on memory allocation tests # skipped_memcheck = [ "xmlLoadCatalog", "xmlAddEncodingAlias", "xmlSchemaInitTypes", "xmlNanoFTPProxy", "xmlNanoFTPScanProxy", "xmlNanoHTTPScanProxy", "xmlResetLastError", "xmlCatalogConvert", "xmlCatalogRemove", "xmlLoadCatalogs", "xmlCleanupCharEncodingHandlers", "xmlInitCharEncodingHandlers", "xmlCatalogCleanup", "xmlSchemaGetBuiltInType", "htmlParseFile", "htmlCtxtReadFile", # loads the catalogs "xmlTextReaderSchemaValidate", "xmlSchemaCleanupTypes" # initialize the schemas type system ] # # Extra code needed for some test cases # extra_pre_call = { "xmlSAXUserParseFile": """ #ifdef LIBXML_SAX1_ENABLED if (sax == (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) user_data = NULL; #endif """, "xmlSAXUserParseMemory": """ #ifdef LIBXML_SAX1_ENABLED if (sax == (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) user_data = NULL; #endif """, "xmlParseBalancedChunkMemory": """ #ifdef LIBXML_SAX1_ENABLED if (sax == (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) user_data = NULL; #endif """, "xmlParseBalancedChunkMemoryRecover": """ #ifdef LIBXML_SAX1_ENABLED if (sax == (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) user_data = NULL; #endif """, "xmlParserInputBufferCreateFd": "if (fd >= 0) fd = -1;", } extra_post_call = { "xmlAddChild": "if (ret_val == NULL) { xmlFreeNode(cur) ; cur = NULL ; }", "xmlAddChildList": "if (ret_val == NULL) { xmlFreeNodeList(cur) ; cur = NULL ; }", "xmlAddSibling": "if (ret_val == NULL) { xmlFreeNode(elem) ; elem = NULL ; }", "xmlAddNextSibling": "if (ret_val == NULL) { xmlFreeNode(elem) ; elem = NULL ; }", "xmlAddPrevSibling": "if (ret_val == NULL) { xmlFreeNode(elem) ; elem = NULL ; }", "xmlDocSetRootElement": "if (doc == NULL) { xmlFreeNode(root) ; root = NULL ; }", "xmlReplaceNode": """if (cur != NULL) { xmlUnlinkNode(cur); xmlFreeNode(cur) ; cur = NULL ; } if (old != NULL) { xmlUnlinkNode(old); xmlFreeNode(old) ; old = NULL ; } ret_val = NULL;""", "xmlTextMerge": """if ((first != NULL) && (first->type != XML_TEXT_NODE)) { xmlUnlinkNode(second); xmlFreeNode(second) ; second = NULL ; }""", "xmlBuildQName": """if ((ret_val != NULL) && (ret_val != ncname) && (ret_val != prefix) && (ret_val != memory)) xmlFree(ret_val); ret_val = NULL;""", "xmlNewDocElementContent": """xmlFreeDocElementContent(doc, ret_val); ret_val = NULL;""", "xmlDictReference": "xmlDictFree(dict);", # Functions which deallocates one of their parameters "xmlXPathConvertBoolean": """val = NULL;""", "xmlXPathConvertNumber": """val = NULL;""", "xmlXPathConvertString": """val = NULL;""", "xmlSaveFileTo": """buf = NULL;""", "xmlSaveFormatFileTo": """buf = NULL;""", "xmlIOParseDTD": "input = NULL;", "xmlRemoveProp": "cur = NULL;", "xmlNewNs": "if ((node == NULL) && (ret_val != NULL)) xmlFreeNs(ret_val);", "xmlCopyNamespace": "if (ret_val != NULL) xmlFreeNs(ret_val);", "xmlCopyNamespaceList": "if (ret_val != NULL) xmlFreeNsList(ret_val);", "xmlNewTextWriter": "if (ret_val != NULL) out = NULL;", "xmlNewTextWriterPushParser": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;} if (ret_val != NULL) ctxt = NULL;", "xmlNewIOInputStream": "if (ret_val != NULL) input = NULL;", "htmlParseChunk": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;}", "htmlParseDocument": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;}", "xmlParseDocument": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;}", "xmlParseChunk": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;}", "xmlParseExtParsedEnt": "if (ctxt != NULL) {xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL;}", "xmlDOMWrapAdoptNode": "if ((node != NULL) && (node->parent == NULL)) {xmlUnlinkNode(node);xmlFreeNode(node);node = NULL;}", } modules = [] def is_skipped_module(name): for mod in skipped_modules: if mod == name: return 1 return 0 def is_skipped_function(name): for fun in skipped_functions: if fun == name: return 1 # Do not test destructors if string.find(name, 'Free') != -1: return 1 return 0 def is_skipped_memcheck(name): for fun in skipped_memcheck: if fun == name: return 1 return 0 missing_types = {} def add_missing_type(name, func): try: list = missing_types[name] list.append(func) except: missing_types[name] = [func] generated_param_types = [] def add_generated_param_type(name): generated_param_types.append(name) generated_return_types = [] def add_generated_return_type(name): generated_return_types.append(name) missing_functions = {} missing_functions_nr = 0 def add_missing_functions(name, module): global missing_functions_nr missing_functions_nr = missing_functions_nr + 1 try: list = missing_functions[module] list.append(name) except: missing_functions[module] = [name] # # Provide the type generators and destructors for the parameters # def type_convert(str, name, info, module, function, pos): # res = string.replace(str, " ", " ") # res = string.replace(str, " ", " ") # res = string.replace(str, " ", " ") res = string.replace(str, " *", "_ptr") # res = string.replace(str, "*", "_ptr") res = string.replace(res, " ", "_") if res == 'const_char_ptr': if string.find(name, "file") != -1 or \ string.find(name, "uri") != -1 or \ string.find(name, "URI") != -1 or \ string.find(info, "filename") != -1 or \ string.find(info, "URI") != -1 or \ string.find(info, "URL") != -1: if string.find(function, "Save") != -1 or \ string.find(function, "Create") != -1 or \ string.find(function, "Write") != -1 or \ string.find(function, "Fetch") != -1: return('fileoutput') return('filepath') if res == 'void_ptr': if module == 'nanoftp' and name == 'ctx': return('xmlNanoFTPCtxtPtr') if function == 'xmlNanoFTPNewCtxt' or \ function == 'xmlNanoFTPConnectTo' or \ function == 'xmlNanoFTPOpen': return('xmlNanoFTPCtxtPtr') if module == 'nanohttp' and name == 'ctx': return('xmlNanoHTTPCtxtPtr') if function == 'xmlNanoHTTPMethod' or \ function == 'xmlNanoHTTPMethodRedir' or \ function == 'xmlNanoHTTPOpen' or \ function == 'xmlNanoHTTPOpenRedir': return('xmlNanoHTTPCtxtPtr'); if function == 'xmlIOHTTPOpen': return('xmlNanoHTTPCtxtPtr') if string.find(name, "data") != -1: return('userdata') if string.find(name, "user") != -1: return('userdata') if res == 'xmlDoc_ptr': res = 'xmlDocPtr' if res == 'xmlNode_ptr': res = 'xmlNodePtr' if res == 'xmlDict_ptr': res = 'xmlDictPtr' if res == 'xmlNodePtr' and pos != 0: if (function == 'xmlAddChild' and pos == 2) or \ (function == 'xmlAddChildList' and pos == 2) or \ (function == 'xmlAddNextSibling' and pos == 2) or \ (function == 'xmlAddSibling' and pos == 2) or \ (function == 'xmlDocSetRootElement' and pos == 2) or \ (function == 'xmlReplaceNode' and pos == 2) or \ (function == 'xmlTextMerge') or \ (function == 'xmlAddPrevSibling' and pos == 2): return('xmlNodePtr_in'); if res == 'const xmlBufferPtr': res = 'xmlBufferPtr' if res == 'xmlChar_ptr' and name == 'name' and \ string.find(function, "EatName") != -1: return('eaten_name') if res == 'void_ptr*': res = 'void_ptr_ptr' if res == 'char_ptr*': res = 'char_ptr_ptr' if res == 'xmlChar_ptr*': res = 'xmlChar_ptr_ptr' if res == 'const_xmlChar_ptr*': res = 'const_xmlChar_ptr_ptr' if res == 'const_char_ptr*': res = 'const_char_ptr_ptr' if res == 'FILE_ptr' and module == 'debugXML': res = 'debug_FILE_ptr'; if res == 'int' and name == 'options': if module == 'parser' or module == 'xmlreader': res = 'parseroptions' return res known_param_types = [] def is_known_param_type(name, rtype): global test for type in known_param_types: if type == name: return 1 for type in generated_param_types: if type == name: return 1 if name[-3:] == 'Ptr' or name[-4:] == '_ptr': if rtype[0:6] == 'const ': crtype = rtype[6:] else: crtype = rtype define = 0 if modules_defines.has_key(module): test.write("#ifdef %s\n" % (modules_defines[module])) define = 1 test.write(""" #define gen_nb_%s 1 static %s gen_%s(int no ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { return(NULL); } static void des_%s(int no ATTRIBUTE_UNUSED, %s val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { } """ % (name, crtype, name, name, rtype)) if define == 1: test.write("#endif\n\n") add_generated_param_type(name) return 1 return 0 # # Provide the type destructors for the return values # known_return_types = [] def is_known_return_type(name): for type in known_return_types: if type == name: return 1 return 0 # # Copy the beginning of the C test program result # try: input = open("testapi.c", "r") except: input = open(srcPref + "testapi.c", "r") test = open('testapi.c.new', 'w') def compare_and_save(): global test test.close() try: input = open("testapi.c", "r").read() except: input = '' test = open('testapi.c.new', "r").read() if input != test: try: os.system("rm testapi.c; mv testapi.c.new testapi.c") except: os.system("mv testapi.c.new testapi.c") print("Updated testapi.c") else: print("Generated testapi.c is identical") line = input.readline() while line != "": if line == "/* CUT HERE: everything below that line is generated */\n": break; if line[0:15] == "#define gen_nb_": type = string.split(line[15:])[0] known_param_types.append(type) if line[0:19] == "static void desret_": type = string.split(line[19:], '(')[0] known_return_types.append(type) test.write(line) line = input.readline() input.close() if line == "": print "Could not find the CUT marker in testapi.c skipping generation" test.close() sys.exit(0) print("Scanned testapi.c: found %d parameters types and %d return types\n" % ( len(known_param_types), len(known_return_types))) test.write("/* CUT HERE: everything below that line is generated */\n") # # Open the input API description # doc = libxml2.readFile(srcPref + 'doc/libxml2-api.xml', None, 0) if doc == None: print "Failed to load doc/libxml2-api.xml" sys.exit(1) ctxt = doc.xpathNewContext() # # Generate a list of all function parameters and select only # those used in the api tests # argtypes = {} args = ctxt.xpathEval("/api/symbols/function/arg") for arg in args: mod = arg.xpathEval('string(../@file)') func = arg.xpathEval('string(../@name)') if (mod not in skipped_modules) and (func not in skipped_functions): type = arg.xpathEval('string(@type)') if not argtypes.has_key(type): argtypes[type] = func # similarly for return types rettypes = {} rets = ctxt.xpathEval("/api/symbols/function/return") for ret in rets: mod = ret.xpathEval('string(../@file)') func = ret.xpathEval('string(../@name)') if (mod not in skipped_modules) and (func not in skipped_functions): type = ret.xpathEval('string(@type)') if not rettypes.has_key(type): rettypes[type] = func # # Generate constructors and return type handling for all enums # which are used as function parameters # enums = ctxt.xpathEval("/api/symbols/typedef[@type='enum']") for enum in enums: module = enum.xpathEval('string(@file)') name = enum.xpathEval('string(@name)') # # Skip any enums which are not in our filtered lists # if (name == None) or ((name not in argtypes) and (name not in rettypes)): continue; define = 0 if argtypes.has_key(name) and is_known_param_type(name, name) == 0: values = ctxt.xpathEval("/api/symbols/enum[@type='%s']" % name) i = 0 vals = [] for value in values: vname = value.xpathEval('string(@name)') if vname == None: continue; i = i + 1 if i >= 5: break; vals.append(vname) if vals == []: print "Didn't find any value for enum %s" % (name) continue if modules_defines.has_key(module): test.write("#ifdef %s\n" % (modules_defines[module])) define = 1 test.write("#define gen_nb_%s %d\n" % (name, len(vals))) test.write("""static %s gen_%s(int no, int nr ATTRIBUTE_UNUSED) {\n""" % (name, name)) i = 1 for value in vals: test.write(" if (no == %d) return(%s);\n" % (i, value)) i = i + 1 test.write(""" return(0); } static void des_%s(int no ATTRIBUTE_UNUSED, %s val ATTRIBUTE_UNUSED, int nr ATTRIBUTE_UNUSED) { } """ % (name, name)); known_param_types.append(name) if (is_known_return_type(name) == 0) and (name in rettypes): if define == 0 and modules_defines.has_key(module): test.write("#ifdef %s\n" % (modules_defines[module])) define = 1 test.write("""static void desret_%s(%s val ATTRIBUTE_UNUSED) { } """ % (name, name)) known_return_types.append(name) if define == 1: test.write("#endif\n\n") # # Load the interfaces # headers = ctxt.xpathEval("/api/files/file") for file in headers: name = file.xpathEval('string(@name)') if (name == None) or (name == ''): continue # # Some module may be skipped because they don't really consists # of user callable APIs # if is_skipped_module(name): continue # # do not test deprecated APIs # desc = file.xpathEval('string(description)') if string.find(desc, 'DEPRECATED') != -1: print "Skipping deprecated interface %s" % name continue; test.write("#include <libxml/%s.h>\n" % name) modules.append(name) # # Generate the callers signatures # for module in modules: test.write("static int test_%s(void);\n" % module); # # Generate the top caller # test.write(""" /** * testlibxml2: * * Main entry point of the tester for the full libxml2 module, * it calls all the tester entry point for each module. * * Returns the number of error found */ static int testlibxml2(void) { int test_ret = 0; """) for module in modules: test.write(" test_ret += test_%s();\n" % module) test.write(""" printf("Total: %d functions, %d tests, %d errors\\n", function_tests, call_tests, test_ret); return(test_ret); } """) # # How to handle a function # nb_tests = 0 def generate_test(module, node): global test global nb_tests nb_cond = 0 no_gen = 0 name = node.xpathEval('string(@name)') if is_skipped_function(name): return # # check we know how to handle the args and return values # and store the informations for the generation # try: args = node.xpathEval("arg") except: args = [] t_args = [] n = 0 for arg in args: n = n + 1 rtype = arg.xpathEval("string(@type)") if rtype == 'void': break; info = arg.xpathEval("string(@info)") nam = arg.xpathEval("string(@name)") type = type_convert(rtype, nam, info, module, name, n) if is_known_param_type(type, rtype) == 0: add_missing_type(type, name); no_gen = 1 if (type[-3:] == 'Ptr' or type[-4:] == '_ptr') and \ rtype[0:6] == 'const ': crtype = rtype[6:] else: crtype = rtype t_args.append((nam, type, rtype, crtype, info)) try: rets = node.xpathEval("return") except: rets = [] t_ret = None for ret in rets: rtype = ret.xpathEval("string(@type)") info = ret.xpathEval("string(@info)") type = type_convert(rtype, 'return', info, module, name, 0) if rtype == 'void': break if is_known_return_type(type) == 0: add_missing_type(type, name); no_gen = 1 t_ret = (type, rtype, info) break test.write(""" static int test_%s(void) { int test_ret = 0; """ % (name)) if no_gen == 1: add_missing_functions(name, module) test.write(""" /* missing type support */ return(test_ret); } """) return try: conds = node.xpathEval("cond") for cond in conds: test.write("#if %s\n" % (cond.get_content())) nb_cond = nb_cond + 1 except: pass define = 0 if function_defines.has_key(name): test.write("#ifdef %s\n" % (function_defines[name])) define = 1 # Declare the memory usage counter no_mem = is_skipped_memcheck(name) if no_mem == 0: test.write(" int mem_base;\n"); # Declare the return value if t_ret != None: test.write(" %s ret_val;\n" % (t_ret[1])) # Declare the arguments for arg in t_args: (nam, type, rtype, crtype, info) = arg; # add declaration test.write(" %s %s; /* %s */\n" % (crtype, nam, info)) test.write(" int n_%s;\n" % (nam)) test.write("\n") # Cascade loop on of each argument list of values for arg in t_args: (nam, type, rtype, crtype, info) = arg; # test.write(" for (n_%s = 0;n_%s < gen_nb_%s;n_%s++) {\n" % ( nam, nam, type, nam)) # log the memory usage if no_mem == 0: test.write(" mem_base = xmlMemBlocks();\n"); # prepare the call i = 0; for arg in t_args: (nam, type, rtype, crtype, info) = arg; # test.write(" %s = gen_%s(n_%s, %d);\n" % (nam, type, nam, i)) i = i + 1; # do the call, and clanup the result if extra_pre_call.has_key(name): test.write(" %s\n"% (extra_pre_call[name])) if t_ret != None: test.write("\n ret_val = %s(" % (name)) need = 0 for arg in t_args: (nam, type, rtype, crtype, info) = arg if need: test.write(", ") else: need = 1 if rtype != crtype: test.write("(%s)" % rtype) test.write("%s" % nam); test.write(");\n") if extra_post_call.has_key(name): test.write(" %s\n"% (extra_post_call[name])) test.write(" desret_%s(ret_val);\n" % t_ret[0]) else: test.write("\n %s(" % (name)); need = 0; for arg in t_args: (nam, type, rtype, crtype, info) = arg; if need: test.write(", ") else: need = 1 if rtype != crtype: test.write("(%s)" % rtype) test.write("%s" % nam) test.write(");\n") if extra_post_call.has_key(name): test.write(" %s\n"% (extra_post_call[name])) test.write(" call_tests++;\n"); # Free the arguments i = 0; for arg in t_args: (nam, type, rtype, crtype, info) = arg; # This is a hack to prevent generating a destructor for the # 'input' argument in xmlTextReaderSetup. There should be # a better, more generic way to do this! if string.find(info, 'destroy') == -1: test.write(" des_%s(n_%s, " % (type, nam)) if rtype != crtype: test.write("(%s)" % rtype) test.write("%s, %d);\n" % (nam, i)) i = i + 1; test.write(" xmlResetLastError();\n"); # Check the memory usage if no_mem == 0: test.write(""" if (mem_base != xmlMemBlocks()) { printf("Leak of %%d blocks found in %s", xmlMemBlocks() - mem_base); test_ret++; """ % (name)); for arg in t_args: (nam, type, rtype, crtype, info) = arg; test.write(""" printf(" %%d", n_%s);\n""" % (nam)) test.write(""" printf("\\n");\n""") test.write(" }\n") for arg in t_args: test.write(" }\n") test.write(" function_tests++;\n") # # end of conditional # while nb_cond > 0: test.write("#endif\n") nb_cond = nb_cond -1 if define == 1: test.write("#endif\n") nb_tests = nb_tests + 1; test.write(""" return(test_ret); } """) # # Generate all module callers # for module in modules: # gather all the functions exported by that module try: functions = ctxt.xpathEval("/api/symbols/function[@file='%s']" % (module)) except: print "Failed to gather functions from module %s" % (module) continue; # iterate over all functions in the module generating the test i = 0 nb_tests_old = nb_tests for function in functions: i = i + 1 generate_test(module, function); # header test.write("""static int test_%s(void) { int test_ret = 0; if (quiet == 0) printf("Testing %s : %d of %d functions ...\\n"); """ % (module, module, nb_tests - nb_tests_old, i)) # iterate over all functions in the module generating the call for function in functions: name = function.xpathEval('string(@name)') if is_skipped_function(name): continue test.write(" test_ret += test_%s();\n" % (name)) # footer test.write(""" if (test_ret != 0) printf("Module %s: %%d errors\\n", test_ret); return(test_ret); } """ % (module)) # # Generate direct module caller # test.write("""static int test_module(const char *module) { """); for module in modules: test.write(""" if (!strcmp(module, "%s")) return(test_%s());\n""" % ( module, module)) test.write(""" return(0); } """); print "Generated test for %d modules and %d functions" %(len(modules), nb_tests) compare_and_save() missing_list = [] for missing in missing_types.keys(): if missing == 'va_list' or missing == '...': continue; n = len(missing_types[missing]) missing_list.append((n, missing)) def compare_missing(a, b): return b[0] - a[0] missing_list.sort(compare_missing) print "Missing support for %d functions and %d types see missing.lst" % (missing_functions_nr, len(missing_list)) lst = open("missing.lst", "w") lst.write("Missing support for %d types" % (len(missing_list))) lst.write("\n") for miss in missing_list: lst.write("%s: %d :" % (miss[1], miss[0])) i = 0 for n in missing_types[miss[1]]: i = i + 1 if i > 5: lst.write(" ...") break lst.write(" %s" % (n)) lst.write("\n") lst.write("\n") lst.write("\n") lst.write("Missing support per module"); for module in missing_functions.keys(): lst.write("module %s:\n %s\n" % (module, missing_functions[module])) lst.close()
Python
#!/usr/bin/python import sys import time import os import string sys.path.insert(0, "python") import libxml2 test_nr = 0 test_succeed = 0 test_failed = 0 test_error = 0 # # the testsuite description # CONF="xml-test-suite/xmlconf/xmlconf.xml" LOG="check-xml-test-suite.log" log = open(LOG, "w") # # Error and warning handlers # error_nr = 0 error_msg = '' def errorHandler(ctx, str): global error_nr global error_msg error_nr = error_nr + 1 if len(error_msg) < 300: if len(error_msg) == 0 or error_msg[-1] == '\n': error_msg = error_msg + " >>" + str else: error_msg = error_msg + str libxml2.registerErrorHandler(errorHandler, None) #warning_nr = 0 #warning = '' #def warningHandler(ctx, str): # global warning_nr # global warning # # warning_nr = warning_nr + 1 # warning = warning + str # #libxml2.registerWarningHandler(warningHandler, None) # # Used to load the XML testsuite description # def loadNoentDoc(filename): ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return None ctxt.replaceEntities(1) ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if ctxt.wellFormed() != 1: doc.freeDoc() return None return doc # # The conformance testing routines # def testNotWf(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if doc != None: doc.freeDoc() if ret == 0 or ctxt.wellFormed() != 0: print "%s: error: Well Formedness error not detected" % (id) log.write("%s: error: Well Formedness error not detected\n" % (id)) return 0 return 1 def testNotWfEnt(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.replaceEntities(1) ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if doc != None: doc.freeDoc() if ret == 0 or ctxt.wellFormed() != 0: print "%s: error: Well Formedness error not detected" % (id) log.write("%s: error: Well Formedness error not detected\n" % (id)) return 0 return 1 def testNotWfEntDtd(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.replaceEntities(1) ctxt.loadSubset(1) ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if doc != None: doc.freeDoc() if ret == 0 or ctxt.wellFormed() != 0: print "%s: error: Well Formedness error not detected" % (id) log.write("%s: error: Well Formedness error not detected\n" % (id)) return 0 return 1 def testWfEntDtd(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.replaceEntities(1) ctxt.loadSubset(1) ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if doc == None or ret != 0 or ctxt.wellFormed() == 0: print "%s: error: wrongly failed to parse the document" % (id) log.write("%s: error: wrongly failed to parse the document\n" % (id)) if doc != None: doc.freeDoc() return 0 if error_nr != 0: print "%s: warning: WF document generated an error msg" % (id) log.write("%s: error: WF document generated an error msg\n" % (id)) doc.freeDoc() return 2 doc.freeDoc() return 1 def testError(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.replaceEntities(1) ctxt.loadSubset(1) ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None if doc != None: doc.freeDoc() if ctxt.wellFormed() == 0: print "%s: warning: failed to parse the document but accepted" % (id) log.write("%s: warning: failed to parse the document but accepte\n" % (id)) return 2 if error_nr != 0: print "%s: warning: WF document generated an error msg" % (id) log.write("%s: error: WF document generated an error msg\n" % (id)) return 2 return 1 def testInvalid(filename, id): global error_nr global error_msg global log error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.validate(1) ret = ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None valid = ctxt.isValid() if doc == None: print "%s: error: wrongly failed to parse the document" % (id) log.write("%s: error: wrongly failed to parse the document\n" % (id)) return 0 if valid == 1: print "%s: error: Validity error not detected" % (id) log.write("%s: error: Validity error not detected\n" % (id)) doc.freeDoc() return 0 if error_nr == 0: print "%s: warning: Validity error not reported" % (id) log.write("%s: warning: Validity error not reported\n" % (id)) doc.freeDoc() return 2 doc.freeDoc() return 1 def testValid(filename, id): global error_nr global error_msg error_nr = 0 error_msg = '' ctxt = libxml2.createFileParserCtxt(filename) if ctxt == None: return -1 ctxt.validate(1) ctxt.parseDocument() try: doc = ctxt.doc() except: doc = None valid = ctxt.isValid() if doc == None: print "%s: error: wrongly failed to parse the document" % (id) log.write("%s: error: wrongly failed to parse the document\n" % (id)) return 0 if valid != 1: print "%s: error: Validity check failed" % (id) log.write("%s: error: Validity check failed\n" % (id)) doc.freeDoc() return 0 if error_nr != 0 or valid != 1: print "%s: warning: valid document reported an error" % (id) log.write("%s: warning: valid document reported an error\n" % (id)) doc.freeDoc() return 2 doc.freeDoc() return 1 def runTest(test): global test_nr global test_succeed global test_failed global error_msg global log uri = test.prop('URI') id = test.prop('ID') if uri == None: print "Test without ID:", uri return -1 if id == None: print "Test without URI:", id return -1 base = test.getBase(None) URI = libxml2.buildURI(uri, base) if os.access(URI, os.R_OK) == 0: print "Test %s missing: base %s uri %s" % (URI, base, uri) return -1 type = test.prop('TYPE') if type == None: print "Test %s missing TYPE" % (id) return -1 extra = None if type == "invalid": res = testInvalid(URI, id) elif type == "valid": res = testValid(URI, id) elif type == "not-wf": extra = test.prop('ENTITIES') # print URI #if extra == None: # res = testNotWfEntDtd(URI, id) #elif extra == 'none': # res = testNotWf(URI, id) #elif extra == 'general': # res = testNotWfEnt(URI, id) #elif extra == 'both' or extra == 'parameter': res = testNotWfEntDtd(URI, id) #else: # print "Unknow value %s for an ENTITIES test value" % (extra) # return -1 elif type == "error": res = testError(URI, id) else: # TODO skipped for now return -1 test_nr = test_nr + 1 if res > 0: test_succeed = test_succeed + 1 elif res == 0: test_failed = test_failed + 1 elif res < 0: test_error = test_error + 1 # Log the ontext if res != 1: log.write(" File: %s\n" % (URI)) content = string.strip(test.content) while content[-1] == '\n': content = content[0:-1] if extra != None: log.write(" %s:%s:%s\n" % (type, extra, content)) else: log.write(" %s:%s\n\n" % (type, content)) if error_msg != '': log.write(" ----\n%s ----\n" % (error_msg)) error_msg = '' log.write("\n") return 0 def runTestCases(case): profile = case.prop('PROFILE') if profile != None and \ string.find(profile, "IBM XML Conformance Test Suite - Production") < 0: print "=>", profile test = case.children while test != None: if test.name == 'TEST': runTest(test) if test.name == 'TESTCASES': runTestCases(test) test = test.next conf = loadNoentDoc(CONF) if conf == None: print "Unable to load %s" % CONF sys.exit(1) testsuite = conf.getRootElement() if testsuite.name != 'TESTSUITE': print "Expecting TESTSUITE root element: aborting" sys.exit(1) profile = testsuite.prop('PROFILE') if profile != None: print profile start = time.time() case = testsuite.children while case != None: if case.name == 'TESTCASES': old_test_nr = test_nr old_test_succeed = test_succeed old_test_failed = test_failed old_test_error = test_error runTestCases(case) print " Ran %d tests: %d suceeded, %d failed and %d generated an error" % ( test_nr - old_test_nr, test_succeed - old_test_succeed, test_failed - old_test_failed, test_error - old_test_error) case = case.next conf.freeDoc() log.close() print "Ran %d tests: %d suceeded, %d failed and %d generated an error in %.2f s." % ( test_nr, test_succeed, test_failed, test_error, time.time() - start)
Python
#!/usr/bin/python -u # # Original script modified in November 2003 to take advantage of # the character-validation range routines, and updated to the # current Unicode information (Version 4.0.1) # # NOTE: there is an 'alias' facility for blocks which are not present in # the current release, but are needed for ABI compatibility. This # must be accomplished MANUALLY! Please see the comments below under # 'blockAliases' # import sys import string import time webpage = "http://www.unicode.org/Public/4.0-Update1/UCD-4.0.1.html" sources = "Blocks-4.0.1.txt UnicodeData-4.0.1.txt" # # blockAliases is a small hack - it is used for mapping block names which # were were used in the 3.1 release, but are missing or changed in the current # release. The format is "OldBlockName:NewBlockName1[,NewBlockName2[,...]]" blockAliases = [] blockAliases.append("CombiningMarksforSymbols:CombiningDiacriticalMarksforSymbols") blockAliases.append("Greek:GreekandCoptic") blockAliases.append("PrivateUse:PrivateUseArea,SupplementaryPrivateUseArea-A," + "SupplementaryPrivateUseArea-B") # minTableSize gives the minimum number of ranges which must be present # before a range table is produced. If there are less than this # number, inline comparisons are generated minTableSize = 8 (blockfile, catfile) = string.split(sources) # # Now process the "blocks" file, reducing it to a dictionary # indexed by blockname, containing a tuple with the applicable # block range # BlockNames = {} try: blocks = open(blockfile, "r") except: print "Missing %s, aborting ..." % blockfile sys.exit(1) for line in blocks.readlines(): if line[0] == '#': continue line = string.strip(line) if line == '': continue try: fields = string.split(line, ';') range = string.strip(fields[0]) (start, end) = string.split(range, "..") name = string.strip(fields[1]) name = string.replace(name, ' ', '') except: print "Failed to process line: %s" % (line) continue start = "0x" + start end = "0x" + end try: BlockNames[name].append((start, end)) except: BlockNames[name] = [(start, end)] blocks.close() print "Parsed %d blocks descriptions" % (len(BlockNames.keys())) for block in blockAliases: alias = string.split(block,':') alist = string.split(alias[1],',') for comp in alist: if BlockNames.has_key(comp): if alias[0] not in BlockNames: BlockNames[alias[0]] = [] for r in BlockNames[comp]: BlockNames[alias[0]].append(r) else: print "Alias %s: %s not in Blocks" % (alias[0], comp) continue # # Next process the Categories file. This is more complex, since # the file is in code sequence, and we need to invert it. We use # a dictionary with index category-name, with each entry containing # all the ranges (codepoints) of that category. Note that category # names comprise two parts - the general category, and the "subclass" # within that category. Therefore, both "general category" (which is # the first character of the 2-character category-name) and the full # (2-character) name are entered into this dictionary. # try: data = open(catfile, "r") except: print "Missing %s, aborting ..." % catfile sys.exit(1) nbchar = 0; Categories = {} for line in data.readlines(): if line[0] == '#': continue line = string.strip(line) if line == '': continue try: fields = string.split(line, ';') point = string.strip(fields[0]) value = 0 while point != '': value = value * 16 if point[0] >= '0' and point[0] <= '9': value = value + ord(point[0]) - ord('0') elif point[0] >= 'A' and point[0] <= 'F': value = value + 10 + ord(point[0]) - ord('A') elif point[0] >= 'a' and point[0] <= 'f': value = value + 10 + ord(point[0]) - ord('a') point = point[1:] name = fields[2] except: print "Failed to process line: %s" % (line) continue nbchar = nbchar + 1 # update entry for "full name" try: Categories[name].append(value) except: try: Categories[name] = [value] except: print "Failed to process line: %s" % (line) # update "general category" name try: Categories[name[0]].append(value) except: try: Categories[name[0]] = [value] except: print "Failed to process line: %s" % (line) blocks.close() print "Parsed %d char generating %d categories" % (nbchar, len(Categories.keys())) # # The data is now all read. Time to process it into a more useful form. # # reduce the number list into ranges for cat in Categories.keys(): list = Categories[cat] start = -1 prev = -1 end = -1 ranges = [] for val in list: if start == -1: start = val prev = val continue elif val == prev + 1: prev = val continue elif prev == start: ranges.append((prev, prev)) start = val prev = val continue else: ranges.append((start, prev)) start = val prev = val continue if prev == start: ranges.append((prev, prev)) else: ranges.append((start, prev)) Categories[cat] = ranges # # Assure all data is in alphabetic order, since we will be doing binary # searches on the tables. # bkeys = BlockNames.keys() bkeys.sort() ckeys = Categories.keys() ckeys.sort() # # Generate the resulting files # try: header = open("include/libxml/xmlunicode.h", "w") except: print "Failed to open include/libxml/xmlunicode.h" sys.exit(1) try: output = open("xmlunicode.c", "w") except: print "Failed to open xmlunicode.c" sys.exit(1) date = time.asctime(time.localtime(time.time())) header.write( """/* * Summary: Unicode character APIs * Description: API for the Unicode character APIs * * This file is automatically generated from the * UCS description files of the Unicode Character Database * %s * using the genUnicode.py Python script. * * Generation date: %s * Sources: %s * Author: Daniel Veillard */ #ifndef __XML_UNICODE_H__ #define __XML_UNICODE_H__ #include <libxml/xmlversion.h> #ifdef LIBXML_UNICODE_ENABLED #ifdef __cplusplus extern "C" { #endif """ % (webpage, date, sources)); output.write( """/* * xmlunicode.c: this module implements the Unicode character APIs * * This file is automatically generated from the * UCS description files of the Unicode Character Database * %s * using the genUnicode.py Python script. * * Generation date: %s * Sources: %s * Daniel Veillard <veillard@redhat.com> */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_UNICODE_ENABLED #include <string.h> #include <libxml/xmlversion.h> #include <libxml/xmlunicode.h> #include <libxml/chvalid.h> typedef int (xmlIntFunc)(int); /* just to keep one's mind untwisted */ typedef struct { const char *rangename; xmlIntFunc *func; } xmlUnicodeRange; typedef struct { xmlUnicodeRange *table; int numentries; } xmlUnicodeNameTable; static xmlIntFunc *xmlUnicodeLookup(xmlUnicodeNameTable *tptr, const char *tname); static xmlUnicodeRange xmlUnicodeBlocks[] = { """ % (webpage, date, sources)); flag = 0 for block in bkeys: name = string.replace(block, '-', '') if flag: output.write(',\n') else: flag = 1 output.write(' {"%s", xmlUCSIs%s}' % (block, name)) output.write('};\n\n') output.write('static xmlUnicodeRange xmlUnicodeCats[] = {\n') flag = 0; for name in ckeys: if flag: output.write(',\n') else: flag = 1 output.write(' {"%s", xmlUCSIsCat%s}' % (name, name)) output.write('};\n\n') # # For any categories with more than minTableSize ranges we generate # a range table suitable for xmlCharInRange # for name in ckeys: if len(Categories[name]) > minTableSize: numshort = 0 numlong = 0 ranges = Categories[name] sptr = "NULL" lptr = "NULL" for range in ranges: (low, high) = range if high < 0x10000: if numshort == 0: pline = "static const xmlChSRange xml%sS[] = {" % name sptr = "xml%sS" % name else: pline += ", " numshort += 1 else: if numlong == 0: if numshort > 0: output.write(pline + " };\n") pline = "static const xmlChLRange xml%sL[] = {" % name lptr = "xml%sL" % name else: pline += ", " numlong += 1 if len(pline) > 60: output.write(pline + "\n") pline = " " pline += "{%s, %s}" % (hex(low), hex(high)) output.write(pline + " };\nstatic xmlChRangeGroup xml%sG = {%s,%s,%s,%s};\n\n" % (name, numshort, numlong, sptr, lptr)) output.write( """static xmlUnicodeNameTable xmlUnicodeBlockTbl = {xmlUnicodeBlocks, %s}; static xmlUnicodeNameTable xmlUnicodeCatTbl = {xmlUnicodeCats, %s}; /** * xmlUnicodeLookup: * @tptr: pointer to the name table * @name: name to be found * * binary table lookup for user-supplied name * * Returns pointer to range function if found, otherwise NULL */ static xmlIntFunc *xmlUnicodeLookup(xmlUnicodeNameTable *tptr, const char *tname) { int low, high, mid, cmp; xmlUnicodeRange *sptr; if ((tptr == NULL) || (tname == NULL)) return(NULL); low = 0; high = tptr->numentries - 1; sptr = tptr->table; while (low <= high) { mid = (low + high) / 2; if ((cmp=strcmp(tname, sptr[mid].rangename)) == 0) return (sptr[mid].func); if (cmp < 0) high = mid - 1; else low = mid + 1; } return (NULL); } """ % (len(BlockNames), len(Categories)) ) for block in bkeys: name = string.replace(block, '-', '') header.write("XMLPUBFUN int XMLCALL xmlUCSIs%s\t(int code);\n" % name) output.write("/**\n * xmlUCSIs%s:\n * @code: UCS code point\n" % (name)) output.write(" *\n * Check whether the character is part of %s UCS Block\n"% (block)) output.write(" *\n * Returns 1 if true 0 otherwise\n */\n"); output.write("int\nxmlUCSIs%s(int code) {\n return(" % name) flag = 0 for (start, end) in BlockNames[block]: if flag: output.write(" ||\n ") else: flag = 1 output.write("((code >= %s) && (code <= %s))" % (start, end)) output.write(");\n}\n\n") header.write("\nXMLPUBFUN int XMLCALL xmlUCSIsBlock\t(int code, const char *block);\n\n") output.write( """/** * xmlUCSIsBlock: * @code: UCS code point * @block: UCS block name * * Check whether the character is part of the UCS Block * * Returns 1 if true, 0 if false and -1 on unknown block */ int xmlUCSIsBlock(int code, const char *block) { xmlIntFunc *func; func = xmlUnicodeLookup(&xmlUnicodeBlockTbl, block); if (func == NULL) return (-1); return (func(code)); } """) for name in ckeys: ranges = Categories[name] header.write("XMLPUBFUN int XMLCALL xmlUCSIsCat%s\t(int code);\n" % name) output.write("/**\n * xmlUCSIsCat%s:\n * @code: UCS code point\n" % (name)) output.write(" *\n * Check whether the character is part of %s UCS Category\n"% (name)) output.write(" *\n * Returns 1 if true 0 otherwise\n */\n"); output.write("int\nxmlUCSIsCat%s(int code) {\n" % name) if len(Categories[name]) > minTableSize: output.write(" return(xmlCharInRange((unsigned int)code, &xml%sG)" % name) else: start = 1 for range in ranges: (begin, end) = range; if start: output.write(" return("); start = 0 else: output.write(" ||\n "); if (begin == end): output.write("(code == %s)" % (hex(begin))) else: output.write("((code >= %s) && (code <= %s))" % ( hex(begin), hex(end))) output.write(");\n}\n\n") header.write("\nXMLPUBFUN int XMLCALL xmlUCSIsCat\t(int code, const char *cat);\n") output.write( """/** * xmlUCSIsCat: * @code: UCS code point * @cat: UCS Category name * * Check whether the character is part of the UCS Category * * Returns 1 if true, 0 if false and -1 on unknown category */ int xmlUCSIsCat(int code, const char *cat) { xmlIntFunc *func; func = xmlUnicodeLookup(&xmlUnicodeCatTbl, cat); if (func == NULL) return (-1); return (func(code)); } #define bottom_xmlunicode #include "elfgcchack.h" #endif /* LIBXML_UNICODE_ENABLED */ """) header.write(""" #ifdef __cplusplus } #endif #endif /* LIBXML_UNICODE_ENABLED */ #endif /* __XML_UNICODE_H__ */ """); header.close() output.close()
Python
#!/usr/bin/python import sys import time import os import string import StringIO sys.path.insert(0, "python") import libxml2 # Memory debug specific libxml2.debugMemory(1) debug = 0 quiet = 1 # # the testsuite description # CONF=os.path.join(os.path.dirname(__file__), "test/relaxng/testsuite.xml") LOG="check-relaxng-test-suite2.log" log = open(LOG, "w") nb_schemas_tests = 0 nb_schemas_success = 0 nb_schemas_failed = 0 nb_instances_tests = 0 nb_instances_success = 0 nb_instances_failed = 0 libxml2.lineNumbersDefault(1) # # Resolver callback # resources = {} def resolver(URL, ID, ctxt): global resources if resources.has_key(URL): return(StringIO.StringIO(resources[URL])) log.write("Resolver failure: asked %s\n" % (URL)) log.write("resources: %s\n" % (resources)) return None # # Load the previous results # #results = {} #previous = {} # #try: # res = libxml2.parseFile(RES) #except: # log.write("Could not parse %s" % (RES)) # # handle a valid instance # def handle_valid(node, schema): global log global nb_instances_success global nb_instances_failed instance = node.prop("dtd") if instance == None: instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next # mem = libxml2.debugMemory(1); try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nFailed to parse correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 return if debug: print "instance line %d" % (node.lineNo()) try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) del ctxt except: ret = -1 doc.freeDoc() # if mem != libxml2.debugMemory(1): # print "validating instance %d line %d leaks" % ( # nb_instances_tests, node.lineNo()) if ret != 0: log.write("\nFailed to validate correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 # # handle an invalid instance # def handle_invalid(node, schema): global log global nb_instances_success global nb_instances_failed instance = node.prop("dtd") if instance == None: instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next # mem = libxml2.debugMemory(1); try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nStrange: failed to parse incorrect instance:\n-----\n") log.write(instance) log.write("\n-----\n") return if debug: print "instance line %d" % (node.lineNo()) try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) del ctxt except: ret = -1 doc.freeDoc() # mem2 = libxml2.debugMemory(1) # if mem != mem2: # print "validating instance %d line %d leaks %d bytes" % ( # nb_instances_tests, node.lineNo(), mem2 - mem) if ret == 0: log.write("\nFailed to detect validation problem in instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 # # handle an incorrect test # def handle_correct(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs == None: log.write("\nFailed to compile correct schema:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: nb_schemas_success = nb_schemas_success + 1 return rngs def handle_incorrect(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs != None: log.write("\nFailed to detect schema error in:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: # log.write("\nSuccess detecting schema error in:\n-----\n") # log.write(schema) # log.write("\n-----\n") nb_schemas_success = nb_schemas_success + 1 return None # # resource handling: keep a dictionary of URL->string mappings # def handle_resource(node, dir): global resources try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name res = "" child = node.children while child != None: if child.type != 'text': res = res + child.serialize() child = child.next resources[name] = res # # dir handling: pseudo directory resources # def handle_dir(node, dir): try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, name) res = node.xpathEval('resource') for r in res: handle_resource(r, name) # # handle a testCase element # def handle_testCase(node): global nb_schemas_tests global nb_instances_tests global resources sections = node.xpathEval('string(section)') log.write("\n ======== test %d line %d section %s ==========\n" % ( nb_schemas_tests, node.lineNo(), sections)) resources = {} if debug: print "test %d line %d" % (nb_schemas_tests, node.lineNo()) dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, None) res = node.xpathEval('resource') for r in res: handle_resource(r, None) tsts = node.xpathEval('incorrect') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <incorrect> example" %(node.lineNo()) schema = handle_incorrect(tsts[0]) else: tsts = node.xpathEval('correct') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <correct> example"% (node.lineNo()) schema = handle_correct(tsts[0]) else: print "warning <testCase> line %d has no <correct> nor <incorrect> child" % (node.lineNo()) nb_schemas_tests = nb_schemas_tests + 1; valids = node.xpathEval('valid') invalids = node.xpathEval('invalid') nb_instances_tests = nb_instances_tests + len(valids) + len(invalids) if schema != None: for valid in valids: handle_valid(valid, schema) for invalid in invalids: handle_invalid(invalid, schema) # # handle a testSuite element # def handle_testSuite(node, level = 0): global nb_schemas_tests, nb_schemas_success, nb_schemas_failed global nb_instances_tests, nb_instances_success, nb_instances_failed if level >= 1: old_schemas_tests = nb_schemas_tests old_schemas_success = nb_schemas_success old_schemas_failed = nb_schemas_failed old_instances_tests = nb_instances_tests old_instances_success = nb_instances_success old_instances_failed = nb_instances_failed docs = node.xpathEval('documentation') authors = node.xpathEval('author') if docs != []: msg = "" for doc in docs: msg = msg + doc.content + " " if authors != []: msg = msg + "written by " for author in authors: msg = msg + author.content + " " if quiet == 0: print msg sections = node.xpathEval('section') if sections != [] and level <= 0: msg = "" for section in sections: msg = msg + section.content + " " if quiet == 0: print "Tests for section %s" % (msg) for test in node.xpathEval('testCase'): handle_testCase(test) for test in node.xpathEval('testSuite'): handle_testSuite(test, level + 1) if level >= 1 and sections != []: msg = "" for section in sections: msg = msg + section.content + " " print "Result of tests for section %s" % (msg) if nb_schemas_tests != old_schemas_tests: print "found %d test schemas: %d success %d failures" % ( nb_schemas_tests - old_schemas_tests, nb_schemas_success - old_schemas_success, nb_schemas_failed - old_schemas_failed) if nb_instances_tests != old_instances_tests: print "found %d test instances: %d success %d failures" % ( nb_instances_tests - old_instances_tests, nb_instances_success - old_instances_success, nb_instances_failed - old_instances_failed) # # Parse the conf file # libxml2.substituteEntitiesDefault(1); testsuite = libxml2.parseFile(CONF) # # Error and warnng callbacks # def callback(ctx, str): global log log.write("%s%s" % (ctx, str)) libxml2.registerErrorHandler(callback, "") libxml2.setEntityLoader(resolver) root = testsuite.getRootElement() if root.name != 'testSuite': print "%s doesn't start with a testSuite element, aborting" % (CONF) sys.exit(1) if quiet == 0: print "Running Relax NG testsuite" handle_testSuite(root) if quiet == 0: print "\nTOTAL:\n" if quiet == 0 or nb_schemas_failed != 0: print "found %d test schemas: %d success %d failures" % ( nb_schemas_tests, nb_schemas_success, nb_schemas_failed) if quiet == 0 or nb_instances_failed != 0: print "found %d test instances: %d success %d failures" % ( nb_instances_tests, nb_instances_success, nb_instances_failed) testsuite.freeDoc() # Memory debug specific libxml2.relaxNGCleanupTypes() libxml2.cleanupParser() if libxml2.debugMemory(1) == 0: if quiet == 0: print "OK" else: print "Memory leak %d bytes" % (libxml2.debugMemory(1)) libxml2.dumpMemory()
Python
#!/usr/bin/python import sys import time import os import string import StringIO sys.path.insert(0, "python") import libxml2 # Memory debug specific libxml2.debugMemory(1) debug = 0 verbose = 0 quiet = 1 # # the testsuite description # CONF=os.path.join(os.path.dirname(__file__), "test/xsdtest/xsdtestsuite.xml") LOG="check-xsddata-test-suite.log" log = open(LOG, "w") nb_schemas_tests = 0 nb_schemas_success = 0 nb_schemas_failed = 0 nb_instances_tests = 0 nb_instances_success = 0 nb_instances_failed = 0 libxml2.lineNumbersDefault(1) # # Error and warnng callbacks # def callback(ctx, str): global log log.write("%s%s" % (ctx, str)) libxml2.registerErrorHandler(callback, "") # # Resolver callback # resources = {} def resolver(URL, ID, ctxt): global resources if resources.has_key(URL): return(StringIO.StringIO(resources[URL])) log.write("Resolver failure: asked %s\n" % (URL)) log.write("resources: %s\n" % (resources)) return None # # handle a valid instance # def handle_valid(node, schema): global log global nb_instances_success global nb_instances_failed instance = node.prop("dtd") if instance == None: instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next mem = libxml2.debugMemory(1); try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nFailed to parse correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 return if debug: print "instance line %d" % (node.lineNo()) try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) del ctxt except: ret = -1 doc.freeDoc() if mem != libxml2.debugMemory(1): print "validating instance %d line %d leaks" % ( nb_instances_tests, node.lineNo()) if ret != 0: log.write("\nFailed to validate correct instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 # # handle an invalid instance # def handle_invalid(node, schema): global log global nb_instances_success global nb_instances_failed instance = node.prop("dtd") if instance == None: instance = "" child = node.children while child != None: if child.type != 'text': instance = instance + child.serialize() child = child.next # mem = libxml2.debugMemory(1); try: doc = libxml2.parseDoc(instance) except: doc = None if doc == None: log.write("\nStrange: failed to parse incorrect instance:\n-----\n") log.write(instance) log.write("\n-----\n") return if debug: print "instance line %d" % (node.lineNo()) try: ctxt = schema.relaxNGNewValidCtxt() ret = doc.relaxNGValidateDoc(ctxt) del ctxt except: ret = -1 doc.freeDoc() # if mem != libxml2.debugMemory(1): # print "validating instance %d line %d leaks" % ( # nb_instances_tests, node.lineNo()) if ret == 0: log.write("\nFailed to detect validation problem in instance:\n-----\n") log.write(instance) log.write("\n-----\n") nb_instances_failed = nb_instances_failed + 1 else: nb_instances_success = nb_instances_success + 1 # # handle an incorrect test # def handle_correct(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs == None: log.write("\nFailed to compile correct schema:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: nb_schemas_success = nb_schemas_success + 1 return rngs def handle_incorrect(node): global log global nb_schemas_success global nb_schemas_failed schema = "" child = node.children while child != None: if child.type != 'text': schema = schema + child.serialize() child = child.next try: rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) rngs = rngp.relaxNGParse() except: rngs = None if rngs != None: log.write("\nFailed to detect schema error in:\n-----\n") log.write(schema) log.write("\n-----\n") nb_schemas_failed = nb_schemas_failed + 1 else: # log.write("\nSuccess detecting schema error in:\n-----\n") # log.write(schema) # log.write("\n-----\n") nb_schemas_success = nb_schemas_success + 1 return None # # resource handling: keep a dictionary of URL->string mappings # def handle_resource(node, dir): global resources try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name res = "" child = node.children while child != None: if child.type != 'text': res = res + child.serialize() child = child.next resources[name] = res # # dir handling: pseudo directory resources # def handle_dir(node, dir): try: name = node.prop('name') except: name = None if name == None or name == '': log.write("resource has no name") return; if dir != None: # name = libxml2.buildURI(name, dir) name = dir + '/' + name dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, name) res = node.xpathEval('resource') for r in res: handle_resource(r, name) # # handle a testCase element # def handle_testCase(node): global nb_schemas_tests global nb_instances_tests global resources sections = node.xpathEval('string(section)') log.write("\n ======== test %d line %d section %s ==========\n" % ( nb_schemas_tests, node.lineNo(), sections)) resources = {} if debug: print "test %d line %d" % (nb_schemas_tests, node.lineNo()) dirs = node.xpathEval('dir') for dir in dirs: handle_dir(dir, None) res = node.xpathEval('resource') for r in res: handle_resource(r, None) tsts = node.xpathEval('incorrect') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <incorrect> example" %(node.lineNo()) schema = handle_incorrect(tsts[0]) else: tsts = node.xpathEval('correct') if tsts != []: if len(tsts) != 1: print "warning test line %d has more than one <correct> example"% (node.lineNo()) schema = handle_correct(tsts[0]) else: print "warning <testCase> line %d has no <correct> nor <incorrect> child" % (node.lineNo()) nb_schemas_tests = nb_schemas_tests + 1; valids = node.xpathEval('valid') invalids = node.xpathEval('invalid') nb_instances_tests = nb_instances_tests + len(valids) + len(invalids) if schema != None: for valid in valids: handle_valid(valid, schema) for invalid in invalids: handle_invalid(invalid, schema) # # handle a testSuite element # def handle_testSuite(node, level = 0): global nb_schemas_tests, nb_schemas_success, nb_schemas_failed global nb_instances_tests, nb_instances_success, nb_instances_failed if verbose and level >= 0: old_schemas_tests = nb_schemas_tests old_schemas_success = nb_schemas_success old_schemas_failed = nb_schemas_failed old_instances_tests = nb_instances_tests old_instances_success = nb_instances_success old_instances_failed = nb_instances_failed docs = node.xpathEval('documentation') authors = node.xpathEval('author') if docs != []: msg = "" for doc in docs: msg = msg + doc.content + " " if authors != []: msg = msg + "written by " for author in authors: msg = msg + author.content + " " if quiet == 0: print msg sections = node.xpathEval('section') if verbose and sections != [] and level <= 0: msg = "" for section in sections: msg = msg + section.content + " " if quiet == 0: print "Tests for section %s" % (msg) for test in node.xpathEval('testCase'): handle_testCase(test) for test in node.xpathEval('testSuite'): handle_testSuite(test, level + 1) if verbose and level >= 0 : if sections != []: msg = "" for section in sections: msg = msg + section.content + " " print "Result of tests for section %s" % (msg) elif docs != []: msg = "" for doc in docs: msg = msg + doc.content + " " print "Result of tests for %s" % (msg) if nb_schemas_tests != old_schemas_tests: print "found %d test schemas: %d success %d failures" % ( nb_schemas_tests - old_schemas_tests, nb_schemas_success - old_schemas_success, nb_schemas_failed - old_schemas_failed) if nb_instances_tests != old_instances_tests: print "found %d test instances: %d success %d failures" % ( nb_instances_tests - old_instances_tests, nb_instances_success - old_instances_success, nb_instances_failed - old_instances_failed) # # Parse the conf file # libxml2.substituteEntitiesDefault(1); testsuite = libxml2.parseFile(CONF) # # Error and warnng callbacks # def callback(ctx, str): global log log.write("%s%s" % (ctx, str)) libxml2.registerErrorHandler(callback, "") libxml2.setEntityLoader(resolver) root = testsuite.getRootElement() if root.name != 'testSuite': print "%s doesn't start with a testSuite element, aborting" % (CONF) sys.exit(1) if quiet == 0: print "Running Relax NG testsuite" handle_testSuite(root) if quiet == 0 or nb_schemas_failed != 0: print "\nTOTAL:\nfound %d test schemas: %d success %d failures" % ( nb_schemas_tests, nb_schemas_success, nb_schemas_failed) if quiet == 0 or nb_instances_failed != 0: print "found %d test instances: %d success %d failures" % ( nb_instances_tests, nb_instances_success, nb_instances_failed) testsuite.freeDoc() # Memory debug specific libxml2.relaxNGCleanupTypes() libxml2.cleanupParser() if libxml2.debugMemory(1) == 0: if quiet == 0: print "OK" else: print "Memory leak %d bytes" % (libxml2.debugMemory(1)) libxml2.dumpMemory()
Python
#!/usr/bin/env python import elFinder elFinder.connector({ 'root': '/home/user/Sites/elfinder/files', 'URL': 'http://localhost/~user/elfinder/files', ## other options # 'debug': True, # 'dirSize': True, # 'dotFiles': True, # 'perms': { # 'backup': { # 'read': True, # 'write': False, # 'rm': False # }, # '^/pics': { # 'read': True, # 'write': False, # 'rm': False # } # }, # 'uploadDeny': ['image', 'application'], # 'uploadAllow': ['image/png', 'image/jpeg'], # 'uploadOrder': ['deny', 'allow'] }).run()
Python
#!/usr/bin/env python # # Connector for elFinder File Manager # author Troex Nevelin <troex@fury.scancode.ru> import cgi import hashlib import json import mimetypes import os import os.path import re import shutil import sys import time from datetime import datetime class connector(): """Connector for elFinder""" _options = { 'root': '', 'URL': '', 'rootAlias': 'Home', 'dotFiles': False, 'dirSize': True, 'fileMode': 0644, 'dirMode': 0755, 'imgLib': 'auto', 'tmbDir': '.tmb', 'tmbAtOnce': 5, 'tmbSize': 48, 'fileURL': True, 'uploadMaxSize': 256, 'uploadWriteChunk': 8192, 'uploadAllow': [], 'uploadDeny': [], 'uploadOrder': ['deny', 'allow'], # 'aclObj': None, # TODO # 'aclRole': 'user', # TODO 'defaults': { 'read': True, 'write': True, 'rm': True }, 'perms': {}, 'archiveMimes': {}, 'archivers': {}, 'disabled': [], 'debug': False } _commands = { 'open': '__open', 'reload': '__reload', 'mkdir': '__mkdir', 'mkfile': '__mkfile', 'rename': '__rename', 'upload': '__upload', 'paste': '__paste', 'rm': '__rm', 'duplicate': '__duplicate', 'read': '__read', 'edit': '__edit', 'extract': '__extract', 'archive': '__archive', 'resize': '__resize', 'tmb': '__thumbnails', 'ping': '__ping' } _mimeType = { # text 'txt': 'text/plain', 'php': 'text/x-php', 'html': 'text/html', 'htm': 'text/html', 'js' : 'text/javascript', 'css': 'text/css', 'rtf': 'text/rtf', 'rtfd': 'text/rtfd', 'py' : 'text/x-python', 'java': 'text/x-java-source', 'rb' : 'text/x-ruby', 'sh' : 'text/x-shellscript', 'pl' : 'text/x-perl', 'sql': 'text/x-sql', # apps 'doc': 'application/msword', 'ogg': 'application/ogg', '7z': 'application/x-7z-compressed', # video 'ogm': 'appllication/ogm', 'mkv': 'video/x-matroska' } _time = 0 _request = {} _response = {} _errorData = {} _form = {} _im = None _sp = None _today = 0 _yesterday = 0 def __init__(self, opts): self._response['debug'] = {} if self._options['debug']: self._time = time.time() t = datetime.fromtimestamp(self._time) self._today = time.mktime(datetime(t.year, t.month, t.day).timetuple()) self._yesterday = self._today - 86400 import cgitb cgitb.enable() for opt in opts: self._options[opt] = opts.get(opt) self._options['URL'] = self._options['URL'].rstrip('/') self._options['root'] = self._options['root'].rstrip(os.sep) self.__debug('URL', self._options['URL']) self.__debug('root', self._options['root']) for cmd in self._options['disabled']: if cmd in self._commands: del self._commands[cmd] if self._options['tmbDir']: self._options['tmbDir'] = os.path.join(self._options['root'], self._options['tmbDir']) if not os.path.exists(self._options['tmbDir']): self._options['tmbDir'] = False def run(self): rootOk = True if not os.path.exists(self._options['root']) or self._options['root'] == '': rootOk = False self._response['error'] = 'Invalid backend configuration' elif not self.__isAllowed(self._options['root'], 'read'): rootOk = False self._response['error'] = 'Access denied' possible_fields = ['cmd', 'target', 'targets[]', 'current', 'tree', 'name', 'content', 'src', 'dst', 'cut', 'init', 'type', 'width', 'height'] self._form = cgi.FieldStorage() for field in possible_fields: if field in self._form: self._request[field] = self._form.getvalue(field) if rootOk is True: if 'cmd' in self._request: if self._request['cmd'] in self._commands: cmd = self._commands[self._request['cmd']] func = getattr(self, '_' + self.__class__.__name__ + cmd, None) if callable(func): try: func() except Exception, e: self._response['error'] = 'Command Failed' self.__debug('exception', e) else: self._response['error'] = 'Unknown command' else: self.__open() if 'init' in self._request: self.__checkArchivers() self._response['disabled'] = self._options['disabled'] if not self._options['fileURL']: url = '' else: url = self._options['URL'] self._response['params'] = { 'dotFiles': self._options['dotFiles'], 'uplMaxSize': str(self._options['uploadMaxSize']) + 'M', 'archives': self._options['archiveMimes'], 'extract': self._options['archivers']['extract'].keys(), 'url': url } if self._errorData: self._response['errorData'] = self._errorData if self._options['debug']: self.__debug('time', (time.time() - self._time)) else: if 'debug' in self._response: del self._response['debug'] if ('cmd' in self._request and self._request['cmd'] == 'upload') or self._options['debug']: print 'Content-type: text/html\n' else: print 'Content-type: application/json\n' print json.dumps(self._response, indent = bool(self._options['debug'])) return # sys.exit(0) def __open(self): """Open file or directory""" # try to open file if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if not curDir or not curFile or os.path.isdir(curFile): print 'HTTP/1.x 404 Not Found\n\n' sys.exit('File not found') if not self.__isAllowed(curDir, 'read') or not self.__isAllowed(curFile, 'read'): print 'HTTP/1.x 403 Access Denied\n\n' sys.exit('Access denied') if os.path.islink(curFile): curFile = self.__readlink(curFile) if not curFile or os.path.isdir(curFile): print 'HTTP/1.x 404 Not Found\n\n' sys.exit('File not found') if ( not self.__isAllowed(os.path.dirname(curFile), 'read') or not self.__isAllowed(curFile, 'read') ): print 'HTTP/1.x 403 Access Denied\n\n' sys.exit('Access denied') mime = self.__mimetype(curFile) parts = mime.split('/', 2) if parts[0] == 'image': disp = 'image' elif parts[0] == 'text': disp = 'inline' else: disp = 'attachments' print 'Content-Type: ' + mime print 'Content-Disposition: ' + disp + '; filename=' + os.path.basename(curFile) print 'Content-Location: ' + curFile.replace(self._options['root'], '') print 'Content-Transfer-Encoding: binary' print 'Content-Length: ' + str(os.lstat(curFile).st_size) print 'Connection: close\n' print open(curFile, 'r').read() sys.exit(0); # try dir else: path = self._options['root'] if 'target' in self._request: target = self.__findDir(self._request['target'], None) if not target: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(target, 'read'): self._response['error'] = 'Access denied' else: path = target self.__content(path, 'tree' in self._request) pass def __rename(self): """Rename file or dir""" current = name = target = None curDir = curName = newName = None if 'name' in self._request and 'current' in self._request and 'target' in self._request: name = self._request['name'] current = self._request['current'] target = self._request['target'] curDir = self.__findDir(current, None) curName = self.__find(target, curDir) newName = os.path.join(curDir, name) if not curDir or not curName: self._response['error'] = 'File not found' elif not self.__isAllowed(curDir, 'write') and self.__isAllowed(curName, 'rm'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newName): self._response['error'] = 'File or folder with the same name already exists' else: self.__rmTmb(curName) try: os.rename(curName, newName) self._response['select'] = [self.__hash(newName)] self.__content(curDir, os.path.isdir(newName)) except: self._response['error'] = 'Unable to rename file' def __mkdir(self): """Create new directory""" current = None path = None newDir = None if 'name' in self._request and 'current' in self._request: name = self._request['name'] current = self._request['current'] path = self.__findDir(current, None) newDir = os.path.join(path, name) if not path: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(path, 'write'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newDir): self._response['error'] = 'File or folder with the same name already exists' else: try: os.mkdir(newDir, int(self._options['dirMode'])) self._response['select'] = [self.__hash(newDir)] self.__content(path, True) except: self._response['error'] = 'Unable to create folder' def __mkfile(self): """Create new file""" name = current = None curDir = newFile = None if 'name' in self._request and 'current' in self._request: name = self._request['name'] current = self._request['current'] curDir = self.__findDir(current, None) newFile = os.path.join(curDir, name) if not curDir or not name: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newFile): self._response['error'] = 'File or folder with the same name already exists' else: try: open(newFile, 'w').close() self._response['select'] = [self.__hash(newFile)] self.__content(curDir, False) except: self._response['error'] = 'Unable to create file' def __rm(self): current = rmList = None curDir = rmFile = None if 'current' in self._request and 'targets[]' in self._request: current = self._request['current'] rmList = self._request['targets[]'] curDir = self.__findDir(current, None) if not rmList or not curDir: self._response['error'] = 'Invalid parameters' return False if not isinstance(rmList, list): rmList = [rmList] for rm in rmList: rmFile = self.__find(rm, curDir) if not rmFile: continue self.__remove(rmFile) # TODO if errorData not empty return error self.__content(curDir, True) def __upload(self): try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) if not curDir: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' return if not 'upload[]' in self._form: self._response['error'] = 'No file to upload' return upFiles = self._form['upload[]'] if not isinstance(upFiles, list): upFiles = [upFiles] self._response['select'] = [] total = 0 upSize = 0 maxSize = self._options['uploadMaxSize'] * 1024 * 1024 for up in upFiles: name = up.filename if name: total += 1 name = os.path.basename(name) if not self.__checkName(name): self.__errorData(name, 'Invalid name') else: name = os.path.join(curDir, name) try: f = open(name, 'wb', self._options['uploadWriteChunk']) for chunk in self.__fbuffer(up.file): f.write(chunk) f.close() upSize += os.lstat(name).st_size if self.__isUploadAllow(name): os.chmod(name, self._options['fileMode']) self._response['select'].append(self.__hash(name)) else: self.__errorData(name, 'Not allowed file type') try: os.unlink(name) except: pass except: self.__errorData(name, 'Unable to save uploaded file') if upSize > maxSize: try: os.unlink(name) self.__errorData(name, 'File exceeds the maximum allowed filesize') except: pass # TODO ? self.__errorData(name, 'File was only partially uploaded') break if self._errorData: if len(self._errorData) == total: self._response['error'] = 'Unable to upload files' else: self._response['error'] = 'Some files was not uploaded' self.__content(curDir, False) return def __paste(self): if 'current' in self._request and 'src' in self._request and 'dst' in self._request: curDir = self.__findDir(self._request['current'], None) src = self.__findDir(self._request['src'], None) dst = self.__findDir(self._request['dst'], None) if not curDir or not src or not dst or not 'targets[]' in self._request: self._response['error'] = 'Invalid parameters' return files = self._request['targets[]'] if not isinstance(files, list): files = [files] cut = False if 'cut' in self._request: if self._request['cut'] == '1': cut = True if not self.__isAllowed(src, 'read') or not self.__isAllowed(dst, 'write'): self._response['error'] = 'Access denied' return for fhash in files: f = self.__find(fhash, src) if not f: self._response['error'] = 'File not found' return newDst = os.path.join(dst, os.path.basename(f)) if dst.find(f) == 0: self._response['error'] = 'Unable to copy into itself' return if cut: if not self.__isAllowed(f, 'rm'): self._response['error'] = 'Move failed' self._errorData(f, 'Access denied') self.__content(curDir, True) return # TODO thumbs if os.path.exists(newDst): self._response['error'] = 'Unable to move files' self._errorData(f, 'File or folder with the same name already exists') self.__content(curDir, True) return try: os.rename(f, newDst) self.__rmTmb(f) continue except: self._response['error'] = 'Unable to move files' self._errorData(f, 'Unable to move') self.__content(curDir, True) return else: if not self.__copy(f, newDst): self._response['error'] = 'Unable to copy files' self.__content(curDir, True) return continue self.__content(curDir, True) else: self._response['error'] = 'Invalid parameters' return def __duplicate(self): if 'current' in self._request and 'target' in self._request: curDir = self.__findDir(self._request['current'], None) target = self.__find(self._request['target'], curDir) if not curDir or not target: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(target, 'read') or not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' newName = self.__uniqueName(target) if not self.__copy(target, newName): self._response['error'] = 'Unable to create file copy' return self.__content(curDir, True) return def __resize(self): if not ( 'current' in self._request and 'target' in self._request and 'width' in self._request and 'height' in self._request ): self._response['error'] = 'Invalid parameters' return width = int(self._request['width']) height = int(self._request['height']) curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if width < 1 or height < 1 or not curDir or not curFile: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(curFile, 'write'): self._response['error'] = 'Access denied' return if not self.__mimetype(curFile).find('image') == 0: self._response['error'] = 'File is not an image' return self.__debug('resize ' + curFile, str(width) + ':' + str(height)) self.__initImgLib() try: im = self._im.open(curFile) imResized = im.resize((width, height), self._im.ANTIALIAS) imResized.save(curFile) except Exception, e: self.__debug('resizeFailed_' + path, str(e)) self._response['error'] = 'Unable to resize image' return self._response['select'] = [self.__hash(curFile)] self.__content(curDir, False) return def __thumbnails(self): if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) if not curDir or curDir == self._options['tmbDir']: return False else: return False self.__initImgLib() if self.__canCreateTmb(): if self._options['tmbAtOnce'] > 0: tmbMax = self._options['tmbAtOnce'] else: tmbMax = 5 self._response['current'] = self.__hash(curDir) self._response['images'] = {} i = 0 for f in os.listdir(curDir): path = os.path.join(curDir, f) fhash = self.__hash(path) if self.__canCreateTmb(path) and self.__isAllowed(path, 'read'): tmb = os.path.join(self._options['tmbDir'], fhash + '.png') if not os.path.exists(tmb): if self.__tmb(path, tmb): self._response['images'].update({ fhash: self.__path2url(tmb) }) i += 1 if i >= tmbMax: self._response['tmb'] = True break else: return False return def __content(self, path, tree): """CWD + CDC + maybe(TREE)""" self.__cwd(path) self.__cdc(path) if tree: self._response['tree'] = self.__tree(self._options['root']) def __cwd(self, path): """Current Working Directory""" name = os.path.basename(path) if path == self._options['root']: name = self._options['rootAlias'] root = True else: root = False if self._options['rootAlias']: basename = self._options['rootAlias'] else: basename = os.path.basename(self._options['root']) rel = basename + path[len(self._options['root']):] self._response['cwd'] = { 'hash': self.__hash(path), 'name': name, 'mime': 'directory', 'rel': rel, 'size': 0, 'date': datetime.fromtimestamp(os.stat(path).st_mtime).strftime("%d %b %Y %H:%M"), 'read': True, 'write': self.__isAllowed(path, 'write'), 'rm': not root and self.__isAllowed(path, 'rm') } def __cdc(self, path): """Current Directory Content""" files = [] dirs = [] for f in sorted(os.listdir(path)): if not self.__isAccepted(f): continue pf = os.path.join(path, f) info = {} info = self.__info(pf) info['hash'] = self.__hash(pf) if info['mime'] == 'directory': dirs.append(info) else: files.append(info) dirs.extend(files) self._response['cdc'] = dirs def __info(self, path): mime = '' filetype = 'file' if os.path.isfile(path): filetype = 'file' if os.path.isdir(path): filetype = 'dir' if os.path.islink(path): filetype = 'link' stat = os.lstat(path) statDate = datetime.fromtimestamp(stat.st_mtime) fdate = '' if stat.st_mtime >= self._today: fdate = 'Today ' + statDate.strftime("%H:%M") elif stat.st_mtime >= self._yesterday and stat.st_mtime < self._today: fdate = 'Yesterday ' + statDate.strftime("%H:%M") else: fdate = statDate.strftime("%d %b %Y %H:%M") info = { 'name': os.path.basename(path), 'hash': self.__hash(path), 'mime': 'directory' if filetype == 'dir' else self.__mimetype(path), 'date': fdate, 'size': self.__dirSize(path) if filetype == 'dir' else stat.st_size, 'read': self.__isAllowed(path, 'read'), 'write': self.__isAllowed(path, 'write'), 'rm': self.__isAllowed(path, 'rm') } if filetype == 'link': lpath = self.__readlink(path) if not lpath: info['mime'] = 'symlink-broken' return info if os.path.isdir(lpath): info['mime'] = 'directory' else: info['parent'] = self.__hash(os.path.dirname(lpath)) info['mime'] = self.__mimetype(lpath) if self._options['rootAlias']: basename = self._options['rootAlias'] else: basename = os.path.basename(self._options['root']) info['link'] = self.__hash(lpath) info['linkTo'] = basename + lpath[len(self._options['root']):] info['read'] = info['read'] and self.__isAllowed(lpath, 'read') info['write'] = info['write'] and self.__isAllowed(lpath, 'write') info['rm'] = self.__isAllowed(lpath, 'rm') else: lpath = False if not info['mime'] == 'directory': if self._options['fileURL'] and info['read'] is True: if lpath: info['url'] = self.__path2url(lpath) else: info['url'] = self.__path2url(path) if info['mime'][0:5] == 'image': if self.__canCreateTmb(): dim = self.__getImgSize(path) if dim: info['dim'] = dim info['resize'] = True # if we are in tmb dir, files are thumbs itself if os.path.dirname(path) == self._options['tmbDir']: info['tmb'] = self.__path2url(path) return info tmb = os.path.join(self._options['tmbDir'], info['hash'] + '.png') if os.path.exists(tmb): tmbUrl = self.__path2url(tmb) info['tmb'] = tmbUrl else: self._response['tmb'] = True return info def __tree(self, path): """Return directory tree starting from path""" if not os.path.isdir(path): return '' if os.path.islink(path): return '' if path == self._options['root'] and self._options['rootAlias']: name = self._options['rootAlias'] else: name = os.path.basename(path) tree = { 'hash': self.__hash(path), 'name': name, 'read': self.__isAllowed(path, 'read'), 'write': self.__isAllowed(path, 'write'), 'dirs': [] } if self.__isAllowed(path, 'read'): for d in sorted(os.listdir(path)): pd = os.path.join(path, d) if os.path.isdir(pd) and not os.path.islink(pd) and self.__isAccepted(d): tree['dirs'].append(self.__tree(pd)) return tree def __uniqueName(self, path, copy = ' copy'): curDir = os.path.dirname(path) curName = os.path.basename(path) lastDot = curName.rfind('.') ext = newName = '' if not os.path.isdir(path) and re.search(r'\..{3}\.(gz|bz|bz2)$', curName): pos = -7 if curName[-1:] == '2': pos -= 1 ext = curName[pos:] oldName = curName[0:pos] newName = oldName + copy elif os.path.isdir(path) or lastDot <= 0: oldName = curName newName = oldName + copy pass else: ext = curName[lastDot:] oldName = curName[0:lastDot] newName = oldName + copy pos = 0 if oldName[-len(copy):] == copy: newName = oldName elif re.search(r'' + copy +'\s\d+$', oldName): pos = oldName.rfind(copy) + len(copy) newName = oldName[0:pos] else: newPath = os.path.join(curDir, newName + ext) if not os.path.exists(newPath): return newPath # if we are here then copy already exists or making copy of copy # we will make new indexed copy *black magic* idx = 1 if pos > 0: idx = int(oldName[pos:]) while True: idx += 1 newNameExt = newName + ' ' + str(idx) + ext newPath = os.path.join(curDir, newNameExt) if not os.path.exists(newPath): return newPath # if idx >= 1000: break # possible loop return def __remove(self, target): if not self.__isAllowed(target, 'rm'): self.__errorData(target, 'Access denied') if not os.path.isdir(target): try: os.unlink(target) return True except: self.__errorData(target, 'Remove failed') return False else: for i in os.listdir(target): if self.__isAccepted(i): self.__remove(os.path.join(target, i)) try: os.rmdir(target) return True except: self.__errorData(target, 'Remove failed') return False pass def __copy(self, src, dst): dstDir = os.path.dirname(dst) if not self.__isAllowed(src, 'read'): self.__errorData(src, 'Access denied') return False if not self.__isAllowed(dstDir, 'write'): self.__errorData(dstDir, 'Access denied') return False if os.path.exists(dst): self.__errorData(dst, 'File or folder with the same name already exists') return False if not os.path.isdir(src): try: shutil.copyfile(src, dst) shutil.copymode(src, dst) return True except: self.__errorData(src, 'Unable to copy files') return False else: try: os.mkdir(dst) shutil.copymode(src, dst) except: self.__errorData(src, 'Unable to copy files') return False for i in os.listdir(src): newSrc = os.path.join(src, i) newDst = os.path.join(dst, i) if not self.__copy(newSrc, newDst): self.__errorData(newSrc, 'Unable to copy files') return False return True def __checkName(self, name): """Check for valid file/dir name""" pattern = r'[\/\\\:\<\>]' if re.search(pattern, name): return False return True def __findDir(self, fhash, path): """Find directory by hash""" fhash = str(fhash) if not path: path = self._options['root'] if fhash == self.__hash(path): return path if not os.path.isdir(path): return None for d in os.listdir(path): pd = os.path.join(path, d) if os.path.isdir(pd) and not os.path.islink(pd): if fhash == self.__hash(pd): return pd else: ret = self.__findDir(fhash, pd) if ret: return ret return None def __find(self, fhash, parent): """Find file/dir by hash""" fhash = str(fhash) if os.path.isdir(parent): for i in os.listdir(parent): path = os.path.join(parent, i) if fhash == self.__hash(path): return path return None def __read(self): if 'current' in self._request and 'target' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if curDir and curFile: if self.__isAllowed(curFile, 'read'): self._response['content'] = open(curFile, 'r').read() else: self._response['error'] = 'Access denied' return self._response['error'] = 'Invalid parameters' return def __edit(self): error = '' if 'current' in self._request and 'target' in self._request and 'content' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) error = curFile if curFile and curDir: if self.__isAllowed(curFile, 'write'): try: f = open(curFile, 'w+') f.write(self._request['content']) f.close() self._response['target'] = self.__info(curFile) except: self._response['error'] = 'Unable to write to file' else: self._response['error'] = 'Access denied' return self._response['error'] = 'Invalid parameters' return def __archive(self): self.__checkArchivers() if ( not self._options['archivers']['create'] or not 'type' in self._request or not 'current' in self._request or not 'targets[]' in self._request or not 'name' in self._request ): self._response['error'] = 'Invalid parameters' return curDir = self.__findDir(self._request['current'], None) archiveType = self._request['type'] if ( not archiveType in self._options['archivers']['create'] or not archiveType in self._options['archiveMimes'] or not curDir or not self.__isAllowed(curDir, 'write') ): self._response['error'] = 'Unable to create archive' return files = self._request['targets[]'] if not isinstance(files, list): files = [files] realFiles = [] for fhash in files: curFile = self.__find(fhash, curDir) if not curFile: self._response['error'] = 'File not found' return realFiles.append(os.path.basename(curFile)) arc = self._options['archivers']['create'][archiveType] if len(realFiles) > 1: archiveName = self._request['name'] else: archiveName = realFiles[0] archiveName += '.' + arc['ext'] archiveName = self.__uniqueName(archiveName, '') archivePath = os.path.join(curDir, archiveName) cmd = [arc['cmd']] for a in arc['argc'].split(): cmd.append(a) cmd.append(archiveName) for f in realFiles: cmd.append(f) curCwd = os.getcwd() os.chdir(curDir) self.__runSubProcess(cmd) os.chdir(curCwd) if os.path.exists(archivePath): self.__content(curDir, False) self._response['select'] = [self.__hash(archivePath)] else: self._response['error'] = 'Unable to create archive' return def __extract(self): if not 'current' in self._request or not 'target' in self._request: self._response['error'] = 'Invalid parameters' return curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) mime = self.__mimetype(curFile) self.__checkArchivers() if ( not mime in self._options['archivers']['extract'] or not curDir or not curFile or not self.__isAllowed(curDir, 'write') ): self._response['error'] = 'Invalid parameters' return arc = self._options['archivers']['extract'][mime] cmd = [arc['cmd']] for a in arc['argc'].split(): cmd.append(a) cmd.append(curFile) curCwd = os.getcwd() os.chdir(curDir) ret = self.__runSubProcess(cmd) os.chdir(curCwd) if ret: self.__content(curDir, True) else: self._response['error'] = 'Unable to extract files from archive' return def __ping(self): """Workaround for Safari""" print 'Connection: close\n' sys.exit(0) def __mimetype(self, path): mime = mimetypes.guess_type(path)[0] or 'unknown' ext = path[path.rfind('.') + 1:] if mime == 'unknown' and ('.' + ext) in mimetypes.types_map: mime = mimetypes.types_map['.' + ext] if mime == 'text/plain' and ext == 'pl': mime = self._mimeType[ext] if mime == 'application/vnd.ms-office' and ext == 'doc': mime = self._mimeType[ext] if mime == 'unknown': if os.path.basename(path) in ['README', 'ChangeLog']: mime = 'text/plain' else: if ext in self._mimeType: mime = self._mimeType[ext] # self.__debug('mime ' + os.path.basename(path), ext + ' ' + mime) return mime def __tmb(self, path, tmb): try: im = self._im.open(path).copy() size = self._options['tmbSize'], self._options['tmbSize'] box = self.__cropTuple(im.size) if box: im = im.crop(box) im.thumbnail(size, self._im.ANTIALIAS) im.save(tmb, 'PNG') except Exception, e: self.__debug('tmbFailed_' + path, str(e)) return False return True def __rmTmb(self, path): tmb = self.__tmbPath(path) if self._options['tmbDir']: if os.path.exists(tmb): try: os.unlink(tmb) except: pass def __cropTuple(self, size): w, h = size if w > h: # landscape l = int((w - h) / 2) u = 0 r = l + h d = h return (l, u, r, d) elif h > w: # portrait l = 0 u = int((h - w) / 2) r = w d = u + w return (l, u, r, d) else: # cube pass return False def __readlink(self, path): """Read link and return real path if not broken""" target = os.readlink(path); if not target[0] == '/': target = os.path.join(os.path.dirname(path), target) target = os.path.normpath(target) if os.path.exists(target): if not target.find(self._options['root']) == -1: return target return False def __dirSize(self, path): total_size = 0 if self._options['dirSize']: for dirpath, dirnames, filenames in os.walk(path): for f in filenames: fp = os.path.join(dirpath, f) if os.path.exists(fp): total_size += os.stat(fp).st_size else: total_size = os.lstat(path).st_size return total_size def __fbuffer(self, f, chunk_size = _options['uploadWriteChunk']): while True: chunk = f.read(chunk_size) if not chunk: break yield chunk def __canCreateTmb(self, path = None): if self._options['imgLib'] and self._options['tmbDir']: if path is not None: mime = self.__mimetype(path) if not mime[0:5] == 'image': return False return True else: return False def __tmbPath(self, path): tmb = False if self._options['tmbDir']: if not os.path.dirname(path) == self._options['tmbDir']: tmb = os.path.join(self._options['tmbDir'], self.__hash(path) + '.png') return tmb def __isUploadAllow(self, name): allow = False deny = False mime = self.__mimetype(name) if 'all' in self._options['uploadAllow']: allow = True else: for a in self._options['uploadAllow']: if mime.find(a) == 0: allow = True if 'all' in self._options['uploadDeny']: deny = True else: for d in self._options['uploadDeny']: if mime.find(d) == 0: deny = True if self._options['uploadOrder'][0] == 'allow': # ,deny if deny is True: return False elif allow is True: return True else: return False else: # deny,allow if allow is True: return True elif deny is True: return False else: return True def __isAccepted(self, target): if target == '.' or target == '..': return False if target[0:1] == '.' and not self._options['dotFiles']: return False return True def __isAllowed(self, path, access): if not os.path.exists(path): return False if access == 'read': if not os.access(path, os.R_OK): self.__errorData(path, access) return False elif access == 'write': if not os.access(path, os.W_OK): self.__errorData(path, access) return False elif access == 'rm': if not os.access(os.path.dirname(path), os.W_OK): self.__errorData(path, access) return False else: return False path = path[len(os.path.normpath(self._options['root'])):] for ppath in self._options['perms']: regex = r'' + ppath if re.search(regex, path) and access in self._options['perms'][ppath]: return self._options['perms'][ppath][access] return self._options['defaults'][access] def __hash(self, path): """Hash of the path""" m = hashlib.md5() m.update(path) return str(m.hexdigest()) def __path2url(self, path): curDir = path length = len(self._options['root']) url = str(self._options['URL'] + curDir[length:]).replace(os.sep, '/') try: import urllib url = urllib.quote(url, '/:~') except: pass return url def __errorData(self, path, msg): """Collect error/warning messages""" self._errorData[path] = msg def __initImgLib(self): if not self._options['imgLib'] is False and self._im is None: try: import Image Image self._im = Image self._options['imgLib'] = 'PIL' except: self._options['imgLib'] = False self._im = False self.__debug('imgLib', self._options['imgLib']) return self._options['imgLib'] def __getImgSize(self, path): self.__initImgLib(); if self.__canCreateTmb(): try: im = self._im.open(path) return str(im.size[0]) + 'x' + str(im.size[1]) except: pass return False def __debug(self, k, v): if self._options['debug']: self._response['debug'].update({k: v}) return def __checkArchivers(self): # import subprocess # sp = subprocess.Popen(['tar', '--version'], shell = False, # stdout = subprocess.PIPE, stderr=subprocess.PIPE) # out, err = sp.communicate() # print 'out:', out, '\nerr:', err, '\n' archive = { 'create': {}, 'extract': {} } c = archive['create'] e = archive['extract'] tar = self.__runSubProcess(['tar', '--version']) gzip = self.__runSubProcess(['gzip', '--version']) bzip2 = self.__runSubProcess(['bzip2', '--version']) zipc = self.__runSubProcess(['zip', '--version']) unzip = self.__runSubProcess(['unzip', '--help']) rar = self.__runSubProcess(['rar', '--version'], validReturn = [0, 7]) unrar = self.__runSubProcess(['unrar'], validReturn = [0, 7]) p7z = self.__runSubProcess(['7z', '--help']) p7za = self.__runSubProcess(['7za', '--help']) p7zr = self.__runSubProcess(['7zr', '--help']) # tar = False tar = gzip = bzip2 = zipc = unzip = rar = unrar = False # print tar, gzip, bzip2, zipc, unzip, rar, unrar, p7z, p7za, p7zr if tar: mime = 'application/x-tar' c.update({mime: {'cmd': 'tar', 'argc': '-cf', 'ext': 'tar'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xf', 'ext': 'tar'}}) if tar and gzip: mime = 'application/x-gzip' c.update({mime: {'cmd': 'tar', 'argc': '-czf', 'ext': 'tar.gz'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xzf', 'ext': 'tar.gz'}}) if tar and bzip2: mime = 'application/x-bzip2' c.update({mime: {'cmd': 'tar', 'argc': '-cjf', 'ext': 'tar.bz2'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xjf', 'ext': 'tar.bz2'}}) mime = 'application/zip' if zipc: c.update({mime: {'cmd': 'zip', 'argc': '-r9', 'ext': 'zip'}}) if unzip: e.update({mime: {'cmd': 'unzip', 'argc': '', 'ext': 'zip'}}) mime = 'application/x-rar' if rar: c.update({mime: {'cmd': 'rar', 'argc': 'a', 'ext': 'rar'}}) e.update({mime: {'cmd': 'rar', 'argc': 'x', 'ext': 'rar'}}) elif unrar: e.update({mime: {'cmd': 'unrar', 'argc': 'x', 'ext': 'rar'}}) p7zip = None if p7z: p7zip = '7z' elif p7za: p7zip = '7za' elif p7zr: p7zip = '7zr' if p7zip: mime = 'application/x-7z-compressed' c.update({mime: {'cmd': p7zip, 'argc': 'a -t7z', 'ext': '7z'}}) e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': '7z'}}) mime = 'application/x-tar' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -ttar', 'ext': 'tar'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar'}}) mime = 'application/x-gzip' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tgzip', 'ext': 'gz'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.gz'}}) mime = 'application/x-bzip2' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tbzip2', 'ext': 'bz2'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.bz2'}}) mime = 'application/zip' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tzip', 'ext': 'zip'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'zip'}}) if not self._options['archiveMimes']: self._options['archiveMimes'] = c.keys() else: pass self._options['archivers'] = archive pass def __runSubProcess(self, cmd, validReturn = [0]): if self._sp is None: import subprocess self._sp = subprocess try: sp = self._sp.Popen(cmd, shell = False, stdout = self._sp.PIPE, stderr = self._sp.PIPE) out, err = sp.communicate() ret = sp.returncode # print cmd, ret, out, err except: return False if not ret in validReturn: return False return True
Python
#!/usr/bin/env python import elFinder elFinder.connector({ 'root': '/home/user/Sites/elfinder/files', 'URL': 'http://localhost/~user/elfinder/files', ## other options # 'debug': True, # 'dirSize': True, # 'dotFiles': True, # 'perms': { # 'backup': { # 'read': True, # 'write': False, # 'rm': False # }, # '^/pics': { # 'read': True, # 'write': False, # 'rm': False # } # }, # 'uploadDeny': ['image', 'application'], # 'uploadAllow': ['image/png', 'image/jpeg'], # 'uploadOrder': ['deny', 'allow'] }).run()
Python
#!/usr/bin/env python # # Connector for elFinder File Manager # author Troex Nevelin <troex@fury.scancode.ru> import cgi import hashlib import json import mimetypes import os import os.path import re import shutil import sys import time from datetime import datetime class connector(): """Connector for elFinder""" _options = { 'root': '', 'URL': '', 'rootAlias': 'Home', 'dotFiles': False, 'dirSize': True, 'fileMode': 0644, 'dirMode': 0755, 'imgLib': 'auto', 'tmbDir': '.tmb', 'tmbAtOnce': 5, 'tmbSize': 48, 'fileURL': True, 'uploadMaxSize': 256, 'uploadWriteChunk': 8192, 'uploadAllow': [], 'uploadDeny': [], 'uploadOrder': ['deny', 'allow'], # 'aclObj': None, # TODO # 'aclRole': 'user', # TODO 'defaults': { 'read': True, 'write': True, 'rm': True }, 'perms': {}, 'archiveMimes': {}, 'archivers': {}, 'disabled': [], 'debug': False } _commands = { 'open': '__open', 'reload': '__reload', 'mkdir': '__mkdir', 'mkfile': '__mkfile', 'rename': '__rename', 'upload': '__upload', 'paste': '__paste', 'rm': '__rm', 'duplicate': '__duplicate', 'read': '__read', 'edit': '__edit', 'extract': '__extract', 'archive': '__archive', 'resize': '__resize', 'tmb': '__thumbnails', 'ping': '__ping' } _mimeType = { # text 'txt': 'text/plain', 'php': 'text/x-php', 'html': 'text/html', 'htm': 'text/html', 'js' : 'text/javascript', 'css': 'text/css', 'rtf': 'text/rtf', 'rtfd': 'text/rtfd', 'py' : 'text/x-python', 'java': 'text/x-java-source', 'rb' : 'text/x-ruby', 'sh' : 'text/x-shellscript', 'pl' : 'text/x-perl', 'sql': 'text/x-sql', # apps 'doc': 'application/msword', 'ogg': 'application/ogg', '7z': 'application/x-7z-compressed', # video 'ogm': 'appllication/ogm', 'mkv': 'video/x-matroska' } _time = 0 _request = {} _response = {} _errorData = {} _form = {} _im = None _sp = None _today = 0 _yesterday = 0 def __init__(self, opts): self._response['debug'] = {} if self._options['debug']: self._time = time.time() t = datetime.fromtimestamp(self._time) self._today = time.mktime(datetime(t.year, t.month, t.day).timetuple()) self._yesterday = self._today - 86400 import cgitb cgitb.enable() for opt in opts: self._options[opt] = opts.get(opt) self._options['URL'] = self._options['URL'].rstrip('/') self._options['root'] = self._options['root'].rstrip(os.sep) self.__debug('URL', self._options['URL']) self.__debug('root', self._options['root']) for cmd in self._options['disabled']: if cmd in self._commands: del self._commands[cmd] if self._options['tmbDir']: self._options['tmbDir'] = os.path.join(self._options['root'], self._options['tmbDir']) if not os.path.exists(self._options['tmbDir']): self._options['tmbDir'] = False def run(self): rootOk = True if not os.path.exists(self._options['root']) or self._options['root'] == '': rootOk = False self._response['error'] = 'Invalid backend configuration' elif not self.__isAllowed(self._options['root'], 'read'): rootOk = False self._response['error'] = 'Access denied' possible_fields = ['cmd', 'target', 'targets[]', 'current', 'tree', 'name', 'content', 'src', 'dst', 'cut', 'init', 'type', 'width', 'height'] self._form = cgi.FieldStorage() for field in possible_fields: if field in self._form: self._request[field] = self._form.getvalue(field) if rootOk is True: if 'cmd' in self._request: if self._request['cmd'] in self._commands: cmd = self._commands[self._request['cmd']] func = getattr(self, '_' + self.__class__.__name__ + cmd, None) if callable(func): try: func() except Exception, e: self._response['error'] = 'Command Failed' self.__debug('exception', e) else: self._response['error'] = 'Unknown command' else: self.__open() if 'init' in self._request: self.__checkArchivers() self._response['disabled'] = self._options['disabled'] if not self._options['fileURL']: url = '' else: url = self._options['URL'] self._response['params'] = { 'dotFiles': self._options['dotFiles'], 'uplMaxSize': str(self._options['uploadMaxSize']) + 'M', 'archives': self._options['archiveMimes'], 'extract': self._options['archivers']['extract'].keys(), 'url': url } if self._errorData: self._response['errorData'] = self._errorData if self._options['debug']: self.__debug('time', (time.time() - self._time)) else: if 'debug' in self._response: del self._response['debug'] if ('cmd' in self._request and self._request['cmd'] == 'upload') or self._options['debug']: print 'Content-type: text/html\n' else: print 'Content-type: application/json\n' print json.dumps(self._response, indent = bool(self._options['debug'])) return # sys.exit(0) def __open(self): """Open file or directory""" # try to open file if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if not curDir or not curFile or os.path.isdir(curFile): print 'HTTP/1.x 404 Not Found\n\n' sys.exit('File not found') if not self.__isAllowed(curDir, 'read') or not self.__isAllowed(curFile, 'read'): print 'HTTP/1.x 403 Access Denied\n\n' sys.exit('Access denied') if os.path.islink(curFile): curFile = self.__readlink(curFile) if not curFile or os.path.isdir(curFile): print 'HTTP/1.x 404 Not Found\n\n' sys.exit('File not found') if ( not self.__isAllowed(os.path.dirname(curFile), 'read') or not self.__isAllowed(curFile, 'read') ): print 'HTTP/1.x 403 Access Denied\n\n' sys.exit('Access denied') mime = self.__mimetype(curFile) parts = mime.split('/', 2) if parts[0] == 'image': disp = 'image' elif parts[0] == 'text': disp = 'inline' else: disp = 'attachments' print 'Content-Type: ' + mime print 'Content-Disposition: ' + disp + '; filename=' + os.path.basename(curFile) print 'Content-Location: ' + curFile.replace(self._options['root'], '') print 'Content-Transfer-Encoding: binary' print 'Content-Length: ' + str(os.lstat(curFile).st_size) print 'Connection: close\n' print open(curFile, 'r').read() sys.exit(0); # try dir else: path = self._options['root'] if 'target' in self._request: target = self.__findDir(self._request['target'], None) if not target: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(target, 'read'): self._response['error'] = 'Access denied' else: path = target self.__content(path, 'tree' in self._request) pass def __rename(self): """Rename file or dir""" current = name = target = None curDir = curName = newName = None if 'name' in self._request and 'current' in self._request and 'target' in self._request: name = self._request['name'] current = self._request['current'] target = self._request['target'] curDir = self.__findDir(current, None) curName = self.__find(target, curDir) newName = os.path.join(curDir, name) if not curDir or not curName: self._response['error'] = 'File not found' elif not self.__isAllowed(curDir, 'write') and self.__isAllowed(curName, 'rm'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newName): self._response['error'] = 'File or folder with the same name already exists' else: self.__rmTmb(curName) try: os.rename(curName, newName) self._response['select'] = [self.__hash(newName)] self.__content(curDir, os.path.isdir(newName)) except: self._response['error'] = 'Unable to rename file' def __mkdir(self): """Create new directory""" current = None path = None newDir = None if 'name' in self._request and 'current' in self._request: name = self._request['name'] current = self._request['current'] path = self.__findDir(current, None) newDir = os.path.join(path, name) if not path: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(path, 'write'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newDir): self._response['error'] = 'File or folder with the same name already exists' else: try: os.mkdir(newDir, int(self._options['dirMode'])) self._response['select'] = [self.__hash(newDir)] self.__content(path, True) except: self._response['error'] = 'Unable to create folder' def __mkfile(self): """Create new file""" name = current = None curDir = newFile = None if 'name' in self._request and 'current' in self._request: name = self._request['name'] current = self._request['current'] curDir = self.__findDir(current, None) newFile = os.path.join(curDir, name) if not curDir or not name: self._response['error'] = 'Invalid parameters' elif not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' elif not self.__checkName(name): self._response['error'] = 'Invalid name' elif os.path.exists(newFile): self._response['error'] = 'File or folder with the same name already exists' else: try: open(newFile, 'w').close() self._response['select'] = [self.__hash(newFile)] self.__content(curDir, False) except: self._response['error'] = 'Unable to create file' def __rm(self): current = rmList = None curDir = rmFile = None if 'current' in self._request and 'targets[]' in self._request: current = self._request['current'] rmList = self._request['targets[]'] curDir = self.__findDir(current, None) if not rmList or not curDir: self._response['error'] = 'Invalid parameters' return False if not isinstance(rmList, list): rmList = [rmList] for rm in rmList: rmFile = self.__find(rm, curDir) if not rmFile: continue self.__remove(rmFile) # TODO if errorData not empty return error self.__content(curDir, True) def __upload(self): try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) if not curDir: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' return if not 'upload[]' in self._form: self._response['error'] = 'No file to upload' return upFiles = self._form['upload[]'] if not isinstance(upFiles, list): upFiles = [upFiles] self._response['select'] = [] total = 0 upSize = 0 maxSize = self._options['uploadMaxSize'] * 1024 * 1024 for up in upFiles: name = up.filename if name: total += 1 name = os.path.basename(name) if not self.__checkName(name): self.__errorData(name, 'Invalid name') else: name = os.path.join(curDir, name) try: f = open(name, 'wb', self._options['uploadWriteChunk']) for chunk in self.__fbuffer(up.file): f.write(chunk) f.close() upSize += os.lstat(name).st_size if self.__isUploadAllow(name): os.chmod(name, self._options['fileMode']) self._response['select'].append(self.__hash(name)) else: self.__errorData(name, 'Not allowed file type') try: os.unlink(name) except: pass except: self.__errorData(name, 'Unable to save uploaded file') if upSize > maxSize: try: os.unlink(name) self.__errorData(name, 'File exceeds the maximum allowed filesize') except: pass # TODO ? self.__errorData(name, 'File was only partially uploaded') break if self._errorData: if len(self._errorData) == total: self._response['error'] = 'Unable to upload files' else: self._response['error'] = 'Some files was not uploaded' self.__content(curDir, False) return def __paste(self): if 'current' in self._request and 'src' in self._request and 'dst' in self._request: curDir = self.__findDir(self._request['current'], None) src = self.__findDir(self._request['src'], None) dst = self.__findDir(self._request['dst'], None) if not curDir or not src or not dst or not 'targets[]' in self._request: self._response['error'] = 'Invalid parameters' return files = self._request['targets[]'] if not isinstance(files, list): files = [files] cut = False if 'cut' in self._request: if self._request['cut'] == '1': cut = True if not self.__isAllowed(src, 'read') or not self.__isAllowed(dst, 'write'): self._response['error'] = 'Access denied' return for fhash in files: f = self.__find(fhash, src) if not f: self._response['error'] = 'File not found' return newDst = os.path.join(dst, os.path.basename(f)) if dst.find(f) == 0: self._response['error'] = 'Unable to copy into itself' return if cut: if not self.__isAllowed(f, 'rm'): self._response['error'] = 'Move failed' self._errorData(f, 'Access denied') self.__content(curDir, True) return # TODO thumbs if os.path.exists(newDst): self._response['error'] = 'Unable to move files' self._errorData(f, 'File or folder with the same name already exists') self.__content(curDir, True) return try: os.rename(f, newDst) self.__rmTmb(f) continue except: self._response['error'] = 'Unable to move files' self._errorData(f, 'Unable to move') self.__content(curDir, True) return else: if not self.__copy(f, newDst): self._response['error'] = 'Unable to copy files' self.__content(curDir, True) return continue self.__content(curDir, True) else: self._response['error'] = 'Invalid parameters' return def __duplicate(self): if 'current' in self._request and 'target' in self._request: curDir = self.__findDir(self._request['current'], None) target = self.__find(self._request['target'], curDir) if not curDir or not target: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(target, 'read') or not self.__isAllowed(curDir, 'write'): self._response['error'] = 'Access denied' newName = self.__uniqueName(target) if not self.__copy(target, newName): self._response['error'] = 'Unable to create file copy' return self.__content(curDir, True) return def __resize(self): if not ( 'current' in self._request and 'target' in self._request and 'width' in self._request and 'height' in self._request ): self._response['error'] = 'Invalid parameters' return width = int(self._request['width']) height = int(self._request['height']) curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if width < 1 or height < 1 or not curDir or not curFile: self._response['error'] = 'Invalid parameters' return if not self.__isAllowed(curFile, 'write'): self._response['error'] = 'Access denied' return if not self.__mimetype(curFile).find('image') == 0: self._response['error'] = 'File is not an image' return self.__debug('resize ' + curFile, str(width) + ':' + str(height)) self.__initImgLib() try: im = self._im.open(curFile) imResized = im.resize((width, height), self._im.ANTIALIAS) imResized.save(curFile) except Exception, e: self.__debug('resizeFailed_' + path, str(e)) self._response['error'] = 'Unable to resize image' return self._response['select'] = [self.__hash(curFile)] self.__content(curDir, False) return def __thumbnails(self): if 'current' in self._request: curDir = self.__findDir(self._request['current'], None) if not curDir or curDir == self._options['tmbDir']: return False else: return False self.__initImgLib() if self.__canCreateTmb(): if self._options['tmbAtOnce'] > 0: tmbMax = self._options['tmbAtOnce'] else: tmbMax = 5 self._response['current'] = self.__hash(curDir) self._response['images'] = {} i = 0 for f in os.listdir(curDir): path = os.path.join(curDir, f) fhash = self.__hash(path) if self.__canCreateTmb(path) and self.__isAllowed(path, 'read'): tmb = os.path.join(self._options['tmbDir'], fhash + '.png') if not os.path.exists(tmb): if self.__tmb(path, tmb): self._response['images'].update({ fhash: self.__path2url(tmb) }) i += 1 if i >= tmbMax: self._response['tmb'] = True break else: return False return def __content(self, path, tree): """CWD + CDC + maybe(TREE)""" self.__cwd(path) self.__cdc(path) if tree: self._response['tree'] = self.__tree(self._options['root']) def __cwd(self, path): """Current Working Directory""" name = os.path.basename(path) if path == self._options['root']: name = self._options['rootAlias'] root = True else: root = False if self._options['rootAlias']: basename = self._options['rootAlias'] else: basename = os.path.basename(self._options['root']) rel = basename + path[len(self._options['root']):] self._response['cwd'] = { 'hash': self.__hash(path), 'name': name, 'mime': 'directory', 'rel': rel, 'size': 0, 'date': datetime.fromtimestamp(os.stat(path).st_mtime).strftime("%d %b %Y %H:%M"), 'read': True, 'write': self.__isAllowed(path, 'write'), 'rm': not root and self.__isAllowed(path, 'rm') } def __cdc(self, path): """Current Directory Content""" files = [] dirs = [] for f in sorted(os.listdir(path)): if not self.__isAccepted(f): continue pf = os.path.join(path, f) info = {} info = self.__info(pf) info['hash'] = self.__hash(pf) if info['mime'] == 'directory': dirs.append(info) else: files.append(info) dirs.extend(files) self._response['cdc'] = dirs def __info(self, path): mime = '' filetype = 'file' if os.path.isfile(path): filetype = 'file' if os.path.isdir(path): filetype = 'dir' if os.path.islink(path): filetype = 'link' stat = os.lstat(path) statDate = datetime.fromtimestamp(stat.st_mtime) fdate = '' if stat.st_mtime >= self._today: fdate = 'Today ' + statDate.strftime("%H:%M") elif stat.st_mtime >= self._yesterday and stat.st_mtime < self._today: fdate = 'Yesterday ' + statDate.strftime("%H:%M") else: fdate = statDate.strftime("%d %b %Y %H:%M") info = { 'name': os.path.basename(path), 'hash': self.__hash(path), 'mime': 'directory' if filetype == 'dir' else self.__mimetype(path), 'date': fdate, 'size': self.__dirSize(path) if filetype == 'dir' else stat.st_size, 'read': self.__isAllowed(path, 'read'), 'write': self.__isAllowed(path, 'write'), 'rm': self.__isAllowed(path, 'rm') } if filetype == 'link': lpath = self.__readlink(path) if not lpath: info['mime'] = 'symlink-broken' return info if os.path.isdir(lpath): info['mime'] = 'directory' else: info['parent'] = self.__hash(os.path.dirname(lpath)) info['mime'] = self.__mimetype(lpath) if self._options['rootAlias']: basename = self._options['rootAlias'] else: basename = os.path.basename(self._options['root']) info['link'] = self.__hash(lpath) info['linkTo'] = basename + lpath[len(self._options['root']):] info['read'] = info['read'] and self.__isAllowed(lpath, 'read') info['write'] = info['write'] and self.__isAllowed(lpath, 'write') info['rm'] = self.__isAllowed(lpath, 'rm') else: lpath = False if not info['mime'] == 'directory': if self._options['fileURL'] and info['read'] is True: if lpath: info['url'] = self.__path2url(lpath) else: info['url'] = self.__path2url(path) if info['mime'][0:5] == 'image': if self.__canCreateTmb(): dim = self.__getImgSize(path) if dim: info['dim'] = dim info['resize'] = True # if we are in tmb dir, files are thumbs itself if os.path.dirname(path) == self._options['tmbDir']: info['tmb'] = self.__path2url(path) return info tmb = os.path.join(self._options['tmbDir'], info['hash'] + '.png') if os.path.exists(tmb): tmbUrl = self.__path2url(tmb) info['tmb'] = tmbUrl else: self._response['tmb'] = True return info def __tree(self, path): """Return directory tree starting from path""" if not os.path.isdir(path): return '' if os.path.islink(path): return '' if path == self._options['root'] and self._options['rootAlias']: name = self._options['rootAlias'] else: name = os.path.basename(path) tree = { 'hash': self.__hash(path), 'name': name, 'read': self.__isAllowed(path, 'read'), 'write': self.__isAllowed(path, 'write'), 'dirs': [] } if self.__isAllowed(path, 'read'): for d in sorted(os.listdir(path)): pd = os.path.join(path, d) if os.path.isdir(pd) and not os.path.islink(pd) and self.__isAccepted(d): tree['dirs'].append(self.__tree(pd)) return tree def __uniqueName(self, path, copy = ' copy'): curDir = os.path.dirname(path) curName = os.path.basename(path) lastDot = curName.rfind('.') ext = newName = '' if not os.path.isdir(path) and re.search(r'\..{3}\.(gz|bz|bz2)$', curName): pos = -7 if curName[-1:] == '2': pos -= 1 ext = curName[pos:] oldName = curName[0:pos] newName = oldName + copy elif os.path.isdir(path) or lastDot <= 0: oldName = curName newName = oldName + copy pass else: ext = curName[lastDot:] oldName = curName[0:lastDot] newName = oldName + copy pos = 0 if oldName[-len(copy):] == copy: newName = oldName elif re.search(r'' + copy +'\s\d+$', oldName): pos = oldName.rfind(copy) + len(copy) newName = oldName[0:pos] else: newPath = os.path.join(curDir, newName + ext) if not os.path.exists(newPath): return newPath # if we are here then copy already exists or making copy of copy # we will make new indexed copy *black magic* idx = 1 if pos > 0: idx = int(oldName[pos:]) while True: idx += 1 newNameExt = newName + ' ' + str(idx) + ext newPath = os.path.join(curDir, newNameExt) if not os.path.exists(newPath): return newPath # if idx >= 1000: break # possible loop return def __remove(self, target): if not self.__isAllowed(target, 'rm'): self.__errorData(target, 'Access denied') if not os.path.isdir(target): try: os.unlink(target) return True except: self.__errorData(target, 'Remove failed') return False else: for i in os.listdir(target): if self.__isAccepted(i): self.__remove(os.path.join(target, i)) try: os.rmdir(target) return True except: self.__errorData(target, 'Remove failed') return False pass def __copy(self, src, dst): dstDir = os.path.dirname(dst) if not self.__isAllowed(src, 'read'): self.__errorData(src, 'Access denied') return False if not self.__isAllowed(dstDir, 'write'): self.__errorData(dstDir, 'Access denied') return False if os.path.exists(dst): self.__errorData(dst, 'File or folder with the same name already exists') return False if not os.path.isdir(src): try: shutil.copyfile(src, dst) shutil.copymode(src, dst) return True except: self.__errorData(src, 'Unable to copy files') return False else: try: os.mkdir(dst) shutil.copymode(src, dst) except: self.__errorData(src, 'Unable to copy files') return False for i in os.listdir(src): newSrc = os.path.join(src, i) newDst = os.path.join(dst, i) if not self.__copy(newSrc, newDst): self.__errorData(newSrc, 'Unable to copy files') return False return True def __checkName(self, name): """Check for valid file/dir name""" pattern = r'[\/\\\:\<\>]' if re.search(pattern, name): return False return True def __findDir(self, fhash, path): """Find directory by hash""" fhash = str(fhash) if not path: path = self._options['root'] if fhash == self.__hash(path): return path if not os.path.isdir(path): return None for d in os.listdir(path): pd = os.path.join(path, d) if os.path.isdir(pd) and not os.path.islink(pd): if fhash == self.__hash(pd): return pd else: ret = self.__findDir(fhash, pd) if ret: return ret return None def __find(self, fhash, parent): """Find file/dir by hash""" fhash = str(fhash) if os.path.isdir(parent): for i in os.listdir(parent): path = os.path.join(parent, i) if fhash == self.__hash(path): return path return None def __read(self): if 'current' in self._request and 'target' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) if curDir and curFile: if self.__isAllowed(curFile, 'read'): self._response['content'] = open(curFile, 'r').read() else: self._response['error'] = 'Access denied' return self._response['error'] = 'Invalid parameters' return def __edit(self): error = '' if 'current' in self._request and 'target' in self._request and 'content' in self._request: curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) error = curFile if curFile and curDir: if self.__isAllowed(curFile, 'write'): try: f = open(curFile, 'w+') f.write(self._request['content']) f.close() self._response['target'] = self.__info(curFile) except: self._response['error'] = 'Unable to write to file' else: self._response['error'] = 'Access denied' return self._response['error'] = 'Invalid parameters' return def __archive(self): self.__checkArchivers() if ( not self._options['archivers']['create'] or not 'type' in self._request or not 'current' in self._request or not 'targets[]' in self._request or not 'name' in self._request ): self._response['error'] = 'Invalid parameters' return curDir = self.__findDir(self._request['current'], None) archiveType = self._request['type'] if ( not archiveType in self._options['archivers']['create'] or not archiveType in self._options['archiveMimes'] or not curDir or not self.__isAllowed(curDir, 'write') ): self._response['error'] = 'Unable to create archive' return files = self._request['targets[]'] if not isinstance(files, list): files = [files] realFiles = [] for fhash in files: curFile = self.__find(fhash, curDir) if not curFile: self._response['error'] = 'File not found' return realFiles.append(os.path.basename(curFile)) arc = self._options['archivers']['create'][archiveType] if len(realFiles) > 1: archiveName = self._request['name'] else: archiveName = realFiles[0] archiveName += '.' + arc['ext'] archiveName = self.__uniqueName(archiveName, '') archivePath = os.path.join(curDir, archiveName) cmd = [arc['cmd']] for a in arc['argc'].split(): cmd.append(a) cmd.append(archiveName) for f in realFiles: cmd.append(f) curCwd = os.getcwd() os.chdir(curDir) self.__runSubProcess(cmd) os.chdir(curCwd) if os.path.exists(archivePath): self.__content(curDir, False) self._response['select'] = [self.__hash(archivePath)] else: self._response['error'] = 'Unable to create archive' return def __extract(self): if not 'current' in self._request or not 'target' in self._request: self._response['error'] = 'Invalid parameters' return curDir = self.__findDir(self._request['current'], None) curFile = self.__find(self._request['target'], curDir) mime = self.__mimetype(curFile) self.__checkArchivers() if ( not mime in self._options['archivers']['extract'] or not curDir or not curFile or not self.__isAllowed(curDir, 'write') ): self._response['error'] = 'Invalid parameters' return arc = self._options['archivers']['extract'][mime] cmd = [arc['cmd']] for a in arc['argc'].split(): cmd.append(a) cmd.append(curFile) curCwd = os.getcwd() os.chdir(curDir) ret = self.__runSubProcess(cmd) os.chdir(curCwd) if ret: self.__content(curDir, True) else: self._response['error'] = 'Unable to extract files from archive' return def __ping(self): """Workaround for Safari""" print 'Connection: close\n' sys.exit(0) def __mimetype(self, path): mime = mimetypes.guess_type(path)[0] or 'unknown' ext = path[path.rfind('.') + 1:] if mime == 'unknown' and ('.' + ext) in mimetypes.types_map: mime = mimetypes.types_map['.' + ext] if mime == 'text/plain' and ext == 'pl': mime = self._mimeType[ext] if mime == 'application/vnd.ms-office' and ext == 'doc': mime = self._mimeType[ext] if mime == 'unknown': if os.path.basename(path) in ['README', 'ChangeLog']: mime = 'text/plain' else: if ext in self._mimeType: mime = self._mimeType[ext] # self.__debug('mime ' + os.path.basename(path), ext + ' ' + mime) return mime def __tmb(self, path, tmb): try: im = self._im.open(path).copy() size = self._options['tmbSize'], self._options['tmbSize'] box = self.__cropTuple(im.size) if box: im = im.crop(box) im.thumbnail(size, self._im.ANTIALIAS) im.save(tmb, 'PNG') except Exception, e: self.__debug('tmbFailed_' + path, str(e)) return False return True def __rmTmb(self, path): tmb = self.__tmbPath(path) if self._options['tmbDir']: if os.path.exists(tmb): try: os.unlink(tmb) except: pass def __cropTuple(self, size): w, h = size if w > h: # landscape l = int((w - h) / 2) u = 0 r = l + h d = h return (l, u, r, d) elif h > w: # portrait l = 0 u = int((h - w) / 2) r = w d = u + w return (l, u, r, d) else: # cube pass return False def __readlink(self, path): """Read link and return real path if not broken""" target = os.readlink(path); if not target[0] == '/': target = os.path.join(os.path.dirname(path), target) target = os.path.normpath(target) if os.path.exists(target): if not target.find(self._options['root']) == -1: return target return False def __dirSize(self, path): total_size = 0 if self._options['dirSize']: for dirpath, dirnames, filenames in os.walk(path): for f in filenames: fp = os.path.join(dirpath, f) if os.path.exists(fp): total_size += os.stat(fp).st_size else: total_size = os.lstat(path).st_size return total_size def __fbuffer(self, f, chunk_size = _options['uploadWriteChunk']): while True: chunk = f.read(chunk_size) if not chunk: break yield chunk def __canCreateTmb(self, path = None): if self._options['imgLib'] and self._options['tmbDir']: if path is not None: mime = self.__mimetype(path) if not mime[0:5] == 'image': return False return True else: return False def __tmbPath(self, path): tmb = False if self._options['tmbDir']: if not os.path.dirname(path) == self._options['tmbDir']: tmb = os.path.join(self._options['tmbDir'], self.__hash(path) + '.png') return tmb def __isUploadAllow(self, name): allow = False deny = False mime = self.__mimetype(name) if 'all' in self._options['uploadAllow']: allow = True else: for a in self._options['uploadAllow']: if mime.find(a) == 0: allow = True if 'all' in self._options['uploadDeny']: deny = True else: for d in self._options['uploadDeny']: if mime.find(d) == 0: deny = True if self._options['uploadOrder'][0] == 'allow': # ,deny if deny is True: return False elif allow is True: return True else: return False else: # deny,allow if allow is True: return True elif deny is True: return False else: return True def __isAccepted(self, target): if target == '.' or target == '..': return False if target[0:1] == '.' and not self._options['dotFiles']: return False return True def __isAllowed(self, path, access): if not os.path.exists(path): return False if access == 'read': if not os.access(path, os.R_OK): self.__errorData(path, access) return False elif access == 'write': if not os.access(path, os.W_OK): self.__errorData(path, access) return False elif access == 'rm': if not os.access(os.path.dirname(path), os.W_OK): self.__errorData(path, access) return False else: return False path = path[len(os.path.normpath(self._options['root'])):] for ppath in self._options['perms']: regex = r'' + ppath if re.search(regex, path) and access in self._options['perms'][ppath]: return self._options['perms'][ppath][access] return self._options['defaults'][access] def __hash(self, path): """Hash of the path""" m = hashlib.md5() m.update(path) return str(m.hexdigest()) def __path2url(self, path): curDir = path length = len(self._options['root']) url = str(self._options['URL'] + curDir[length:]).replace(os.sep, '/') try: import urllib url = urllib.quote(url, '/:~') except: pass return url def __errorData(self, path, msg): """Collect error/warning messages""" self._errorData[path] = msg def __initImgLib(self): if not self._options['imgLib'] is False and self._im is None: try: import Image Image self._im = Image self._options['imgLib'] = 'PIL' except: self._options['imgLib'] = False self._im = False self.__debug('imgLib', self._options['imgLib']) return self._options['imgLib'] def __getImgSize(self, path): self.__initImgLib(); if self.__canCreateTmb(): try: im = self._im.open(path) return str(im.size[0]) + 'x' + str(im.size[1]) except: pass return False def __debug(self, k, v): if self._options['debug']: self._response['debug'].update({k: v}) return def __checkArchivers(self): # import subprocess # sp = subprocess.Popen(['tar', '--version'], shell = False, # stdout = subprocess.PIPE, stderr=subprocess.PIPE) # out, err = sp.communicate() # print 'out:', out, '\nerr:', err, '\n' archive = { 'create': {}, 'extract': {} } c = archive['create'] e = archive['extract'] tar = self.__runSubProcess(['tar', '--version']) gzip = self.__runSubProcess(['gzip', '--version']) bzip2 = self.__runSubProcess(['bzip2', '--version']) zipc = self.__runSubProcess(['zip', '--version']) unzip = self.__runSubProcess(['unzip', '--help']) rar = self.__runSubProcess(['rar', '--version'], validReturn = [0, 7]) unrar = self.__runSubProcess(['unrar'], validReturn = [0, 7]) p7z = self.__runSubProcess(['7z', '--help']) p7za = self.__runSubProcess(['7za', '--help']) p7zr = self.__runSubProcess(['7zr', '--help']) # tar = False tar = gzip = bzip2 = zipc = unzip = rar = unrar = False # print tar, gzip, bzip2, zipc, unzip, rar, unrar, p7z, p7za, p7zr if tar: mime = 'application/x-tar' c.update({mime: {'cmd': 'tar', 'argc': '-cf', 'ext': 'tar'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xf', 'ext': 'tar'}}) if tar and gzip: mime = 'application/x-gzip' c.update({mime: {'cmd': 'tar', 'argc': '-czf', 'ext': 'tar.gz'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xzf', 'ext': 'tar.gz'}}) if tar and bzip2: mime = 'application/x-bzip2' c.update({mime: {'cmd': 'tar', 'argc': '-cjf', 'ext': 'tar.bz2'}}) e.update({mime: {'cmd': 'tar', 'argc': '-xjf', 'ext': 'tar.bz2'}}) mime = 'application/zip' if zipc: c.update({mime: {'cmd': 'zip', 'argc': '-r9', 'ext': 'zip'}}) if unzip: e.update({mime: {'cmd': 'unzip', 'argc': '', 'ext': 'zip'}}) mime = 'application/x-rar' if rar: c.update({mime: {'cmd': 'rar', 'argc': 'a', 'ext': 'rar'}}) e.update({mime: {'cmd': 'rar', 'argc': 'x', 'ext': 'rar'}}) elif unrar: e.update({mime: {'cmd': 'unrar', 'argc': 'x', 'ext': 'rar'}}) p7zip = None if p7z: p7zip = '7z' elif p7za: p7zip = '7za' elif p7zr: p7zip = '7zr' if p7zip: mime = 'application/x-7z-compressed' c.update({mime: {'cmd': p7zip, 'argc': 'a -t7z', 'ext': '7z'}}) e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': '7z'}}) mime = 'application/x-tar' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -ttar', 'ext': 'tar'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar'}}) mime = 'application/x-gzip' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tgzip', 'ext': 'gz'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.gz'}}) mime = 'application/x-bzip2' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tbzip2', 'ext': 'bz2'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.bz2'}}) mime = 'application/zip' if not mime in c: c.update({mime: {'cmd': p7zip, 'argc': 'a -tzip', 'ext': 'zip'}}) if not mime in e: e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'zip'}}) if not self._options['archiveMimes']: self._options['archiveMimes'] = c.keys() else: pass self._options['archivers'] = archive pass def __runSubProcess(self, cmd, validReturn = [0]): if self._sp is None: import subprocess self._sp = subprocess try: sp = self._sp.Popen(cmd, shell = False, stdout = self._sp.PIPE, stderr = self._sp.PIPE) out, err = sp.communicate() ret = sp.returncode # print cmd, ret, out, err except: return False if not ret in validReturn: return False return True
Python
#!/usr/bin/python # # Copyright (C) 2012 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__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
Python
#!/usr/bin/python # # Copyright (C) 2012 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__ = 'afshar@google.com (Ali Afshar)' # Add the library location to the path import sys sys.path.insert(0, 'lib') import os import httplib2 import sessions from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build from apiclient.http import MediaUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import AccessTokenRefreshError from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') def SibPath(name): """Generate a path that is a sibling of this file. Args: name: Name of sibling file. Returns: Path to sibling file. """ return os.path.join(os.path.dirname(__file__), name) # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session-secret SESSION_SECRET = open(SibPath('session.secret')).read() INDEX_HTML = open(SibPath('index.html')).read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials. The CredentialsProperty is provided by the Google API Python Client, and is used by the Storage classes to store OAuth 2.0 credentials in the data store.""" credentials = CredentialsProperty() def CreateService(service, version, creds): """Create a Google API service. Load an API service from a discovery document and authorize it with the provided credentials. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). creds: Credentials used to authorize service. Returns: Authorized Google API service. """ # Instantiate an Http instance http = httplib2.Http() # Authorize the Http instance with the passed credentials creds.authorize(http) # Build a service from the passed discovery document path return build(service, version, http=http) class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.ids = [] @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get('state')) class BaseDriveHandler(webapp.RequestHandler): """Base request handler for drive applications. Adds Authorization support for Drive. """ def CreateOAuthFlow(self): """Create OAuth2.0 flow controller This controller can be used to perform all parts of the OAuth 2.0 dance including exchanging an Authorization code. Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = flow_from_clientsecrets('client_secrets.json', scope='') # Dynamically set the redirect_uri based on the request URL. This is extremely # convenient for debugging to an alternative host without manually setting the # redirect URI. flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0] return flow def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. code = self.request.get('code') if not code: # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. users_service = CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. userid = users_service.userinfo().get().execute().get('id') # Store the user id in the user's cookie-based session. session = sessions.LilCookies(self, SESSION_SECRET) session.set_secure_cookie(name='userid', value=userid) # Store the credentials in the data store using the userid as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.redirect(uri) def RespondJSON(self, data): """Generate a JSON response and return it to the client. Args: data: The data that will be converted to JSON to return. """ self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(data)) def CreateAuthorizedService(self, service, version): """Create an authorize service instance. The service can only ever retrieve the credentials from the session. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). Returns: Authorized service or redirect to authorization flow if no credentials. """ # For the service, the session holds the credentials creds = self.GetSessionCredentials() if creds: # If the session contains credentials, use them to create a Drive service # instance. return CreateService(service, version, creds) else: # If no credentials could be loaded from the session, redirect the user to # the authorization page. self.RedirectAuth() def CreateDrive(self): """Create a drive client instance.""" return self.CreateAuthorizedService('drive', 'v2') def CreateUserInfo(self): """Create a user info client instance.""" return self.CreateAuthorizedService('oauth2', 'v2') class MainPage(BaseDriveHandler): """Web handler for the main page. Handles requests and returns the user interface for Open With and Create cases. Responsible for parsing the state provided from the Drive UI and acting appropriately. """ def get(self): """Handle GET for Create New and Open With. This creates an authorized client, and checks whether a resource id has been passed or not. If a resource ID has been passed, this is the Open With use-case, otherwise it is the Create New use-case. """ # Generate a state instance for the request, this includes the action, and # the file id(s) that have been sent from the Drive user interface. drive_state = DriveState.FromRequest(self.request) if drive_state.action == 'open' and len(drive_state.ids) > 0: code = self.request.get('code') if code: code = '?code=%s' % code self.redirect('/#edit/%s%s' % (drive_state.ids[0], code)) return # Fetch the credentials by extracting an OAuth 2.0 authorization code from # the request URL. If the code is not present, redirect to the OAuth 2.0 # authorization URL. creds = self.GetCodeCredentials() if not creds: return self.RedirectAuth() # Extract the numerical portion of the client_id from the stored value in # the OAuth flow. You could also store this value as a separate variable # somewhere. client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0] self.RenderTemplate() def RenderTemplate(self): """Render a named template in a context.""" self.response.headers['Content-Type'] = 'text/html' self.response.out.write(INDEX_HTML) class ServiceHandler(BaseDriveHandler): """Web handler for the service to read and write to Drive.""" def post(self): """Called when HTTP POST requests are received by the web application. The POST body is JSON which is deserialized and used as values to create a new file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() # Create a new file data structure. resource = { 'title': data['title'], 'description': data['description'], 'mimeType': data['mimeType'], } try: # Make an insert request to create a new file. A MediaInMemoryUpload # instance is used to upload the file body. resource = service.files().insert( body=resource, media_body=MediaInMemoryUpload( data.get('content', ''), data['mimeType'], resumable=True) ).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: resp, f['content'] = service._http.request(downloadUrl) else: f['content'] = '' else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() def put(self): """Called when HTTP PUT requests are received by the web application. The PUT body is JSON which is deserialized and used as values to update a file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() try: # Create a new file data structure. content = data.get('content') if 'content' in data: data.pop('content') if content is not None: # Make an update request to update the file. A MediaInMemoryUpload # instance is used to upload the file body. Because of a limitation, this # request must be made in two parts, the first to update the metadata, and # the second to update the body. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data, media_body=MediaInMemoryUpload( content, data['mimeType'], resumable=True) ).execute() else: # Only update the metadata, a patch request is prefered but not yet # supported on Google App Engine; see # http://code.google.com/p/googleappengine/issues/detail?id=6316. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body) class UserHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateUserInfo() if service is None: return try: result = service.userinfo().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class AboutHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateDrive() if service is None: return try: result = service.about().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] # Create an WSGI application suitable for running on App Engine application = webapp.WSGIApplication( [('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler), ('/user', UserHandler)], # XXX Set to False in production. debug=True ) def main(): """Main entry point for executing a request with this handler.""" run_wsgi_app(application) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # # Copyright (c) 2002, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # --- # Author: Chad Lester # Design and style contributions by: # Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, # Eric Veach, Laurence Gonsalves, Matthew Springer # Code reorganized a bit by Craig Silverstein """This module is used to define and parse command line flags. This module defines a *distributed* flag-definition policy: rather than an application having to define all flags in or near main(), each python module defines flags that are useful to it. When one python module imports another, it gains access to the other's flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.) Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it's seen on the command line. IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a 'FlagValues' object (typically the global FlagValues FLAGS, defined here). The 'FlagValues' object can scan the command line arguments and pass flag arguments to the corresponding 'Flag' objects for value-checking and type conversion. The converted flag values are available as attributes of the 'FlagValues' object. Code can access the flag through a FlagValues object, for instance gflags.FLAGS.myflag. Typically, the __main__ module passes the command line arguments to gflags.FLAGS for parsing. At bottom, this module calls getopt(), so getopt functionality is supported, including short- and long-style flags, and the use of -- to terminate flags. Methods defined by the flag module will throw 'FlagsError' exceptions. The exception argument will be a human-readable string. FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag. DEFINE_string: takes any input, and interprets it as a string. DEFINE_bool or DEFINE_boolean: typically does not take an argument: say --myflag to set FLAGS.myflag to true, or --nomyflag to set FLAGS.myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=1 or --myflag=false or --myflag=f or --myflag=0 DEFINE_float: takes an input and interprets it as a floating point number. Takes optional args lower_bound and upper_bound; if the number specified on the command line is out of range, it will raise a FlagError. DEFINE_integer: takes an input and interprets it as an integer. Takes optional args lower_bound and upper_bound as for floats. DEFINE_enum: takes a list of strings which represents legal values. If the command-line value is not in this list, raise a flag error. Otherwise, assign to FLAGS.flag as a string. DEFINE_list: Takes a comma-separated list of strings on the commandline. Stores them in a python list object. DEFINE_spaceseplist: Takes a space-separated list of strings on the commandline. Stores them in a python list object. Example: --myspacesepflag "foo bar baz" DEFINE_multistring: The same as DEFINE_string, except the flag can be specified more than once on the commandline. The result is a python list object (list of strings), even if the flag is only on the command line once. DEFINE_multi_int: The same as DEFINE_integer, except the flag can be specified more than once on the commandline. The result is a python list object (list of ints), even if the flag is only on the command line once. SPECIAL FLAGS: There are a few flags that have special meaning: --help prints a list of all the flags in a human-readable fashion --helpshort prints a list of all key flags (see below). --helpxml prints a list of all flags, in XML format. DO NOT parse the output of --help and --helpshort. Instead, parse the output of --helpxml. For more info, see "OUTPUT FOR --helpxml" below. --flagfile=foo read flags from file foo. --undefok=f1,f2 ignore unrecognized option errors for f1,f2. For boolean flags, you should use --undefok=boolflag, and --boolflag and --noboolflag will be accepted. Do not use --undefok=noboolflag. -- as in getopt(), terminates flag-processing FLAGS VALIDATORS: If your program: - requires flag X to be specified - needs flag Y to match a regular expression - or requires any more general constraint to be satisfied then validators are for you! Each validator represents a constraint over one flag, which is enforced starting from the initial parsing of the flags and until the program terminates. Also, lower_bound and upper_bound for numerical flags are enforced using flag validators. Howto: If you want to enforce a constraint over one flag, use gflags.RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS) After flag values are initially parsed, and after any change to the specified flag, method checker(flag_value) will be executed. If constraint is not satisfied, an IllegalFlagValue exception will be raised. See RegisterValidator's docstring for a detailed explanation on how to construct your own checker. EXAMPLE USAGE: FLAGS = gflags.FLAGS gflags.DEFINE_integer('my_version', 0, 'Version number.') gflags.DEFINE_string('filename', None, 'Input file name', short_name='f') gflags.RegisterValidator('my_version', lambda value: value % 2 == 0, message='--my_version must be divisible by 2') gflags.MarkFlagAsRequired('filename') NOTE ON --flagfile: Flags may be loaded from text files in addition to being specified on the commandline. Any flags you don't feel like typing, throw them in a file, one flag per line, for instance: --myflag=myvalue --nomyboolean_flag You then specify your file with the special flag '--flagfile=somefile'. You CAN recursively nest flagfile= tokens OR use multiple files on the command line. Lines beginning with a single hash '#' or a double slash '//' are comments in your flagfile. Any flagfile=<file> will be interpreted as having a relative path from the current working directory rather than from the place the file was included from: myPythonScript.py --flagfile=config/somefile.cfg If somefile.cfg includes further --flagfile= directives, these will be referenced relative to the original CWD, not from the directory the including flagfile was found in! The caveat applies to people who are including a series of nested files in a different dir than they are executing out of. Relative path names are always from CWD, not from the directory of the parent include flagfile. We do now support '~' expanded directory names. Absolute path names ALWAYS work! EXAMPLE USAGE: FLAGS = gflags.FLAGS # Flag names are globally defined! So in general, we need to be # careful to pick names that are unlikely to be used by other libraries. # If there is a conflict, we'll get an error at import time. gflags.DEFINE_string('name', 'Mr. President', 'your name') gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) gflags.DEFINE_boolean('debug', False, 'produces debugging output') gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') def main(argv): try: argv = FLAGS(argv) # parse flags except gflags.FlagsError, e: print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if FLAGS.debug: print 'non-flag arguments:', argv print 'Happy Birthday', FLAGS.name if FLAGS.age is not None: print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender) if __name__ == '__main__': main(sys.argv) KEY FLAGS: As we already explained, each module gains access to all flags defined by all the other modules it transitively imports. In the case of non-trivial scripts, this means a lot of flags ... For documentation purposes, it is good to identify the flags that are key (i.e., really important) to a module. Clearly, the concept of "key flag" is a subjective one. When trying to determine whether a flag is key to a module or not, assume that you are trying to explain your module to a potential user: which flags would you really like to mention first? We'll describe shortly how to declare which flags are key to a module. For the moment, assume we know the set of key flags for each module. Then, if you use the app.py module, you can use the --helpshort flag to print only the help for the flags that are key to the main module, in a human-readable format. NOTE: If you need to parse the flag help, do NOT use the output of --help / --helpshort. That output is meant for human consumption, and may be changed in the future. Instead, use --helpxml; flags that are key for the main module are marked there with a <key>yes</key> element. The set of key flags for a module M is composed of: 1. Flags defined by module M by calling a DEFINE_* function. 2. Flags that module M explictly declares as key by using the function DECLARE_key_flag(<flag_name>) 3. Key flags of other modules that M specifies by using the function ADOPT_module_key_flags(<other_module>) This is a "bulk" declaration of key flags: each flag that is key for <other_module> becomes key for the current module too. Notice that if you do not use the functions described at points 2 and 3 above, then --helpshort prints information only about the flags defined by the main module of our script. In many cases, this behavior is good enough. But if you move part of the main module code (together with the related flags) into a different module, then it is nice to use DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort lists all relevant flags (otherwise, your code refactoring may confuse your users). Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own pluses and minuses: DECLARE_key_flag is more targeted and may lead a more focused --helpshort documentation. ADOPT_module_key_flags is good for cases when an entire module is considered key to the current script. Also, it does not require updates to client scripts when a new flag is added to the module. EXAMPLE USAGE 2 (WITH KEY FLAGS): Consider an application that contains the following three files (two auxiliary modules and a main module) File libfoo.py: import gflags gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') ... some code ... File libbar.py: import gflags gflags.DEFINE_string('bar_gfs_path', '/gfs/path', 'Path to the GFS files for libbar.') gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', 'Email address for bug reports about module libbar.') gflags.DEFINE_boolean('bar_risky_hack', False, 'Turn on an experimental and buggy optimization.') ... some code ... File myscript.py: import gflags import libfoo import libbar gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') # Declare that all flags that are key for libfoo are # key for this module too. gflags.ADOPT_module_key_flags(libfoo) # Declare that the flag --bar_gfs_path (defined in libbar) is key # for this module. gflags.DECLARE_key_flag('bar_gfs_path') ... some code ... When myscript is invoked with the flag --helpshort, the resulted help message lists information about all the key flags for myscript: --num_iterations, --num_replicas, --rpc2, and --bar_gfs_path. Of course, myscript uses all the flags declared by it (in this case, just --num_replicas) or by any of the modules it transitively imports (e.g., the modules libfoo, libbar). E.g., it can access the value of FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key flag for myscript. OUTPUT FOR --helpxml: The --helpxml flag generates output with the following structure: <?xml version="1.0"?> <AllFlags> <program>PROGRAM_BASENAME</program> <usage>MAIN_MODULE_DOCSTRING</usage> (<flag> [<key>yes</key>] <file>DECLARING_MODULE</file> <name>FLAG_NAME</name> <meaning>FLAG_HELP_MESSAGE</meaning> <default>DEFAULT_FLAG_VALUE</default> <current>CURRENT_FLAG_VALUE</current> <type>FLAG_TYPE</type> [OPTIONAL_ELEMENTS] </flag>)* </AllFlags> Notes: 1. The output is intentionally similar to the output generated by the C++ command-line flag library. The few differences are due to the Python flags that do not have a C++ equivalent (at least not yet), e.g., DEFINE_list. 2. New XML elements may be added in the future. 3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can pass for this flag on the command-line. E.g., for a flag defined using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. 4. CURRENT_FLAG_VALUE is produced using str(). This means that the string 'false' will be represented in the same way as the boolean False. Using repr() would have removed this ambiguity and simplified parsing, but would have broken the compatibility with the C++ command-line flags. 5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of flags: lower_bound, upper_bound (for flags that specify bounds), enum_value (for enum flags), list_separator (for flags that consist of a list of values, separated by a special token). 6. We do not provide any example here: please use --helpxml instead. This module requires at least python 2.2.1 to run. """ import cgi import getopt import os import re import string import struct import sys # pylint: disable-msg=C6204 try: import fcntl except ImportError: fcntl = None try: # Importing termios will fail on non-unix platforms. import termios except ImportError: termios = None import gflags_validators # pylint: enable-msg=C6204 # Are we running under pychecker? _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): """Returns the name of the module that's calling into this module.""" return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): """Returns: (module object, module name) for this module.""" return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): """The base class for all flags errors.""" pass class DuplicateFlag(FlagsError): """Raised if there is a flag naming conflict.""" pass class CantOpenFlagFileError(FlagsError): """Raised if flagfile fails to open: doesn't exist, wrong permissions, etc.""" pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): """Special case of DuplicateFlag -- SWIG flag value can't be set to None. This can be raised when a duplicate flag is created. Even if allow_override is True, we still abort if the new value is None, because it's currently impossible to pass None default value back to SWIG. See FlagValues.SetDefault for details. """ pass class DuplicateFlagError(DuplicateFlag): """A DuplicateFlag whose message cites the conflicting definitions. A DuplicateFlagError conveys more information than a DuplicateFlag, namely the modules where the conflicting definitions occur. This class was created to avoid breaking external modules which depend on the existing DuplicateFlags interface. """ def __init__(self, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. """ self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): """The flag command line argument is illegal.""" pass class UnrecognizedFlag(FlagsError): """Raised if a flag is unrecognized.""" pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value # of the flag and its argument, if any, allowing handling of unrecognized flags # in an exception handler. # If flagvalue is the empty string, then this exception is an due to a # reference to a flag that was not already defined. class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) # Global variable used by expvar _exported_flags = {} _help_width = 80 # width of help output def GetHelpWidth(): """Returns: an integer, the width of help lines that is used in TextWrap.""" if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable if columns >= 40: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): """Removes a common space prefix from the lines of a multiline text. If the first line does not start with a space, it is left as it is and only in the remaining lines a common space prefix is being searched for. That means the first line will stay untouched. This is especially useful to turn doc strings into help texts. This is because some people prefer to have the doc comment start already after the apostrophe and then align the following lines while others have the apostrophes on a separate line. The function also drops trailing empty lines and ignores empty lines following the initial content line while calculating the initial common whitespace. Args: text: text to work on Returns: the resulting text """ text_lines = text.splitlines() # Drop trailing empty lines while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: # We got some content, is the first line starting with a space? if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] # Calculate length of common leading whitespace (only over content lines) common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) # If we have a common space prefix, drop it from all lines if space_prefix_len: for index in xrange(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): """Wraps a given text to a maximum line length and returns it. We turn lines that only contain whitespace into empty lines. We keep new lines and tabs (e.g., we do not treat tabs as spaces). Args: text: text to wrap length: maximum length of a line, includes indentation if this is None then use GetHelpWidth() indent: indent for all but first line firstline_indent: indent for first line; if None, fall back to indent tabs: replacement for tabs Returns: wrapped text Raises: FlagsError: if indent not shorter than length FlagsError: if firstline_indent not shorter than length """ # Get defaults where callee used None if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') # In line we will be holding the current line which is to be started # with indent (or firstline_indent if available) and then appended # with words. if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') # If the callee does not care about tabs we simply convert them to # spaces If callee wanted tabs to be single space then we do that # already here. if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) # Split the text into lines and the lines with the regex above. The # resulting lines are collected in result[]. For each split we get the # spaces, the tabs and the next non white space (e.g. next word). result = [] for text_line in text.splitlines(): # Store result length so we can find out whether processing the next # line gave any new content old_result_len = len(result) # Process next line with line_regex. For optimization we do an rstrip(). # - process tabs (changes either line or word, see below) # - process word (first try to squeeze on line, then wrap or force wrap) # Spaces found on the line are ignored, they get added while wrapping as # needed. for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): # If tabs weren't converted to spaces, handle them now if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] # Add the tabs, if that means adding whitespace, just add it at # the line, the rstrip() code while shorten the line down if # necessary if tabs_are_whitespace: line += tabs * len(current_tabs) else: # if not all tab replacement is whitespace we prepend it to the word word = tabs * len(current_tabs) + word # Handle the case where word cannot be squeezed onto current last line if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' # No space left on line or can we append a space? if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # Add word and shorten it up to allowed line length. Restart next # line with indent and repeat, or add a space if we're done (word # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: A pair consisting of (1) module object and (2) module name (a string). Returns (None, None) if the module could not be identified. """ # The use of .items() (instead of .iteritems()) is NOT a mistake: if # a parallel thread imports a module while we iterate over # .iteritems() (not nice, but possible), we get a RuntimeError ... # Hence, we use the slightly slower but safer .items(). for name, module in sys.modules.items(): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': # Pick a more informative name for the main module. name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): """Returns: string, name of the module from which execution started.""" # First, try to use the same logic used by _GetCallingModuleObjectAndName(), # i.e., call _GetModuleObjectAndName(). For that we first need to # find the dictionary that the main module uses to store the # globals. # # That's (normally) the same dictionary object that the deepest # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues: """Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: gflags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. """ def __init__(self): # Since everything in this class is so heavily overloaded, the only # way of defining and using fields is to access __dict__ directly. # Dictionary: flag name (string) -> Flag object. self.__dict__['__flags'] = {} # Dictionary: module name (string) -> list of Flag objects that are defined # by that module. self.__dict__['__flags_by_module'] = {} # Dictionary: module id (int) -> list of Flag objects that are defined by # that module. self.__dict__['__flags_by_module_id'] = {} # Dictionary: module name (string) -> list of Flag objects that are # key for that module. self.__dict__['__key_flags_by_module'] = {} # Set if we should use new style gnu_getopt rather than getopt when parsing # the args. Only possible with Python 2.3+ self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): """Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): """Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): """Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ key_flags_by_module = self.KeyFlagsByModuleDict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module, flags in self.FlagsByModuleDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from """ for flag_name, flag in flag_values.FlagDict().iteritems(): # Each flags with shortname appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError) with double flag registration, we # perform a check to make sure that the entry we're looking at is # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): """Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove. """ for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): """Retrieves the Flag object for the flag --name.""" return self.FlagDict()[name] def __getattr__(self, name): """Retrieves the 'value' attribute of the flag --name.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): """Sets the 'value' attribute of the flag --name.""" fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().itervalues(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corresponding Flag object (it is still registered under the longer name). Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under some name. """ flag_dict = self.FlagDict() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True # The flag cannot be registered under any other name, so we do not # need to do a full search through the values of self.FlagDict(). return False def __delattr__(self, flag_name): """Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer('foo', 1, 'Integer flag.') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there is no registered flag named flag_name. """ fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): # If the Flag object indicated by flag_name is no longer # registered (please see the docstring of _FlagIsRegistered), then # we delete the occurrences of the flag object in all our internal # dictionaries. self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): """Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object. """ for unused_module, flags_in_module in flags_by_module_dict.iteritems(): # while (as opposed to if) takes care of multiple occurrences of a # flag in the list for the same module. while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): """Changes the default value of the named flag object.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): """Returns True if name is a value (flag) in the dict.""" return name in self.FlagDict() has_key = __contains__ # a synonym for __contains__() def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be converted to a list. Returns: The list of arguments not parsed as options, including argv[0] Raises: FlagsError: on any parsing error """ # Support any sequence type that can be converted to a list argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() # This pre parses the argv list for --flagfile=<> options. argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Correct the argv to support the google style of passing boolean # parameters. Boolean parameters may be passed by using --mybool, # --nomybool, --mybool=(true|false|1|0). getopt does not support # having options that may or may not have a parameter. We replace # instances of the short form --mybool and --nomybool with their # full forms: --mybool=(true|false). original_argv = list(argv) # list() makes a copy shortest_matches = None for name, flag in fl.items(): if not flag.boolean: continue if shortest_matches is None: # Determine the smallest allowable prefix for all flag names shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] # Replace all occurrences of this boolean with extended forms for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) # Loop over all of the flags, building up the lists of short options # and long options that will be passed to getopt. Short options are # specified as a string of letters, each letter followed by a colon # if it takes an argument. Long options are stored in an array of # strings. Each string ends with an '=' if it takes an argument. for name, flag in fl.items(): longopts.append(name + "=") if len(name) == 1: # one-letter option: allow short flag type also shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] # In case --undefok is specified, loop to pick up unrecognized # options one by one. unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError, e: if not e.opt or e.opt in fl: # Not an unrecognized option, re-raise the exception as a FlagsError raise FlagsError(e) # Remove offender from args and try again for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # We should have found the option, so we don't expect to get # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will # accept --nonoboolflag here. We are choosing not to do the conversion # from noboolflag -> boolflag because of the ambiguity that flag names # can start with 'no'. undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): # long option name = name[2:] short_option = 0 else: # short option name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) # If there were unrecognized options, raise an exception unless # the options were named via --undefok. for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: # if using gnu_getopt just return the program name + remainder of argv. ret_val = argv[:1] + unparsed_args else: # unparsed_args becomes the first non-flag detected by getopt to # the end of argv. Because argv may have been modified above, # return original_argv for this region. ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): """Resets the values to the point before FLAGS(argv) was called.""" for f in self.FlagDict().values(): f.Unparse() def RegisteredFlags(self): """Returns: a list of the names and short names of all registered flags.""" return list(self.FlagDict()) def FlagValuesDict(self): """Returns: a dictionary that maps flag names to flag values.""" flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp() def GetHelp(self, prefix=''): """Generates a help string for all known flags.""" helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', _SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. self.__RenderFlagList( self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): """Generates a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): """Generates a help string for a given module.""" flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): """Describe the key flags of the main module. Returns: string describing the key flags of a module. """ return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # It's possible this flag got deleted or overridden since being # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): """Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None. """ value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): """Returns: dictionary; maps flag names to their shortest unique prefix.""" # Sort the list of flag names sorted_flags = [] for name, flag in fl.items(): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() # For each name in the sorted list, determine the shortest unique # prefix by comparing itself to the next name and to the previous # name (the latter check uses cached info from the previous loop). shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): # curr longer than next or no more chars in common shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: # curr shorter than (or equal to) next shortest_matches[curr] = curr prev_idx = curr_idx + 1 # next will need at least one more char return shortest_matches def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): """Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError, e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing obeys normal flag semantics. If True, --flagfile parsing instead follows gnu_getopt semantics. *** WARNING *** force_gnu=False may become the future default! Returns: A new list which has the original list combined with what we read from any flagfile(s). References: Global gflags.FLAG class instance. This function should be called before the normal FLAGS(argv) call. This function scans the input list for a flag that looks like: --flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list between the first item of the list and any subsequent items in the list. Note that your application's flags are still defined the usual way using gflags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> Flags from the command line argv _should_ always take precedence! --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile. It will be processed after the parent flag file is done. --> For duplicate flags, first one we hit should "win". --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. """ parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): # This handles the case of -(-)flagfile foo. In this case the # next arg really is part of this one. if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: # This handles the case of (-)-flagfile=foo. flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) # Stop parsing after '--', like getopt and gnu_getopt. if current_arg == '--': break # Stop parsing after a non-flag, like getopt. if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags """ s = '' for flag in self.FlagDict().values(): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): """Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags """ out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) # Get list of key flags for the main module. key_flags = self._GetKeyFlagsForModule(_GetMainModule()) # Sort flags by declaring module name and next by flag name. flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) # end of FlagValues definition # The global FlagValues instance FLAGS = FlagValues() def _StrOrUnicode(value): """Converts value to a python string or, if necessary, unicode-string.""" try: return str(value) except UnicodeEncodeError: return unicode(value) def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" s = cgi.escape(s) # Escape <, >, and & # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag: """Information about a command-line flag. 'Flag' objects define the following fields: .name - the name for this flag .default - the default value for this flag .default_as_str - default value as repr'd string, e.g., "'true'" (or None) .value - the most recent parsed value of this flag; set by Parse() .help - a help string or None if no help is available .short_name - the single letter alias for this flag (or None) .boolean - if 'true', this flag does not accept arguments .present - true if this flag was parsed from command line flags. .parser - an ArgumentParser object .serializer - an ArgumentSerializer object .allow_override - the flag may be redefined without raising an error The only public method of a 'Flag' object is Parse(), but it is typically only called by a 'FlagValues' object. The Parse() method is a thin wrapper around the 'ArgumentParser' Parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, a FlagsError is raised. Parse() is also called during __init__ to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the __main__ module neglects to parse the command line arguments. The .present attribute is cleared after __init__ parsing. If the default value is set to None, then the __init__ parsing step is skipped and the .value attribute is initialized to None. Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag. """ def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError, e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): """Changes the default value (and current value too) for this Flag.""" # We can't allow a None override because it may end up not being # passed to C++ code when we're overriding C++ flags. So we # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check # validators). # The simplest solution I see is to make this method private. # Another approach would be to store reference to the corresponding # FlagValues with each flag, but this seems to be an overkill. if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): """Returns: a string that describes the type of this Flag.""" # NOTE: we use strings, and not the types.*Type constants because # our flags can have more exotic types, e.g., 'comma separated list # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): """Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. module_name: A string, the name of the module that defines this flag. is_key: A boolean, True iff this flag is key for main module. indent: A string that is prepended to each generated line. """ outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) # Print flag features that are relevant for all flags. _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) # The default flag value can either be represented as a string like on the # command line, or as a Python object. We serialize this value in the # latter case in order to remain consistent. if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) # Print extra flag features this flag may have. self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): """Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line. """ # Usually, the parser knows the extra details about the flag, so # we just forward the call to it. self.parser.WriteCustomInfoInXMLFormat(outfile, indent) # End of Flag definition class _ArgumentParserCache(type): """Metaclass used to cache and share argument parsers among flags.""" _instances = {} def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args) class ArgumentParser(object): """Base class used to parse and convert arguments. The Parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal. Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values. Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only. """ __metaclass__ = _ArgumentParserCache syntactic_help = "" def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer: """Base class for generating string representations of a flag value.""" def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) # Flags validators def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: string, name of the flag to be checked. checker: method to validate the flag. input - value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). See file's docstring for examples. output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags_validators.Error(desired_error_message). message: error text to be shown to the user if checker returns False. If checker raises gflags_validators.Error, message from the raised Error will be shown. flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): """Enforce lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser). Provides lower and upper bounds, and help text to display. name: string, name of the flag flag_values: FlagValues """ if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) # The DEFINE functions are explained in mode details in the module doc string. def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser that is used to parse the flag arguments. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object the flag will be registered with. serializer: ArgumentSerializer that serializes the flag value. args: Dictionary with extra keyword args that are passes to the Flag __init__. """ DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): """Declares a flag as key for the calling module. Internal function. User code should call DECLARE_key_flag or ADOPT_module_key_flags instead. Args: flag_names: A list of strings that are names of already-registered Flag objects. flag_values: A FlagValues object that the flags listed in flag_names have registered with (the value of the flag_values argument from the DEFINE_* calls that defined those flags). This should almost never need to be overridden. key_flag_values: A FlagValues object that (among possibly many other things) keeps track of the key flags for each module. Default None means "same as flag_values". This should almost never need to be overridden. Raises: UnrecognizedFlagError: when we refer to a flag that was not defined yet. """ key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --help). Sample usage: gflags.DECLARED_key_flag('flag_1') Args: flag_name: A string, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) flag_values: A FlagValues object. This should almost never need to be overridden. """ if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: FlagsError: When given an argument that is a module name (a string), instead of a module object. """ # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import # types for such a tiny use. if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) # If module is this flag module, take _SPECIAL_FLAGS into account. if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # As we associate flags with _GetCallingModuleObjectAndName(), the # special flags defined in this module are incorrectly registered with # a different module. So, we can't use _GetKeyFlagsForModule. # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in _SPECIAL_FLAGS.FlagDict().values()], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): """Parser of boolean values.""" def Convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): """Basic boolean flag. Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name. For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox. """ def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): """ HelpFlag is a special boolean flag that prints usage information and raises a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --help flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) class HelpXMLFlag(BooleanFlag): """Similar to HelpFlag, but generates output in XML format.""" def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): """ HelpshortFlag is a special boolean flag that prints usage information for the "main" module, and rasies a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --helpshort flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): """Parser of numeric values. Parsed value may be bounded to a given upper and lower bound. """ def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): """Parser of floating point values. Parsed value may be bounded to a given upper and lower bound. """ number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): """Parser of an integer value. Parsed value may be bounded to a given upper and lower bound. """ number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): """Parser of a string enum value (a string value from a given set). If enum_values (see below) is not specified, any string is allowed. """ def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): """Basic enum flag; its value can be any string from list of enum_values.""" def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): """Base class for a parser of lists of strings. To extend, inherit from this class; from the subclass __init__, call BaseListParser.__init__(self, token, name) where token is a character used to tokenize, and name is a description of the separator. """ def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): """Parser for a comma-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): """Parser for a whitespace-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings.""" parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. """ parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): """A flag that can appear multiple time on the command-line. The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line. See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here: * The default value may be either a single value or a list of values. A single value is interpreted as the [value] singleton list. * The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value """ def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary integers. Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
Python
#!/usr/bin/env python # Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module to enforce different constraints on flags. A validator represents an invariant, enforced over a one or more flags. See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual. """ __author__ = 'olexiy@google.com (Olexiy Oryeshko)' class Error(Exception): """Thrown If validator constraint is not satisfied.""" class Validator(object): """Base class for flags validators. Users should NOT overload these classes, and use gflags.Register... methods instead. """ # Used to assign each validator an unique insertion_index validators_count = 0 def __init__(self, checker, message): """Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user """ self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered (CL/18694236) self.insertion_index = Validator.validators_count def Verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._GetInputToCheckerFunction(flag_values) if not self.checker(param): raise Error(self.message) def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded') def PrintFlagsWithValues(self, flag_values): raise NotImplementedError('This method should be overloaded') def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator. """ raise NotImplementedError('This method should be overloaded') class SimpleValidator(Validator): """Validator behind RegisterValidator() method. Validates that a single flag passes its checker function. The checker function takes the flag value and returns True (if value looks fine) or, if flag value is not valid, either returns False or raises an Exception.""" def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name def GetFlagsNames(self): return [self.flag_name] def PrintFlagsWithValues(self, flag_values): return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value) def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag. """ return flag_values[self.flag_name].value class DictionaryValidator(Validator): """Validator behind RegisterDictionaryValidator method. Validates that flag values pass their common checker function. The checker function takes flag values and returns True (if values look fine) or, if values are not valid, either returns False or raises an Exception. """ def __init__(self, flag_names, checker, message): """Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names) def PrintFlagsWithValues(self, flag_values): prefix = 'flags ' flags_with_values = [] for key in self.flag_names: flags_with_values.append('%s=%s' % (key, flag_values[key].value)) return prefix + ', '.join(flags_with_values) def GetFlagsNames(self): return self.flag_names
Python
# Copyright (C) 2010 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. """Utilities for Google App Engine Utilities for making it easier to use OAuth 2.0 on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import httplib2 import logging import pickle import time import clientsecrets from anyjson import simplejson from client import AccessTokenRefreshError from client import AssertionCredentials from client import Credentials from client import Flow from client import OAuth2WebServerFlow from client import Storage from google.appengine.api import memcache from google.appengine.api import users from google.appengine.api import app_identity from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' class InvalidClientSecretsError(Exception): """The client_secrets.json file is malformed or missing required fields.""" pass class AppAssertionCredentials(AssertionCredentials): """Credentials object for App Engine Assertion Grants This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ def __init__(self, scope, **kwargs): """Constructor for AppAssertionCredentials Args: scope: string or list of strings, scope(s) of the credentials being requested. """ if type(scope) is list: scope = ' '.join(scope) self.scope = scope super(AppAssertionCredentials, self).__init__( None, None, None) @classmethod def from_json(cls, json): data = simplejson.loads(json) return AppAssertionCredentials(data['scope']) def _refresh(self, http_request): """Refreshes the access_token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ try: (token, _) = app_identity.get_access_token(self.scope) except app_identity.Error, e: raise AccessTokenRefreshError(str(e)) self.access_token = token class FlowProperty(db.Property): """App Engine datastore Property for Flow. Utility property that allows easy storage and retreival of an oauth2client.Flow""" # Tell what the user type is. data_type = Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, Flow): raise db.BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials """ # Tell what the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logging.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: cred = '' else: cred = cred.to_json() return db.Blob(cred) # For reading from datastore. def make_value_from_datastore(self, value): logging.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials def validate(self, value): value = super(CredentialsProperty, self).validate(value) logging.info("validate: Got type " + str(type(value))) if value is not None and not isinstance(value, Credentials): raise db.BadValueError('Property %s must be convertible ' 'to a Credentials instance (%s)' % (self.name, value)) #if value is not None and not isinstance(value, Credentials): # return None return value class StorageByKeyName(Storage): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name, cache=None): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty cache: memcache, a write-through cache to put in front of the datastore """ self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ if self._cache: json = self._cache.get(self._key_name) if json: return Credentials.new_from_json(json) credential = None entity = self._model.get_by_key_name(self._key_name) if entity is not None: credential = getattr(entity, self._property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) if self._cache: self._cache.set(self._key_name, credential.to_json()) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json()) def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) entity = self._model.get_by_key_name(self._key_name) if entity is not None: entity.delete() class CredentialsModel(db.Model): """Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsProperty() class OAuth2Decorator(object): """Utility for making OAuth 2.0 easier. Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods. Example: decorator = OAuth2Decorator( client_id='837...ent.com', client_secret='Qh...wwI', scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, client_id, client_secret, scope, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', user_agent=None, message=None, **kwargs): """Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. user_agent: string, User agent of your application, default to None. message: Message to display if there are problems with the OAuth 2.0 configuration. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. **kwargs: dict, Keyword arguments are be passed along as kwargs to the OAuth2WebServerFlow constructor. """ self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent, auth_uri, token_uri, **kwargs) self.credentials = None self._request_handler = None self._message = message self._in_error = False def _display_error_message(self, request_handler): request_handler.response.out.write('<html><body>') request_handler.response.out.write(self._message) request_handler.response.out.write('</body></html>') def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return # Store the request URI in 'state' so we can use it later self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: method(request_handler, *args, **kwargs) except AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) return check_oauth def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() method(request_handler, *args, **kwargs) return setup_oauth def has_credentials(self): """True if for the logged in user there are valid access Credentials. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ return self.credentials is not None and not self.credentials.invalid def authorize_url(self): """Returns the URL to start the OAuth dance. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ callback = self._request_handler.request.relative_url('/oauth2callback') url = self.flow.step1_get_authorize_url(callback) user = users.get_current_user() memcache.set(user.user_id(), pickle.dumps(self.flow), namespace=OAUTH2CLIENT_NAMESPACE) return str(url) def http(self): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. """ return self.credentials.authorize(httplib2.Http()) class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): """An OAuth2Decorator that builds from a clientsecrets file. Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator. Example: decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json') scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, filename, scope, message=None): """Constructor Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, client_info['auth_uri'], client_info['token_uri'], message) except clientsecrets.InvalidClientSecretsError: self._in_error = True if message is not None: self._message = message else: self._message = "Please configure your application for OAuth 2.0" def oauth2decorator_from_clientsecrets(filename, scope, message=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message) class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: %s' % errormsg) else: user = users.get_current_user() flow = pickle.loads(memcache.get(user.user_id(), namespace=OAUTH2CLIENT_NAMESPACE)) # This code should be ammended with application specific error # handling. The following cases should be considered: # 1. What if the flow doesn't exist in memcache? Or is corrupt? # 2. What if the step2_exchange fails? if flow: credentials = flow.step2_exchange(self.request.params) StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').put(credentials) self.redirect(str(self.request.get('state'))) else: # TODO Add error handling here. pass application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)]) def main(): run_wsgi_app(application)
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 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 base64 import hashlib import logging import time from OpenSSL import crypto from anyjson import simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds class AppIdentityError(Exception): pass class Verifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was singed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return Verifier(pubkey) class Signer(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey, The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in P12 format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ pkey = crypto.load_pkcs12(key, password).get_privatekey() return Signer(pkey) def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logging.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Locked file interface that should work on Unix and Windows pythons. This module first tries to use fcntl locking to ensure serialized access to a file, then falls back on a lock file if that is unavialable. Usage: f = LockedFile('filename', 'r+b', 'rb') f.open_and_lock() if f.is_locked(): print 'Acquired filename with r+b mode' f.file_handle().write('locked data') else: print 'Aquired filename with rb mode' f.unlock_and_close() """ __author__ = 'cache@google.com (David T McWherter)' import errno import logging import os import time logger = logging.getLogger(__name__) class AlreadyLockedException(Exception): """Trying to lock a file that has already been locked by the LockedFile.""" pass class _Opener(object): """Base class for different locking primitives.""" def __init__(self, filename, mode, fallback_mode): """Create an Opener. Args: filename: string, The pathname of the file. mode: string, The preferred mode to access the file with. fallback_mode: string, The mode to use if locking fails. """ self._locked = False self._filename = filename self._mode = mode self._fallback_mode = fallback_mode self._fh = None def is_locked(self): """Was the file locked.""" return self._locked def file_handle(self): """The file handle to the file. Valid only after opened.""" return self._fh def filename(self): """The filename that is being locked.""" return self._filename def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. """ pass def unlock_and_close(self): """Unlock and close the file.""" pass class _PosixOpener(_Opener): """Lock files using Posix advisory lock files.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Tries to create a .lock file next to the file we're trying to open. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) self._locked = False try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return lock_filename = self._posix_lockfile(self._filename) start_time = time.time() while True: try: self._lock_fd = os.open(lock_filename, os.O_CREAT|os.O_EXCL|os.O_RDWR) self._locked = True break except OSError, e: if e.errno != errno.EEXIST: raise if (time.time() - start_time) >= timeout: logger.warn('Could not acquire lock %s in %s seconds' % ( lock_filename, timeout)) # Close the file and open in fallback_mode. if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Unlock a file by removing the .lock file, and close the handle.""" if self._locked: lock_filename = self._posix_lockfile(self._filename) os.unlink(lock_filename) os.close(self._lock_fd) self._locked = False self._lock_fd = None if self._fh: self._fh.close() def _posix_lockfile(self, filename): """The name of the lock file to use for posix locking.""" return '%s.lock' % filename try: import fcntl class _FcntlOpener(_Opener): """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX) self._locked = True return except IOError, e: # If not retrying, then just pass on the error. if timeout == 0: raise e if e.errno != errno.EACCES: raise e # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the fcntl.lockf primitive.""" if self._locked: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN) self._locked = False if self._fh: self._fh.close() except ImportError: _FcntlOpener = None try: import pywintypes import win32con import win32file class _Win32Opener(_Opener): """Open, lock, and unlock a file using windows primitives.""" # Error #33: # 'The process cannot access the file because another process' FILE_IN_USE_ERROR = 33 # Error #158: # 'The segment is already unlocked.' FILE_ALREADY_UNLOCKED_ERROR = 158 def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.LockFileEx( hfile, (win32con.LOCKFILE_FAIL_IMMEDIATELY| win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000, pywintypes.OVERLAPPED()) self._locked = True return except pywintypes.error, e: if timeout == 0: raise e # If the error is not that the file is already in use, raise. if e[0] != _Win32Opener.FILE_IN_USE_ERROR: raise # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the win32 primitive.""" if self._locked: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED()) except pywintypes.error, e: if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR: raise self._locked = False if self._fh: self._fh.close() except ImportError: _Win32Opener = None class LockedFile(object): """Represent a file that has exclusive access.""" def __init__(self, filename, mode, fallback_mode, use_native_locking=True): """Construct a LockedFile. Args: filename: string, The path of the file to open. mode: string, The mode to try to open the file with. fallback_mode: string, The mode to use if locking fails. use_native_locking: bool, Whether or not fcntl/win32 locking is used. """ opener = None if not opener and use_native_locking: if _Win32Opener: opener = _Win32Opener(filename, mode, fallback_mode) if _FcntlOpener: opener = _FcntlOpener(filename, mode, fallback_mode) if not opener: opener = _PosixOpener(filename, mode, fallback_mode) self._opener = opener def filename(self): """Return the filename we were constructed with.""" return self._opener._filename def file_handle(self): """Return the file_handle to the opened file.""" return self._opener.file_handle() def is_locked(self): """Return whether we successfully locked the file.""" return self._opener.is_locked() def open_and_lock(self, timeout=0, delay=0.05): """Open the file, trying to lock it. Args: timeout: float, The number of seconds to try to acquire the lock. delay: float, The number of seconds to wait between retry attempts. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ self._opener.open_and_lock(timeout, delay) def unlock_and_close(self): """Unlock and close a file.""" self._opener.unlock_and_close()
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '<client id>', 'userAgent': '<user agent>', 'scope': '<scope>' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import errno import logging import os import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials from locked_file import LockedFile logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or list of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ filename = os.path.realpath(os.path.expanduser(filename)) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly)) finally: _multistores_lock.release() if type(scope) is list: scope = ' '.join(scope) return multistore._get_storage(client_id, user_agent, scope) class _MultiStore(object): """A file backed store for multiple credentials.""" def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._file = LockedFile(filename, 'r+b', 'rb') self._thread_lock = threading.Lock() self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # (client_id, user_agent, scope) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, client_id, user_agent, scope): self._multistore = multistore self._client_id = client_id self._user_agent = user_agent self._scope = scope def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential( self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(credentials, self._scope) def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._delete_credential(self._client_id, self._user_agent, self._scope) def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._file.filename()): old_umask = os.umask(0177) try: open(self._file.filename(), 'a+b').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() self._file.open_and_lock() if not self._file.is_locked(): self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._file.filename()) if os.path.getsize(self._file.filename()) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" self._file.unlock_and_close() self._thread_lock.release() def _locked_json_read(self): """Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON. """ assert self._thread_lock.locked() self._file.file_handle().seek(0) return simplejson.load(self._file.file_handle()) def _locked_json_write(self, data): """Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written. """ assert self._thread_lock.locked() if self._read_only: return self._file.file_handle().seek(0) simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2) self._file.file_handle().truncate() def _refresh_data_cache(self): """Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store. """ self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. ' 'Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object. """ raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = { 'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2] } raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_credential(self, client_id, user_agent, scope): """Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present """ key = (client_id, user_agent, scope) return self._data.get(key, None) def _update_credential(self, cred, scope): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: cred: The OAuth2Credential to update/set scope: The scope(s) that this credential covers """ key = (cred.client_id, cred.user_agent, scope) self._data[key] = cred self._write() def _delete_credential(self, client_id, user_agent, scope): """Delete a credential and write the multistore. This must be called when the multistore is locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: The scope(s) that this credential covers """ key = (client_id, user_agent, scope) try: del self._data[key] except KeyError: pass self._write() def _get_storage(self, client_id, user_agent, scope): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, client_id, user_agent, scope)
Python
# Copyright (C) 2010 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. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover # Should work for Python2.6 and higher. import json as simplejson except ImportError: # pragma: no cover try: import simplejson except ImportError: # Try to import from django, should work on App Engine from django.utils import simplejson
Python
# Copyright (C) 2010 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. """Command-line tools for authenticating via OAuth 2.0 Do the OAuth 2.0 Web Server dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ['run'] import BaseHTTPServer import gflags import socket import sys import webbrowser from client import FlowExchangeError from client import OOB_CALLBACK_URN try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage, http=None): """Core code for a command-line application. Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. http: An instance of httplib2.Http.request or something that acts like it. Returns: Credentials, the obtained credential. """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if not success: print 'Failed to start a local webserver listening on either port 8080' print 'or port 9090. Please check your firewall settings and locally' print 'running programs that may be blocking or using those ports.' print print 'Falling back to --noauth_local_webserver and continuing with', print 'authorization.' print if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = OOB_CALLBACK_URN authorize_url = flow.step1_get_authorize_url(oauth_callback) if FLAGS.auth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print 'Your browser has been opened to visit:' print print ' ' + authorize_url print print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter ' print print ' --noauth_local_webserver' print else: print 'Go to the following link in your browser:' print print ' ' + authorize_url print code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential
Python
# Copyright (C) 2010 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. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse from anyjson import simplejson HAS_OPENSSL = False try: from oauth2client.crypt import Signer from oauth2client.crypt import make_signed_jwt from oauth2client.crypt import verify_signed_jwt_with_certs HAS_OPENSSL = True except ImportError: pass try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' # Constant to use for the out of band OAuth 2.0 flow. OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob' class Error(Exception): """Base error for this module.""" pass class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" pass class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" pass class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ pass class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" pass class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" pass def _abstract(): raise NotImplementedError('You need to override this function') class MemoryCache(object): """httplib2 Cache implementation which only caches locally.""" def __init__(self): self.cache = {} def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value def delete(self, key): self.cache.pop(key, None) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Credentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract() def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ _abstract() def _to_json(self, strip): """Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: if member in d: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] try: m = __import__(module) except ImportError: # In case there's an object from the old package structure, update it module = module.replace('.apiclient', '') m = __import__(module) m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ return Credentials() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() def delete(self): """Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None """ self.acquire_lock() try: return self.locked_delete() finally: self.release_lock() class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. id_token: object, The identity of the resource owner. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not self.access_token: logger.info('Attempting refresh to obtain initial access_token') self._refresh(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} self.apply(headers) if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) if resp.status == 401: logger.info('Refreshing due to a 401') self._refresh(request_orig) self.apply(headers) return request_orig(uri, method, body, headers, redirections, connection_type) else: return (resp, content) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. setattr(http.request, 'credentials', self) return http def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ self._refresh(http.request) def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ headers['Authorization'] = 'Bearer ' + self.access_token def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ data = simplejson.loads(s) if 'token_expiry' in data and not isinstance(data['token_expiry'], datetime.datetime): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], data.get('id_token', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = datetime.datetime.utcnow() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ if not self.store: self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refreshing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except: pass raise AccessTokenRefreshError(error_msg) class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable that when passed a Credential will store the credential back to where it came from. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed.") class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion_type': self.assertion_type, 'assertion': assertion, 'grant_type': 'assertion', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() if HAS_OPENSSL: # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then # don't create the SignedJwtAssertionCredentials or the verify_id_token() # method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in P12 format. scope: string or list of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key. user_agent: string, HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. kwargs: kwargs, Additional parameters to add to the JWT token, for example prn=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( 'http://oauth.net/grant_type/jwt/1.0/bearer', user_agent, token_uri=token_uri, ) if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.private_key = private_key self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], data['private_key'], data['private_key_password'], data['scope'], data['user_agent'], data['token_uri'], data['kwargs'] ) retval.invalid = data['invalid'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logger.debug(str(payload)) return make_signed_jwt( Signer.from_string(self.private_key, self.private_key_password), payload) # Only used in verify_id_token(), which is always calling to the same URI # for the certs. _cached_http = httplib2.Http(MemoryCache()) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = _cached_http resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri = 'postmessage', http=None, user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token'): """Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token """ flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent, 'https://accounts.google.com/o/oauth2/auth', token_uri) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials def credentials_from_clientsecrets_and_code(filename, scope, code, message = None, redirect_uri = 'postmessage', http=None): """Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ flow = flow_from_clientsecrets(filename, scope, message) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = { 'access_type': 'offline', } self.params.update(kwargs) self.redirect_uri = None def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ self.redirect_uri = redirect_uri query = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, } query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def step2_exchange(self, code, http=None): """Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError if a problem occured exchanging the code for a refresh_token. """ if not (isinstance(code, str) or isinstance(code, unicode)): if 'code' not in code: if 'error' in code: error_msg = code['error'] else: error_msg = 'No code was supplied in the query parameters.' raise FlowExchangeError(error_msg) else: code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if simplejson.loads fails? d = simplejson.loads(content) access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token: %s' % content) return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, id_token=d.get('id_token', None)) else: logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except: pass raise FlowExchangeError(error_msg) def flow_from_clientsecrets(filename, scope, message=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) to request. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, None, # user_agent client_info['auth_uri'], client_info['token_uri']) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
Python
# Copyright (C) 2011 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. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
Python