<commit_before>#  This file is part of the myhdl library, a Python package for using
#  Python as a Hardware Description Language.
#
#  Copyright (C) 2003-2015 Jan Decaluwe
#
#  The myhdl library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the
#  License, or (at your option) any later version.
#
#  This library is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Lesser General Public License for more details.

#  You should have received a copy of the GNU Lesser General Public
#  License along with this library; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

""" Module that provides the ShadowSignal classes

"""
from __future__ import absolute_import

import warnings
from copy import deepcopy

from myhdl._compat import long
from myhdl._Signal import _Signal
from myhdl._Waiter import _SignalWaiter, _SignalTupleWaiter
from myhdl._intbv import intbv
from myhdl._simulator import _siglist
from myhdl._bin import bin

# shadow signals

class _ShadowSignal(_Signal):

    __slots__ = ('_waiter', )

    def __init__(self, val):
        _Signal.__init__(self, val)
        # self._driven = True # set this in conversion analyzer

    # remove next attribute assignment
    @_Signal.next.setter
    def next(self, val):
        raise AttributeError("ShadowSignals are readonly")

class _SliceSignal(_ShadowSignal):

    __slots__ = ('_sig', '_left', '_right')

    def __init__(self, sig, left, right=None):
        # XXX error checks
        if right is None:
            _ShadowSignal.__init__(self, sig[left])
        else:
            _ShadowSignal.__init__(self, sig[left:right])
        self._sig = sig
        self._left = left
        self._right = right
        if right is None:
            gen = self._genfuncIndex()
        else:
            gen = self._genfuncSlice()
        self._waiter = _SignalWaiter(gen)

    def _genfuncIndex(self):
        sig, index = self._sig, self._left
        set_next = _Signal.next.fset
        while 1:
            set_next(self, sig[index])
            yield sig

    def _genfuncSlice(self):
        sig, left, right = self._sig, self._left, self._right
        set_next = _Signal.next.fset
        while 1:
            set_next(self, sig[left:right])
            yield sig

    def _setName(self, hdl):
        if self._right is None:
            if hdl == 'Verilog':
                self._name = "%s[%s]" % (self._sig._name, self._left)
            else:
                self._name = "%s(%s)" % (self._sig._name, self._left)
        else:
            if hdl == 'Verilog':
                self._name = "%s[%s-1:%s]" % (self._sig._name, self._left, self._right)
            else:
                self._name = "%s(%s-1 downto %s)" % (self._sig._name, self._left, self._right)

    def _markRead(self):
        self._read = True
        self._sig._read = True

    def _markUsed(self):
        self._used = True
        self._sig._used = True

    def toVerilog(self):
        if self._right is None:
            return "assign %s = %s[%s];" % (self._name, self._sig._name, self._left)
        else:
            return "assign %s = %s[%s-1:%s];" % (self._name, self._sig._name, self._left, self._right)

    def toVHDL(self):
        if self._right is None:
            return "%s <= %s(%s);" % (self._name, self._sig._name, self._left)
        else:
            return "%s <= %s(%s-1 downto %s);" % (self._name, self._sig._name, self._left, self._right)

class ConcatSignal(_ShadowSignal):

    __slots__ = ('_args', '_sigargs', '_initval')

    def __init__(self, *args):
        assert len(args) >= 2
        self._args = args
        self._sigargs = sigargs = []

        nrbits = 0
        val = 0
        for a in args:
            if isinstance(a, intbv):
                w = a._nrbits
                v = a._val
            elif isinstance(a, _Signal):
                sigargs.append(a)
                w = a._nrbits
                if isinstance(a._val, intbv):
                    v = a._val._val
                else:
                    v = a._val
            elif isinstance(a, bool):
                w = 1
                v = a
            elif isinstance(a, str):
                w = len(a)
                v = long(a, 2)
            else:
                raise TypeError("ConcatSignal: inappropriate argument type: %s"
                                % type(a))
            nrbits += w
            val = val << w | v & (long(1) << w) - 1
        self._initval = val
        ini = intbv(val)[nrbits:]
        _ShadowSignal.__init__(self, ini)
        gen = self.genfunc()
        self._waiter = _SignalTupleWaiter(gen)

    def genfunc(self):
        set_next = _Signal.next.fset
        args = self._args
        sigargs = self._sigargs
        nrbits = self._nrbits
        newval = intbv(self._initval)[nrbits:]
        while 1:
            hi = nrbits
            for a in args:
                if isinstance(a, bool):
                    w = 1
                else:
                    w = len(a)
                lo = hi - w
                # note: 'a in sigargs' is equivalence check, not identity
                if isinstance(a, _Signal):
                    if isinstance(a._val, intbv):
                        newval[hi:lo] = a[w:]
                    else:
                        newval[hi:lo] = a
                hi = lo
            set_next(self, newval)
            yield sigargs

    def _markRead(self):
        self._read = True
        for s in self._sigargs:
            s._markRead()

    def _markUsed(self):
        self._used = True
        for s in self._sigargs:
            s._markUsed()

    def toVHDL(self):
        lines = []
        ini = intbv(self._initval)[self._nrbits:]
        hi = self._nrbits
        for a in self._args:
            if isinstance(a, bool):
                w = 1
            else:
                w = len(a)
            lo = hi - w
            if w == 1:
                if isinstance(a, _Signal):
                    if a._type == bool:  # isinstance(a._type , bool): <- doesn't work
                        lines.append("%s(%s) <= %s;" % (self._name, lo, a._name))
                    else:
                        lines.append("%s(%s) <= %s(0);" % (self._name, lo, a._name))
                else:
                    lines.append("%s(%s) <= '%s';" % (self._name, lo, bin(ini[lo])))
            else:
                if isinstance(a, _Signal):
                    lines.append("%s(%s-1 downto %s) <= %s;" % (self._name, hi, lo, a._name))
                else:
                    lines.append('%s(%s-1 downto %s) <= "%s";' %
                                 (self._name, hi, lo, bin(ini[hi:lo], w)))
            hi = lo
        return "\n".join(lines)

    def toVerilog(self):
        lines = []
        ini = intbv(self._initval)[self._nrbits:]
        hi = self._nrbits
        for a in self._args:
            if isinstance(a, bool):
                w = 1
            else:
                w = len(a)
            lo = hi - w
            if w == 1:
                if isinstance(a, _Signal):
                    if a._type == bool:
                        lines.append("assign %s[%s] = %s;" % (self._name, lo, a._name))
                    else:
                        lines.append("assign %s[%s] = %s[0];" % (self._name, lo, a._name))
                else:
                    lines.append("assign %s[%s] = 'b%s;" % (self._name, lo, bin(ini[lo])))
            else:
                if isinstance(a, _Signal):
                    lines.append("assign %s[%s-1:%s] = %s;" % (self._name, hi, lo, a._name))
                else:
                    lines.append("assign %s[%s-1:%s] = 'b%s;" %
                                 (self._name, hi, lo, bin(ini[hi:lo], w)))
            hi = lo
        return "\n".join(lines)

# Tristate signal

class BusContentionWarning(UserWarning):
    pass

warnings.filterwarnings('always', r".*", BusContentionWarning)

# def Tristate(val, delay=None):
#     """ Return a new Tristate(default or delay 0) or DelayedTristate """
#     if delay is not None:
#         if delay < 0:
#             raise TypeError("Signal: delay should be >= 0")
#         return _DelayedTristate(val, delay)
#     else:
#         return _Tristate(val)

def TristateSignal(val):
    return _TristateSignal(val)

class _TristateSignal(_ShadowSignal):

    __slots__ = ('_drivers', '_orival')

    def __init__(self, val):
        self._drivers = []
        # construct normally to set type / size info right
        _ShadowSignal.__init__(self, val)
        self._orival = deepcopy(val)  # keep for drivers
        # reset signal values to None
        self._next = self._val = self._init = None
        self._waiter = _SignalTupleWaiter(self._resolve())

    def driver(self):
        d = _TristateDriver(self)
        self._drivers.append(d)
        return d

    def _resolve(self):
        # set_next = _ShadowSignal._set_next
        senslist = self._drivers
        while 1:
            yield senslist
            res = None
            for d in senslist:
                if res is None:
                    res = d._val
                elif d._val is not None:
                    warnings.warn("Bus contention", category=BusContentionWarning)
                    res = None
                    break
            self._next = res
            _siglist.append(self)

    def toVerilog(self):
        lines = []
        for d in self._drivers:
            if d._driven:
                lines.append("assign %s = %s;" % (self._name, d._name))
        return "\n".join(lines)

    def toVHDL(self):
        lines = []
        for d in self._drivers:
            if d._driven:
                lines.append("%s <= %s;" % (self._name, d._name))
        return "\n".join(lines)

class _TristateDriver(_Signal):

    __slots__ = ('_sig',)

    def __init__(self, sig):
        _Signal.__init__(self, sig._orival)
        # reset signal values to None
        self._next = self._val = self._init = None
        self._sig = sig

    @_Signal.next.setter
    def next(self, val):
        if isinstance(val, _Signal):
            val = val._val
        if val is None:
            self._next = None
        else:
            # restore original value to cater for intbv handler
            self._next = self._sig._orival
            self._setNextVal(val)
        _siglist.append(self)
