Skip to content
Snippets Groups Projects
PyOTRS.py 3.79 KiB
Newer Older
Robert Habermann's avatar
Robert Habermann committed
# -*- coding: utf-8 -*-
""" cli """

Robert Habermann's avatar
Robert Habermann committed
import os
import stat
Robert Habermann's avatar
Robert Habermann committed
import click

Robert Habermann's avatar
Robert Habermann committed
from pyotrs.version import __version__
from pyotrs.lib import Client
Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
Robert Habermann's avatar
Robert Habermann committed


Robert Habermann's avatar
Robert Habermann committed
def load_config(config_file):
Robert Habermann's avatar
Robert Habermann committed
    """ load config from file and export to environment

    Args:
        config_file (str): absolute path of config file

    """
Robert Habermann's avatar
Robert Habermann committed

    if not os.path.isfile(config_file):
        click.secho("No config file found at: %s" % config_file, fg="yellow")
        return

    if not oct(stat.S_IMODE(os.stat(config_file).st_mode)) == "0600":
        raise Exception("Permissions to %s too open. Should be 0600!" % config_file)
Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
    try:
        with click.open_file(config_file) as f:
            for line_raw in f:
                # ignore blank lines and lines starting with #
                # leading and trailing whitespaces are stripped
                line = line_raw.strip()
                if not line.startswith("#") and not line.startswith(" ") and not line == "":
                    key, value = line.rstrip("").split("=")
                    if not os.environ.get(key, None):  # if env key is already set preserve it
                        os.environ[key] = value
Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
        click.secho('Using config: %s' % config_file, fg="green")
Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
    except IOError:
        # no config file in default location; that's fine -> continue
        click.secho("No valid file found at: %s (I/O Error)" % config_file, fg="yellow")
Robert Habermann's avatar
Robert Habermann committed
    except ValueError as err:
        click.secho("Does not look like a valid config file: %s" % config_file, fg="yellow")
        raise Exception("Does not look like a valid config file: %s" % err)
    except Exception as err:
        click.secho("An unexpected error occurred: %s" % err, fg="red")
        raise Exception("An unexpected error occurred: %s" % err)
Robert Habermann's avatar
Robert Habermann committed


Robert Habermann's avatar
Robert Habermann committed
@click.option('--config', 'config_file', type=click.Path(dir_okay=False),
              help='Config File')
@click.version_option(version=__version__)
@click.group(context_settings=CONTEXT_SETTINGS)  # context enables -h as alias for --help
def cli(config_file=None):
    click.secho("Starting PyOTRS CLI")
Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
    if not config_file:
        config_file = click.get_app_dir('PyOTRS', force_posix=True)
    load_config(config_file)

Robert Habermann's avatar
Robert Habermann committed

Robert Habermann's avatar
Robert Habermann committed
@click.option('-t', '--ticket-id', type=click.INT, prompt=True,
              envvar='PYOTRS_TICKET_ID',
              help='Ticket ID')
@click.option('-p', '--password', type=click.STRING, prompt=True, hide_input=True,
              envvar="PYOTRS_PASSWORD",
              help='Password')
@click.option('-u', '--username', type=click.STRING, prompt=True,
              envvar="PYOTRS_USERNAME",
              help='Username')
@click.option('-w', '--webservicename', type=click.STRING, prompt=True,
              envvar="PYOTRS_WEBSERVICENAME",
              help='Webservice Name')
@click.option('-b', '--baseurl', type=click.STRING, prompt=True,
              envvar="PYOTRS_BASEURL",
              help='Base URL')
@cli.command(name="get")
def get(baseurl=None, webservicename=None, username=None, password=None, ticket_id=None):
Robert Habermann's avatar
Robert Habermann committed
    """ PyOTRS get command

    Args:
        baseurl (str): Base URL for OTRS System, no trailing slash e.g. http://otrs.example.com
        webservicename (str): OTRS REST Web Service Name
        username (str): Username
        password (str): Password
        ticket_id (int): Ticket ID (not Ticket Number!)

    """
Robert Habermann's avatar
Robert Habermann committed
    click.secho("Connecting to %s as %s.." % (baseurl, username))
    client = Client(baseurl, webservicename, username, password)
    client.session_create()
    ticket = client.ticket_get_by_id(ticket_id)

    click.secho("Ticket: \t%s" % ticket['Title'])
    click.secho("Queue: \t\t%s" % ticket['Queue'])
    click.secho("State: \t\t%s" % ticket['State'])
    click.secho("Priority: \t%s" % ticket['Priority'])

Robert Habermann's avatar
Robert Habermann committed
    click.secho("\nRaw Ticket:")
Robert Habermann's avatar
Robert Habermann committed
    print(ticket)