Beispiel #1
0
def get_presence(jid, from_jid=None):
    """Gets the presence for a JID.

  Args:
    jid: The JID of the contact whose presence is requested.
    from_jid: The optional custom JID to use for sending. Currently, the default
      is <appid>@appspot.com. This is supported as a value. Custom JIDs can be
      of the form <anything>@<appid>.appspotchat.com.

  Returns:
    bool, Whether the user is online.

  Raises:
    InvalidJidError if any of the JIDs passed are invalid.
    Error if an unspecified error happens processing the request.
  """
    if not jid:
        raise InvalidJidError()

    request = xmpp_service_pb.PresenceRequest()
    response = xmpp_service_pb.PresenceResponse()

    request.set_jid(_to_str(jid))
    if from_jid:
        request.set_from_jid(_to_str(from_jid))

    try:
        apiproxy_stub_map.MakeSyncCall("xmpp", "GetPresence", request,
                                       response)
    except apiproxy_errors.ApplicationError, e:
        if (e.application_error == xmpp_service_pb.XmppServiceError.INVALID_JID
            ):
            raise InvalidJidError()
        else:
            raise Error()
Beispiel #2
0
def create_channel(application_key):
    """Create a channel.

  Args:
    application_key: A key to identify this channel on the server side.

  Returns:
    A string id that the client can use to connect to the channel.

  Raises:
    InvalidChannelTimeoutError: if the specified timeout is invalid.
    Other errors returned by _ToChannelError
  """

    request = channel_service_pb.CreateChannelRequest()
    response = channel_service_pb.CreateChannelResponse()

    request.set_application_key(application_key)

    try:
        apiproxy_stub_map.MakeSyncCall(
            'channel',  #_GetService(),
            'CreateChannel',
            request,
            response)
    except apiproxy_errors.ApplicationError, e:
        raise _ToChannelError(e)
Beispiel #3
0
def send_invite(jid, from_jid=None):
    """Sends an invitation to chat to a JID.

  Args:
    jid: The JID of the contact to invite.
    from_jid: The optional custom JID to use for sending. Currently, the default
      is <appid>@appspot.com. This is supported as a value. Custom JIDs can be
      of the form <anything>@<appid>.appspotchat.com.

  Raises:
    InvalidJidError if the JID passed is invalid.
    Error if an unspecified error happens processing the request.
  """
    if not jid:
        raise InvalidJidError()

    request = xmpp_service_pb.XmppInviteRequest()
    response = xmpp_service_pb.XmppInviteResponse()

    request.set_jid(_to_str(jid))
    if from_jid:
        request.set_from_jid(_to_str(from_jid))

    try:
        apiproxy_stub_map.MakeSyncCall("xmpp", "SendInvite", request, response)
    except apiproxy_errors.ApplicationError, e:
        if (e.application_error == xmpp_service_pb.XmppServiceError.INVALID_JID
            ):
            raise InvalidJidError()
        else:
            raise Error()
Beispiel #4
0
    def _TransactionalBulkAdd(self, request):
        """Uses datastore.AddActions to associate tasks with a transaction.

    Args:
      request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the
        tasks to add. N.B. all tasks in the request have been validated and
        assigned unique names.
    """
        try:
            apiproxy_stub_map.MakeSyncCall('datastore_v3', 'AddActions',
                                           request, api_base_pb.VoidProto())
        except apiproxy_errors.ApplicationError, e:
            raise apiproxy_errors.ApplicationError(
                e.application_error +
                taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR,
                e.error_detail)
Beispiel #5
0
def _Call(call, req, resp):
    """Generic method for making a datastore API call.

  Args:
    call: string, the name of the RPC call
    req: the request PB. if the app_id field is not set, it defaults to the
      local app.
    resp: the response PB
  """
    if hasattr(req, 'app_id'):
        req.set_app_id(datastore_types.ResolveAppId(req.app_id()))

    try:
        result = apiproxy_stub_map.MakeSyncCall('datastore_v3', call, req,
                                                resp)
        if result:
            return result
        return resp
    except apiproxy_errors.ApplicationError, err:
        raise datastore._ToDatastoreError(err)