<commit_msg>Modified the shadow signal conversion code to check if the concatenated signals are driven. If one of the concatenated signal is not driven it now warns and uses the init val of that signal as a constant.<commit_after>#  This file is part of the myhdl library, a Python package for using
#  Python as a Hardware Description Language.
#
#  Copyright (C) 2003-2015 Jan Decaluwe
#
#  The myhdl library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the
#  License, or (at your option) any later version.
#
#  This library is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Lesser General Public License for more details.

#  You should have received a copy of the GNU Lesser General Public
#  License along with this library; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

""" Module that provides the ShadowSignal classes

"""
from __future__ import absolute_import

import warnings
from copy import deepcopy

from myhdl._compat import long
from myhdl._Signal import _Signal
from myhdl._Waiter import _SignalWaiter, _SignalTupleWaiter
from myhdl._intbv import intbv
from myhdl._simulator import _siglist
from myhdl._bin import bin

# shadow signals

class _ShadowSignal(_Signal):

    __slots__ = ('_waiter', )

    def __init__(self, val):
        _Signal.__init__(self, val)
        # self._driven = True # set this in conversion analyzer

    # remove next attribute assignment
    @_Signal.next.setter
    def next(self, val):
        raise AttributeError("ShadowSignals are readonly")

class _SliceSignal(_ShadowSignal):

    __slots__ = ('_sig', '_left', '_right')

    def __init__(self, sig, left, right=None):
        # XXX error checks
        if right is None:
            _ShadowSignal.__init__(self, sig[left])
        else:
            _ShadowSignal.__init__(self, sig[left:right])
        self._sig = sig
        self._left = left
        self._right = right
        if right is None:
            gen = self._genfuncIndex()
        else:
            gen = self._genfuncSlice()
        self._waiter = _SignalWaiter(gen)

    def _genfuncIndex(self):
        sig, index = self._sig, self._left
        set_next = _Signal.next.fset
        while 1:
            set_next(self, sig[index])
            yield sig

    def _genfuncSlice(self):
        sig, left, right = self._sig, self._left, self._right
        set_next = _Signal.next.fset
        while 1:
            set_next(self, sig[left:right])
            yield sig

    def _setName(self, hdl):
        if self._right is None:
            if hdl == 'Verilog':
                self._name = "%s[%s]" % (self._sig._name, self._left)
            else:
                self._name = "%s(%s)" % (self._sig._name, self._left)
        else:
            if hdl == 'Verilog':
                self._name = "%s[%s-1:%s]" % (self._sig._name, self._left, self._right)
            else:
                self._name = "%s(%s-1 downto %s)" % (self._sig._name, self._left, self._right)

    def _markRead(self):
        self._read = True
        self._sig._read = True

    def _markUsed(self):
        self._used = True
        self._sig._used = True

    def toVerilog(self):
        if self._right is None:
            return "assign %s = %s[%s];" % (self._name, self._sig._name, self._left)
        else:
            return "assign %s = %s[%s-1:%s];" % (self._name, self._sig._name, self._left, self._right)

    def toVHDL(self):
        if self._right is None:
            return "%s <= %s(%s);" % (self._name, self._sig._name, self._left)
        else:
            return "%s <= %s(%s-1 downto %s);" % (self._name, self._sig._name, self._left, self._right)

class ConcatSignal(_ShadowSignal):

    __slots__ = ('_args', '_sigargs', '_initval')

    def __init__(self, *args):
        assert len(args) >= 2
        self._args = args
        self._sigargs = sigargs = []

        nrbits = 0
        val = 0
        for a in args:
            if isinstance(a, intbv):
                w = a._nrbits
                v = a._val
            elif isinstance(a, _Signal):
                sigargs.append(a)
                w = a._nrbits
                if isinstance(a._val, intbv):
                    v = a._val._val
                else:
                    v = a._val
            elif isinstance(a, bool):
                w = 1
                v = a
            elif isinstance(a, str):
                w = len(a)
                v = long(a, 2)
            else:
                raise TypeError("ConcatSignal: inappropriate argument type: %s"
                                % type(a))
            nrbits += w
            val = val << w | v & (long(1) << w) - 1
        self._initval = val
        ini = intbv(val)[nrbits:]
        _ShadowSignal.__init__(self, ini)
        gen = self.genfunc()
        self._waiter = _SignalTupleWaiter(gen)

    def genfunc(self):
        set_next = _Signal.next.fset
        args = self._args
        sigargs = self._sigargs
        nrbits = self._nrbits
        newval = intbv(self._initval)[nrbits:]
        while 1:
            hi = nrbits
            for a in args:
                if isinstance(a, bool):
                    w = 1
                else:
                    w = len(a)
                lo = hi - w
                # note: 'a in sigargs' is equivalence check, not identity
                if isinstance(a, _Signal):
                    if isinstance(a._val, intbv):
                        newval[hi:lo] = a[w:]
                    else:
                        newval[hi:lo] = a
                hi = lo
            set_next(self, newval)
            yield sigargs

    def _markRead(self):
        self._read = True
        for s in self._sigargs:
            s._markRead()

    def _markUsed(self):
        self._used = True
        for s in self._sigargs:
            s._markUsed()

    def toVHDL(self):
        lines = []
        ini = intbv(self._initval)[self._nrbits:]
        hi = self._nrbits
        for a in self._args:

            if isinstance(a, bool):
                w = 1
            else:
                w = len(a)

            lo = hi - w

            if isinstance(a, _Signal) and not a.driven:
                # Check that signal a is driven and raise a warning if not
                from myhdl.conversion._misc import _error
                from myhdl import ToVHDLWarning

                if w == 1:
                    warnings.warn(
                        "%s: %s[%s]" % (_error.UndrivenSignal, self._name, lo),
                        category=ToVHDLWarning)
                else:
                    warnings.warn(
                        "%s: %s[%s:%s]" % (_error.UndrivenSignal, self._name, hi, lo),
                        category=ToVHDLWarning)

            if w == 1:
                if isinstance(a, _Signal) and a.driven:
                    if a._type == bool:  # isinstance(a._type , bool): <- doesn't work
                        lines.append("%s(%s) <= %s;" % (self._name, lo, a._name))
                    else:
                        lines.append("%s(%s) <= %s(0);" % (self._name, lo, a._name))
                else:
                    lines.append("%s(%s) <= '%s';" % (self._name, lo, bin(ini[lo])))
            else:
                if isinstance(a, _Signal) and a.driven:
                    lines.append("%s(%s-1 downto %s) <= %s;" % (self._name, hi, lo, a._name))
                else:
                    lines.append('%s(%s-1 downto %s) <= "%s";' %
                                 (self._name, hi, lo, bin(ini[hi:lo], w)))
            hi = lo
        return "\n".join(lines)

    def toVerilog(self):
        lines = []
        ini = intbv(self._initval)[self._nrbits:]
        hi = self._nrbits
        for a in self._args:

            if isinstance(a, _Signal) and not a.driven:
                # Check that signal a is driven and raise a warning if not
                from myhdl.conversion._misc import _error
                from myhdl import ToVerilogWarning

                if w == 1:
                    warnings.warn(
                        "%s: %s[%s]" % (_error.UndrivenSignal, self._name, lo),
                        category=ToVerilogWarning)
                else:
                    warnings.warn(
                        "%s: %s[%s:%s]" % (_error.UndrivenSignal, self._name, hi, lo),
                        category=ToVerilogWarning)

            if isinstance(a, bool):
                w = 1
            else:
                w = len(a)
            lo = hi - w
            if w == 1:
                if isinstance(a, _Signal) and a.driven:
                    if a._type == bool:
                        lines.append("assign %s[%s] = %s;" % (self._name, lo, a._name))
                    else:
                        lines.append("assign %s[%s] = %s[0];" % (self._name, lo, a._name))
                else:
                    lines.append("assign %s[%s] = 'b%s;" % (self._name, lo, bin(ini[lo])))
            else:
                if isinstance(a, _Signal) and a.driven:
                    lines.append("assign %s[%s-1:%s] = %s;" % (self._name, hi, lo, a._name))
                else:
                    lines.append("assign %s[%s-1:%s] = 'b%s;" %
                                 (self._name, hi, lo, bin(ini[hi:lo], w)))
            hi = lo
        return "\n".join(lines)

# Tristate signal

class BusContentionWarning(UserWarning):
    pass

warnings.filterwarnings('always', r".*", BusContentionWarning)

# def Tristate(val, delay=None):
#     """ Return a new Tristate(default or delay 0) or DelayedTristate """
#     if delay is not None:
#         if delay < 0:
#             raise TypeError("Signal: delay should be >= 0")
#         return _DelayedTristate(val, delay)
#     else:
#         return _Tristate(val)

def TristateSignal(val):
    return _TristateSignal(val)

