1#-------------------------------------------------------------------------
2# Copyright (c) Microsoft.  All rights reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#   http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#--------------------------------------------------------------------------
15import sys
16if sys.version_info >= (3,):
17    from io import BytesIO
18else:
19    try:
20        from cStringIO import StringIO as BytesIO
21    except:
22        from StringIO import StringIO as BytesIO
23
24try:
25    from xml.etree import cElementTree as ETree
26except ImportError:
27    from xml.etree import ElementTree as ETree
28
29from xml.sax.saxutils import escape as xml_escape
30from .._common_conversion import (
31    _str,
32)
33from ._encryption import (
34    _encrypt_queue_message,
35)
36
37def _get_path(queue_name=None, include_messages=None, message_id=None):
38    '''
39    Creates the path to access a queue resource.
40
41    queue_name:
42        Name of queue.
43    include_messages:
44        Whether or not to include messages.
45    message_id:
46        Message id.
47    '''
48    if queue_name and include_messages and message_id:
49        return '/{0}/messages/{1}'.format(_str(queue_name), message_id)
50    if queue_name and include_messages:
51        return '/{0}/messages'.format(_str(queue_name))
52    elif queue_name:
53        return '/{0}'.format(_str(queue_name))
54    else:
55        return '/'
56
57
58def _convert_queue_message_xml(message_text, encode_function, key_encryption_key):
59    '''
60    <?xml version="1.0" encoding="utf-8"?>
61    <QueueMessage>
62        <MessageText></MessageText>
63    </QueueMessage>
64    '''
65    queue_message_element = ETree.Element('QueueMessage');
66
67    # Enabled
68    message_text = encode_function(message_text)
69    if key_encryption_key is not None:
70            message_text = _encrypt_queue_message(message_text, key_encryption_key)
71    ETree.SubElement(queue_message_element, 'MessageText').text = message_text
72
73    # Add xml declaration and serialize
74    try:
75        stream = BytesIO()
76        ETree.ElementTree(queue_message_element).write(stream, xml_declaration=True, encoding='utf-8', method='xml')
77        output = stream.getvalue()
78    finally:
79        stream.close()
80
81    return output
82