Beispiel #6
0
    def histogram(self):
        """Calculates the histogram of the image.

    Returns: 3 256-element lists containing the number of occurences of each
    value of each color in the order RGB. As described at
    http://en.wikipedia.org/wiki/Color_histogram for N = 256. i.e. the first
    value of the first list contains the number of pixels with a red value of
    0, the second the number with a red value of 1.

    Raises:
      NotImageError when the image data given is not an image.
      BadImageError when the image data given is corrupt.
      LargeImageError when the image data given is too large to process.
      Error when something unknown, but bad, happens.
    """
        request = images_service_pb.ImagesHistogramRequest()
        response = images_service_pb.ImagesHistogramResponse()

        self._set_imagedata(request.mutable_image())

        try:
            apiproxy_stub_map.MakeSyncCall("images", "Histogram", request,
                                           response)
        except apiproxy_errors.ApplicationError, e:
            if (e.application_error ==
                    images_service_pb.ImagesServiceError.NOT_IMAGE):
                raise NotImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.BAD_IMAGE_DATA):
                raise BadImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.IMAGE_TOO_LARGE):
                raise LargeImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.INVALID_BLOB_KEY):
                raise InvalidBlobKeyError()
            else:
                raise Error()
Beispiel #7
0
    def __AddTasks(self, tasks, transactional):
        """Internal implementation of .add() where tasks must be a list."""

        request = taskqueue_service_pb.TaskQueueBulkAddRequest()
        response = taskqueue_service_pb.TaskQueueBulkAddResponse()

        task_names = set()
        for task in tasks:
            if task.name:
                if task.name in task_names:
                    raise DuplicateTaskNameError(
                        'The task name %r is used more than once in the request'
                        % task.name)
                task_names.add(task.name)

            self.__FillAddRequest(task, request.add_add_request(),
                                  transactional)

        try:
            apiproxy_stub_map.MakeSyncCall('taskqueue', 'BulkAdd', request,
                                           response)
        except apiproxy_errors.ApplicationError, e:
            raise self.__TranslateError(e.application_error, e.error_detail)
Beispiel #8
0
def send_message(application_key, message):
    """Send a message to a channel.

  Args:
    application_key: The key passed to create_channel.
    message: A string representing the message to send.

  Raises:
    Errors returned by _ToChannelError
  """
    request = channel_service_pb.SendMessageRequest()
    response = api_base_pb.VoidProto()

    request.set_application_key(application_key)
    request.set_message(message)

    try:
        apiproxy_stub_map.MakeSyncCall(
            'channel',  #_GetService(),
            'SendChannelMessage',
            request,
            response)
    except apiproxy_errors.ApplicationError, e:
        raise _ToChannelError(e)