class _TristateSignal(_ShadowSignal):

    __slots__ = ('_drivers', '_orival')

    def __init__(self, val):
        self._drivers = []
        # construct normally to set type / size info right
        _ShadowSignal.__init__(self, val)
        self._orival = deepcopy(val)  # keep for drivers
        # reset signal values to None
        self._next = self._val = self._init = None
        self._waiter = _SignalTupleWaiter(self._resolve())

    def driver(self):
        d = _TristateDriver(self)
        self._drivers.append(d)
        return d

    def _resolve(self):
        # set_next = _ShadowSignal._set_next
        senslist = self._drivers
        while 1:
            yield senslist
            res = None
            for d in senslist:
                if res is None:
                    res = d._val
                elif d._val is not None:
                    warnings.warn("Bus contention", category=BusContentionWarning)
                    res = None
                    break
            self._next = res
            _siglist.append(self)

    def toVerilog(self):
        lines = []
        for d in self._drivers:
            if d._driven:
                lines.append("assign %s = %s;" % (self._name, d._name))
        return "\n".join(lines)

    def toVHDL(self):
        lines = []
        for d in self._drivers:
            if d._driven:
                lines.append("%s <= %s;" % (self._name, d._name))
        return "\n".join(lines)

class _TristateDriver(_Signal):

    __slots__ = ('_sig',)

    def __init__(self, sig):
        _Signal.__init__(self, sig._orival)
        # reset signal values to None
        self._next = self._val = self._init = None
        self._sig = sig

    @_Signal.next.setter
    def next(self, val):
        if isinstance(val, _Signal):
            val = val._val
        if val is None:
            self._next = None
        else:
            # restore original value to cater for intbv handler
            self._next = self._sig._orival
            self._setNextVal(val)
        _siglist.append(self)
<|endoftext|>


<commit_before># coding: utf-8

from flask import Flask
from flask.ext.babel import Babel
from flask.ext.script import Manager
from flask_wtf.csrf import CsrfProtect

app = Flask('csvsimpletools')
app.config.from_object('config')
manager = Manager(app)
CsrfProtect(app)
babel = Babel(app)

from csvsimpletools import views
<commit_msg>Add logging<commit_after># coding: utf-8

from flask import Flask
from flask.ext.babel import Babel
from flask.ext.script import Manager
from flask_wtf.csrf import CsrfProtect

app = Flask('csvsimpletools')
app.config.from_object('config')
manager = Manager(app)
CsrfProtect(app)
babel = Babel(app)

if not app.config['DEBUG']:
    import logging
    from logging.handlers import RotatingFileHandler
    filepath = app.config['BASEDIR'].child('errors.log')
    handler = RotatingFileHandler(filepath, 'a', 1 * 1024 * 1024, 10)
    row = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    formatter = logging.Formatter(row)
    handler.setFormatter(formatter)
    handler.setLevel(logging.INFO)
    app.logger.setLevel(logging.INFO)
    app.logger.addHandler(handler)
    app.logger.info('{} started successfully.'.format(app.config['TITLE']))

from csvsimpletools import views
<|endoftext|>


<commit_before>"""
Copyright (c) 2008 Marian Tietz
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"""

import time
from dbus import UInt64

config = None
gui = None
com = None

commands = {}

def parseInput(text):
	"""
		TODO: document
	"""
	if not text:
		return

	serverTab,channelTab = gui.tabs.getCurrentTabs()

	if text[:2]=="//" or text[0] != "/":
		if not channelTab:
			return
		com.sendMessage(serverTab.name, channelTab.name, text)

	else:
		list = text[1:].split(" ")
		cmd = list[0]

		if not cmd:
			return gui.myPrint("No command given.")
		elif not commands.has_key(cmd):
			if not serverTab:
				return gui.myPrint("No server active.")
			gui.myPrint("Unknown command '%s'; Forwarding raw." % (cmd))
			com.raw(serverTab.name, cmd.upper() + " ".join(list[1:]))

		else:
			commands[cmd](serverTab, channelTab, list[1:])

def makiConnect(currentServer, currentChannel, args):
	"""
		Connect to the given server.

		Usage: /connect <server>
	"""
	if not args:
		return gui.myPrint("Usage: /connect <servername>")

	com.connectServer(args[0])

def makiQuit(currentServer, currentChannel, args):
	"""
		Quit the given server with an optional reason.
		If no server is given, the current server is quit.

		Usage: /quit <server> [<reason>]
		       /quit [<reason>]
	"""
	if args:
		# /quit <server> [<reason>]
		if gui.tabs.searchTab(None, args[0]):
			com.quitServer(args[0], " ".join(args[1:]))
		else:
			# /quit [<reason>]
			if not currentServer:
				return gui.myPrint("Could not determine server.")
			com.quitServer(currentServer.name, " ".join(args))
	else:
		# /quit
		if not currentServer:
			return gui.myPrint("Could not determine server.")
		com.quitServer(currentServer.name,"")

def makiNick(currentServer, currentChannel, args):
	"""
		Change your current nick to the given nick.

		Usage: /nick <new nick>
	"""
	if not args:
		return gui.myPrint("Usage: /nick <new nick>")

	if not currentServer:
		return gui.myPrint("Can't determine my server.")

	com.nick(currentServer.name, args[0])

def makiPart(currentServer, currentChannel, args):
	"""
		Part the given channel with an optional reason.
		If no channel is given, the current channel is parted.

		Usage: /part <channel> [<reason>]
		       /part [<reason>]
	"""
	if args and currentServer:
		# /part <channel> [<reason>]
		if gui.tabs.searchTab(currentServer.name, args[0]):
			com.part(args[0], " ".join(args[1:]))
		else:
			# /part [<reason>]
			if not currentChannel:
				return gui.myPrint("Could not determine channel.")
			com.part(currentServer.name, currentChannel.name, " ".join(args))
	else:
		# /part
		if not currentChannel:
			return gui.myPrint("Could not determine channel.")
		com.part(currentServer.name, currentChannel.name,"")

def makiJoin(currentServer, currentChannel, args):
	"""
		Joins the given channel with the optional key.

		Usage: /join <channel> [<key>]
	"""
	if not currentServer:
		return gui.myPrint("Can't determine server.")

	if not args:
		return gui.myPrint("Usage: /join <channel> [<key>]")

	com.join(currentServer.name, args[0], " ".join(args[1:]))

def makiAction(currentServer, currentChannel, args):
	"""
		Sends an action in third person view.

		Usage: /me <text>

		Example: nemo types: /me giggles.
		Results in: nemo giggles.
	"""
	if not args:
		return gui.myPrint("Usage: /me <text>")

	if not currentChannel:
		return gui.myPrint("Can't find active channel.")

	com.action(currentServer.name, currentChannel.name, " ".join(args))

def makiKick(currentServer, currentTab, args):
	"""
		Kick the given user with an optional reason from the
		current channel.

		Usage: /kick <user> [<reason>]
	"""
	if not args:
		return gui.myPrint("Usage: /kick <user> [<reason>]")

	if not channelTab or not channelTab.is_channel():
		return gui.myPrint("You're not on a channel")

	self.com.kick(serverTab.name, channelTab.name, args[0], " ".join(args[1:]))

def makiMode(currentServer, currentChannel, args):
	"""
		Sets a mode on the target.

		Usage: /mode <target> (+|-)<mode> [<param>]

		Example: /mode #xesio +o nemo
		OR:      /mode nemo +x
		OR:      /mode #xesio +m
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /mode <target> (+|-)<mode> [<param>]")

	if not currentServer:
		return gui.myPrint("Could not determine server.")

	if len(args) > 2:
		# a parameter is given
		param = " ".join(args[2:])

	com.mode(currentServer.name, args[0], "%s %s" % (args[1],param))

def makiTopic(serverTab, channelTab, args):
	"""
		Sets the topic in the current channel.

		Usage: /topic <text>
	"""
	if not args:
		return gui.myPrint("Usage: /topic <text>")
	else:
		topic = " ".join(args)

	if not channelTab or not channelTab.is_channel():
		return gui.myPrint("No channel active.")

	com.setTopic(serverTab.name, channelTab.name, topic)

def makiAway(serverTab, channelTab, args):
	"""
		Sets you away with an optional reason.

		Usage: /away [<reason>]
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")

	com.setAway(serverTab.name, " ".join(args))

def makiBack(serverTab, channelTab, args):
	"""
		Sets you back from being away.

		Usage: /back
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")
	com.setBack(serverTab.name)

def makiNickserv(serverTab, channelTab, args):
	"""
		Authenticates you at NickServ with
		the data stored in maki.

		Usage: /nickserv
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")

	com.nickserv(server)

def makiCTCP(serverTab, channelTab, args):
	"""
		Sends a CTCP message to the given target.

		Usage: /ctcp <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /ctcp <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.ctcp(serverTab.name, args[0], args[1])

def makiNotice(serverTab, channelTab, args):
	"""
		Sends a notice to the given target.
		The difference between /ctcp and /notice
		is, that /ctcp sends directly to the user
		while /notice sends the message over the
		server.

		Usage: /notice <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /notice <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.notice(serverTab.name, args[0], " ".join(args[1:]))

