├── otrs ├── faq │ ├── __init__.py │ ├── objects.py │ ├── template.py │ └── operations.py ├── ticket │ ├── __init__.py │ ├── template.py │ ├── objects.py │ └── operations.py ├── session │ ├── __init__.py │ └── operations.py ├── __init__.py ├── objects.py └── client.py ├── MANIFEST.in ├── setup.cfg ├── .gitignore ├── AUTHORS ├── setup.py ├── README.rst ├── tests.py └── LICENSE /otrs/faq/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /otrs/ticket/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /otrs/session/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | -------------------------------------------------------------------------------- /otrs/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Erwin Sterrenburg' 2 | __email__ = 'e.w.sterrenburg@gmail.com' 3 | __version__ = '0.4.3' 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | *.sqlite3 4 | local_settings.py 5 | *.vagrant 6 | *.log 7 | supervisord.pid 8 | *.lock 9 | build 10 | dist 11 | *.egg-info 12 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Copyright : Oasiswork, 2014 2 | 3 | Authors : 4 | - Jocelyn Delalande 5 | - Hugo Castilho 6 | - Michiel Beijen 7 | - Erwin Sterrenburg 8 | - David Trudgian 9 | - Michael Ducharme 10 | - Chris Halls 11 | - Kishor Bhat 12 | -------------------------------------------------------------------------------- /otrs/faq/objects.py: -------------------------------------------------------------------------------- 1 | """OTRS :: faq :: objects.""" 2 | from otrs.objects import Attachment 3 | from otrs.objects import AttachmentContainer 4 | from otrs.objects import OTRSObject 5 | 6 | 7 | class Category(OTRSObject): 8 | """An OTRS FAQ Category.""" 9 | 10 | XML_NAME = 'Category' 11 | 12 | 13 | class Language(OTRSObject): 14 | """An OTRS FAQ Language.""" 15 | 16 | XML_NAME = 'Language' 17 | 18 | 19 | class FAQItem(OTRSObject, AttachmentContainer): 20 | """An OTRS FAQ Item.""" 21 | 22 | XML_NAME = 'FAQItem' 23 | CHILD_MAP = {'Attachment': Attachment} 24 | -------------------------------------------------------------------------------- /otrs/faq/template.py: -------------------------------------------------------------------------------- 1 | """OTRS :: faq :: template.""" 2 | from otrs.client import WebService 3 | from otrs.faq.operations import LanguageList 4 | from otrs.faq.operations import PublicCategoryList 5 | from otrs.faq.operations import PublicFAQGet 6 | from otrs.faq.operations import PublicFAQSearch 7 | 8 | 9 | def GenericFAQConnectorSOAP(webservice_name='GenericFAQConnectorSOAP'): 10 | """Return a GenericFAQConnectorSOAP Webservice object. 11 | 12 | @returns a WebService object with the GenericFAQConnectorSOAP operations 13 | """ 14 | return WebService(webservice_name, 'http://www.otrs.org/FAQConnector', 15 | LanguageList=LanguageList(), 16 | PublicCategoryList=PublicCategoryList(), 17 | PublicFAQGet=PublicFAQGet(), 18 | PublicFAQSearch=PublicFAQSearch()) 19 | -------------------------------------------------------------------------------- /otrs/ticket/template.py: -------------------------------------------------------------------------------- 1 | """OTRS :: ticket:: template.""" 2 | from otrs.client import WebService 3 | from otrs.session.operations import SessionCreate 4 | from otrs.ticket.operations import TicketCreate 5 | from otrs.ticket.operations import TicketGet 6 | from otrs.ticket.operations import TicketSearch 7 | from otrs.ticket.operations import TicketUpdate 8 | 9 | 10 | def GenericTicketConnectorSOAP(webservice_name='GenericTicketConnectorSOAP'): 11 | """Return a GenericTicketConnectorSOAP Webservice object. 12 | 13 | @returns a WebService object with the GenericTicketConnectorSOAP operations 14 | """ 15 | return WebService(webservice_name, 'http://www.otrs.org/TicketConnector', 16 | SessionCreate=SessionCreate(), 17 | TicketCreate=TicketCreate(), 18 | TicketGet=TicketGet(), TicketSearch=TicketSearch(), 19 | TicketUpdate=TicketUpdate()) 20 | -------------------------------------------------------------------------------- /otrs/ticket/objects.py: -------------------------------------------------------------------------------- 1 | """OTRS :: ticket :: objects.""" 2 | from otrs.objects import Attachment 3 | from otrs.objects import AttachmentContainer 4 | from otrs.objects import DynamicField 5 | from otrs.objects import DynamicFieldContainer 6 | from otrs.objects import OTRSObject 7 | 8 | 9 | class Article(OTRSObject, AttachmentContainer, DynamicFieldContainer): 10 | """An OTRS article.""" 11 | 12 | XML_NAME = 'Article' 13 | CHILD_MAP = {'Attachment': Attachment, 'DynamicField': DynamicField} 14 | 15 | 16 | class Ticket(OTRSObject, DynamicFieldContainer): 17 | """An OTRS ticket.""" 18 | 19 | XML_NAME = 'Ticket' 20 | CHILD_MAP = {'Article': Article, 'DynamicField': DynamicField} 21 | 22 | def articles(self): 23 | """Return the articles for a ticket as a list. 24 | 25 | @returns a list of Article objects. 26 | """ 27 | try: 28 | return self.childs['Article'] 29 | except KeyError: 30 | return [] 31 | -------------------------------------------------------------------------------- /otrs/session/operations.py: -------------------------------------------------------------------------------- 1 | """OTRS :: session :: operations.""" 2 | from otrs.client import OperationBase 3 | 4 | 5 | class Session(OperationBase): 6 | """Base class for OTRS Session:: operations.""" 7 | 8 | 9 | class SessionCreate(Session): 10 | """Class to handle OTRS Session::SessionCreate operation.""" 11 | 12 | def __call__(self, password, user_login=None, customer_user_login=None): 13 | """Create an User session or CustomerUser session. 14 | 15 | @returns the session_id 16 | """ 17 | if user_login: 18 | ret = self.req('SessionCreate', 19 | UserLogin=user_login, 20 | Password=password) 21 | else: 22 | ret = self.req('SessionCreate', 23 | CustomerUserLogin=customer_user_login, 24 | Password=password) 25 | signal = self._unpack_resp_one(ret) 26 | session_id = signal.text 27 | 28 | # sets the session id for the entire client to this 29 | self.session_id = session_id 30 | 31 | # returns the session id in case you want it, 32 | # but its not normally needed 33 | return session_id 34 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | from setuptools import find_packages 6 | from setuptools import setup 7 | 8 | README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() 9 | 10 | setup( 11 | name='python-otrs', 12 | version='0.4.3', 13 | description='A programmatic interface to OTRS SOAP API.', 14 | long_description=README, 15 | author='Erwin Sterrenburg', 16 | author_email='e.w.sterrenburg@gmail.com', 17 | url='https://github.com/ewsterrenburg/python-otrs', 18 | license='GPLv3', 19 | zip_safe=False, 20 | packages=find_packages(), 21 | install_requires=['defusedxml'], 22 | include_package_data=True, 23 | python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4', 24 | keywords='otrs ticket support soap interface helpdesk', 25 | classifiers=[ 26 | # How mature is this project? Common values are 27 | # 3 - Alpha 28 | # 4 - Beta 29 | # 5 - Production/Stable 30 | 'Development Status :: 4 - Beta', 31 | 'Environment :: Web Environment', 32 | 'Natural Language :: English', 33 | # Indicate who your project is intended for 34 | 'Intended Audience :: Developers', 35 | 'Operating System :: OS Independent', 36 | 'Topic :: Office/Business', 37 | 'Topic :: Software Development :: Bug Tracking', 38 | # Pick your license as you wish (should match "license" above) 39 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 40 | # Specify the Python versions you support here. In particular, ensure 41 | # that you indicate whether you support Python 2, Python 3 or both. 42 | 'Programming Language :: Python :: 2', 43 | 'Programming Language :: Python :: 2.7', 44 | 'Programming Language :: Python :: 3', 45 | 'Programming Language :: Python :: 3.5', 46 | ], ) 47 | -------------------------------------------------------------------------------- /otrs/faq/operations.py: -------------------------------------------------------------------------------- 1 | """OTRS :: faq :: operations.""" 2 | from otrs.client import authenticated 3 | from otrs.client import OperationBase 4 | from otrs.faq.objects import Category as CategoryObject 5 | from otrs.faq.objects import FAQItem as FAQItemObject 6 | from otrs.faq.objects import Language as LanguageObject 7 | 8 | 9 | class FAQ(OperationBase): 10 | """Base class for OTRS FAQ:: operations.""" 11 | 12 | 13 | class LanguageList(FAQ): 14 | """Class to handle OTRS ITSM FAQ::LanguageList operation.""" 15 | 16 | @authenticated 17 | def __call__(self, *args, **kwargs): 18 | """Return the Language List from FAQ. 19 | 20 | @returns list of languages 21 | """ 22 | ret = self.req('LanguageList', **kwargs) 23 | elements = self._unpack_resp_several(ret) 24 | return [LanguageObject.from_xml(language) for language in elements] 25 | 26 | 27 | class PublicCategoryList(FAQ): 28 | """Class to handle OTRS ITSM FAQ::PublicCategoryList operation.""" 29 | 30 | @authenticated 31 | def __call__(self, **kwargs): 32 | """Return the Public Category List from FAQ. 33 | 34 | @returns list of category objects 35 | """ 36 | ret = self.req('PublicCategoryList', **kwargs) 37 | elements = self._unpack_resp_several(ret) 38 | return [CategoryObject.from_xml(category) for category in elements] 39 | 40 | 41 | class PublicFAQGet(FAQ): 42 | """Class to handle OTRS ITSM FAQ::PublicFAQGet operation.""" 43 | 44 | @authenticated 45 | def __call__(self, item_id, get_attachments=False, **kwargs): 46 | """Get a public FAQItem by id. 47 | 48 | @param item_id : the ItemID of the public FAQItem 49 | NOTE: ItemID != FAQ Number 50 | 51 | @return an `FAQItem` 52 | """ 53 | params = {'ItemID': str(item_id)} 54 | params.update(kwargs) 55 | if get_attachments: 56 | params['GetAttachmentContents'] = 1 57 | else: 58 | params['GetAttachmentContents'] = 0 59 | 60 | ret = self.req('PublicFAQGet', **params) 61 | return FAQItemObject.from_xml(self._unpack_resp_one(ret)) 62 | 63 | 64 | class PublicFAQSearch(FAQ): 65 | """Class to handle OTRS ITSM FAQ :: PublicFAQSearch operation.""" 66 | 67 | @authenticated 68 | def __call__(self, *args, **kwargs): 69 | """Search for matching public FAQItems. 70 | 71 | @returns a list of matching public FAQItem IDs 72 | """ 73 | ret = self.req('PublicFAQSearch', **kwargs) 74 | return [int(i.text) for i in self._unpack_resp_several(ret)] 75 | -------------------------------------------------------------------------------- /otrs/objects.py: -------------------------------------------------------------------------------- 1 | """OTRS :: objects.""" 2 | from __future__ import unicode_literals 3 | import base64 4 | from defusedxml import ElementTree as etree 5 | import os 6 | import sys 7 | # defusedxml doesn't define these non-parsing related objects 8 | from xml.etree.ElementTree import Element 9 | from xml.etree.ElementTree import SubElement 10 | from xml.etree.ElementTree import tostring 11 | 12 | etree.Element = _ElementType = Element 13 | etree.SubElement = SubElement 14 | etree.tostring = tostring 15 | 16 | # Fix Python 3.x. 17 | try: 18 | UNICODE_EXISTS = bool(type(unicode)) 19 | except NameError: 20 | unicode = lambda s: str(s) 21 | 22 | 23 | class OTRSObject(object): 24 | """Represents an object for OTRS (mappable to an XML element).""" 25 | 26 | # Map : {'TagName' -> Class} 27 | CHILD_MAP = {} 28 | 29 | def __init__(self, *args, **kwargs): 30 | """Initialize OTRS Object.""" 31 | self.attrs = kwargs 32 | self.childs = {} 33 | 34 | def __getattr__(self, k): 35 | """Get an attribute for aan OTRSObject. 36 | 37 | attrs are simple xml child tags (val), complex children, 38 | are accessible via dedicated methods. 39 | 40 | @returns a simple type 41 | """ 42 | return autocast(self.attrs[k]) 43 | 44 | @classmethod 45 | def from_xml(cls, xml_element): 46 | """Create an OTRS Object from xml. 47 | 48 | @param xml_element an etree.Element 49 | @returns an OTRSObject 50 | """ 51 | child_tags = cls.CHILD_MAP.keys() 52 | 53 | if not xml_element.tag.endswith(cls.XML_NAME): 54 | raise ValueError( 55 | 'xml_element should be a {} node, not {}'.format( 56 | cls.XML_NAME, xml_element.tag)) 57 | attrs = {} 58 | childs = [] 59 | for t in list(xml_element): 60 | name = extract_tagname(t) 61 | if name in child_tags: 62 | # Complex child tags 63 | SubClass = cls.CHILD_MAP[name] 64 | sub_obj = SubClass.from_xml(t) 65 | childs.append(sub_obj) 66 | else: 67 | # Simple child tags 68 | attrs[name] = t.text 69 | obj = cls(**attrs) 70 | 71 | for i in childs: 72 | obj.add_child(i) 73 | 74 | return obj 75 | 76 | def add_child(self, childobj): 77 | """Add a child object to an OTRS Object. 78 | 79 | @param childobj : an OTRSObject 80 | """ 81 | xml_name = childobj.XML_NAME 82 | 83 | if xml_name in self.childs: 84 | self.childs[xml_name].append(childobj) 85 | else: 86 | self.childs[xml_name] = [childobj] 87 | 88 | def check_fields(self, fields): 89 | """Check that the list of fields is bound. 90 | 91 | @param fields rules, as list 92 | 93 | items n fields can be either : 94 | - a field name : this field is required 95 | - a tuple of field names : on of this fields is required 96 | """ 97 | set_keys = set(self.attrs.keys()) 98 | 99 | for i in fields: 100 | if isinstance(i, str): 101 | set_fields = set([i]) 102 | else: 103 | set_fields = set(i) 104 | 105 | if set_keys.intersection(set_fields): 106 | valid = True 107 | else: 108 | valid = False 109 | 110 | if not valid: 111 | raise ValueError('{} should be filled'.format(i)) 112 | 113 | def to_xml(self): 114 | """Create an XML representation of an OTRS Object. 115 | 116 | @returns am etree.Element 117 | """ 118 | root = etree.Element(self.XML_NAME) 119 | for k, v in self.attrs.items(): 120 | e = etree.Element(k) 121 | if isinstance(e, str): 122 | v = v.encode('utf-8') 123 | if sys.version_info[0] == 3: 124 | e.text = str(v) 125 | else: 126 | e.text = unicode(v) 127 | root.append(e) 128 | return root 129 | 130 | 131 | def extract_tagname(element): 132 | """Return the name of the tag, without namespace. 133 | 134 | element.tag lib gives "{namespace}tagname", we want only "tagname" 135 | 136 | @param element : an etree.Element 137 | @returns : a str, the name of the tag 138 | """ 139 | qualified_name = element.tag 140 | try: 141 | return qualified_name.split('}')[1] 142 | except IndexError: 143 | # if it's not namespaced, then return the tag name itself 144 | return element.tag 145 | # raise ValueError('"{}" is not a tag name'.format(qualified_name)) 146 | 147 | 148 | def autocast(s): 149 | """Try to guess the simple type and convert the value to it. 150 | 151 | @param s string 152 | @returns the relevant type : a float, string or int 153 | """ 154 | try: 155 | return int(s) 156 | except ValueError: 157 | try: 158 | return float(s) 159 | except ValueError: 160 | return s 161 | except TypeError: 162 | return s 163 | 164 | 165 | class Attachment(OTRSObject): 166 | """An OTRS attachment.""" 167 | 168 | XML_NAME = 'Attachment' 169 | 170 | 171 | class DynamicField(OTRSObject): 172 | """An OTRS dynamic field.""" 173 | 174 | XML_NAME = 'DynamicField' 175 | 176 | 177 | class AttachmentContainer(object): 178 | """For objects that can have attachments in them (ex. tickets, articles). 179 | 180 | They should inherit this class in addition to OTRSObject. 181 | """ 182 | 183 | def attachments(self): 184 | """Return the dynamic fields for an object ket as a list. 185 | 186 | @returns a list of Attachment objects. 187 | """ 188 | try: 189 | return self.childs['Attachment'] 190 | except KeyError: 191 | return [] 192 | 193 | def save_attachments(self, folder): 194 | """Save the attachments of an article to the specified folder. 195 | 196 | @param folder : a str, folder to save the attachments 197 | """ 198 | for a in self.attachments(): 199 | fname = a.attrs['Filename'] 200 | fpath = os.path.join(folder, fname) 201 | content = a.attrs['Content'] 202 | fcontent = base64.b64decode(content) 203 | ffile = open(fpath, 'wb') 204 | ffile.write(fcontent) 205 | ffile.close() 206 | 207 | 208 | class DynamicFieldContainer(object): 209 | """For objects that can have dynamic fields in them (ex. tickets, articles). 210 | 211 | They should inherit this class in addition to OTRSObject. 212 | """ 213 | 214 | def dynamicfields(self): 215 | """Return the dynamic fields for an object ket as a list. 216 | 217 | @returns a list of DynamicField objects. 218 | """ 219 | try: 220 | return self.childs['DynamicField'] 221 | except KeyError: 222 | return [] 223 | 224 | 225 | # the two functions below are here only for backward compatibility 226 | # with old code that imported these classes from this file 227 | # the classes are now in tickets/objects.py 228 | 229 | 230 | def Ticket(*args, **kwargs): 231 | """Return an OTRS ticket.""" 232 | import otrs.ticket.objects 233 | return otrs.ticket.objects.Ticket(*args, **kwargs) 234 | 235 | 236 | def Article(*args, **kwargs): 237 | """Return an OTRS article.""" 238 | import otrs.ticket.objects 239 | return otrs.ticket.objects.Article(*args, **kwargs) 240 | -------------------------------------------------------------------------------- /otrs/ticket/operations.py: -------------------------------------------------------------------------------- 1 | """OTRS :: ticket :: operations.""" 2 | from otrs.client import authenticated 3 | from otrs.client import OperationBase 4 | from otrs.client import WrongOperatorException 5 | from otrs.objects import DynamicField 6 | from otrs.objects import extract_tagname 7 | from otrs.ticket.objects import Ticket as TicketObject 8 | 9 | 10 | class Ticket(OperationBase): 11 | """Base class for OTRS Ticket:: operations.""" 12 | 13 | 14 | class TicketCreate(Ticket): 15 | """Class to handle OTRS Ticket::TicketCreate operation.""" 16 | 17 | @authenticated 18 | def __call__(self, ticket, article, dynamic_fields=None, 19 | attachments=None, **kwargs): 20 | """Create a new ticket. 21 | 22 | @param ticket a Ticket 23 | @param article an Article 24 | @param dynamic_fields a list of Dynamic Fields 25 | @param attachments a list of Attachments 26 | @returns the ticketID, TicketNumber 27 | """ 28 | ticket_requirements = ( 29 | ('StateID', 'State'), ('PriorityID', 'Priority'), 30 | ('QueueID', 'Queue'), ) 31 | article_requirements = ('Subject', 'Body', 'Charset', 'MimeType') 32 | dynamic_field_requirements = ('Name', 'Value') 33 | attachment_field_requirements = ('Content', 'ContentType', 'Filename') 34 | ticket.check_fields(ticket_requirements) 35 | article.check_fields(article_requirements) 36 | if not (dynamic_fields is None): 37 | for df in dynamic_fields: 38 | df.check_fields(dynamic_field_requirements) 39 | if not (attachments is None): 40 | for att in attachments: 41 | att.check_fields(attachment_field_requirements) 42 | ret = self.req('TicketCreate', ticket=ticket, article=article, 43 | dynamic_fields=dynamic_fields, 44 | attachments=attachments, **kwargs) 45 | elements = self._unpack_resp_several(ret) 46 | infos = {extract_tagname(i): int(i.text) for i in elements} 47 | return infos['TicketID'], infos['TicketNumber'] 48 | 49 | 50 | class TicketGet(Ticket): 51 | """Class to handle OTRS Ticket::TicketGet operation.""" 52 | 53 | @authenticated 54 | def __call__(self, ticket_id, get_articles=False, 55 | get_dynamic_fields=False, 56 | get_attachments=False, *args, **kwargs): 57 | """Get a ticket by id ; beware, TicketID != TicketNumber. 58 | 59 | @param ticket_id : the TicketID of the ticket 60 | @param get_articles : grab articles linked to the ticket 61 | @param get_dynamic_fields : include dynamic fields in result 62 | @param get_attachments : include attachments in result 63 | 64 | @return a `Ticket`, Ticket.articles() will give articles if relevant. 65 | Ticket.articles()[i].attachments() will return the attachments for 66 | an article, wheres Ticket.articles()[i].save_attachments() 67 | will save the attachments of article[i] to the specified folder. 68 | """ 69 | params = {'TicketID': str(ticket_id)} 70 | params.update(kwargs) 71 | if get_articles: 72 | params['AllArticles'] = True 73 | if get_dynamic_fields: 74 | params['DynamicFields'] = True 75 | if get_attachments: 76 | params['Attachments'] = True 77 | 78 | ret = self.req('TicketGet', **params) 79 | return TicketObject.from_xml(self._unpack_resp_one(ret)) 80 | 81 | 82 | class TicketSearch(Ticket): 83 | """Class to handle OTRS Ticket::TicketSearch operation.""" 84 | 85 | @authenticated 86 | def __call__(self, dynamic_fields=None, **kwargs): 87 | """Search for a ticket by. 88 | 89 | @param dynamic_fields a list of Dynamic Fields, in addition to 90 | the combination of `Name` and `Value`, also an `Operator` for the 91 | comparison is expexted `Equals`, `Like`, `GreaterThan`, 92 | `GreaterThanEquals`, `SmallerThan` or `SmallerThanEquals`. 93 | The `Like` operator accepts a %-sign as wildcard. 94 | @returns a list of matching TicketID 95 | """ 96 | df_search_list = [] 97 | dynamic_field_requirements = ('Name', 'Value', 'Operator') 98 | if not (dynamic_fields is None): 99 | for df in dynamic_fields: 100 | df.check_fields(dynamic_field_requirements) 101 | if df.Operator == 'Equals': 102 | df_search = DynamicField(Equals=df.Value) 103 | elif df.Operator == 'Like': 104 | df_search = DynamicField(Like=df.Value) 105 | elif df.Operator == 'GreaterThan': 106 | df_search = DynamicField(GreaterThan=df.Value) 107 | elif df.Operator == 'GreaterThanEquals': 108 | df_search = DynamicField(GreaterThanEquals=df.Value) 109 | elif df.Operator == 'SmallerThan': 110 | df_search = DynamicField(SmallerThan=df.Value) 111 | elif df.Operator == 'SmallerThanEquals': 112 | df_search = DynamicField(SmallerThanEquals=df.Value) 113 | else: 114 | raise WrongOperatorException() 115 | df_search.XML_NAME = 'DynamicField_{0}'.format(df.Name) 116 | df_search_list.append(df_search) 117 | kwargs['DynamicFields'] = df_search_list 118 | 119 | ret = self.req('TicketSearch', **kwargs) 120 | return [int(i.text) for i in self._unpack_resp_several(ret)] 121 | 122 | 123 | class TicketUpdate(Ticket): 124 | """Class to handle OTRS Ticket::TicketUpdate operation.""" 125 | 126 | @authenticated 127 | def __call__(self, ticket_id=None, ticket_number=None, 128 | ticket=None, article=None, dynamic_fields=None, 129 | attachments=None, **kwargs): 130 | """Update an existing ticket. 131 | 132 | @param ticket_id the ticket ID of the ticket to modify 133 | @param ticket_number the ticket Number of the ticket to modify 134 | @param ticket a ticket containing the fields to change on ticket 135 | @param article a new Article to append to the ticket 136 | @param dynamic_fields a list of Dynamic Fields to change on ticket 137 | @param attachments a list of Attachments for a newly appended article 138 | @returns the ticketID, TicketNumber 139 | 140 | 141 | Mandatory : - `ticket_id` xor `ticket_number` 142 | - `ticket` or `article` or `dynamic_fields` 143 | 144 | """ 145 | if not (ticket_id is None): 146 | kwargs['TicketID'] = ticket_id 147 | elif not (ticket_number is None): 148 | kwargs['TicketNumber'] = ticket_number 149 | else: 150 | raise ValueError('requires either ticket_id or ticket_number') 151 | 152 | if (ticket is None) and (article is None) and (dynamic_fields is None): 153 | raise ValueError( 154 | 'requires at least one among ticket, article, dynamic_fields') 155 | elif (article is None) and not (attachments is None): 156 | raise ValueError( 157 | 'Attachments can only be created for a newly appended article') 158 | else: 159 | if (ticket): 160 | kwargs['Ticket'] = ticket 161 | if (article): 162 | kwargs['Article'] = article 163 | if (dynamic_fields): 164 | kwargs['DynamicField'] = dynamic_fields 165 | if (attachments): 166 | kwargs['Attachment'] = attachments 167 | 168 | ret = self.req('TicketUpdate', **kwargs) 169 | elements = self._unpack_resp_several(ret) 170 | infos = {extract_tagname(i): int(i.text) for i in elements} 171 | return infos['TicketID'], infos['TicketNumber'] 172 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Python-OTRS : Python wrapper to OTRS SOAP API 2 | ============================================= 3 | 4 | Let you access the OTRS API a pythonic-way. 5 | 6 | Features 7 | -------- 8 | 9 | - Implements fully communication with the ``GenericTicketConnectorSOAP`` and ``GenericFAQConnectorSOAP`` 10 | provided as webservice example by OTRS; 11 | - Dynamic fields and attachments are supported; 12 | - Authentication is handled programmatically, per-request or per-session; 13 | - Calls are wrapped in OTRSClient methods; 14 | - OTRS XML objects are mapped to Python-style objects. 15 | 16 | To be done 17 | ---------- 18 | 19 | - Test for python3 compatibility and make resulting changes; 20 | - Improve and extend ``tests.py``. 21 | 22 | Compatibility 23 | -------- 24 | - Python 2.7; 25 | - Python 3.5; 26 | 27 | Install 28 | ------- 29 | 30 | :: 31 | 32 | pip install python-otrs 33 | 34 | Ticket and Session Operations 35 | ----------------------------- 36 | 37 | First make sure you installed the ``GenericTicketConnectorSOAP`` webservice, 38 | see `official documentation`_. The file GenericTicketConnectorSOAP.yml can be downloaded 39 | online as the basis for this service. 40 | 41 | Note: in older versions of OTRS, GenericTicketConnectorSOAP was called GenericTicketConnector 42 | 43 | :: 44 | 45 | from otrs.ticket.template import GenericTicketConnectorSOAP 46 | from otrs.client import GenericInterfaceClient 47 | from otrs.ticket.objects import Ticket, Article, DynamicField, Attachment 48 | 49 | server_uri = r'https://otrs.example.net' 50 | webservice_name = 'GenericTicketConnectorSOAP' 51 | client = GenericInterfaceClient(server_uri, tc=GenericTicketConnectorSOAP(webservice_name)) 52 | 53 | Then authenticate, you have three choices : 54 | 55 | :: 56 | 57 | # user session 58 | client.tc.SessionCreate(user_login='login', password='password') 59 | 60 | # customer_user session 61 | client.tc.SessionCreate(customer_user_login='login' , password='password') 62 | 63 | # save user in memory 64 | client.register_credentials(login='login', password='password') 65 | 66 | Play ! 67 | 68 | Create a ticket : 69 | 70 | :: 71 | 72 | import mimetypes 73 | import base64 74 | 75 | t = Ticket(State='new', Priority='3 normal', Queue='Support', 76 | Title='Problem test', CustomerUser='foo@example.fr', 77 | Type='Divers') 78 | a = Article(Subject='UnitTest', Body='bla', Charset='UTF8', 79 | MimeType='text/plain') 80 | df1 = DynamicField(Name='TestName1', Value='TestValue1') 81 | df2 = DynamicField(Name='TestName2', Value='TestValue2') 82 | att_path = r'C:\Temp\image001.png' 83 | mimetype = mimetypes.guess_type(att_path)[0] 84 | att_file = open(att_path , 'rb') 85 | att_content = base64.b64encode(att_file.read()) 86 | att1 = Attachment(Content=att_content, 87 | ContentType=mimetype, Filename="image001.png") 88 | att_file.close() 89 | 90 | t_id, t_number = client.tc.TicketCreate(t, a, [df1, df2], [att1]) 91 | 92 | Update an article : 93 | 94 | :: 95 | 96 | # changes the title of the ticket 97 | t_upd = Ticket(Title='Updated ticket') 98 | client.tc.TicketUpdate(t_id, ticket=t_upd) 99 | 100 | # appends a new article (attachments optional) 101 | new_article = Article(Subject='More info', Body='blabla', Charset='UTF8', 102 | MimeType='text/plain') 103 | client.tc.TicketUpdate(article=new_article, attachments=None) 104 | 105 | Search for tickets : 106 | 107 | :: 108 | 109 | # returns all the tickets of customer 42 110 | tickets = client.tc.TicketSearch(CustomerID=42) 111 | 112 | # returns all tickets in queue Support 113 | # for which Dynamic Field 'Project' starts with 'Pizza': 114 | df2 = DynamicField(Name='Project', Value='Pizza%', Operator="Like") 115 | client.tc.TicketSearch(Queues='Support', dynamic_fields=[df_search]) 116 | 117 | Retrieve a ticket : 118 | 119 | :: 120 | 121 | ticket = client.tc.TicketGet(138, get_articles=True, get_dynamic_fields=True, get_attachments=True) 122 | article = ticket.articles()[0] 123 | article.save_attachments(r'C:\temp') 124 | 125 | Many options are possible with requests, you can use all the options 126 | available in `official documentation`_. 127 | 128 | .. _official documentation: http://otrs.github.io/doc/manual/admin/4.0/en/html/genericinterface.html#generic-ticket-connector 129 | 130 | Public FAQ Operations 131 | --------------------- 132 | 133 | First, make sure you have installed the open-source FAQ add-on module into your OTRS system and added the 134 | GenericFAQConnectorSOAP web service by installing the GenericFAQConnector.yml file. 135 | 136 | :: 137 | 138 | from otrs.ticket.template import GenericTicketConnectorSOAP 139 | from otrs.faq.template import GenericFAQConnectorSOAP 140 | from otrs.client import GenericInterfaceClient 141 | 142 | client = GenericInterfaceClient('https://otrs.mycompany.com', tc=GenericTicketConnectorSOAP('GenericTicketConnectorSOAP'), fc=GenericFAQConnectorSOAP('GenericFAQConnectorSOAP')) 143 | 144 | # first, establish session with the TicketConnector 145 | client.tc.SessionCreate(user_login='someotrsuser', password='p4ssw0rd') 146 | 147 | List FAQ Languages: 148 | 149 | :: 150 | 151 | langlist = client.fc.LanguageList() 152 | for language in langlist: 153 | print language.ID, language.Name 154 | 155 | List FAQ Categories that have Public FAQ items in them: 156 | 157 | :: 158 | 159 | catlist = client.fc.PublicCategoryList() 160 | for category in catlist: 161 | print category.ID, category.Name 162 | 163 | Retrieve a public FAQ article by ID 164 | (note: FAQ Item ID is not the same as the item number!) 165 | 166 | :: 167 | 168 | # retrieves FAQ item ID #190 with attachment contents included 169 | myfaqitem = client.fc.PublicFAQGet(190, get_attachments=True) 170 | # print the FAQ's Problem field 171 | print myfaqitem.Field2 172 | # saves attachments to folder ./tempattach 173 | myfaqitem.save_attachments('./tempattach') 174 | 175 | Search for an FAQ article 176 | 177 | :: 178 | 179 | #find all FAQ articles with Windows in title: 180 | results = client.fc.PublicFAQSearch(Title='*Windows*') 181 | for faqitemid in results: 182 | print "Found FAQ item ID containing Windows: " + str(faqitemid) 183 | 184 | 185 | Custom Web Service Connectors 186 | ----------------------------- 187 | 188 | For the FAQ operations above, note that we still needed the Ticket connector to provide access 189 | to the SessionCreate method. However, if your application only needs to work with FAQ articles 190 | and not tickets, you may wish to create a custom web service in OTRS that not only includes 191 | the four FAQ operations but also includes the SessionCreate operation to allow you to establish 192 | a session. This is very easy to accommodate in python-otrs. 193 | 194 | First, in OTRS, do the following: 195 | 196 | 1. In OTRS Admin->Web Services, add a new web service without using a .yml file. Name it something 197 | like 'ImprovedFAQConnectorSOAP'. 198 | 2. In the settings for the web service, set the transport to HTTP::SOAP 199 | 3. Click Save 200 | 4. Click the 'Configure' button that has appeared next to HTTP::SOAP 201 | 5. Set the namespace name to whatever you want (ex. http://www.otrs.org/FAQConnector). 202 | 6. Enter the maximum message length you want (normally 10000000) 203 | 7. Save the changes and go back to the main web service configuration screen. 204 | 8. Add the operations you want to your custom webservice. For instance, for our improved FAQConnector, 205 | you might add the four FAQ Operations and also the SessionCreate operation. 206 | 9. Save your webservice 207 | 208 | Now that we have a web service in OTRS, we can use our custom web service in python-otrs. To do this, 209 | first create a 'template' for your new ImprovedFAQConnectorSOAP. Specify the namespace name assigned 210 | in step 5 above as the second parameter to the WebService() call. 211 | 212 | :: 213 | 214 | from otrs.faq.operations import LanguageList,PublicCategoryList,PublicFAQGet,PublicFAQSearch 215 | from otrs.session.operations import SessionCreate 216 | from otrs.client import WebService 217 | 218 | def ImprovedFAQConnectorSOAP(webservice_name='ImprovedFAQConnectorSOAP'): 219 | return WebService(webservice_name, 'http://www.otrs.org/FAQConnector', SessionCreate=SessionCreate(), LanguageList=LanguageList(),PublicCategoryList=PublicCategoryList(),PublicFAQGet=PublicFAQGet(),PublicFAQSearch=PublicFAQSearch()) 220 | 221 | Now, use your improved FAQ connector: 222 | 223 | :: 224 | 225 | from otrs.client import GenericInterfaceClient 226 | 227 | client = GenericInterfaceClient('https://otrs.mycompany.com', impfaqc=ImprovedFAQConnectorSOAP('ImprovedFAQConnectorSOAP')) 228 | 229 | # first, establish session 230 | client.impfaqc.SessionCreate(user_login='someotrsuser', password='p4ssw0rd') 231 | 232 | # get an FAQ item: 233 | client.impfaqc.PublicFAQGet(190) 234 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | from defusedxml import ElementTree as etree 2 | import os 3 | from otrs.client import GenericInterfaceClient 4 | from otrs.ticket.objects import Article 5 | from otrs.ticket.objects import Ticket 6 | from otrs.ticket.template import GenericTicketConnectorSOAP 7 | import unittest 8 | 9 | REQUIRED_VARS = 'OTRS_LOGIN', 'OTRS_PASSWORD', 'OTRS_SERVER', 'OTRS_WEBSERVICE' 10 | MISSING_VARS = [] 11 | 12 | for i in REQUIRED_VARS: 13 | if not i in os.environ.keys(): 14 | MISSING_VARS.append(i) 15 | else: 16 | (locals())[i] = os.environ[i] 17 | 18 | SAMPLE_TICKET = """ 19 | 346654 20 | n 21 | 2 22 | 2014-05-16 11:24:19 23 | 1 24 | 1400234702 25 | 2014-05-16 10:05:02 26 | 9 27 | foo@bar.tld 28 | 0 29 | 0 30 | 0 31 | 0 32 | 1 33 | unlock 34 | 1 35 | fbarman 36 | 2 37 | 3 normal 38 | 3 39 | Support 40 | 2 41 | 0 42 | admin 43 | 1 44 | 45 | 46 | closed unsuccessful 47 | 3 48 | closed 49 | 32 50 | 515422152827 51 | Foofoo my title 52 | Divers 53 | 1 54 | 1400239459 55 | 0 56 | 57 | """ 58 | 59 | SAMPLE_TICKET_W_ARTICLES = """ 60 | 863982 61 | n 62 |
63 | 863982 64 | 863982 65 | 101 66 | email-external 67 | 1 68 | 69 | Bonjour, 70 | 71 | Voir echange ci-dessous. 72 | 73 | Cdlt. 74 | 75 | 76 | ACME-CORP - John DOE <john.doe@exemple.fr> 77 | ACME-CORP - John DOE 78 | 2014-05-16 11:24:19 79 | utf-8 80 | utf-8 81 | text/plain; charset=utf-8 82 | 1400234702 83 | 2014-05-16 10:05:02 84 | 1 85 | 9 86 | john.doe@exemple.fr 87 | 0 88 | 0 89 | 0 90 | 0 91 | John DOE <john.doe@exemple.fr> 92 | John DOE 93 | <1586719931.242426547.1400234690351.JavaMail.zimbra@exemple.fr> 94 | 1400234702 95 | unlock 96 | 1 97 | <1586719931.242426547.1400234690351.JavaMail.zimbra@exemple.fr> 98 | text/plain 99 | admin 100 | 2 101 | 3 normal 102 | 3 103 | Support 104 | 2 105 | 0 106 | 107 | 108 | admin 109 | 1 110 | 111 | 112 | customer 113 | 3 114 | 115 | 116 | closed unsuccessful 117 | 3 118 | closed 119 | Title 120 | 32 121 | 515422152827 122 | TEST msg 123 | support test <support-test@exemple.fr> 124 | Support test 125 | Divers 126 | 1 127 | 0 128 |
129 | 2 130 | 2014-05-16 11:24:19 131 | 1 132 | 1400234702 133 | 2014-05-16 10:05:02 134 | 135 | 9 136 | 137 | john.doe@exemple.fr 138 | 0 139 | 0 140 | 0 141 | 0 142 | 1 143 | unlock 144 | 1 145 | admin 146 | 2 147 | 3 normald 148 | 3 149 | Support 150 | 2 151 | 0 152 | admin 153 | 1 154 | 155 | 156 | closed unsuccessful 157 | 3 158 | closed 159 | 32 160 | 515422152827 161 | Test ticket 162 | Divers 163 | 1 164 | 1400239459 165 | 0 166 |
""" 167 | 168 | if not MISSING_VARS: 169 | 170 | class TestOTRSAPI(unittest.TestCase): 171 | def setUp(self): 172 | self.c = GenericInterfaceClient(OTRS_SERVER, tc=GenericTicketConnectorSOAP(OTRS_WEBSERVICE)) 173 | self.c.register_credentials(OTRS_LOGIN, OTRS_PASSWORD) 174 | 175 | def test_session_create(self): 176 | sessid = self.c.tc.SessionCreate(user_login=OTRS_LOGIN, 177 | password=OTRS_PASSWORD) 178 | self.assertEqual(len(sessid), 32) 179 | 180 | def test_ticket_get(self): 181 | t = self.c.tc.TicketGet(1) 182 | self.assertEqual(t.TicketID, 1) 183 | self.assertEqual(t.StateType, 'new') 184 | 185 | def test_ticket_get_with_articles(self): 186 | t = self.c.tc.TicketGet(1, get_articles=True) 187 | self.assertEqual(t.TicketID, 1) 188 | self.assertEqual(t.StateType, 'new') 189 | articles = t.articles() 190 | self.assertIsInstance(articles, (list, tuple)) 191 | self.assertIsInstance(articles[0], Article) 192 | self.assertEqual(articles[0].SenderType, 'customer') 193 | 194 | def test_ticket_search(self): 195 | t_list = self.c.tc.TicketSearch(Title='Welcome to OTRS!') 196 | self.assertIsInstance(t_list, list) 197 | self.assertIn(1, t_list) 198 | 199 | def test_ticket_create(self): 200 | t = Ticket(State='new', 201 | Priority='3 normal', 202 | Queue='Postmaster', 203 | Title='Problem test', 204 | CustomerUser='foo@exemple.fr', 205 | Type='Unclassified') 206 | a = Article(Subject='UnitTest', 207 | Body='bla', 208 | Charset='UTF8', 209 | MimeType='text/plain') 210 | t_id, t_number = self.c.tc.TicketCreate(t, a) 211 | self.assertIsInstance(t_id, int) 212 | self.assertIsInstance(t_number, int) 213 | self.assertTrue(len(str(t_number)) >= 12) 214 | exit 215 | 216 | def test_ticket_update_attrs_by_id(self): 217 | t = Ticket(State='new', 218 | Priority='3 normal', 219 | Queue='Postmaster', 220 | Title='Problem test', 221 | CustomerUser='foo@exemple.fr', 222 | Type='Unclassified') 223 | a = Article(Subject='UnitTest', 224 | Body='bla', 225 | Charset='UTF8', 226 | MimeType='text/plain') 227 | t_id, t_number = self.c.tc.TicketCreate(t, a) 228 | 229 | t = Ticket(Title='Foubar') 230 | upd_tid, upd_tnumber = self.c.tc.TicketUpdate(ticket_id=t_id, 231 | ticket=t) 232 | self.assertIsInstance(upd_tid, int) 233 | self.assertIsInstance(upd_tnumber, int) 234 | self.assertTrue(len(str(upd_tnumber)) >= 12) 235 | 236 | self.assertEqual(upd_tid, t_id) 237 | self.assertEqual(upd_tnumber, t_number) 238 | 239 | upd_t = self.c.tc.TicketGet(t_id) 240 | self.assertEqual(upd_t.Title, 'Foubar') 241 | self.assertEqual(upd_t.Queue, 'Postmaster') 242 | 243 | def test_ticket_update_attrs_by_number(self): 244 | t = Ticket(State='new', 245 | Priority='3 normal', 246 | Queue='Postmaster', 247 | Title='Problem test', 248 | CustomerUser='foo@exemple.fr', 249 | Type='Unclassified') 250 | a = Article(Subject='UnitTest', 251 | Body='bla', 252 | Charset='UTF8', 253 | MimeType='text/plain') 254 | t_id, t_number = self.c.tc.TicketCreate(t, a) 255 | 256 | t = Ticket(Title='Foubar') 257 | upd_tid, upd_tnumber = self.c.tc.TicketUpdate(ticket_number=t_number, 258 | ticket=t) 259 | self.assertIsInstance(upd_tid, int) 260 | self.assertIsInstance(upd_tnumber, int) 261 | self.assertTrue(len(str(upd_tnumber)) >= 12) 262 | 263 | self.assertEqual(upd_tid, t_id) 264 | self.assertEqual(upd_tnumber, t_number) 265 | 266 | upd_t = self.c.tc.TicketGet(t_id) 267 | self.assertEqual(upd_t.Title, 'Foubar') 268 | self.assertEqual(upd_t.Queue, 'Postmaster') 269 | 270 | def test_ticket_update_new_article(self): 271 | t = Ticket(State='new', 272 | Priority='3 normal', 273 | Queue='Postmaster', 274 | Title='Problem test', 275 | CustomerUser='foo@exemple.fr', 276 | Type='Unclassified') 277 | a = Article(Subject='UnitTest', 278 | Body='bla', 279 | Charset='UTF8', 280 | MimeType='text/plain') 281 | t_id, t_number = self.c.tc.TicketCreate(t, a) 282 | 283 | a2 = Article(Subject='UnitTest2', 284 | Body='bla', 285 | Charset='UTF8', 286 | MimeType='text/plain') 287 | 288 | a3 = Article(Subject='UnitTest3', 289 | Body='bla', 290 | Charset='UTF8', 291 | MimeType='text/plain') 292 | 293 | self.c.tc.TicketUpdate(t_id, article=a2) 294 | self.c.tc.TicketUpdate(t_id, article=a3) 295 | 296 | t_upd = self.c.tc.TicketGet(t_id, get_articles=True) 297 | arts_upd = t_upd.articles() 298 | self.assertIsInstance(arts_upd, list) 299 | self.assertEqual(len(arts_upd), 3) 300 | self.assertEqual(arts_upd[0].Subject, 'UnitTest') 301 | self.assertEqual(arts_upd[1].Subject, 'UnitTest2') 302 | self.assertEqual(arts_upd[2].Subject, 'UnitTest3') 303 | 304 | else: 305 | print("Set OTRS_LOGIN, OTRS_PASSWORD, OTRS_SERVER and OTRS_WEBSERVICE\n" 306 | "env vars if you want to run tests against a REAL OTRS web service\n\n" 307 | "example:\n\n" 308 | "export OTRS_LOGIN=mylogin\n" 309 | "export OTRS_PASSWORD=mypassword\n" 310 | "export OTRS_SERVER=https://myotrs.example.com\n" 311 | "export OTRS_WEBSERVICE=GenericTicketConnectorSOAP\n") 312 | 313 | 314 | class TestObjects(unittest.TestCase): 315 | def test_ticket(self): 316 | t = Ticket(TicketID=42, EscalationResponseTime='43') 317 | self.assertEqual(t.TicketID, 42) 318 | self.assertEqual(t.EscalationResponseTime, 43) 319 | 320 | def test_ticket_from_xml(self): 321 | xml = etree.fromstring(SAMPLE_TICKET) 322 | t = Ticket.from_xml(xml) 323 | self.assertEqual(t.TicketID, 32) 324 | self.assertEqual(t.CustomerUserID, 'foo@bar.tld') 325 | 326 | def test_ticket_from_xml_with_articles(self): 327 | xml = etree.fromstring(SAMPLE_TICKET_W_ARTICLES) 328 | t = Ticket.from_xml(xml) 329 | self.assertEqual(t.TicketID, 32) 330 | self.assertEqual(t.CustomerUserID, 'john.doe@exemple.fr') 331 | articles = t.articles() 332 | self.assertIsInstance(articles, list) 333 | self.assertEqual(len(articles), 1) 334 | self.assertIsInstance(articles[0], Article) 335 | self.assertEqual(articles[0].AgeTimeUnix, 863982) 336 | 337 | def test_ticket_to_xml(self): 338 | t = Ticket(State='open', Priority='3 normal', Queue='Postmaster') 339 | xml = t.to_xml() 340 | xml_childs = list(xml) 341 | 342 | xml_childs_dict = {i.tag: i.text for i in xml_childs} 343 | 344 | self.assertEqual(xml.tag, 'Ticket') 345 | self.assertEqual(len(xml_childs), 3) 346 | self.assertEqual(xml_childs_dict['State'], 'open') 347 | self.assertEqual(xml_childs_dict['Priority'], '3 normal') 348 | self.assertEqual(xml_childs_dict['Queue'], 'Postmaster') 349 | 350 | 351 | if __name__ == '__main__': 352 | unittest.main() 353 | -------------------------------------------------------------------------------- /otrs/client.py: -------------------------------------------------------------------------------- 1 | """OTRS :: client.""" 2 | import abc 3 | import codecs 4 | import socket 5 | 6 | from defusedxml import ElementTree as etree 7 | try: 8 | import http.client as httplib 9 | import urllib.request as urllib2 10 | except ImportError: 11 | import httplib 12 | import urllib2 13 | from otrs.objects import extract_tagname 14 | from otrs.objects import OTRSObject 15 | from posixpath import join as urljoin 16 | import sys 17 | # defusedxml doesn't define these non-parsing related objects 18 | from xml.etree.ElementTree import Element 19 | from xml.etree.ElementTree import SubElement 20 | from xml.etree.ElementTree import tostring 21 | 22 | etree.Element = _ElementType = Element 23 | etree.SubElement = SubElement 24 | etree.tostring = tostring 25 | 26 | # Fix Python 2.x. 27 | try: 28 | UNICODE_EXISTS = bool(type(unicode)) 29 | except NameError: 30 | unicode = lambda s: str(s) 31 | 32 | 33 | class OTRSError(Exception): 34 | """Base class for OTRS Errors.""" 35 | 36 | def __init__(self, fd): 37 | """Initialize OTRS Error.""" 38 | self.code = fd.getcode() 39 | self.msg = fd.read() 40 | 41 | def __str__(self): 42 | """Return error message for OTRS Error.""" 43 | return '{} : {}'.format(self.code, self.msg) 44 | 45 | 46 | class BadStatusLineError(Exception): 47 | """Base class for BadStatusLineError Errors.""" 48 | 49 | def __init__(self, url): 50 | """Initialize BadStatusLineError Error.""" 51 | self.url = url 52 | 53 | def __str__(self): 54 | """Return error message for BadStatusLine Error.""" 55 | return '''BadStatusLine Exception when trying to reach {0}. 56 | Are you using the correct webservice name?'''.format(self.url) 57 | 58 | 59 | class SOAPError(OTRSError): 60 | """OTRS Error originating from an incorrect SOAP request.""" 61 | 62 | def __init__(self, tag): 63 | """Initialize OTRS SOAPError.""" 64 | d = {extract_tagname(i): i.text for i in list(tag)} 65 | self.errcode = d['ErrorCode'] 66 | self.errmsg = d['ErrorMessage'] 67 | 68 | def __str__(self): 69 | """Return error message for OTRS SOAPError.""" 70 | return '{} ({})'.format(self.errmsg, self.errcode) 71 | 72 | 73 | class NoCredentialsException(OTRSError): 74 | """OTRS Error that is returned when no credentials are provided.""" 75 | 76 | def __init__(self): 77 | """Initialize OTRS NoCredentialsException.""" 78 | pass 79 | 80 | def __str__(self): 81 | """Return error message for OTRS NoCredentialsException.""" 82 | return 'Register credentials first with register_credentials() method' 83 | 84 | 85 | class WrongOperatorException(OTRSError): 86 | """OTRS Error that is returned when a non-existent operation is called.""" 87 | 88 | def __init__(self): 89 | """Initialize OTRS WrongOperatorException.""" 90 | pass 91 | 92 | def __str__(self): 93 | """Return error message for OTRS WrongOperatorException.""" 94 | return '''Please use one of the following operators for the 95 | query on a dynamic field: `Equals`, `Like`, `GreaterThan`, 96 | `GreaterThanEquals`, `SmallerThan` or `SmallerThanEquals`. 97 | ''' 98 | 99 | 100 | def authenticated(func): 101 | """Decorator to add authentication parameters to a request.""" 102 | def add_auth(self, *args, **kwargs): 103 | if self.session_id: 104 | kwargs['SessionID'] = self.session_id 105 | elif self.login and self.password: 106 | kwargs['UserLogin'] = self.login 107 | kwargs['Password'] = self.password 108 | else: 109 | raise NoCredentialsException() 110 | 111 | return func(self, *args, **kwargs) 112 | 113 | return add_auth 114 | 115 | 116 | class OperationBase(object): 117 | """Base class for OTRS operations.""" 118 | 119 | __metaclass__ = abc.ABCMeta 120 | 121 | def __init__(self, opName=None): 122 | """Initialize OperationBase.""" 123 | if opName is None: 124 | self.operName = type(self).__name__ 125 | else: 126 | self.operName = opName # otrs connector operation name 127 | self.wsObject = None # web services object this operation belongs to 128 | 129 | def getWebServiceObjectAttribute(self, attribName): 130 | """Return attribute of the WebService object.""" 131 | return getattr(self.wsObject, attribName) 132 | 133 | def getClientObjectAttribute(self, attribName): 134 | """Return attribute of the clientobject of the WebService object.""" 135 | return self.wsObject.getClientObjectAttribute(attribName) 136 | 137 | def setClientObjectAttribute(self, attribName, attribValue): 138 | """Set attribute of the clientobject of the WebService object.""" 139 | self.wsObject.setClientObjectAttribute(attribName, attribValue) 140 | 141 | @abc.abstractmethod 142 | def __call__(self): 143 | """.""" 144 | return 145 | 146 | @property 147 | def endpoint(self): 148 | """Return endpoint of WebService object.""" 149 | return self.getWebServiceObjectAttribute('endpoint') 150 | 151 | @property 152 | def login(self): 153 | """Get login attribute of the clientobject of the WebService object.""" 154 | return self.getClientObjectAttribute('login') 155 | 156 | @property 157 | def password(self): 158 | """Return password attribute of the clientobject of the WebService.""" 159 | return self.getClientObjectAttribute('password') 160 | 161 | @property 162 | def ssl_context(self): 163 | """Return ssl_context of the clientobject of the WebService.""" 164 | return self.getClientObjectAttribute('ssl_context') 165 | 166 | @property 167 | def session_id(self): 168 | """Return session_id of the clientobject of the WebService object.""" 169 | return self.getClientObjectAttribute('session_id') 170 | 171 | @session_id.setter 172 | def session_id(self, sessionid): 173 | """Set session_id of the clientobject of the WebService object.""" 174 | self.setClientObjectAttribute('session_id', sessionid) 175 | 176 | @property 177 | def soap_envelope(self): 178 | """Return soap envelope for WebService object.""" 179 | soap_envelope = '{}' + \ 183 | '' 184 | return soap_envelope 185 | 186 | @property 187 | def timeout(self): 188 | """Return timeout of the clientobject of the WebService object.""" 189 | return self.getClientObjectAttribute('timeout') 190 | 191 | def req(self, reqname, *args, **kwargs): 192 | """Wrapper around a SOAP request. 193 | 194 | @param reqname: the SOAP name of the request 195 | @param kwargs : to define the tags included in the request. 196 | @return : the full etree.Element of the response 197 | 198 | keyword arguments can be either 199 | - simple types (they'l be converted to value) 200 | - `OTRSObject`, they will be serialized with their `.to_xml()` 201 | - list of `OTRSObject`s: each `OTRSObject`s in the list 202 | will be serialized with their `.to_xml()` (used for 203 | dynamic fields and attachments). 204 | - list of simple types will be converted to multiple 205 | value elements (e.g. used for search filters) 206 | """ 207 | xml_req_root = etree.Element(reqname) 208 | 209 | for k, v in kwargs.items(): 210 | if isinstance(v, OTRSObject): 211 | e = v.to_xml() 212 | xml_req_root.append(e) 213 | elif isinstance(v, (list, tuple)): 214 | for vv in v: 215 | if isinstance(vv, OTRSObject): 216 | e = vv.to_xml() 217 | else: 218 | e = etree.Element(k) 219 | e.text = unicode(vv) 220 | xml_req_root.append(e) 221 | else: 222 | e = etree.Element(k) 223 | e.text = unicode(v) 224 | xml_req_root.append(e) 225 | 226 | request = urllib2.Request( 227 | self.endpoint, self._pack_req(xml_req_root), 228 | {'Content-Type': 'text/xml;charset=utf-8'}) 229 | 230 | try: 231 | if ((sys.version_info[0] == 3 and sys.version_info < (3, 4, 3)) or 232 | (sys.version_info < (2, 7, 9))): 233 | fd = urllib2.urlopen(request, timeout=self.timeout) 234 | else: 235 | try: 236 | fd = urllib2.urlopen(request, context=self.ssl_context, timeout=self.timeout) 237 | except TypeError: 238 | fd = urllib2.urlopen(request, timeout=self.timeout) 239 | except httplib.BadStatusLine: 240 | raise BadStatusLineError(request.get_full_url()) 241 | 242 | if fd.getcode() != 200: 243 | raise OTRSError(fd) 244 | else: 245 | try: 246 | s = fd.read() 247 | e = etree.fromstring(s) 248 | 249 | unpacked = self._unpack_resp_several(e) 250 | if (len(unpacked) > 0) and (unpacked[0].tag.endswith('Error')): 251 | raise SOAPError(unpacked[0]) 252 | return e 253 | except etree.ParseError: 254 | print('error parsing:') 255 | print('-' * 80) 256 | print(s) 257 | print('-' * 80) 258 | raise 259 | 260 | @staticmethod 261 | def _unpack_resp_several(element): 262 | """Unpack an etree element and return a list of children. 263 | 264 | @param element : a etree.Element 265 | @return : a list of etree.Element 266 | """ 267 | return list(list(list(element)[0])[0]) 268 | 269 | @staticmethod 270 | def _unpack_resp_one(element): 271 | """Unpack an etree element an return first child. 272 | 273 | @param element : a etree.Element 274 | @return : a etree.Element (first child of the response) 275 | """ 276 | return list(list(list(element)[0])[0])[0] 277 | 278 | def _pack_req(self, element): 279 | """Pack an etree Element. 280 | 281 | @param element : a etree.Element 282 | @returns : a string, wrapping element within the request tags 283 | """ 284 | return self.soap_envelope.format( 285 | codecs.decode(etree.tostring(element), 'utf-8')).encode('utf-8') 286 | 287 | 288 | class WebService(object): 289 | """Base class for OTRS Web Service.""" 290 | 291 | def __init__(self, wsName, wsNamespace, **kwargs): 292 | """Initialize WebService object.""" 293 | self.clientObject = None # link to parent client object 294 | self.wsName = wsName # name for OTRS web service 295 | self.wsNamespace = wsNamespace # OTRS namespace url 296 | 297 | # add all variables in kwargs into the local dictionary 298 | self.__dict__.update(kwargs) 299 | 300 | # for operations, set backlinks to their associated webservice 301 | for arg in kwargs: 302 | # if attribute is type OperationBase, set backlink to WebService 303 | if isinstance(getattr(self, arg), OperationBase): 304 | getattr(self, arg).wsObject = self 305 | 306 | # set defaults if attributes are not present 307 | if not hasattr(self, 'wsRequestNameScheme'): 308 | self.wsRequestNameScheme = 'DATA' 309 | if not hasattr(self, 'wsResponseNameScheme'): 310 | ns = 'DATA' 311 | self.wsResponseNameScheme = ns 312 | 313 | def getClientObjectAttribute(self, attribName): 314 | """Return attribute of the clientobject of the WebService object.""" 315 | return getattr(self.clientObject, attribName) 316 | 317 | def setClientObjectAttribute(self, attribName, attribValue): 318 | """Set attribute of the clientobject of the WebService object.""" 319 | setattr(self.clientObject, attribName, attribValue) 320 | 321 | @property 322 | def endpoint(self): 323 | """Return endpoint of WebService object.""" 324 | return urljoin(self.getClientObjectAttribute('giurl'), self.wsName) 325 | 326 | 327 | class GenericInterfaceClient(object): 328 | """Client for the OTRS Generic Interface.""" 329 | 330 | def __init__(self, server, ssl_context=None, timeout=None, **kwargs): 331 | """Initialize GenericInterfaceClient. 332 | 333 | @param server : the http(s) URL of the root installation of OTRS 334 | (e.g: https://tickets.example.net) 335 | """ 336 | # add all variables in kwargs into the local dictionary 337 | self.__dict__.update(kwargs) 338 | 339 | # for webservices attached to this client object, backlink them 340 | # to this client object to allow access to session login/password 341 | 342 | for arg in kwargs: 343 | # set backlink for web services to this obj 344 | if isinstance(getattr(self, arg), WebService): 345 | getattr(self, arg).clientObject = self 346 | self.login = None 347 | self.password = None 348 | self.session_id = None 349 | self.ssl_context = ssl_context 350 | self.giurl = urljoin( 351 | server, 'otrs/nph-genericinterface.pl/Webservice/') 352 | 353 | if timeout is None: 354 | self.timeout = socket._GLOBAL_DEFAULT_TIMEOUT 355 | else: 356 | self.timeout = timeout 357 | 358 | def register_credentials(self, login, password): 359 | """Save the identifiers in memory. 360 | 361 | They will be used with each subsequent request requiring authentication 362 | """ 363 | self.login = login 364 | self.password = password 365 | 366 | 367 | class OldGTCClass(GenericInterfaceClient): 368 | """DEPRECATED - Old generic ticket connector class. 369 | 370 | Used for backward compatibility with previous versions. All 371 | methods in here are deprecated. 372 | """ 373 | 374 | def session_create(self, password, user_login=None, 375 | customer_user_login=None): 376 | """DEPRECATED - creates a session for an User or CustomerUser. 377 | 378 | @returns the session_id 379 | """ 380 | self.tc.SessionCreate(password, user_login=user_login, 381 | customer_user_login=customer_user_login) 382 | 383 | def user_session_register(self, user, password): 384 | """DEPRECATED - creates a session for an User.""" 385 | self.session_create(password=password, user_login=user) 386 | 387 | def customer_user_session_register(self, user, password): 388 | """DEPRECATED - creates a session for a CustomerUser.""" 389 | self.session_create(password=password, customer_user_login=user) 390 | 391 | @authenticated 392 | def ticket_create(self, ticket, article, dynamic_fields=None, 393 | attachments=None, **kwargs): 394 | """DEPRECATED - now calls operation of GenericTicketConnectorSOAP.""" 395 | return self.tc.TicketCreate(ticket, 396 | article, 397 | dynamic_fields=dynamic_fields, 398 | attachments=attachments, 399 | **kwargs) 400 | 401 | @authenticated 402 | def ticket_get(self, ticket_id, get_articles=False, 403 | get_dynamic_fields=False, get_attachments=False, 404 | *args, **kwargs): 405 | """DEPRECATED - now calls operation of GenericTicketConnectorSOAP.""" 406 | return self.tc.TicketGet(ticket_id, 407 | get_articles=get_articles, 408 | get_dynamic_fields=get_dynamic_fields, 409 | get_attachments=get_attachments, 410 | *args, 411 | **kwargs) 412 | 413 | @authenticated 414 | def ticket_search(self, dynamic_fields=None, **kwargs): 415 | """DEPRECATED - now calls operation of GenericTicketConnectorSOAP.""" 416 | return self.tc.TicketSearch(dynamic_fields=dynamic_fields, **kwargs) 417 | 418 | @authenticated 419 | def ticket_update(self, ticket_id=None, ticket_number=None, 420 | ticket=None, article=None, dynamic_fields=None, 421 | attachments=None, **kwargs): 422 | """DEPRECATED - now calls operation of GenericTicketConnectorSOAP.""" 423 | return self.tc.TicketUpdate(ticket_id=ticket_id, 424 | ticket_number=ticket_number, 425 | ticket=ticket, 426 | article=article, 427 | dynamic_fields=dynamic_fields, 428 | attachments=attachments, **kwargs) 429 | 430 | 431 | def GenericTicketConnector(server, 432 | webservice_name='GenericTicketConnector', 433 | ssl_context=None): 434 | """DEPRECATED - now calls operation of GenericTicketConnectorSOAP.""" 435 | from otrs.session.operations import SessionCreate 436 | from otrs.ticket.operations import TicketCreate 437 | from otrs.ticket.operations import TicketGet 438 | from otrs.ticket.operations import TicketSearch 439 | from otrs.ticket.operations import TicketUpdate 440 | 441 | ticketconnector = WebService( 442 | webservice_name, 443 | 'http://www.otrs.org/TicketConnector', 444 | ssl_context=ssl_context, 445 | SessionCreate=SessionCreate(), 446 | TicketCreate=TicketCreate(), 447 | TicketGet=TicketGet(), 448 | TicketSearch=TicketSearch(), 449 | TicketUpdate=TicketUpdate()) 450 | return OldGTCClass(server, tc=ticketconnector) 451 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------