<commit_before>#!/usr/bin/env python3
import io
import shutil

key = input("Be sure to run this as root/sudo. Press enter to continue.")
webhook = input("Paste your slack webhook url: ").encode()
filename = "slacknotif"

with io.FileIO("%s" % filename, "w") as file:
    file.write(
"""#!/usr/bin/env python3
import socket
import io
import requests
import json
import sys

def post_to_slack():
    slack_message = "".join(sys.argv)
    slack_username = socket.gethostname()
    payload = {'username': slack_username, 'text': slack_message,}
    requests.post("%s", json=payload)
post_to_slack()""".encode() % webhook)

shutil.move("./slacknotif", "/opt/%s" % filename)<commit_msg>Bug and usability fix.<commit_after>#!/usr/bin/env python3
import io
import shutil

key = input("Be sure to run this as root/sudo. Press enter to continue.")
webhook = input("Paste your slack webhook url: ").encode()
filename = "slacknotif"

with io.FileIO("%s" % filename, "w") as file:
    file.write(
"""#!/usr/bin/env python3
import socket
import io
import requests
import json
import sys

def post_to_slack():
    slack_message = "".join(sys.stdin)
    slack_username = socket.gethostname()
    payload = {'username': slack_username, 'text': slack_message,}
    requests.post("%s", json=payload)
post_to_slack()""".encode() % webhook)

shutil.move("./slacknotif", "/opt/%s" % filename)<|endoftext|>


<commit_before># Copyright 2020 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import api, fields, models

class StockInvoiceOnshipping(models.TransientModel):

    _inherit = 'stock.invoice.onshipping'

    @api.multi
    def _simulate_invoice_line_onchange(self, values, price_unit=None):
        """
        Simulate onchange for invoice line
        :param values: dict
        :return: dict
        """
        new_values = super()._simulate_invoice_line_onchange(
            values.copy(), price_unit=price_unit)
        line = self.env['account.invoice.line'].new(new_values.copy())
        if price_unit:
            line.price_unit = price_unit
            line._compute_price()
        new_values.update(line._convert_to_write(line._cache))
        values.update(new_values)
        return values

    @api.multi
    def _build_invoice_values_from_pickings(self, pickings):
        """
        Build dict to create a new invoice from given pickings
        :param pickings: stock.picking recordset
        :return: dict
        """
        invoice, values = super()._build_invoice_values_from_pickings(pickings)

        pick = fields.first(pickings)
        if pick.sale_id:
            if pick.sale_id.payment_term_id.id != values['payment_term_id']:
                values.update({
                    'payment_term_id': pick.sale_id.payment_term_id.id,
                })

        return invoice, values
<commit_msg>[REM] Unnecessary method.<commit_after># Copyright 2020 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import api, fields, models

class StockInvoiceOnshipping(models.TransientModel):

    _inherit = 'stock.invoice.onshipping'

    @api.multi
    def _build_invoice_values_from_pickings(self, pickings):
        """
        Build dict to create a new invoice from given pickings
        :param pickings: stock.picking recordset
        :return: dict
        """
        invoice, values = super()._build_invoice_values_from_pickings(pickings)

        pick = fields.first(pickings)
        if pick.sale_id:
            if pick.sale_id.payment_term_id.id != values['payment_term_id']:
                values.update({
                    'payment_term_id': pick.sale_id.payment_term_id.id,
                })

        return invoice, values
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import xmlrpclib
import time
from Tkinter import *

def message_window(text):
    ''' Open Standard message for output
    '''
    root = Tk()
    frame = Frame(root)
    frame.pack()
    label = Label(frame, text=text)
    label.pack()
    quitButton = Button(frame, text='OK', command=frame.quit)
    quitButton.pack()
    root.mainloop()

try:
    # -------------------------------------------------------------------------
    # Command parameters:
    # -------------------------------------------------------------------------
    hostname = sys.argv[1]
    port = sys.argv[2]
    launch_command = sys.argv[3]
except:
    text = '''
[INFO]
Launch syntax error, use:
python RCP_call.py <IP RDP Server> <Port RDP Server> <command>
ex.:
python RCP_call.py 192.168.1.100 7000 invoice
'''
    print text
    message_window(text)
    sys.exit()

try:
    # -------------------------------------------------------------------------
    # RDP Operation:
    # -------------------------------------------------------------------------
    sock = xmlrpclib.ServerProxy(
        'http://%s:%s/RPC2' % (hostname, port), allow_none=True)
    reply = sock.execute('batch', {'command': launch_command})
    text = reply.get('comment', '???')
    print text
    if not reply.get('esit', False):
        message_window('[ERROR]\n%s' % text)

except:
    print '[ERROR] Server not reply'
    message_window('[ERROR]\nServer not ready')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>generic bugfix (fast message)<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import xmlrpclib
import time
from Tkinter import *

def message_window(text):
    ''' Open Standard message for output
    '''
    root = Tk()
    frame = Frame(root)
    frame.pack()
    label = Label(frame, text=text)
    label.pack()
    quitButton = Button(frame, text='OK', command=frame.quit)
    quitButton.pack()
    root.mainloop()

try:
    # -------------------------------------------------------------------------
    # Command parameters:
    # -------------------------------------------------------------------------
    hostname = sys.argv[1]
    port = sys.argv[2]
    launch_command = sys.argv[3]
except:
    text = '''
[INFO]
Sintassi errata, utilizzare:
python RCP_call.py <IP RDP Server> <Porta RDP Server> <comando>
ex.:
python RCP_call.py 192.168.1.100 7000 invoice
'''
    print text
    message_window(text)
    sys.exit()

try:
    # -------------------------------------------------------------------------
    # RDP Operation:
    # -------------------------------------------------------------------------
    sock = xmlrpclib.ServerProxy(
        'http://%s:%s/RPC2' % (hostname, port), allow_none=True)
    reply = sock.execute('batch', {'command': launch_command})
    text = reply.get('comment', '???')
    print text
    if not reply.get('esit', False):
        message_window('[ERROR]\n%s' % text)

except:
    text = '[ERROR] Nessuna risposta del server\nverificare il servizio!'
    print text
    message_window(text)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>import logging
from flask import current_app as app
from flask_babel import lazy_gettext
from superdesk import get_resource_service

logger = logging.getLogger(__name__)

def get_default_content_template(item, **kwargs):
    if "dest_desk_id" in kwargs:
        desk = None
        desk_id = kwargs["dest_desk_id"]
    elif "desk" in kwargs:
        desk = kwargs["desk"]
        desk_id = kwargs["desk"]["_id"]
    elif "task" in item and "desk" in item["task"]:
        desk = None
        desk_id = item["task"].get("desk")
    else:
        logger.warning("Can't set default data, no desk identifier found")
        return

    if desk is None:
        desk = get_resource_service("desks").find_one(req=None, _id=desk_id)
    if not desk:
        logger.warning('Can\'t find desk with id "{desk_id}"'.format(desk_id=desk_id))
        return

    content_template_id = desk.get("default_content_template")
    if not content_template_id:
        logger.warning("No default content template set for {desk_name}".format(desk_name=desk.get("name", desk_id)))
        return
    content_template = get_resource_service("content_templates").find_one(req=None, _id=content_template_id)
    if not content_template:
        logger.warning(
            'Can\'t find content_template with id "{content_template_id}"'.format(
                content_template_id=content_template_id
            )
        )
        return

    return content_template