def makiMessage(serverTab, channelTab, args):
	"""
		Sends a message (PRIVMSG) to the target.
		The target can be a channel or a user.

		Usage: /msg <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /msg <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.sendMessage(serverTab.name, args[0], " ".join(args[1]))

def makiOper(serverTab, channelTab, args):
	"""
		Authentificate as IRC operator.

		Usage: /oper <user> <pass>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /oper <user> <pass>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.oper(serverTab.name, args[0], " ".join(args[1:]))

def makiKill(serverTab, channelTab, args):
	"""
		Kill a user on the network with an optional reason.

		Usage: /kill <user> [<reason>]
	"""
	if not args or len(args) < 1:
		return gui.myPrint("Usage: /kill <user> [<reason>]")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.kill(serverTab.name, args[0], " ".join(args[1:]))

def makiList(serverTab, channelTab, args):
	"""
		Start a channel listing.
		If channel is given, only the channel
		is listed.

		Usage: /list [<channel>]
	"""
	if not serverTab:
		return gui.myPrint("Could not determine server.")

	try:
		# channel specific listing?
		channel = args[0]
	except IndexError:
		# start a complete list..
		channel = ""

	gui.serverPrint(time.time(), serverTab.name, "Start of list.")
	com.list(serverTab.name, channel)