Beispiel #9
0
def get_serving_url(blob_key, size=None, crop=False):
    """Obtain a url that will serve the underlying image.

  This URL is served by a high-performance dynamic image serving infrastructure.
  This URL format also allows dynamic resizing and crop with certain
  restrictions. To get dynamic resizing and cropping, specify size and crop
  arguments, or simply append options to the end of the default url obtained via
  this call.  Here is an example:

  get_serving_url -> "http://lh3.ggpht.com/SomeCharactersGoesHere"

  To get a 32 pixel sized version (aspect-ratio preserved) simply append
  "=s32" to the url:

  "http://lh3.ggpht.com/SomeCharactersGoesHere=s32"

  To get a 32 pixel cropped version simply append "=s32-c":

  "http://lh3.ggpht.com/SomeCharactersGoesHere=s32-c"

  Available sizes for resize are:
  (e.g. "=sX" where X is one of the following values)

  0, 32, 48, 64, 72, 80, 90, 94, 104, 110, 120, 128, 144,
  150, 160, 200, 220, 288, 320, 400, 512, 576, 640, 720,
  800, 912, 1024, 1152, 1280, 1440, 1600

  Available sizes for crop are:
  (e.g. "=sX-c" where X is one of the following values)

  32, 48, 64, 72, 80, 104, 136, 144, 150, 160

  These values are also available as IMG_SERVING_SIZES and
  IMG_SERVING_CROP_SIZES integer lists.

  Args:
    size: int, size of resulting images
    crop: bool, True requests a cropped image, False a resized one.

  Returns:
    str, a url

  Raises:
    BlobKeyRequiredError: when no blobkey was specified in the ctor.
    UnsupportedSizeError: when size parameters uses unsupported sizes.
    BadRequestError: when crop/size are present in wrong combination.
  """
    if not blob_key:
        raise BlobKeyRequiredError("A Blobkey is required for this operation.")

    if crop and not size:
        raise BadRequestError("Size should be set for crop operation")

    if size and crop and not size in IMG_SERVING_CROP_SIZES:
        raise UnsupportedSizeError("Unsupported crop size")

    if size and not crop and not size in IMG_SERVING_SIZES:
        raise UnsupportedSizeError("Unsupported size")

    request = images_service_pb.ImagesGetUrlBaseRequest()
    response = images_service_pb.ImagesGetUrlBaseResponse()

    request.set_blob_key(blob_key)

    try:
        apiproxy_stub_map.MakeSyncCall("images", "GetUrlBase", request,
                                       response)
    except apiproxy_errors.ApplicationError, e:
        if (e.application_error ==
                images_service_pb.ImagesServiceError.NOT_IMAGE):
            raise NotImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.BAD_IMAGE_DATA):
            raise BadImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.IMAGE_TOO_LARGE):
            raise LargeImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.INVALID_BLOB_KEY):
            raise InvalidBlobKeyError()
        else:
            raise Error()