def set_default_template_metadata(item, **kwargs):

    fields_to_exclude = app.config.get("DEFAULT_TEMPLATE_METADATA_MACRO_EXCLUDE", {})
    fields_to_override = app.config.get("DEFAULT_TEMPLATE_METADATA_MACRO_OVERRIDE", {})

    """Replace some metadata from default content template"""

    content_template = get_default_content_template(item, **kwargs)
    if not content_template:
        return

    data = content_template["data"]

    vocabularies = get_resource_service("vocabularies").get(req=None, lookup={"field_type": {"$exists": True}})
    for vocabulary in vocabularies:
        fields_to_exclude.append(vocabulary["_id"])

    for key, value in data.items():
        if (not item.get(key) and key not in fields_to_exclude) or key in fields_to_override:
            item[key] = data.get(key)

    # subject contains remaining metadata to copy
    subject = data.setdefault("subject", [])

    # we first take out the metadata which we want to add, if any
    to_add = []
    for sub in subject:
        if sub.get("scheme") and not any(
            subjects.get("scheme") == sub.get("scheme") for subjects in item.get("subject", [])
        ):
            to_add.append(sub)

    # and now we add the new one
    item.setdefault("subject", []).extend([i for i in to_add if i.get("scheme") and to_add])

    if not item["subject"] and data.get("subject"):
        item["subject"] = data.get("subject")

    return item