def makiRaw(serverTab, channelTab, args):
	"""
		Sends a command with optional args to maki
		which acts only as forwarder. The command
		goes unchanged to the server.

		Usage: /raw <command> [<further text>]
	"""
	if not args:
		return gui.myPrint("Usage: /raw <command>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	# upper-case the command
	args[0] = args[0].upper()

	com.raw(server, " ".join(args))

def makiWhois(currentServer, currentChannel, args):
	"""
		Query a user's identity on the current server.

		Usage: /whois <user mask>
	"""
	if not args:
		return gui.myPrint("No server activated.")

	com.sushi.whois(currentServer.name, args[0])

""" TEKKA USER COMMANDS """

def tekkaQuery(currentServer, currentTab, args):
	"""
		Starts a query dialog with the given user.

		Usage: /query <nick>
	"""
	if not args:
		return gui.myPrint("Usage: /query <nick>")

	if not serverTab:
		return gui.myPrint("Can't determine server.")

	if not gui.tabs.searchTab(currentServer.name, args[0]):
		# no query started

		tab = gui.tabs.createQuery(serverTab.name, nick)
		tab.connected = True
		gui.tabs.addTab(serverTab.name, tab)

		output = tab.buffer

		# fetch and write history to query (if any)
		for line in com.fetchLog(serverTab.name, nick,
			UInt64(config.get("chatting","last_log_lines","10"))):

			output.insertHTML(output.get_end_iter(),
				"%s" % self.gui.escape(line))

def tekkaClear(currentServer, currentTab, args):
	"""
		Clears the output of the current channel.

		Usage: /clear
	"""
	if currentTab: currentTab.buffer.set_text("")
	elif currentServer: currentServer.buffer.set_text("")

def tekkaHelp(currentServer, currentTab, args):
	"""
		Prints the doc-string of the given command.

		Usage: /help <command>
	"""
	if not args:
		return gui.myPrint("Usage: /help <command>")
	if commands.has_key(args[0]):
		gui.myPrint(commands[args[0]].__doc__.replace("\t",""))
	else:
		gui.myPrint("No help for %s available." % (args[0]))

def setup(_config, _gui, _com):
	"""
		Setup the command module.
		  * Set modules
		  * Set command mapping
	"""
	global config, gui, com, commands

	config = _config
	gui = _gui
	com = _com

	commands = {
		"connect" : makiConnect,
		"nick" : makiNick,
		"part" : makiPart,
		"join" : makiJoin,
			"j" : makiJoin,
		"me"   : makiAction,
		"kick" : makiKick,
		"mode" : makiMode,
		"topic": makiTopic,
		"quit" : makiQuit,
		"away" : makiAway,
		"back" : makiBack,
	"nickserv" : makiNickserv,
		"ctcp" : makiCTCP,
		"notice" : makiNotice,
		"msg" : makiMessage,
		"oper" : makiOper,
		"kill" : makiKill,
		"list" : makiList,
		"raw" : makiRaw,
		"whois" : makiWhois,
		"query": tekkaQuery,
		"clear": tekkaClear,
		"help": tekkaHelp
	}
<commit_msg>Fix /query.<commit_after>"""
Copyright (c) 2008 Marian Tietz
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"""

import time
from dbus import UInt64

config = None
gui = None
com = None

commands = {}

def parseInput(text):
	"""
		TODO: document
	"""
	if not text:
		return

	serverTab,channelTab = gui.tabs.getCurrentTabs()

	if text[:2]=="//" or text[0] != "/":
		if not channelTab:
			return
		com.sendMessage(serverTab.name, channelTab.name, text)

	else:
		list = text[1:].split(" ")
		cmd = list[0]

		if not cmd:
			return gui.myPrint("No command given.")
		elif not commands.has_key(cmd):
			if not serverTab:
				return gui.myPrint("No server active.")
			gui.myPrint("Unknown command '%s'; Forwarding raw." % (cmd))
			com.raw(serverTab.name, cmd.upper() + " ".join(list[1:]))

		else:
			commands[cmd](serverTab, channelTab, list[1:])

def makiConnect(currentServer, currentChannel, args):
	"""
		Connect to the given server.

		Usage: /connect <server>
	"""
	if not args:
		return gui.myPrint("Usage: /connect <servername>")

	com.connectServer(args[0])

def makiQuit(currentServer, currentChannel, args):
	"""
		Quit the given server with an optional reason.
		If no server is given, the current server is quit.

		Usage: /quit <server> [<reason>]
		       /quit [<reason>]
	"""
	if args:
		# /quit <server> [<reason>]
		if gui.tabs.searchTab(None, args[0]):
			com.quitServer(args[0], " ".join(args[1:]))
		else:
			# /quit [<reason>]
			if not currentServer:
				return gui.myPrint("Could not determine server.")
			com.quitServer(currentServer.name, " ".join(args))
	else:
		# /quit
		if not currentServer:
			return gui.myPrint("Could not determine server.")
		com.quitServer(currentServer.name,"")

def makiNick(currentServer, currentChannel, args):
	"""
		Change your current nick to the given nick.

		Usage: /nick <new nick>
	"""
	if not args:
		return gui.myPrint("Usage: /nick <new nick>")

	if not currentServer:
		return gui.myPrint("Can't determine my server.")

	com.nick(currentServer.name, args[0])

def makiPart(currentServer, currentChannel, args):
	"""
		Part the given channel with an optional reason.
		If no channel is given, the current channel is parted.

		Usage: /part <channel> [<reason>]
		       /part [<reason>]
	"""
	if args and currentServer:
		# /part <channel> [<reason>]
		if gui.tabs.searchTab(currentServer.name, args[0]):
			com.part(args[0], " ".join(args[1:]))
		else:
			# /part [<reason>]
			if not currentChannel:
				return gui.myPrint("Could not determine channel.")
			com.part(currentServer.name, currentChannel.name, " ".join(args))
	else:
		# /part
		if not currentChannel:
			return gui.myPrint("Could not determine channel.")
		com.part(currentServer.name, currentChannel.name,"")

def makiJoin(currentServer, currentChannel, args):
	"""
		Joins the given channel with the optional key.

		Usage: /join <channel> [<key>]
	"""
	if not currentServer:
		return gui.myPrint("Can't determine server.")

	if not args:
		return gui.myPrint("Usage: /join <channel> [<key>]")

	com.join(currentServer.name, args[0], " ".join(args[1:]))

def makiAction(currentServer, currentChannel, args):
	"""
		Sends an action in third person view.

		Usage: /me <text>

		Example: nemo types: /me giggles.
		Results in: nemo giggles.
	"""
	if not args:
		return gui.myPrint("Usage: /me <text>")

	if not currentChannel:
		return gui.myPrint("Can't find active channel.")

	com.action(currentServer.name, currentChannel.name, " ".join(args))

def makiKick(currentServer, currentTab, args):
	"""
		Kick the given user with an optional reason from the
		current channel.

		Usage: /kick <user> [<reason>]
	"""
	if not args:
		return gui.myPrint("Usage: /kick <user> [<reason>]")

	if not channelTab or not channelTab.is_channel():
		return gui.myPrint("You're not on a channel")

	self.com.kick(serverTab.name, channelTab.name, args[0], " ".join(args[1:]))

def makiMode(currentServer, currentChannel, args):
	"""
		Sets a mode on the target.

		Usage: /mode <target> (+|-)<mode> [<param>]

		Example: /mode #xesio +o nemo
		OR:      /mode nemo +x
		OR:      /mode #xesio +m
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /mode <target> (+|-)<mode> [<param>]")

	if not currentServer:
		return gui.myPrint("Could not determine server.")

	if len(args) > 2:
		# a parameter is given
		param = " ".join(args[2:])

	com.mode(currentServer.name, args[0], "%s %s" % (args[1],param))

def makiTopic(serverTab, channelTab, args):
	"""
		Sets the topic in the current channel.

		Usage: /topic <text>
	"""
	if not args:
		return gui.myPrint("Usage: /topic <text>")
	else:
		topic = " ".join(args)

	if not channelTab or not channelTab.is_channel():
		return gui.myPrint("No channel active.")

	com.setTopic(serverTab.name, channelTab.name, topic)

def makiAway(serverTab, channelTab, args):
	"""
		Sets you away with an optional reason.

		Usage: /away [<reason>]
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")

	com.setAway(serverTab.name, " ".join(args))

def makiBack(serverTab, channelTab, args):
	"""
		Sets you back from being away.

		Usage: /back
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")
	com.setBack(serverTab.name)

def makiNickserv(serverTab, channelTab, args):
	"""
		Authenticates you at NickServ with
		the data stored in maki.

		Usage: /nickserv
	"""
	if not serverTab:
		return gui.myPrint("Can't determine server.")

	com.nickserv(server)

def makiCTCP(serverTab, channelTab, args):
	"""
		Sends a CTCP message to the given target.

		Usage: /ctcp <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /ctcp <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.ctcp(serverTab.name, args[0], args[1])

def makiNotice(serverTab, channelTab, args):
	"""
		Sends a notice to the given target.
		The difference between /ctcp and /notice
		is, that /ctcp sends directly to the user
		while /notice sends the message over the
		server.

		Usage: /notice <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /notice <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.notice(serverTab.name, args[0], " ".join(args[1:]))

def makiMessage(serverTab, channelTab, args):
	"""
		Sends a message (PRIVMSG) to the target.
		The target can be a channel or a user.

		Usage: /msg <target> <message>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /msg <target> <message>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.sendMessage(serverTab.name, args[0], " ".join(args[1]))

def makiOper(serverTab, channelTab, args):
	"""
		Authentificate as IRC operator.

		Usage: /oper <user> <pass>
	"""
	if not args or len(args) < 2:
		return gui.myPrint("Usage: /oper <user> <pass>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.oper(serverTab.name, args[0], " ".join(args[1:]))

def makiKill(serverTab, channelTab, args):
	"""
		Kill a user on the network with an optional reason.

		Usage: /kill <user> [<reason>]
	"""
	if not args or len(args) < 1:
		return gui.myPrint("Usage: /kill <user> [<reason>]")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	com.kill(serverTab.name, args[0], " ".join(args[1:]))

def makiList(serverTab, channelTab, args):
	"""
		Start a channel listing.
		If channel is given, only the channel
		is listed.

		Usage: /list [<channel>]
	"""
	if not serverTab:
		return gui.myPrint("Could not determine server.")

	try:
		# channel specific listing?
		channel = args[0]
	except IndexError:
		# start a complete list..
		channel = ""

	gui.serverPrint(time.time(), serverTab.name, "Start of list.")
	com.list(serverTab.name, channel)

def makiRaw(serverTab, channelTab, args):
	"""
		Sends a command with optional args to maki
		which acts only as forwarder. The command
		goes unchanged to the server.

		Usage: /raw <command> [<further text>]
	"""
	if not args:
		return gui.myPrint("Usage: /raw <command>")

	if not serverTab:
		return gui.myPrint("Could not determine server.")

	# upper-case the command
	args[0] = args[0].upper()

	com.raw(server, " ".join(args))

def makiWhois(currentServer, currentChannel, args):
	"""
		Query a user's identity on the current server.

		Usage: /whois <user mask>
	"""
	if not args:
		return gui.myPrint("No server activated.")

	com.sushi.whois(currentServer.name, args[0])

""" TEKKA USER COMMANDS """

def tekkaQuery(currentServer, currentTab, args):
	"""
		Starts a query dialog with the given user.

		Usage: /query <nick>
	"""
	if not args:
		return gui.myPrint("Usage: /query <nick>")

	if not currentServer:
		return gui.myPrint("Can't determine server.")

	nick = args[0]

	if not gui.tabs.searchTab(currentServer.name, nick):
		# no query started

		tab = gui.tabs.createQuery(currentServer.name, nick)
		tab.connected = True
		gui.tabs.addTab(currentServer.name, tab)

		output = tab.buffer

		# fetch and write history to query (if any)
		for line in com.fetchLog(currentServer.name, nick,
			UInt64(config.get("chatting","last_log_lines","10"))):

			output.insertHTML(output.get_end_iter(),
				"%s" % gui.escape(line))

def tekkaClear(currentServer, currentTab, args):
	"""
		Clears the output of the current channel.

		Usage: /clear
	"""
	if currentTab: currentTab.buffer.set_text("")
	elif currentServer: currentServer.buffer.set_text("")

def tekkaHelp(currentServer, currentTab, args):
	"""
		Prints the doc-string of the given command.

		Usage: /help <command>
	"""
	if not args:
		return gui.myPrint("Usage: /help <command>")
	if commands.has_key(args[0]):
		gui.myPrint(commands[args[0]].__doc__.replace("\t",""))
	else:
		gui.myPrint("No help for %s available." % (args[0]))

def setup(_config, _gui, _com):
	"""
		Setup the command module.
		  * Set modules
		  * Set command mapping
	"""
	global config, gui, com, commands

	config = _config
	gui = _gui
	com = _com

	commands = {
		"connect" : makiConnect,
		"nick" : makiNick,
		"part" : makiPart,
		"join" : makiJoin,
			"j" : makiJoin,
		"me"   : makiAction,
		"kick" : makiKick,
		"mode" : makiMode,
		"topic": makiTopic,
		"quit" : makiQuit,
		"away" : makiAway,
		"back" : makiBack,
	"nickserv" : makiNickserv,
		"ctcp" : makiCTCP,
		"notice" : makiNotice,
		"msg" : makiMessage,
		"oper" : makiOper,
		"kill" : makiKill,
		"list" : makiList,
		"raw" : makiRaw,
		"whois" : makiWhois,
		"query": tekkaQuery,
		"clear": tekkaClear,
		"help": tekkaHelp
	}
<|endoftext|>


<commit_before># A job for creating and managing key generation

from os import environ
import subprocess

jenkins_scripts = environ.get("JENKINS_SCRIPTS")
aws_access_key = environ.get("AWS_ACCESS_KEY")
aws_secret_key = environ.get("AWS_SECRET_KEY")

domain_name=environ.get('Domain_Name')
state=environ.get('State')
city=environ.get('City')
legal_name=environ.get('Legal_Name')
bucket=environ.get('Databag_Name')

# Enter the required information about the company
# Run the SSL command
command='openssl req -new -newkey rsa:2048 -nodes -out /tmp/{domain_name}.csr -keyout /tmp/{domain_name}.key -subj'.format(domain_name=domain_name).split(" ")
command+=['"/C=US/ST={state}/L={city}/O={legal_name}/CN={domain_name}"'.format(state=state, city=city, legal_name=legal_name, domain_name=domain_name)]
out = subprocess.check_output(command)
print out

# Upload the CSR file to EC2
command="s3upload -l DEBUG -k {aws_access_key} -sk {aws_secret_key} -f -np 8 -s 100 /tmp/{domain_name}.csr s3://{bucket}/{domain_name}.csr".format(aws_access_key=aws_access_key,aws_secret_key=aws_secret_key,domain_name=domain_name, bucket=bucket)
out = subprocess.check_output(command.split(" "))
print out

# Upload the KEY file to EC2
command="s3upload -l DEBUG -k {aws_access_key} -sk {aws_secret_key} -f -np 8 -s 100 /tmp/{domain_name}.key s3://{bucket}/{domain_name}.key".format(aws_access_key=aws_access_key,aws_secret_key=aws_secret_key,domain_name=domain_name, bucket=bucket)
out = subprocess.check_output(command.split(" "))
print out

# Clean-up the local files
os.remove("/tmp/{domain_name}.csr")
os.remove("/tmp/{domain_name}.key")

# Input them into the nmdproxy/certs databag? TODO

# Show the nmd file commands to pull the files and share them
print "Your cert files have been uploaded to the nmdarchive. To download them, copy paste the following text into iTerm:\n"
print "mkdir ~/Downloads/{bucket} &&".format(bucket=bucket)
print "cd ~/Downloads/{bucket} &&".format(bucket=bucket)
print "nmd file get {bucket}/{domain_name}.key &&".format(bucket=bucket, domain_name=domain_name)
print "nmd file get {bucket}/{domain_name}.csr &&".format(bucket=bucket, domain_name=domain_name)
print "open ."<commit_msg>Debug.<commit_after># A job for creating and managing key generation

from os import environ
import subprocess

jenkins_scripts = environ.get("JENKINS_SCRIPTS")
aws_access_key = environ.get("AWS_ACCESS_KEY")
aws_secret_key = environ.get("AWS_SECRET_KEY")

domain_name=environ.get('Domain_Name')
state=environ.get('State')
city=environ.get('City')
legal_name=environ.get('Legal_Name')
bucket=environ.get('Databag_Name')

# Enter the required information about the company
# Run the SSL command
command='openssl req -new -newkey rsa:2048 -nodes -out /tmp/{domain_name}.csr -keyout /tmp/{domain_name}.key -subj'.format(domain_name=domain_name).split(" ")
command+=['"/C=US/ST={state}/L={city}/O={legal_name}/CN={domain_name}"'.format(state=state, city=city, legal_name=legal_name, domain_name=domain_name)]
print " ".join(command)
out = subprocess.check_output(command)
print out

# Upload the CSR file to EC2
command="s3upload -l DEBUG -k {aws_access_key} -sk {aws_secret_key} -f -np 8 -s 100 /tmp/{domain_name}.csr s3://{bucket}/{domain_name}.csr".format(aws_access_key=aws_access_key,aws_secret_key=aws_secret_key,domain_name=domain_name, bucket=bucket)
out = subprocess.check_output(command.split(" "))
print out

# Upload the KEY file to EC2
command="s3upload -l DEBUG -k {aws_access_key} -sk {aws_secret_key} -f -np 8 -s 100 /tmp/{domain_name}.key s3://{bucket}/{domain_name}.key".format(aws_access_key=aws_access_key,aws_secret_key=aws_secret_key,domain_name=domain_name, bucket=bucket)
out = subprocess.check_output(command.split(" "))
print out

# Clean-up the local files
os.remove("/tmp/{domain_name}.csr")
os.remove("/tmp/{domain_name}.key")

# Input them into the nmdproxy/certs databag? TODO

# Show the nmd file commands to pull the files and share them
print "Your cert files have been uploaded to the nmdarchive. To download them, copy paste the following text into iTerm:\n"
print "mkdir ~/Downloads/{bucket} &&".format(bucket=bucket)
print "cd ~/Downloads/{bucket} &&".format(bucket=bucket)
print "nmd file get {bucket}/{domain_name}.key &&".format(bucket=bucket, domain_name=domain_name)
print "nmd file get {bucket}/{domain_name}.csr &&".format(bucket=bucket, domain_name=domain_name)
print "open ."<|endoftext|>


<commit_before>"""
pymysensors - Python implementation of the MySensors SerialGateway
"""
import serial
import time
import threading
from .const import Internal, MessageType
import logging
import pickle

LOGGER = logging.getLogger(__name__)

class Gateway(object):
    """ Base implementation for a MySensors Gateway. """

    def __init__(self, event_callback=None, persistence=False):
        self.event_callback = event_callback
        self.sensors = {}
        self.metric = True   # if true - use metric, if false - use imperial
        self.debug = False   # if true - print all received messages
        self.persistence = persistence  # if true - save sensors to disk
        if persistence:
            self._load_sensors()

    def _handle_presentation(self, msg):
        """ Processes a presentation message. """
        if msg.child_id == 255:
            # this is a presentation of the sensor platform
            self.add_sensor(msg.node_id)
            self.sensors[msg.node_id].type = msg.sub_type
            self.sensors[msg.node_id].version = msg.payload
            self.alert(msg.node_id)
        else:
            # this is a presentation of a child sensor
            self.sensors[msg.node_id].add_child_sensor(msg.child_id,
                                                       msg.sub_type)
            self.alert(msg.node_id)

    def _handle_set(self, msg):
        """ Processes a set message. """
        if self.is_sensor(msg.node_id, msg.child_id):
            self.sensors[msg.node_id].set_child_value(
                msg.child_id, msg.sub_type, msg.payload)
            self.alert(msg.node_id)

    def _handle_internal(self, msg):
        """ Processes an internal protocol message. """
        if msg.sub_type == Internal.I_ID_REQUEST:
            return msg.copy(ack=0,
                            sub_type=Internal.I_ID_RESPONSE,
                            payload=self.add_sensor())
        elif msg.sub_type == Internal.I_SKETCH_NAME:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].sketch_name = msg.payload
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_SKETCH_VERSION:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].sketch_version = msg.payload
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_CONFIG:
            return msg.copy(ack=0, payload='M' if self.metric else 'I')
        elif msg.sub_type == Internal.I_BATTERY_LEVEL:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].battery_level = int(msg.payload)
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_TIME:
            return msg.copy(ack=0, payload=int(time.time()))
        elif msg.sub_type == Internal.I_LOG_MESSAGE and self.debug:
            LOGGER.debug("n:%s c:%s t:%s s:%s p:%s",
                         msg.node_id,
                         msg.child_id,
                         msg.type,
                         msg.sub_type,
                         msg.payload)

    def send(self, message):
        """ Should be implemented by a child class. """
        pass

    def logic(self, data):
        """
        Parse the data and respond to it appropriately.
        Response is returned to the caller and has to be sent
        data is a mysensors command string
        """
        msg = Message(data)

        if msg.type == MessageType.presentation:
            self._handle_presentation(msg)
        elif msg.type == MessageType.set:
            self._handle_set(msg)
        elif msg.type == MessageType.internal:
            return self._handle_internal(msg)
        return None

    def _save_sensors(self):
        """ Save sensors to file """
        f = open('mysensors.pickle', 'wb')
        with open('mysensors.pickle', 'wb') as f:
            pickle.dump(self.sensors, f, pickle.HIGHEST_PROTOCOL)

    def _load_sensors(self):
        """ Load sensors from file """
        try:
            with open('mysensors.pickle', 'rb') as f:
                self.sensors = pickle.load(f)
        except IOError:
            pass

    def alert(self, nid):
        """
        Tell anyone who wants to know that a sensor was updated. Also save
        sensors if persistence is enabled
        """
        if self.event_callback is not None:
            self.event_callback("sensor_update", nid)

        if self.persistence:
            self._save_sensors()

    def _get_next_id(self):
        """ Returns the next available sensor id. """
        if len(self.sensors):
            next_id = max(self.sensors.keys()) + 1
        else:
            next_id = 1
        if next_id <= 254:
            return next_id
        return None

    def add_sensor(self, sensorid=None):
        """ Adds a sensor to the gateway. """
        if sensorid is None:
            sensorid = self._get_next_id()

        if sensorid is not None and sensorid not in self.sensors:
            self.sensors[sensorid] = Sensor(sensorid)
            return sensorid
        return None

    def is_sensor(self, sensorid, child_id=None):
        """ Returns True if a sensor and its child exists. """
        if sensorid not in self.sensors:
            return False
        if child_id is not None:
            return child_id in self.sensors[sensorid].children
        return True