Beispiel #10
0
def composite(inputs,
              width,
              height,
              color=0,
              output_encoding=PNG,
              quality=None):
    """Composite one or more images onto a canvas.

  Args:
    inputs: a list of tuples (image_data, x_offset, y_offset, opacity, anchor)
    where
      image_data: str, source image data.
      x_offset: x offset in pixels from the anchor position
      y_offset: y offset in piyels from the anchor position
      opacity: opacity of the image specified as a float in range [0.0, 1.0]
      anchor: anchoring point from ANCHOR_POINTS. The anchor point of the image
      is aligned with the same anchor point of the canvas. e.g. TOP_RIGHT would
      place the top right corner of the image at the top right corner of the
      canvas then apply the x and y offsets.
    width: canvas width in pixels.
    height: canvas height in pixels.
    color: canvas background color encoded as a 32 bit unsigned int where each
    color channel is represented by one byte in order ARGB.
    output_encoding: a value from OUTPUT_ENCODING_TYPES.
    quality: A value between 1 and 100 to specify the quality of the
    encoding.  This value is only used for JPEG quality control.

  Returns:
      str, image data of the composited image.

  Raises:
    TypeError If width, height, color, x_offset or y_offset are not of type
    int or long or if opacity is not a float
    BadRequestError If more than MAX_TRANSFORMS_PER_REQUEST compositions have
    been requested, if the canvas width or height is greater than 4000 or less
    than or equal to 0, if the color is invalid or if for any composition
    option, the opacity is outside the range [0,1] or the anchor is invalid.
  """
    if (not isinstance(width,
                       (int, long)) or not isinstance(height, (int, long))
            or not isinstance(color, (int, long))):
        raise TypeError("Width, height and color must be integers.")
    if output_encoding not in OUTPUT_ENCODING_TYPES:
        raise BadRequestError(
            "Output encoding type '%s' not in recognized set "
            "%s" % (output_encoding, OUTPUT_ENCODING_TYPES))

    if quality is not None:
        if not isinstance(quality, (int, long)):
            raise TypeError("Quality must be an integer.")
        if quality > 100 or quality < 1:
            raise BadRequestError("Quality must be between 1 and 100.")

    if not inputs:
        raise BadRequestError("Must provide at least one input")
    if len(inputs) > MAX_COMPOSITES_PER_REQUEST:
        raise BadRequestError("A maximum of %d composition operations can be"
                              "performed in a single request" %
                              MAX_COMPOSITES_PER_REQUEST)

    if width <= 0 or height <= 0:
        raise BadRequestError("Width and height must be > 0.")
    if width > 4000 or height > 4000:
        raise BadRequestError("Width and height must be <= 4000.")

    if color > 0xffffffff or color < 0:
        raise BadRequestError("Invalid color")
    if color >= 0x80000000:
        color -= 0x100000000

    image_map = {}

    request = images_service_pb.ImagesCompositeRequest()
    response = images_service_pb.ImagesTransformResponse()
    for (image, x, y, opacity, anchor) in inputs:
        if not image:
            raise BadRequestError("Each input must include an image")
        if (not isinstance(x, (int, long)) or not isinstance(y, (int, long))
                or not isinstance(opacity, (float))):
            raise TypeError(
                "x_offset, y_offset must be integers and opacity must"
                "be a float")
        if x > 4000 or x < -4000:
            raise BadRequestError("xOffsets must be in range [-4000, 4000]")
        if y > 4000 or y < -4000:
            raise BadRequestError("yOffsets must be in range [-4000, 4000]")
        if opacity < 0 or opacity > 1:
            raise BadRequestError("Opacity must be in the range 0.0 to 1.0")
        if anchor not in ANCHOR_TYPES:
            raise BadRequestError("Anchor type '%s' not in recognized set %s" %
                                  (anchor, ANCHOR_TYPES))
        if image not in image_map:
            image_map[image] = request.image_size()

            if isinstance(image, Image):
                image._set_imagedata(request.add_image())
            else:
                request.add_image().set_content(image)

        option = request.add_options()
        option.set_x_offset(x)
        option.set_y_offset(y)
        option.set_opacity(opacity)
        option.set_anchor(anchor)
        option.set_source_index(image_map[image])

    request.mutable_canvas().mutable_output().set_mime_type(output_encoding)
    request.mutable_canvas().set_width(width)
    request.mutable_canvas().set_height(height)
    request.mutable_canvas().set_color(color)

    if ((output_encoding == JPEG) and (quality is not None)):
        request.mutable_canvas().mutable_output().set_quality(quality)

    try:
        apiproxy_stub_map.MakeSyncCall("images", "Composite", request,
                                       response)
    except apiproxy_errors.ApplicationError, e:
        if (e.application_error ==
                images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA):
            raise BadRequestError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.NOT_IMAGE):
            raise NotImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.BAD_IMAGE_DATA):
            raise BadImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.IMAGE_TOO_LARGE):
            raise LargeImageError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.INVALID_BLOB_KEY):
            raise InvalidBlobKeyError()
        elif (e.application_error ==
              images_service_pb.ImagesServiceError.UNSPECIFIED_ERROR):
            raise TransformationError()
        else:
            raise Error()
Beispiel #11
0
    def execute_transforms(self, output_encoding=PNG, quality=None):
        """Perform transformations on given image.

    Args:
      output_encoding: A value from OUTPUT_ENCODING_TYPES.
      quality: A value between 1 and 100 to specify the quality of the
      encoding.  This value is only used for JPEG quality control.

    Returns:
      str, image data after the transformations have been performed on it.

    Raises:
      BadRequestError when there is something wrong with the request
        specifications.
      NotImageError when the image data given is not an image.
      BadImageError when the image data given is corrupt.
      LargeImageError when the image data given is too large to process.
      InvalidBlobKeyError when the blob key provided is invalid.
      TransformtionError when something errors during image manipulation.
      Error when something unknown, but bad, happens.
    """
        if output_encoding not in OUTPUT_ENCODING_TYPES:
            raise BadRequestError("Output encoding type not in recognized set "
                                  "%s" % OUTPUT_ENCODING_TYPES)

        if not self._transforms:
            raise BadRequestError("Must specify at least one transformation.")

        if quality is not None:
            if not isinstance(quality, (int, long)):
                raise TypeError("Quality must be an integer.")
            if quality > 100 or quality < 1:
                raise BadRequestError("Quality must be between 1 and 100.")

        request = images_service_pb.ImagesTransformRequest()
        response = images_service_pb.ImagesTransformResponse()

        self._set_imagedata(request.mutable_image())

        for transform in self._transforms:
            request.add_transform().CopyFrom(transform)

        request.mutable_output().set_mime_type(output_encoding)

        if ((output_encoding == JPEG) and (quality is not None)):
            request.mutable_output().set_quality(quality)

        try:
            apiproxy_stub_map.MakeSyncCall("images", "Transform", request,
                                           response)
        except apiproxy_errors.ApplicationError, e:
            if (e.application_error ==
                    images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA):
                raise BadRequestError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.NOT_IMAGE):
                raise NotImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.BAD_IMAGE_DATA):
                raise BadImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.IMAGE_TOO_LARGE):
                raise LargeImageError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.INVALID_BLOB_KEY):
                raise InvalidBlobKeyError()
            elif (e.application_error ==
                  images_service_pb.ImagesServiceError.UNSPECIFIED_ERROR):
                raise TransformationError()
            else:
                raise Error()