name = "Set Default Template Metadata"
label = lazy_gettext("Set Default Template Metadata")
callback = set_default_template_metadata
access_type = "backend"
action_type = "direct"
<commit_msg>fix bug when using default config (#2300)<commit_after>import logging
from flask import current_app as app
from flask_babel import lazy_gettext
from superdesk import get_resource_service

logger = logging.getLogger(__name__)

def get_default_content_template(item, **kwargs):
    if "dest_desk_id" in kwargs:
        desk = None
        desk_id = kwargs["dest_desk_id"]
    elif "desk" in kwargs:
        desk = kwargs["desk"]
        desk_id = kwargs["desk"]["_id"]
    elif "task" in item and "desk" in item["task"]:
        desk = None
        desk_id = item["task"].get("desk")
    else:
        logger.warning("Can't set default data, no desk identifier found")
        return

    if desk is None:
        desk = get_resource_service("desks").find_one(req=None, _id=desk_id)
    if not desk:
        logger.warning('Can\'t find desk with id "{desk_id}"'.format(desk_id=desk_id))
        return

    content_template_id = desk.get("default_content_template")
    if not content_template_id:
        logger.warning("No default content template set for {desk_name}".format(desk_name=desk.get("name", desk_id)))
        return
    content_template = get_resource_service("content_templates").find_one(req=None, _id=content_template_id)
    if not content_template:
        logger.warning(
            'Can\'t find content_template with id "{content_template_id}"'.format(
                content_template_id=content_template_id
            )
        )
        return

    return content_template

def set_default_template_metadata(item, **kwargs):

    fields_to_exclude = app.config.get("DEFAULT_TEMPLATE_METADATA_MACRO_EXCLUDE", [])
    fields_to_override = app.config.get("DEFAULT_TEMPLATE_METADATA_MACRO_OVERRIDE", [])

    """Replace some metadata from default content template"""

    content_template = get_default_content_template(item, **kwargs)
    if not content_template:
        return

    data = content_template["data"]

    vocabularies = get_resource_service("vocabularies").get(req=None, lookup={"field_type": {"$exists": True}})
    for vocabulary in vocabularies:
        fields_to_exclude.append(vocabulary["_id"])

    for key, value in data.items():
        if (not item.get(key) and key not in fields_to_exclude) or key in fields_to_override:
            item[key] = data.get(key)

    # subject contains remaining metadata to copy
    subject = data.setdefault("subject", [])

    # we first take out the metadata which we want to add, if any
    to_add = []
    for sub in subject:
        if sub.get("scheme") and not any(
            subjects.get("scheme") == sub.get("scheme") for subjects in item.get("subject", [])
        ):
            to_add.append(sub)

    # and now we add the new one
    item.setdefault("subject", []).extend([i for i in to_add if i.get("scheme") and to_add])

    if not item["subject"] and data.get("subject"):
        item["subject"] = data.get("subject")

    return item

name = "Set Default Template Metadata"
label = lazy_gettext("Set Default Template Metadata")
callback = set_default_template_metadata
access_type = "backend"
action_type = "direct"
<|endoftext|>


<commit_before># Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function, division, absolute_import

import unittest
from robofab.world import RFont

from glyphs2ufo import torf
from glyphs2ufo.torf import set_redundant_data

_warnings = []

def _add_warning(message):
    global _warnings
    _warnings.append(message)

def _check_warnings():
    global _warnings
    checked = list(_warnings)
    _warnings = []
    return checked

class SetRedundantDataTest(unittest.TestCase):
    def _run_on_ufo(self, family_name, style_name):
        ufo = RFont()
        ufo.info.familyName = family_name
        ufo.info.styleName = style_name
        set_redundant_data(ufo)
        return ufo

    def test_sets_regular_weight_class_for_missing_weight(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        self.assertEquals(
            reg_ufo.info.openTypeOS2WeightClass,
            italic_ufo.info.openTypeOS2WeightClass)

    def test_sets_regular_weight_class_and_warns_for_unknown_weight(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        bogus_ufo = self._run_on_ufo('MyFont', 'abc123')
        self.assertEquals(
            reg_ufo.info.openTypeOS2WeightClass,
            bogus_ufo.info.openTypeOS2WeightClass)
        self.assertTrue(_check_warnings())

    def test_sets_weight_lib_entry_only_nonregular(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        thin_ufo = self._run_on_ufo('MyFont', 'Thin')
        self.assertFalse(reg_ufo.lib)
        self.assertFalse(italic_ufo.lib)
        self.assertTrue(thin_ufo.lib)

    def test_sets_width_lib_entry_only_condensed(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        cond_ufo = self._run_on_ufo('MyFont Condensed', 'Regular')
        semicond_ufo = self._run_on_ufo('MyFont SemiCondensed', 'Regular')
        self.assertFalse(reg_ufo.lib)
        self.assertFalse(italic_ufo.lib)
        self.assertTrue(cond_ufo.lib)
        self.assertTrue(semicond_ufo.lib)

    def _run_style_map_names_test(self, args):
        for family, style, expected_family, expected_style in args:
            ufo = self._run_on_ufo(family, style)
            self.assertEquals(ufo.info.styleMapFamilyName, expected_family)
            self.assertEquals(ufo.info.styleMapStyleName, expected_style)

    def test_sets_legal_style_map_names(self):
        self._run_style_map_names_test((
            ('MyFont', '', 'MyFont', 'regular'),
            ('MyFont', 'Regular', 'MyFont', 'regular'),
            ('MyFont', 'Bold', 'MyFont', 'bold'),
            ('MyFont', 'Italic', 'MyFont', 'italic'),
            ('MyFont', 'Bold Italic', 'MyFont', 'bold italic'),
            ('MyFont Condensed', '', 'MyFont Condensed', 'regular'),
            ('MyFont Condensed', 'Regular', 'MyFont Condensed', 'regular'),
            ('MyFont Condensed', 'Bold', 'MyFont Condensed', 'bold'),
            ('MyFont Condensed', 'Italic', 'MyFont Condensed', 'italic'),
            ('MyFont Condensed', 'Bold Italic', 'MyFont Condensed',
             'bold italic')))

    def test_moves_nonbold_weight_to_family(self):
        self._run_style_map_names_test((
            ('MyFont', 'Thin', 'MyFont Thin', 'regular'),
            ('MyFont', 'Thin Italic', 'MyFont Thin', 'italic'),
            ('MyFont Condensed', 'Thin', 'MyFont Condensed Thin', 'regular'),
            ('MyFont Condensed', 'Thin Italic', 'MyFont Condensed Thin',
             'italic')))

if __name__ == '__main__':
    torf.warn = _add_warning
    unittest.main()
<commit_msg>Add more unit tests for torf's public functions<commit_after># Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function, division, absolute_import

import unittest
from robofab.world import RFont

from glyphs2ufo import torf
from glyphs2ufo.torf import set_redundant_data, build_family_name, build_style_name, build_postscript_name

_warnings = []

def _add_warning(message):
    global _warnings
    _warnings.append(message)

def _check_warnings():
    global _warnings
    checked = list(_warnings)
    _warnings = []
    return checked

class BuildNameTest(unittest.TestCase):
    def test_family_regular_width(self):
        self.assertEquals(build_family_name('MyFont', {}, 'width'), 'MyFont')

    def test_family_nonregular_width(self):
        self.assertEquals(
            build_family_name('MyFont', {'width': 'Condensed'}, 'width'),
            'MyFont Condensed')

    def test_style_regular_weight(self):
        self.assertEquals(build_style_name({}, 'weight', False), 'Regular')
        self.assertEquals(build_style_name({}, 'weight', True), 'Italic')
        self.assertEquals(build_style_name(
            {'weight': 'Regular'}, 'weight', True), 'Italic')

    def test_style_nonregular_weight(self):
        self.assertEquals(
            build_style_name({'weight': 'Thin'}, 'weight', False), 'Thin')
        self.assertEquals(
            build_style_name({'weight': 'Thin'}, 'weight', True), 'Thin Italic')

    def test_postscript(self):
        self.assertEquals(
            build_postscript_name('MyFont', 'Regular'), 'MyFont-Regular')
        self.assertEquals(
            build_postscript_name('MyFont Condensed', 'Thin Italic'),
            'MyFontCondensed-ThinItalic')

class SetRedundantDataTest(unittest.TestCase):
    def _run_on_ufo(self, family_name, style_name):
        ufo = RFont()
        ufo.info.familyName = family_name
        ufo.info.styleName = style_name
        set_redundant_data(ufo)
        return ufo

    def test_sets_regular_weight_class_for_missing_weight(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        self.assertEquals(
            reg_ufo.info.openTypeOS2WeightClass,
            italic_ufo.info.openTypeOS2WeightClass)

    def test_sets_regular_weight_class_and_warns_for_unknown_weight(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        bogus_ufo = self._run_on_ufo('MyFont', 'abc123')
        self.assertEquals(
            reg_ufo.info.openTypeOS2WeightClass,
            bogus_ufo.info.openTypeOS2WeightClass)
        self.assertTrue(_check_warnings())

    def test_sets_weight_lib_entry_only_nonregular(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        thin_ufo = self._run_on_ufo('MyFont', 'Thin')
        self.assertFalse(reg_ufo.lib)
        self.assertFalse(italic_ufo.lib)
        self.assertTrue(thin_ufo.lib)

    def test_sets_width_lib_entry_only_condensed(self):
        reg_ufo = self._run_on_ufo('MyFont', 'Regular')
        italic_ufo = self._run_on_ufo('MyFont', 'Italic')
        cond_ufo = self._run_on_ufo('MyFont Condensed', 'Regular')
        semicond_ufo = self._run_on_ufo('MyFont SemiCondensed', 'Regular')
        self.assertFalse(reg_ufo.lib)
        self.assertFalse(italic_ufo.lib)
        self.assertTrue(cond_ufo.lib)
        self.assertTrue(semicond_ufo.lib)

    def _run_style_map_names_test(self, args):
        for family, style, expected_family, expected_style in args:
            ufo = self._run_on_ufo(family, style)
            self.assertEquals(ufo.info.styleMapFamilyName, expected_family)
            self.assertEquals(ufo.info.styleMapStyleName, expected_style)

    def test_sets_legal_style_map_names(self):
        self._run_style_map_names_test((
            ('MyFont', '', 'MyFont', 'regular'),
            ('MyFont', 'Regular', 'MyFont', 'regular'),
            ('MyFont', 'Bold', 'MyFont', 'bold'),
            ('MyFont', 'Italic', 'MyFont', 'italic'),
            ('MyFont', 'Bold Italic', 'MyFont', 'bold italic'),
            ('MyFont Condensed', '', 'MyFont Condensed', 'regular'),
            ('MyFont Condensed', 'Regular', 'MyFont Condensed', 'regular'),
            ('MyFont Condensed', 'Bold', 'MyFont Condensed', 'bold'),
            ('MyFont Condensed', 'Italic', 'MyFont Condensed', 'italic'),
            ('MyFont Condensed', 'Bold Italic', 'MyFont Condensed',
             'bold italic')))

    def test_moves_nonbold_weight_to_family(self):
        self._run_style_map_names_test((
            ('MyFont', 'Thin', 'MyFont Thin', 'regular'),
            ('MyFont', 'Thin Italic', 'MyFont Thin', 'italic'),
            ('MyFont Condensed', 'Thin', 'MyFont Condensed Thin', 'regular'),
            ('MyFont Condensed', 'Thin Italic', 'MyFont Condensed Thin',
             'italic')))

if __name__ == '__main__':
    torf.warn = _add_warning
    unittest.main()
<|endoftext|>


<commit_before>import json
import logging

from aiohttp import web

from ..utils import _err, _json
from ..snowflake import get_snowflake
from ..ratelimits import ratelimit

log = logging.getLogger(__name__)

class ChannelsEndpoint:
    """Handle channel/message related endpoints"""
    def __init__(self, server):
        self.server = server

    def register(self, app):

        self.server.add_get('channels/{channel_id}', self.h_get_channel)

        self.server.add_get('channels/{channel_id}/messages', self.h_get_messages)
        self.server.add_get('channels/{channel_id}/messages/{message_id}', self.h_get_single_message)

        self.server.add_post('channels/{channel_id}/messages', self.h_post_message)
        self.server.add_patch('channels/{channel_id}/messages/{message_id}',
                       self.h_patch_message)

        self.server.add_delete('channels/{channel_id}/messages/{message_id}',
                        self.h_delete_message)

        self.server.add_post('channels/{channel_id}/typing', self.h_post_typing)

        # Fill /assets with the good shit
        #app.router.add_get('/channels/@me', self.meme)
        #app.router.add_static('/assets', '~/lkmnds.github/litecord/litecord/_assets')

    async def meme(self, request):
        return web.FileResponse('/home/luna/lkmnds.github/litecord/litecord/_assets/channels/@me/index.html')

    async def h_get_channel(self, request):
        """`GET /channels/{channel_id}`.

        Returns a channel object
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)
        if channel is None:
            return _err(errno=10003)

        guild = channel.guild

        if user.id not in guild.members:
            return _err('401: Unauthorized')

        return _json(channel.as_json)

    async def h_post_typing(self, request):
        """`POST /channels/{channel_id}/typing`.

        Dispatches TYPING_START events to relevant clients.
        Returns a HTTP empty response with status code 204.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)
        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        await self.server.presence.typing_start(user.id, channel_id)
        return web.Response(status=204)

    @ratelimit(5, 5)
    async def h_post_message(self, request):
        """`POST /channels/{channel_id}/messages/`.

        Send a message.
        Dispatches MESSAGE_CREATE events to relevant clients.
        """

        try:
            print('ctype', request.content_type)
        except Exception as err:
            print(f'rip {err!r}')
            pass

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        try:
            payload = await request.json()
        except:
            return _err("error parsing")

        try:
            content = payload['content']
            if len(content) < 1:
                return _err(errno=50006)

            if len(content) > 2000:
                return web.response(status=400)
        except:
            return _err('no useful content provided')

        #tts = payload.get('tts', False)

        _data = {
            'id': get_snowflake(),
            'author_id': user.id,
            'content': content,
        }

        new_message = await self.server.guild_man.new_message(channel, user, _data)
        return _json(new_message.as_json)

    async def h_get_single_message(self, request):
        """`GET /channels/{channel_id}/messages/{message_id}`.

        Get a single message by its snowflake ID.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        return _json(message.as_json)

    @ratelimit(5, 5)
    async def h_get_messages(self, request):
        """`GET /channels/{channel_id}/messages`.

        Returns a list of messages.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        log.info("{request!r}")
        channel_id = request.match_info['channel_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        limit = request.query.get('limit', 50)

        try:
            limit = int(limit)
        except:
            return _err('limit is not a integer')

        if not ((limit >= 1) and (limit <= 100)):
            return _err(f'limit not in 1-100 range, {limit}')

        around = request.query.get('around', -1)
        before = request.query.get('before', -1)
        after = request.query.get('after', -1)

        try:
            around = int(around)
            before = int(before)
            after = int(after)
        except:
            return _err('parameters are not integers')

        message_list = await channel.last_messages(limit)

        if around != -1:
            avg = int(limit / 2)
            before = around + avg
            after = around - avg

            message_list = [m for m in message_list if (m.id < before) and (m.id > after)]

        elif before != -1:
            message_list = [m for m in message_list if (m.id < before)]

        elif after != -1:
            message_list = [m for m in message_list if (m.id > after)]

        return _json([m.as_json for m in message_list])

    async def h_delete_message(self, request):
        """`DELETE /channels/{channel_id}/messages/{message_id}`.

        Delete a message sent by the user.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        if user.id != message.author.id:
            return _err(errno=40001)

        await self.server.guild_man.delete_message(message)
        return web.Response(status=204)

    async def h_patch_message(self, request):
        """`PATCH /channels/{channel_id}/messages/{message_id}`.

        Update a message sent by the current user.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        if user.id != message.author.id:
            return _err(errno=50005)

        try:
            payload = await request.json()
        except:
            return _err("error parsing")

        _data = {
            'content': payload.get('content', None)
        }

        if _data['content'] is None:
            return _err('Erroneous payload')

        await self.server.guild_man.edit_message(message, _data)
        return _json(message.as_json)
<commit_msg>api.channels: Remove unecessary logging line<commit_after>import json
import logging

from aiohttp import web

from ..utils import _err, _json
from ..snowflake import get_snowflake
from ..ratelimits import ratelimit

log = logging.getLogger(__name__)

class ChannelsEndpoint:
    """Handle channel/message related endpoints"""
    def __init__(self, server):
        self.server = server

    def register(self, app):

        self.server.add_get('channels/{channel_id}', self.h_get_channel)

        self.server.add_get('channels/{channel_id}/messages', self.h_get_messages)
        self.server.add_get('channels/{channel_id}/messages/{message_id}', self.h_get_single_message)

        self.server.add_post('channels/{channel_id}/messages', self.h_post_message)
        self.server.add_patch('channels/{channel_id}/messages/{message_id}',
                       self.h_patch_message)

        self.server.add_delete('channels/{channel_id}/messages/{message_id}',
                        self.h_delete_message)

        self.server.add_post('channels/{channel_id}/typing', self.h_post_typing)

        # Fill /assets with the good shit
        #app.router.add_get('/channels/@me', self.meme)
        #app.router.add_static('/assets', '~/lkmnds.github/litecord/litecord/_assets')

    async def meme(self, request):
        return web.FileResponse('/home/luna/lkmnds.github/litecord/litecord/_assets/channels/@me/index.html')

    async def h_get_channel(self, request):
        """`GET /channels/{channel_id}`.

        Returns a channel object
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)
        if channel is None:
            return _err(errno=10003)

        guild = channel.guild

        if user.id not in guild.members:
            return _err('401: Unauthorized')

        return _json(channel.as_json)

    async def h_post_typing(self, request):
        """`POST /channels/{channel_id}/typing`.

        Dispatches TYPING_START events to relevant clients.
        Returns a HTTP empty response with status code 204.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)
        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        await self.server.presence.typing_start(user.id, channel_id)
        return web.Response(status=204)

    @ratelimit(5, 5)
    async def h_post_message(self, request):
        """`POST /channels/{channel_id}/messages/`.

        Send a message.
        Dispatches MESSAGE_CREATE events to relevant clients.
        """

        try:
            print('ctype', request.content_type)
        except Exception as err:
            print(f'rip {err!r}')
            pass

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])

        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        try:
            payload = await request.json()
        except:
            return _err("error parsing")

        try:
            content = payload['content']
            if len(content) < 1:
                return _err(errno=50006)

            if len(content) > 2000:
                return web.response(status=400)
        except:
            return _err('no useful content provided')

        #tts = payload.get('tts', False)

        _data = {
            'id': get_snowflake(),
            'author_id': user.id,
            'content': content,
        }

        new_message = await self.server.guild_man.new_message(channel, user, _data)
        return _json(new_message.as_json)

    async def h_get_single_message(self, request):
        """`GET /channels/{channel_id}/messages/{message_id}`.

        Get a single message by its snowflake ID.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        return _json(message.as_json)

    @ratelimit(5, 5)
    async def h_get_messages(self, request):
        """`GET /channels/{channel_id}/messages`.

        Returns a list of messages.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        limit = request.query.get('limit', 50)

        try:
            limit = int(limit)
        except:
            return _err('limit is not a integer')

        if not ((limit >= 1) and (limit <= 100)):
            return _err(f'limit not in 1-100 range, {limit}')

        around = request.query.get('around', -1)
        before = request.query.get('before', -1)
        after = request.query.get('after', -1)

        try:
            around = int(around)
            before = int(before)
            after = int(after)
        except:
            return _err('parameters are not integers')

        message_list = await channel.last_messages(limit)

        if around != -1:
            avg = int(limit / 2)
            before = around + avg
            after = around - avg

            message_list = [m for m in message_list if (m.id < before) and (m.id > after)]

        elif before != -1:
            message_list = [m for m in message_list if (m.id < before)]

        elif after != -1:
            message_list = [m for m in message_list if (m.id > after)]

        return _json([m.as_json for m in message_list])

    async def h_delete_message(self, request):
        """`DELETE /channels/{channel_id}/messages/{message_id}`.

        Delete a message sent by the user.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        if user.id != message.author.id:
            return _err(errno=40001)

        await self.server.guild_man.delete_message(message)
        return web.Response(status=204)

    async def h_patch_message(self, request):
        """`PATCH /channels/{channel_id}/messages/{message_id}`.

        Update a message sent by the current user.
        """

        _error = await self.server.check_request(request)
        _error_json = json.loads(_error.text)
        if _error_json['code'] == 0:
            return _error

        channel_id = request.match_info['channel_id']
        message_id = request.match_info['message_id']

        user = self.server._user(_error_json['token'])
        channel = self.server.guild_man.get_channel(channel_id)

        if channel is None:
            return _err(errno=10003)

        if user.id not in channel.guild.members:
            return _err(errno=40001)

        message = channel.get_message(message_id)
        if message is None:
            return _err(errno=10008)

        if user.id != message.author.id:
            return _err(errno=50005)

        try:
            payload = await request.json()
        except:
            return _err("error parsing")

        _data = {
            'content': payload.get('content', None)
        }

        if _data['content'] is None:
            return _err('Erroneous payload')

        await self.server.guild_man.edit_message(message, _data)
        return _json(message.as_json)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import win32service
import win32serviceutil
import win32event
import servicemanager
import time

import webservice
import xmlrpclib
import ConfigParser

from datetime import datetime

class PySvc(win32serviceutil.ServiceFramework):
    ''' Class for manage Microsoft Service
    '''
    # -------------------------------------------------------------------------
    #                                  INSTANCE DATA:
    # -------------------------------------------------------------------------
    # Service name (use with net start / stop
    _svc_name_ = 'Micronaet Listener Service'

    # Service name in Service Control Manager (SCM)
    _svc_display_name_ = 'Micronaet Web Service'

    # Help text in SCM
    _svc_description_ = 'This service open a XMLRPC listner for remote call'

    # -------------------------------------------------------------------------
    #                                  PRIVATE METHOD:
    # -------------------------------------------------------------------------
    def _create_setup_file(self, ):
        ''' Create config file if not present in data path
        '''
        if not os.path.isfile(self._setup_file):
            setup_file = open(self._setup_file, 'w')
            setup_file.write('[XMLRPC]%shost: 0.0.0.0%sport: 7000' % (
                self._return,
                self._return,
                ))
            setup_file.close()
            self._log_data('Create empty config file: %s%s' % (
                self._setup_file, self._return))
        return True

    def _log_data(self, event, mode='INFO', registry='activity'):
        ''' Log data on file:
        '''
        # ---------------------------------------------------------------------
        # Chose log registry file:
        # ---------------------------------------------------------------------
        if registry == 'activity':
            if not self._file_activity:
                # Open log file for service session:
                self._file_activity = open(self._log_activity, 'a+')
            current_log = self._file_activity
        else: # service registry
            if not self._file_service:
                # Open log file for service session:
                self._file_service = open(self._log_service, 'a+')
            current_log = self._file_service

        # ---------------------------------------------------------------------
        # Write event:
        # ---------------------------------------------------------------------
        current_log.write('%s. [%s] %s%s' % (
            datetime.now(),
            mode.upper(),
            event,
            self._return,
            ))
        current_log.flush()
        return True

    def _init(self, ):
        ''' Initial setup (launched both init and start service)
        '''
        # ---------------------------------------------------------------------
        # Parameters:
        # ---------------------------------------------------------------------
        # Return:
        self._return = '\r\n'

        # Root folder:
        self._root_path = 'C:\\Micronaet\\Micronaet Listener Service' # TODO
        #self._root_path = os.path.join(
        #    'C:\\',
        #    'Micronaet',
        #    self._svc_name_,
        #    ))

        print 'Root folder: %s' % self._root_path

        # Configuration:
        self._setup_file = os.path.join(self._root_path, 'service.cfg')
        print 'Config file: %s' % self._setup_file

        self._webserver_command = 'start %s "%s"' % (
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                'webservice.py',
                ),
            self._setup_file,
            )
        print 'Web Server: %s' % self._webserver_command

        # Log:
        self._log_path = os.path.join(self._root_path, 'log')
        self._log_service = os.path.join(self._log_path, 'service.log')
        self._log_activity = os.path.join(self._log_path, 'activity.log')
        print 'Log file Service: %s Activity: %s' % (
            self._log_service,
            self._log_activity,
            )

        # Handle file:
        self._file_service = False
        self._file_activity = False

        # Millisecond for waiting:
        self._wait_ms = 5000

        # Create path if not present:
        try:
            os.system('mkdir "%s"' % self._log_path) # create also root folder
        except:
            print 'Error creating folder structure: %s' % self._log_path

        # ---------------------------------------------------------------------
        # Config file:
        # ---------------------------------------------------------------------
        # Create empty if not present:
        self._create_setup_file()

        # Read from config file port used from XMLRPC:
        config = ConfigParser.ConfigParser()
        config.read([self._setup_file])
        self._xmlrpc_port = eval(config.get('XMLRPC', 'port'))

        # XMLRPC server:
        self._xmlrpc_address = 'http://localhost:%s/RPC2' % self._xmlrpc_port

        # ---------------------------------------------------------------------
        # Log install event:
        # ---------------------------------------------------------------------
        self._log_data(
            'Instance %s%s    Log path: %s%s    Config: %s [localhost:%s]' % (
                self._svc_name_, self._return, self._log_path,
                self._return, self._setup_file, self._xmlrpc_port),
                registry='service',
                )
        self._log_data('Web Server command: %s' % self._webserver_command)

    # -------------------------------------------------------------------------
    #                            CONSTRUCTOR:
    # -------------------------------------------------------------------------
    def __init__(self, args):
        ''' Constructor, init method
        '''
        # Setup instance:
        self._init()

        # ---------------------------------------------------------------------
        # Windows intallation:
        # ---------------------------------------------------------------------
        # Launch ancherstor init procedure:
        win32serviceutil.ServiceFramework.__init__(self, args)

        # create an event to listen for stop requests on
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    # -------------------------------------------------------------------------
    #                            PUBLIC METHODS:
    # -------------------------------------------------------------------------
    def SvcDoRun(self):
        ''' Start service method
        '''
        # Reload instance:
        self._init()

        # Log operation:
        self._log_data('Start RPC Service', registry='service')

        # START WEBSERVICE:
        os.system(self._webserver_command) # Launch indipendent task:

        # RUNNING LOOP:
        # If the stop event hasn't been fired keep looping
        check_every = 2 # 20 times
        i = 0

        self._sock = False
        response = None
        while response != win32event.WAIT_OBJECT_0:
            i += 1

            # Check working service:
            if i > check_every:
                try:
                    i = 0
                    if not self._sock:
                        self._sock = xmlrpclib.ServerProxy(
                            self._xmlrpc_address, allow_none=True)
                    self._sock.execute('ping') # Check operation
                    self._log_data('Server is up') # TODO remove
                except:
                    self._log_data('Server is down from remote')
                    #os.system('net stop %s' % self._svc_name_) # is better mode?

            # Stop for X millisecond and listen for stop event
            response = win32event.WaitForSingleObject(
                self.hWaitStop,
                self._wait_ms,
                )

    def SvcStop(self):
        ''' Shutting down service:
        '''
        # ---------------------------------------------------------------------
        #                          STOP OPERATION:
        # ---------------------------------------------------------------------
        # Terminate web server:
        try:
            sock = xmlrpclib.ServerProxy(
                self._xmlrpc_address,
                allow_none=True,
                )
            sock.remote_shutdown()
            time.sleep(1)

            self._log_data(
                'Shutdown RPC Service %s' % self._xmlrpc_address,
                registry='service',
                )
        except:
            self._log_data(
                'Cannot stop RPC: %s [%s]' % (
                    self._xmlrpc_address,
                    sys.exc_info()),
                mode='error',
                registry='service',
                )

        # Close log file
        try:
            self._file_service.close()
        except:
            pass # Service unavailable
        try:
            self._file_activity.close()
        except:
            pass # Service unavailable

        # Service stop part:
        try:
            # Tell the SCM shutting down event:
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

            # Raise the stop event
            win32event.SetEvent(self.hWaitStop)
        except:
            pass # Service unavailable

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(PySvc)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>generic bugfix (fast message)<commit_after># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import win32service
import win32serviceutil
import win32event
import servicemanager
import time

import webservice
import xmlrpclib
import ConfigParser

from datetime import datetime

class PySvc(win32serviceutil.ServiceFramework):
    ''' Class for manage Microsoft Service
    '''
    # -------------------------------------------------------------------------
    #                                  INSTANCE DATA:
    # -------------------------------------------------------------------------
    # Service name (use with net start / stop
    _svc_name_ = 'Micronaet Listener Service'

    # Service name in Service Control Manager (SCM)
    _svc_display_name_ = 'Micronaet Web Service'

    # Help text in SCM
    _svc_description_ = 'This service open a XMLRPC listner for remote call'

    # -------------------------------------------------------------------------
    #                                  PRIVATE METHOD:
    # -------------------------------------------------------------------------
    def _create_setup_file(self, ):
        ''' Create config file if not present in data path
        '''
        if not os.path.isfile(self._setup_file):
            setup_file = open(self._setup_file, 'w')
            setup_file.write('[XMLRPC]%shost: 0.0.0.0%sport: 7000' % (
                self._return,
                self._return,
                ))
            setup_file.close()
            self._log_data('Create empty config file: %s%s' % (
                self._setup_file, self._return))
        return True

    def _log_data(self, event, mode='INFO', registry='activity'):
        ''' Log data on file:
        '''
        # ---------------------------------------------------------------------
        # Chose log registry file:
        # ---------------------------------------------------------------------
        if registry == 'activity':
            if not self._file_activity:
                # Open log file for service session:
                self._file_activity = open(self._log_activity, 'a+')
            current_log = self._file_activity
        else: # service registry
            if not self._file_service:
                # Open log file for service session:
                self._file_service = open(self._log_service, 'a+')
            current_log = self._file_service

        # ---------------------------------------------------------------------
        # Write event:
        # ---------------------------------------------------------------------
        current_log.write('%s. [%s] %s%s' % (
            datetime.now(),
            mode.upper(),
            event,
            self._return,
            ))
        current_log.flush()
        return True

    def _init(self, ):
        ''' Initial setup (launched both init and start service)
        '''
        # ---------------------------------------------------------------------
        # Parameters:
        # ---------------------------------------------------------------------
        # Return:
        self._return = '\r\n'

        # Root folder:
        self._root_path = 'C:\\Micronaet\\Micronaet Listener Service' # TODO
        #self._root_path = os.path.join(
        #    'C:\\',
        #    'Micronaet',
        #    self._svc_name_,
        #    ))

        print 'Root folder: %s' % self._root_path

        # Configuration:
        self._setup_file = os.path.join(self._root_path, 'service.cfg')
        print 'Config file: %s' % self._setup_file

        self._webserver_command = 'start %s "%s"' % (
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                'webservice.py',
                ),
            self._setup_file,
            )
        print 'Web Server: %s' % self._webserver_command

        # Log:
        self._log_path = os.path.join(self._root_path, 'log')
        self._log_service = os.path.join(self._log_path, 'service.log')
        self._log_activity = os.path.join(self._log_path, 'activity.log')
        print 'Log file Service: %s Activity: %s' % (
            self._log_service,
            self._log_activity,
            )

        # Handle file:
        self._file_service = False
        self._file_activity = False

        # Millisecond for waiting:
        self._wait_ms = 5000

        # Create path if not present:
        try:
            os.system('mkdir "%s"' % self._log_path) # create also root folder
        except:
            print 'Error creating folder structure: %s' % self._log_path

        # ---------------------------------------------------------------------
        # Config file:
        # ---------------------------------------------------------------------
        # Create empty if not present:
        self._create_setup_file()

        # Read from config file port used from XMLRPC:
        config = ConfigParser.ConfigParser()
        config.read([self._setup_file])
        self._xmlrpc_port = eval(config.get('XMLRPC', 'port'))

        # XMLRPC server:
        self._xmlrpc_address = 'http://localhost:%s/RPC2' % self._xmlrpc_port

        # ---------------------------------------------------------------------
        # Log install event:
        # ---------------------------------------------------------------------
        self._log_data(
            'Instance %s%s    Log path: %s%s    Config: %s [localhost:%s]' % (
                self._svc_name_, self._return, self._log_path,
                self._return, self._setup_file, self._xmlrpc_port),
                registry='service',
                )
        self._log_data('Web Server command: %s' % self._webserver_command)

    # -------------------------------------------------------------------------
    #                            CONSTRUCTOR:
    # -------------------------------------------------------------------------
    def __init__(self, args):
        ''' Constructor, init method
        '''
        # Setup instance:
        self._init()

        # ---------------------------------------------------------------------
        # Windows intallation:
        # ---------------------------------------------------------------------
        # Launch ancherstor init procedure:
        win32serviceutil.ServiceFramework.__init__(self, args)

        # create an event to listen for stop requests on
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    # -------------------------------------------------------------------------
    #                            PUBLIC METHODS:
    # -------------------------------------------------------------------------
    def SvcDoRun(self):
        ''' Start service method
        '''
        # Reload instance:
        self._init()

        # Log operation:
        self._log_data('Start RPC Service', registry='service')

        # START WEBSERVICE:
        os.system(self._webserver_command) # Launch indipendent task:

        # RUNNING LOOP:
        # If the stop event hasn't been fired keep looping
        check_every = 2 # 20 times
        i = 0

        self._sock = False
        response = None
        while response != win32event.WAIT_OBJECT_0:
            i += 1

            # Check working service:
            if i > check_every:
                try:
                    i = 0
                    if not self._sock:
                        self._sock = xmlrpclib.ServerProxy(
                            self._xmlrpc_address, allow_none=True)
                    self._sock.execute('ping') # Check operation
                    self._log_data('Server is up') # TODO remove
                except:
                    self._log_data('Server is down from remote %s' % (
                        sys.exc_info()
                        ))
                    #os.system('net stop %s' % self._svc_name_) # is better mode?

            # Stop for X millisecond and listen for stop event
            response = win32event.WaitForSingleObject(
                self.hWaitStop,
                self._wait_ms,
                )

    def SvcStop(self):
        ''' Shutting down service:
        '''
        # ---------------------------------------------------------------------
        #                          STOP OPERATION:
        # ---------------------------------------------------------------------
        # Terminate web server:
        try:
            sock = xmlrpclib.ServerProxy(
                self._xmlrpc_address,
                allow_none=True,
                )
            sock.remote_shutdown()
            time.sleep(1)

            self._log_data(
                'Shutdown RPC Service %s' % self._xmlrpc_address,
                registry='service',
                )
        except:
            self._log_data(
                'Cannot stop RPC: %s [%s]' % (
                    self._xmlrpc_address,
                    sys.exc_info()),
                mode='error',
                registry='service',
                )

        # Close log file
        try:
            self._file_service.close()
        except:
            pass # Service unavailable
        try:
            self._file_activity.close()
        except:
            pass # Service unavailable

        # Service stop part:
        try:
            # Tell the SCM shutting down event:
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

            # Raise the stop event
            win32event.SetEvent(self.hWaitStop)
        except:
            pass # Service unavailable

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(PySvc)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>#!/usr/bin/env python

'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__all__ = ["RMFTestCase", "Template", "StaticFile", "InlineTemplate","UnknownConfigurationMock"]

from unittest import TestCase
import json
import os
import imp
import sys
import pprint
from mock.mock import MagicMock, patch
from resource_management.core.environment import Environment
from resource_management.libraries.script.config_dictionary import ConfigDictionary
from resource_management.libraries.script.script import Script
from resource_management.libraries.script.config_dictionary import UnknownConfiguration
import platform

PATH_TO_STACKS = os.path.normpath("main/resources/stacks/HDP")
PATH_TO_STACK_TESTS = os.path.normpath("test/python/stacks/")

class RMFTestCase(TestCase):
  def executeScript(self, path, classname=None, command=None, config_file=None,
                    # common mocks for all the scripts
                    config_overrides = None,
                    shell_mock_value = (0, "OK."),
                    os_type=('Suse','11','Final'),
                    kinit_path_local="/usr/bin/kinit"
                    ):
    norm_path = os.path.normpath(path)
    src_dir = RMFTestCase._getSrcFolder()
    stack_version = norm_path.split(os.sep)[0]
    stacks_path = os.path.join(src_dir, PATH_TO_STACKS)
    configs_path = os.path.join(src_dir, PATH_TO_STACK_TESTS, stack_version, "configs")
    script_path = os.path.join(stacks_path, norm_path)
    config_file_path = os.path.join(configs_path, config_file)

    try:
      with open(config_file_path, "r") as f:
        self.config_dict = json.load(f)
    except IOError:
      raise RuntimeError("Can not read config file: "+ config_file_path)

    if config_overrides:
      for key, value in config_overrides.iteritems():
        self.config_dict[key] = value

    self.config_dict = ConfigDictionary(self.config_dict)

    # append basedir to PYTHONPATH
    scriptsdir = os.path.dirname(script_path)
    basedir = os.path.dirname(scriptsdir)
    sys.path.append(scriptsdir)

    # get method to execute
    try:
      with patch.object(platform, 'linux_distribution', return_value=os_type):
        script_module = imp.load_source(classname, script_path)
    except IOError:
      raise RuntimeError("Cannot load class %s from %s",classname, norm_path)

    script_class_inst = RMFTestCase._get_attr(script_module, classname)()
    method = RMFTestCase._get_attr(script_class_inst, command)

    # Reload params import, otherwise it won't change properties during next import
    if 'params' in sys.modules:
      del(sys.modules["params"])

    # run
    with Environment(basedir, test_mode=True) as RMFTestCase.env:
      with patch('resource_management.core.shell.checked_call', return_value=shell_mock_value): # we must always mock any shell calls
        with patch.object(Script, 'get_config', return_value=self.config_dict): # mocking configurations
          with patch.object(Script, 'install_packages'):
            with patch('resource_management.libraries.functions.get_kinit_path', return_value=kinit_path_local):
              with patch.object(platform, 'linux_distribution', return_value=os_type):
                method(RMFTestCase.env)

  def getConfig(self):
    return self.config_dict

  @staticmethod
  def _getSrcFolder():
    return os.path.join(os.path.abspath(os.path.dirname(__file__)),os.path.normpath("../../../../"))

  @staticmethod
  def _get_attr(module, attr):
    module_methods = dir(module)
    if not attr in module_methods:
      raise RuntimeError("'{0}' has no attribute '{1}'".format(module, attr))
    method = getattr(module, attr)
    return method

  def _ppformat(self, val):
    if isinstance(val, dict):
      return "self.getConfig()['configurations']['?']"

    val = pprint.pformat(val)

    if val.startswith("u'") or val.startswith('u"'):
      return val[1:]

    return val

  def reindent(self, s, numSpaces):
    return "\n".join((numSpaces * " ") + i for i in s.splitlines())

  def printResources(self, intendation=4):
    print
    for resource in RMFTestCase.env.resource_list:
      s = "'{0}', {1},".format(
        resource.__class__.__name__, self._ppformat(resource.name))
      has_arguments = False
      for k,v in resource.arguments.iteritems():
        has_arguments = True
        # correctly output octal mode numbers
        if k == 'mode' and isinstance( v, int ):
          val = oct(v)
        elif  isinstance( v, UnknownConfiguration):
          val = "UnknownConfigurationMock()"
        else:
          val = self._ppformat(v)
        # If value is multiline, format it
        if "\n" in val:
          lines = val.splitlines()
          firstLine = lines[0]
          nextlines = "\n".join(lines [1:])
          nextlines = self.reindent(nextlines, 2)
          val = "\n".join([firstLine, nextlines])
        param_str="{0} = {1},".format(k, val)
        s+="\n" + self.reindent(param_str, intendation)
      # Decide whether we want bracket to be at next line
      if has_arguments:
        before_bracket = "\n"
      else:
        before_bracket = ""
      # Add assertion
      s = "self.assertResourceCalled({0}{1})".format(s, before_bracket)
      # Intendation
      s = self.reindent(s, intendation)
      print s
    print(self.reindent("self.assertNoMoreResources()", intendation))

  def assertResourceCalled(self, resource_type, name, **kwargs):
    with patch.object(UnknownConfiguration, '__getattr__', return_value=lambda: "UnknownConfiguration()"):
      resource = RMFTestCase.env.resource_list.pop(0)
      self.assertEquals(resource_type, resource.__class__.__name__)
      self.assertEquals(name, resource.name)
      self.assertEquals(kwargs, resource.arguments)

  def assertNoMoreResources(self):
    self.assertEquals(len(RMFTestCase.env.resource_list), 0, "There was other resources executed!")

  def assertResourceCalledByIndex(self, index, resource_type, name, **kwargs):
    resource = RMFTestCase.env.resource_list[index]
    self.assertEquals(resource_type, resource.__class__.__name__)
    self.assertEquals(name, resource.name)
    self.assertEquals(kwargs, resource.arguments)

# HACK: This is used to check Templates, StaticFile, InlineTemplate in testcases
def Template(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import Template
    return Template(name, **kwargs)

def StaticFile(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import StaticFile
    return StaticFile(name, **kwargs)

def InlineTemplate(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import InlineTemplate
    return InlineTemplate(name, **kwargs)

class UnknownConfigurationMock():
  def __eq__(self, other):
    return isinstance(other, UnknownConfiguration)

  def __ne__(self, other):
    return not self.__eq__(other)

  def __repr__(self):
    return "UnknownConfigurationMock()"

<commit_msg>AMBARI-5341 Namenode unittests are broken (aonishuk via dsen)<commit_after>#!/usr/bin/env python

'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__all__ = ["RMFTestCase", "Template", "StaticFile", "InlineTemplate","UnknownConfigurationMock"]

from unittest import TestCase
import json
import os
import imp
import sys
import pprint
from mock.mock import MagicMock, patch
import platform
with patch("platform.linux_distribution", return_value = ('Suse','11','Final')):
  from resource_management.core.environment import Environment
  from resource_management.libraries.script.config_dictionary import ConfigDictionary
  from resource_management.libraries.script.script import Script
  from resource_management.libraries.script.config_dictionary import UnknownConfiguration

PATH_TO_STACKS = os.path.normpath("main/resources/stacks/HDP")
PATH_TO_STACK_TESTS = os.path.normpath("test/python/stacks/")

class RMFTestCase(TestCase):
  def executeScript(self, path, classname=None, command=None, config_file=None,
                    # common mocks for all the scripts
                    config_overrides = None,
                    shell_mock_value = (0, "OK."),
                    os_type=('Suse','11','Final'),
                    kinit_path_local="/usr/bin/kinit"
                    ):
    norm_path = os.path.normpath(path)
    src_dir = RMFTestCase._getSrcFolder()
    stack_version = norm_path.split(os.sep)[0]
    stacks_path = os.path.join(src_dir, PATH_TO_STACKS)
    configs_path = os.path.join(src_dir, PATH_TO_STACK_TESTS, stack_version, "configs")
    script_path = os.path.join(stacks_path, norm_path)
    config_file_path = os.path.join(configs_path, config_file)

    try:
      with open(config_file_path, "r") as f:
        self.config_dict = json.load(f)
    except IOError:
      raise RuntimeError("Can not read config file: "+ config_file_path)

    if config_overrides:
      for key, value in config_overrides.iteritems():
        self.config_dict[key] = value

    self.config_dict = ConfigDictionary(self.config_dict)

    # append basedir to PYTHONPATH
    scriptsdir = os.path.dirname(script_path)
    basedir = os.path.dirname(scriptsdir)
    sys.path.append(scriptsdir)

    # get method to execute
    try:
      with patch.object(platform, 'linux_distribution', return_value=os_type):
        script_module = imp.load_source(classname, script_path)
    except IOError:
      raise RuntimeError("Cannot load class %s from %s",classname, norm_path)

    script_class_inst = RMFTestCase._get_attr(script_module, classname)()
    method = RMFTestCase._get_attr(script_class_inst, command)

    # Reload params import, otherwise it won't change properties during next import
    if 'params' in sys.modules:
      del(sys.modules["params"])

    # run
    with Environment(basedir, test_mode=True) as RMFTestCase.env:
      with patch('resource_management.core.shell.checked_call', return_value=shell_mock_value): # we must always mock any shell calls
        with patch.object(Script, 'get_config', return_value=self.config_dict): # mocking configurations
          with patch.object(Script, 'install_packages'):
            with patch('resource_management.libraries.functions.get_kinit_path', return_value=kinit_path_local):
              with patch.object(platform, 'linux_distribution', return_value=os_type):
                method(RMFTestCase.env)
    sys.path.remove(scriptsdir)

  def getConfig(self):
    return self.config_dict

  @staticmethod
  def _getSrcFolder():
    return os.path.join(os.path.abspath(os.path.dirname(__file__)),os.path.normpath("../../../../"))

  @staticmethod
  def _get_attr(module, attr):
    module_methods = dir(module)
    if not attr in module_methods:
      raise RuntimeError("'{0}' has no attribute '{1}'".format(module, attr))
    method = getattr(module, attr)
    return method

  def _ppformat(self, val):
    if isinstance(val, dict):
      return "self.getConfig()['configurations']['?']"

    val = pprint.pformat(val)

    if val.startswith("u'") or val.startswith('u"'):
      return val[1:]

    return val

  def reindent(self, s, numSpaces):
    return "\n".join((numSpaces * " ") + i for i in s.splitlines())

  def printResources(self, intendation=4):
    print
    for resource in RMFTestCase.env.resource_list:
      s = "'{0}', {1},".format(
        resource.__class__.__name__, self._ppformat(resource.name))
      has_arguments = False
      for k,v in resource.arguments.iteritems():
        has_arguments = True
        # correctly output octal mode numbers
        if k == 'mode' and isinstance( v, int ):
          val = oct(v)
        elif  isinstance( v, UnknownConfiguration):
          val = "UnknownConfigurationMock()"
        else:
          val = self._ppformat(v)
        # If value is multiline, format it
        if "\n" in val:
          lines = val.splitlines()
          firstLine = lines[0]
          nextlines = "\n".join(lines [1:])
          nextlines = self.reindent(nextlines, 2)
          val = "\n".join([firstLine, nextlines])
        param_str="{0} = {1},".format(k, val)
        s+="\n" + self.reindent(param_str, intendation)
      # Decide whether we want bracket to be at next line
      if has_arguments:
        before_bracket = "\n"
      else:
        before_bracket = ""
      # Add assertion
      s = "self.assertResourceCalled({0}{1})".format(s, before_bracket)
      # Intendation
      s = self.reindent(s, intendation)
      print s
    print(self.reindent("self.assertNoMoreResources()", intendation))

  def assertResourceCalled(self, resource_type, name, **kwargs):
    with patch.object(UnknownConfiguration, '__getattr__', return_value=lambda: "UnknownConfiguration()"):
      resource = RMFTestCase.env.resource_list.pop(0)
      self.assertEquals(resource_type, resource.__class__.__name__)
      self.assertEquals(name, resource.name)
      self.assertEquals(kwargs, resource.arguments)

  def assertNoMoreResources(self):
    self.assertEquals(len(RMFTestCase.env.resource_list), 0, "There was other resources executed!")

  def assertResourceCalledByIndex(self, index, resource_type, name, **kwargs):
    resource = RMFTestCase.env.resource_list[index]
    self.assertEquals(resource_type, resource.__class__.__name__)
    self.assertEquals(name, resource.name)
    self.assertEquals(kwargs, resource.arguments)

# HACK: This is used to check Templates, StaticFile, InlineTemplate in testcases
def Template(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import Template
    return Template(name, **kwargs)

def StaticFile(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import StaticFile
    return StaticFile(name, **kwargs)

def InlineTemplate(name, **kwargs):
  with RMFTestCase.env:
    from resource_management.core.source import InlineTemplate
    return InlineTemplate(name, **kwargs)

class UnknownConfigurationMock():
  def __eq__(self, other):
    return isinstance(other, UnknownConfiguration)

  def __ne__(self, other):
    return not self.__eq__(other)

  def __repr__(self):
    return "UnknownConfigurationMock()"

<|endoftext|>