class SerialGateway(Gateway, threading.Thread):
    """ MySensors serial gateway. """
    # pylint: disable=too-many-arguments

    def __init__(self, port, event_callback=None, persistence=False, baud=115200,
                 timeout=1.0, reconnect_timeout=10.0):
        threading.Thread.__init__(self)
        Gateway.__init__(self, event_callback, persistence)
        self.serial = None
        self.port = port
        self.baud = baud
        self.timeout = timeout
        self.reconnect_timeout = reconnect_timeout
        self._stop_event = threading.Event()

    def connect(self):
        """ Connects to the serial port. """
        if self.serial:
            return True
        try:
            self.serial = serial.Serial(self.port, self.baud,
                                        timeout=self.timeout)
        except serial.SerialException:
            LOGGER.exception('Unable to connect to %s', self.port)
            return False
        return True

    def disconnect(self):
        """ Disconnects from the serial port. """
        if self.serial is not None:
            self.serial.close()
            self.serial = None

    def stop(self):
        """ Stops the background thread. """
        self._stop_event.set()

    def run(self):
        """ Background thread that reads messages from the gateway. """
        while not self._stop_event.is_set():
            if self.serial is None and not self.connect():
                time.sleep(self.reconnect_timeout)
                continue
            try:
                line = self.serial.readline()
                if not line:
                    continue
            except serial.SerialException:
                LOGGER.exception('Serial exception')
                continue
            except TypeError:
                # pyserial has a bug that causes a TypeError to be thrown when
                # the port disconnects instead of a SerialException
                self.disconnect()
                continue
            try:
                msg = line.decode('utf-8')
                print(msg)
            except ValueError:
                LOGGER.exception('')
                continue
            response = self.logic(msg)
            if response is not None:
                try:
                    self.send(response.encode())
                except ValueError:
                    LOGGER.exception('Invalid response')
                    continue

    def send(self, message):
        """ Writes a Message to the gateway. """
        self.serial.write(message.encode())

class Sensor:
    """ Represents a sensor. """

    def __init__(self, sensor_id):
        self.sensor_id = sensor_id
        self.children = {}
        self.type = None
        self.sketch_name = None
        self.sketch_version = None
        self.battery_level = 0

    def add_child_sensor(self, child_id, child_type):
        """ Creates and adds a child sensor. """
        self.children[child_id] = ChildSensor(child_id, child_type)

    def set_child_value(self, child_id, value_type, value):
        """ Sets a child sensor's value. """
        if child_id in self.children:
            self.children[child_id].values[value_type] = value
        # TODO: Handle error

class ChildSensor:
    """ Represents a child sensor. """
    # pylint: disable=too-few-public-methods

    def __init__(self, child_id, child_type):
        self.id = child_id
        self.type = child_type
        self.values = {}