Beispiel #12
0
def send_message(jids,
                 body,
                 from_jid=None,
                 message_type=MESSAGE_TYPE_CHAT,
                 raw_xml=False):
    """Sends a chat message to a list of JIDs.

  Args:
    jids: A list of JIDs to send the message to, or a single JID to send the
      message to.
    from_jid: The optional custom JID to use for sending. Currently, the default
      is <appid>@appspot.com. This is supported as a value. Custom JIDs can be
      of the form <anything>@<appid>.appspotchat.com.
    body: The body of the message.
    message_type: Optional type of the message. Should be one of the types
      specified in RFC 3921, section 2.1.1. An empty string will result in a
      message stanza without a type attribute. For convenience, all of the
      valid types are in the MESSAGE_TYPE_* constants in this file. The
      default is MESSAGE_TYPE_CHAT. Anything else will throw an exception.
    raw_xml: Optionally specifies that the body should be interpreted as XML. If
      this is false, the contents of the body will be escaped and placed inside
      of a body element inside of the message. If this is true, the contents
      will be made children of the message.

  Returns:
    list, A list of statuses, one for each JID, corresponding to the result of
      sending the message to that JID. Or, if a single JID was passed in,
      returns the status directly.

  Raises:
    InvalidJidError if there is no valid JID in the list.
    InvalidTypeError if the type argument is invalid.
    InvalidXmlError if the body is malformed XML and raw_xml is True.
    NoBodyError if there is no body.
    Error if another error occurs processing the request.
  """
    request = xmpp_service_pb.XmppMessageRequest()
    response = xmpp_service_pb.XmppMessageResponse()

    if not body:
        raise NoBodyError()

    if not jids:
        raise InvalidJidError()

    if not message_type in _VALID_MESSAGE_TYPES:
        raise InvalidTypeError()

    single_jid = False
    if isinstance(jids, basestring):
        single_jid = True
        jids = [jids]

    for jid in jids:
        if not jid:
            raise InvalidJidError()
        request.add_jid(_to_str(jid))

    request.set_body(_to_str(body))
    request.set_type(_to_str(message_type))
    request.set_raw_xml(raw_xml)
    if from_jid:
        request.set_from_jid(_to_str(from_jid))

    try:
        apiproxy_stub_map.MakeSyncCall("xmpp", "SendMessage", request,
                                       response)
    except apiproxy_errors.ApplicationError, e:
        if (e.application_error == xmpp_service_pb.XmppServiceError.INVALID_JID
            ):
            raise InvalidJidError()
        elif (e.application_error ==
              xmpp_service_pb.XmppServiceError.INVALID_TYPE):
            raise InvalidTypeError()
        elif (e.application_error ==
              xmpp_service_pb.XmppServiceError.INVALID_XML):
            raise InvalidXmlError()
        elif (e.application_error == xmpp_service_pb.XmppServiceError.NO_BODY):
            raise NoBodyError()
        raise Error()