class Message:
    """ Represents a message from the gateway. """

    def __init__(self, data=None):
        self.node_id = 0
        self.child_id = 0
        self.type = ""
        self.ack = 0
        self.sub_type = ""
        self.payload = ""
        if data is not None:
            self.decode(data)

    def copy(self, **kwargs):
        """
        Copies a message, optionally replacing attributes with keyword
        arguments.
        """
        msg = Message(self.encode())
        for key, val in kwargs.items():
            setattr(msg, key, val)
        return msg

    def decode(self, data):
        """ Decode a message from command string. """
        data = data.rstrip().split(';')
        self.payload = data.pop()
        (self.node_id,
         self.child_id,
         self.type,
         self.ack,
         self.sub_type) = [int(f) for f in data]

    def encode(self):
        """ Encode a command string from message. """
        return ";".join([str(f) for f in [
            self.node_id,
            self.child_id,
            int(self.type),
            self.ack,
            int(self.sub_type),
            self.payload,
        ]]) + "\n"
<commit_msg>removed forgotten print statement<commit_after>"""
pymysensors - Python implementation of the MySensors SerialGateway
"""
import serial
import time
import threading
from .const import Internal, MessageType
import logging
import pickle

LOGGER = logging.getLogger(__name__)

class Gateway(object):
    """ Base implementation for a MySensors Gateway. """

    def __init__(self, event_callback=None, persistence=False):
        self.event_callback = event_callback
        self.sensors = {}
        self.metric = True   # if true - use metric, if false - use imperial
        self.debug = False   # if true - print all received messages
        self.persistence = persistence  # if true - save sensors to disk
        if persistence:
            self._load_sensors()

    def _handle_presentation(self, msg):
        """ Processes a presentation message. """
        if msg.child_id == 255:
            # this is a presentation of the sensor platform
            self.add_sensor(msg.node_id)
            self.sensors[msg.node_id].type = msg.sub_type
            self.sensors[msg.node_id].version = msg.payload
            self.alert(msg.node_id)
        else:
            # this is a presentation of a child sensor
            self.sensors[msg.node_id].add_child_sensor(msg.child_id,
                                                       msg.sub_type)
            self.alert(msg.node_id)

    def _handle_set(self, msg):
        """ Processes a set message. """
        if self.is_sensor(msg.node_id, msg.child_id):
            self.sensors[msg.node_id].set_child_value(
                msg.child_id, msg.sub_type, msg.payload)
            self.alert(msg.node_id)

    def _handle_internal(self, msg):
        """ Processes an internal protocol message. """
        if msg.sub_type == Internal.I_ID_REQUEST:
            return msg.copy(ack=0,
                            sub_type=Internal.I_ID_RESPONSE,
                            payload=self.add_sensor())
        elif msg.sub_type == Internal.I_SKETCH_NAME:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].sketch_name = msg.payload
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_SKETCH_VERSION:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].sketch_version = msg.payload
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_CONFIG:
            return msg.copy(ack=0, payload='M' if self.metric else 'I')
        elif msg.sub_type == Internal.I_BATTERY_LEVEL:
            if self.is_sensor(msg.node_id):
                self.sensors[msg.node_id].battery_level = int(msg.payload)
                self.alert(msg.node_id)
        elif msg.sub_type == Internal.I_TIME:
            return msg.copy(ack=0, payload=int(time.time()))
        elif msg.sub_type == Internal.I_LOG_MESSAGE and self.debug:
            LOGGER.debug("n:%s c:%s t:%s s:%s p:%s",
                         msg.node_id,
                         msg.child_id,
                         msg.type,
                         msg.sub_type,
                         msg.payload)

    def send(self, message):
        """ Should be implemented by a child class. """
        pass

    def logic(self, data):
        """
        Parse the data and respond to it appropriately.
        Response is returned to the caller and has to be sent
        data is a mysensors command string
        """
        msg = Message(data)

        if msg.type == MessageType.presentation:
            self._handle_presentation(msg)
        elif msg.type == MessageType.set:
            self._handle_set(msg)
        elif msg.type == MessageType.internal:
            return self._handle_internal(msg)
        return None

    def _save_sensors(self):
        """ Save sensors to file """
        f = open('mysensors.pickle', 'wb')
        with open('mysensors.pickle', 'wb') as f:
            pickle.dump(self.sensors, f, pickle.HIGHEST_PROTOCOL)

    def _load_sensors(self):
        """ Load sensors from file """
        try:
            with open('mysensors.pickle', 'rb') as f:
                self.sensors = pickle.load(f)
        except IOError:
            pass

    def alert(self, nid):
        """
        Tell anyone who wants to know that a sensor was updated. Also save
        sensors if persistence is enabled
        """
        if self.event_callback is not None:
            self.event_callback("sensor_update", nid)

        if self.persistence:
            self._save_sensors()

    def _get_next_id(self):
        """ Returns the next available sensor id. """
        if len(self.sensors):
            next_id = max(self.sensors.keys()) + 1
        else:
            next_id = 1
        if next_id <= 254:
            return next_id
        return None

    def add_sensor(self, sensorid=None):
        """ Adds a sensor to the gateway. """
        if sensorid is None:
            sensorid = self._get_next_id()

        if sensorid is not None and sensorid not in self.sensors:
            self.sensors[sensorid] = Sensor(sensorid)
            return sensorid
        return None

    def is_sensor(self, sensorid, child_id=None):
        """ Returns True if a sensor and its child exists. """
        if sensorid not in self.sensors:
            return False
        if child_id is not None:
            return child_id in self.sensors[sensorid].children
        return True

class SerialGateway(Gateway, threading.Thread):
    """ MySensors serial gateway. """
    # pylint: disable=too-many-arguments

    def __init__(self, port, event_callback=None, persistence=False, baud=115200,
                 timeout=1.0, reconnect_timeout=10.0):
        threading.Thread.__init__(self)
        Gateway.__init__(self, event_callback, persistence)
        self.serial = None
        self.port = port
        self.baud = baud
        self.timeout = timeout
        self.reconnect_timeout = reconnect_timeout
        self._stop_event = threading.Event()

    def connect(self):
        """ Connects to the serial port. """
        if self.serial:
            return True
        try:
            self.serial = serial.Serial(self.port, self.baud,
                                        timeout=self.timeout)
        except serial.SerialException:
            LOGGER.exception('Unable to connect to %s', self.port)
            return False
        return True

    def disconnect(self):
        """ Disconnects from the serial port. """
        if self.serial is not None:
            self.serial.close()
            self.serial = None

    def stop(self):
        """ Stops the background thread. """
        self._stop_event.set()

    def run(self):
        """ Background thread that reads messages from the gateway. """
        while not self._stop_event.is_set():
            if self.serial is None and not self.connect():
                time.sleep(self.reconnect_timeout)
                continue
            try:
                line = self.serial.readline()
                if not line:
                    continue
            except serial.SerialException:
                LOGGER.exception('Serial exception')
                continue
            except TypeError:
                # pyserial has a bug that causes a TypeError to be thrown when
                # the port disconnects instead of a SerialException
                self.disconnect()
                continue
            try:
                msg = line.decode('utf-8')
            except ValueError:
                LOGGER.exception('')
                continue
            response = self.logic(msg)
            if response is not None:
                try:
                    self.send(response.encode())
                except ValueError:
                    LOGGER.exception('Invalid response')
                    continue

    def send(self, message):
        """ Writes a Message to the gateway. """
        self.serial.write(message.encode())

class Sensor:
    """ Represents a sensor. """

    def __init__(self, sensor_id):
        self.sensor_id = sensor_id
        self.children = {}
        self.type = None
        self.sketch_name = None
        self.sketch_version = None
        self.battery_level = 0

    def add_child_sensor(self, child_id, child_type):
        """ Creates and adds a child sensor. """
        self.children[child_id] = ChildSensor(child_id, child_type)

    def set_child_value(self, child_id, value_type, value):
        """ Sets a child sensor's value. """
        if child_id in self.children:
            self.children[child_id].values[value_type] = value
        # TODO: Handle error

class ChildSensor:
    """ Represents a child sensor. """
    # pylint: disable=too-few-public-methods

    def __init__(self, child_id, child_type):
        self.id = child_id
        self.type = child_type
        self.values = {}

class Message:
    """ Represents a message from the gateway. """

    def __init__(self, data=None):
        self.node_id = 0
        self.child_id = 0
        self.type = ""
        self.ack = 0
        self.sub_type = ""
        self.payload = ""
        if data is not None:
            self.decode(data)

    def copy(self, **kwargs):
        """
        Copies a message, optionally replacing attributes with keyword
        arguments.
        """
        msg = Message(self.encode())
        for key, val in kwargs.items():
            setattr(msg, key, val)
        return msg

    def decode(self, data):
        """ Decode a message from command string. """
        data = data.rstrip().split(';')
        self.payload = data.pop()
        (self.node_id,
         self.child_id,
         self.type,
         self.ack,
         self.sub_type) = [int(f) for f in data]

    def encode(self):
        """ Encode a command string from message. """
        return ";".join([str(f) for f in [
            self.node_id,
            self.child_id,
            int(self.type),
            self.ack,
            int(self.sub_type),
            self.payload,
        ]]) + "\n"
<|endoftext|>


<commit_before>import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.db import models
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext_lazy as _

class CommentManager(models.Manager):

    def in_moderation(self):
        """
        QuerySet for all comments currently in the moderation queue.
        """
        return self.get_query_set().filter(status='unmoderated')

    def flagged(self):
        """
        QuerySet for all comments approved with flags.
        """
        return self.get_query_set().filter(status='approved', flag_count__gt=0).order_by('-flag_count')

    def for_model(self, model):
        """
        QuerySet for all comments for a particular model (either an instance or
        a class).
        """
        ct = ContentType.objects.get_for_model(model)
        qs = self.get_query_set().filter(content_type=ct)
        if isinstance(model, models.Model):
            qs = qs.filter(object_id=force_unicode(model._get_pk_val()))
        return qs

COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000)

class Comment(models.Model):
    """
    A user comment about some object.
    """

    # Content-object field
    content_type   = models.ForeignKey(ContentType,
            verbose_name=_('content type'),
            related_name="content_type_set_for_%(class)s")
    object_id      = models.IntegerField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_id")

    user = models.ForeignKey(User, verbose_name=_('user'), related_name="%(class)s_comments")

    title = models.CharField(max_length=300)
    comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)

    # Metadata about the comment
    submit_date = models.DateTimeField(_('date/time submitted'), default=None)
    ip_address  = models.IPAddressField(_('IP address'), blank=True, null=True)
    flag_count  = models.IntegerField(default=0)

    # state of this comment
    status = models.CharField(
        max_length = 20,
        default = 'unmoderated',
        choices = (
            ( 'unmoderated', 'Unmoderated' ),
            ( 'approved',    'Approved'    ),
            ( 'rejected',    'Rejected'    ),
        ),
    )

    # Manager
    objects = CommentManager()

    class Meta:
        ordering = ('-submit_date', )
        verbose_name = _('comment')
        verbose_name_plural = _('comments')
        permissions = [
            ("can_moderate", "Can moderate comments"),
            ("can_post_without_moderation", "Can post comments without moderation"),
        ]

    def __unicode__(self):
        return "%s: %s..." % (self.user, self.comment[:50])

    def get_content_object_url(self):
        """
        Get a URL suitable for redirecting to the content object.
        """
        return urlresolvers.reverse(
            "comments-url-redirect",
            args=(self.content_type_id, self.object_id)
        )

    def save(self, *args, **kwargs):
        if self.submit_date is None:
            self.submit_date = datetime.datetime.now()

        # checks if this is an insert
        if not self.id:
            # Let other code check that the user is set (on insert only)
            if self.user_id:
                # If user is trusted then approve the comment
                if self.user.has_perm('comments2.can_post_without_moderation'):
                    self.status = 'approved'

        super(Comment, self).save(*args, **kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ( 'comments-view', [ self.id ] )

    def approve(self):
        """Mark this comment as 'Approved' and clear any flags on it"""
        self.status = 'approved'
        self.flag_count = 0
        self.save()

    def get_as_text(self):
        """
        Return this comment as plain text.  Useful for emails.
        """
        d = {
            'user': self.user or self.name,
            'date': self.submit_date,
            'comment': self.comment,
            'domain': self.site.domain,
            'url': self.get_absolute_url()
        }
        return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d

class CommentFlag(models.Model):
    """
    Records a flag on a comment. The flag does not mean anything other than that
    a moderator should look at this comment. If a moderator looks at a comment
    and decides it is ok the flags should be deleted from the database. If the
    comment is then flagged again the moderator should reconsider it. If
    comments keep getting flagged and those flags should be ignored then we'll
    need to add something to deal with that.
    """

    user      = models.ForeignKey(User, blank=True, null=True, verbose_name=_('user'), related_name="comment_flags")
    comment   = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags")
    flag_date = models.DateTimeField(_('date'), default=None)

    class Meta:
        unique_together = [('user', 'comment')]
        verbose_name = _('comment flag')
        verbose_name_plural = _('comment flags')

    def __unicode__(self):
        return "Flag of comment ID %s by %s" % (self.comment_id, self.user.username)

    def save(self, *args, **kwargs):
        if self.flag_date is None:
            self.flag_date = datetime.datetime.now()
        super(CommentFlag, self).save(*args, **kwargs)

        # update the comment flag_count
        self.comment.flag_count = models.F('flag_count') + 1
        self.comment.save()
<commit_msg>Handle anonymous users in comment flags - closes #369<commit_after>import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.db import models
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext_lazy as _

class CommentManager(models.Manager):

    def in_moderation(self):
        """
        QuerySet for all comments currently in the moderation queue.
        """
        return self.get_query_set().filter(status='unmoderated')

    def flagged(self):
        """
        QuerySet for all comments approved with flags.
        """
        return self.get_query_set().filter(status='approved', flag_count__gt=0).order_by('-flag_count')

    def for_model(self, model):
        """
        QuerySet for all comments for a particular model (either an instance or
        a class).
        """
        ct = ContentType.objects.get_for_model(model)
        qs = self.get_query_set().filter(content_type=ct)
        if isinstance(model, models.Model):
            qs = qs.filter(object_id=force_unicode(model._get_pk_val()))
        return qs

COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000)

class Comment(models.Model):
    """
    A user comment about some object.
    """

    # Content-object field
    content_type   = models.ForeignKey(ContentType,
            verbose_name=_('content type'),
            related_name="content_type_set_for_%(class)s")
    object_id      = models.IntegerField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_id")

    user = models.ForeignKey(User, verbose_name=_('user'), related_name="%(class)s_comments")

    title = models.CharField(max_length=300)
    comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)

    # Metadata about the comment
    submit_date = models.DateTimeField(_('date/time submitted'), default=None)
    ip_address  = models.IPAddressField(_('IP address'), blank=True, null=True)
    flag_count  = models.IntegerField(default=0)

    # state of this comment
    status = models.CharField(
        max_length = 20,
        default = 'unmoderated',
        choices = (
            ( 'unmoderated', 'Unmoderated' ),
            ( 'approved',    'Approved'    ),
            ( 'rejected',    'Rejected'    ),
        ),
    )

    # Manager
    objects = CommentManager()

    class Meta:
        ordering = ('-submit_date', )
        verbose_name = _('comment')
        verbose_name_plural = _('comments')
        permissions = [
            ("can_moderate", "Can moderate comments"),
            ("can_post_without_moderation", "Can post comments without moderation"),
        ]

    def __unicode__(self):
        return "%s: %s..." % (self.user, self.comment[:50])

    def get_content_object_url(self):
        """
        Get a URL suitable for redirecting to the content object.
        """
        return urlresolvers.reverse(
            "comments-url-redirect",
            args=(self.content_type_id, self.object_id)
        )

    def save(self, *args, **kwargs):
        if self.submit_date is None:
            self.submit_date = datetime.datetime.now()

        # checks if this is an insert
        if not self.id:
            # Let other code check that the user is set (on insert only)
            if self.user_id:
                # If user is trusted then approve the comment
                if self.user.has_perm('comments2.can_post_without_moderation'):
                    self.status = 'approved'

        super(Comment, self).save(*args, **kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ( 'comments-view', [ self.id ] )

    def approve(self):
        """Mark this comment as 'Approved' and clear any flags on it"""
        self.status = 'approved'
        self.flag_count = 0
        self.save()

    def get_as_text(self):
        """
        Return this comment as plain text.  Useful for emails.
        """
        d = {
            'user': self.user or self.name,
            'date': self.submit_date,
            'comment': self.comment,
            'domain': self.site.domain,
            'url': self.get_absolute_url()
        }
        return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d

class CommentFlag(models.Model):
    """
    Records a flag on a comment. The flag does not mean anything other than that
    a moderator should look at this comment. If a moderator looks at a comment
    and decides it is ok the flags should be deleted from the database. If the
    comment is then flagged again the moderator should reconsider it. If
    comments keep getting flagged and those flags should be ignored then we'll
    need to add something to deal with that.
    """

    user      = models.ForeignKey(User, blank=True, null=True, verbose_name=_('user'), related_name="comment_flags")
    comment   = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags")
    flag_date = models.DateTimeField(_('date'), default=None)

    class Meta:
        unique_together = [('user', 'comment')]
        verbose_name = _('comment flag')
        verbose_name_plural = _('comment flags')

    def __unicode__(self):
        if self.user:
            username = self.user.username
        else:
            username = 'anonymous'

        return "Flag of comment ID %s by %s" % (self.comment_id, username)

    def save(self, *args, **kwargs):
        if self.flag_date is None:
            self.flag_date = datetime.datetime.now()
        super(CommentFlag, self).save(*args, **kwargs)

        # update the comment flag_count
        self.comment.flag_count = models.F('flag_count') + 1
        self.comment.save()
<|endoftext|>