<commit_before># Copyright (c) 2014 AnsibleWorks, Inc.
# This file is a utility Ansible plugin that is not part of the AWX or Ansible
# packages.  It does not import any code from either package, nor does its
# license apply to Ansible or AWX.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
#    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.
#
#    Neither the name of the <ORGANIZATION> nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.

# Python
import datetime
import glob
import json
import logging
import os
import pwd
import sys
import urllib
import urlparse
import time
from contextlib import closing

# Requests
import requests

# ZeroMQ
import zmq

# PSUtil
try:
    import psutil
except ImportError:
    psutil = None

class TokenAuth(requests.auth.AuthBase):

    def __init__(self, token):
        self.token = token

    def __call__(self, request):
        request.headers['Authorization'] = 'Token %s' % self.token
        return request

class CallbackModule(object):
    '''
    Callback module for logging ansible-playbook job events via the REST API.
    '''

    # These events should never have an associated play.
    EVENTS_WITHOUT_PLAY = [
        'playbook_on_start',
        'playbook_on_stats',
    ]
    # These events should never have an associated task.
    EVENTS_WITHOUT_TASK = EVENTS_WITHOUT_PLAY + [
        'playbook_on_setup',
        'playbook_on_notify',
        'playbook_on_import_for_host',
        'playbook_on_not_import_for_host',
        'playbook_on_no_hosts_matched',
        'playbook_on_no_hosts_remaining',
    ]

    def __init__(self):
        self.job_id = int(os.getenv('JOB_ID'))
        self.base_url = os.getenv('REST_API_URL', '')
        self.auth_token = os.getenv('REST_API_TOKEN', '')
        self.callback_consumer_port = os.getenv('CALLBACK_CONSUMER_PORT', '')
        self.context = None
        self.socket = None
        self._init_logging()
        self._init_connection()
        self.counter = 0

    def _init_logging(self):
        try:
            self.job_callback_debug = int(os.getenv('JOB_CALLBACK_DEBUG', '0'))
        except ValueError:
            self.job_callback_debug = 0
        self.logger = logging.getLogger('awx.plugins.callback.job_event_callback')
        if self.job_callback_debug >= 2:
            self.logger.setLevel(logging.DEBUG)
        elif self.job_callback_debug >= 1:
            self.logger.setLevel(logging.INFO)
        else:
            self.logger.setLevel(logging.WARNING)
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(levelname)-8s %(process)-8d %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.logger.propagate = False

    def _init_connection(self):
        self.context = None
        self.socket = None

    def _start_connection(self):
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.REQ)
        self.socket.connect(self.callback_consumer_port)

    def _post_job_event_queue_msg(self, event, event_data):
        self.counter += 1
        msg = {
            'job_id': self.job_id,
            'event': event,
            'event_data': event_data,
            'counter': self.counter,
            'created': datetime.datetime.utcnow().isoformat(),
        }

        active_pid = os.getpid()
        if self.job_callback_debug:
            msg.update({
                'pid': active_pid,
            })
        for retry_count in xrange(4):
            try:
                if not hasattr(self, 'connection_pid'):
                    self.connection_pid = active_pid
                if self.connection_pid != active_pid:
                    self._init_connection()
                if self.context is None:
                    self._start_connection()

                self.socket.send_json(msg)
                self.socket.recv()
                return
            except Exception, e:
                self.logger.info('Publish Exception: %r, retry=%d', e,
                                 retry_count, exc_info=True)
                # TODO: Maybe recycle connection here?
                if retry_count >= 3:
                    raise

    def _post_rest_api_event(self, event, event_data):
        data = json.dumps({
            'event': event,
            'event_data': event_data,
        })
        parts = urlparse.urlsplit(self.base_url)
        if parts.username and parts.password:
            auth = (parts.username, parts.password)
        elif self.auth_token:
            auth = TokenAuth(self.auth_token)
        else:
            auth = None
        port = parts.port or (443 if parts.scheme == 'https' else 80)
        url = urlparse.urlunsplit([parts.scheme,
                                   '%s:%d' % (parts.hostname, port),
                                   parts.path, parts.query, parts.fragment])
        url_path = '/api/v1/jobs/%d/job_events/' % self.job_id
        url = urlparse.urljoin(url, url_path)
        headers = {'content-type': 'application/json'}
        response = requests.post(url, data=data, headers=headers, auth=auth)
        response.raise_for_status()

    def _log_event(self, event, **event_data):
        play = getattr(self, 'play', None)
        play_name = getattr(play, 'name', '')
        if play_name and event not in self.EVENTS_WITHOUT_PLAY:
            event_data['play'] = play_name
        task = getattr(self, 'task', None)
        task_name = getattr(task, 'name', '')
        role_name = getattr(task, 'role_name', '')
        if task_name and event not in self.EVENTS_WITHOUT_TASK:
            event_data['task'] = task_name
        if role_name and event not in self.EVENTS_WITHOUT_TASK:
            event_data['role'] = role_name

        if self.callback_consumer_port:
            self._post_job_event_queue_msg(event, event_data)
        else:
            self._post_rest_api_event(event, event_data)

    def on_any(self, *args, **kwargs):
        pass

    def runner_on_failed(self, host, res, ignore_errors=False):
        self._log_event('runner_on_failed', host=host, res=res,
                        ignore_errors=ignore_errors)

    def runner_on_ok(self, host, res):
        self._log_event('runner_on_ok', host=host, res=res)

    def runner_on_error(self, host, msg):
        self._log_event('runner_on_error', host=host, msg=msg)

    def runner_on_skipped(self, host, item=None):
        self._log_event('runner_on_skipped', host=host, item=item)

    def runner_on_unreachable(self, host, res):
        self._log_event('runner_on_unreachable', host=host, res=res)

    def runner_on_no_hosts(self):
        self._log_event('runner_on_no_hosts')

    def runner_on_async_poll(self, host, res, jid, clock):
        self._log_event('runner_on_async_poll', host=host, res=res, jid=jid,
                        clock=clock)

    def runner_on_async_ok(self, host, res, jid):
        self._log_event('runner_on_async_ok', host=host, res=res, jid=jid)

    def runner_on_async_failed(self, host, res, jid):
        self._log_event('runner_on_async_failed', host=host, res=res, jid=jid)

    def runner_on_file_diff(self, host, diff):
        self._log_event('runner_on_file_diff', host=host, diff=diff)

    def playbook_on_start(self):
        self._log_event('playbook_on_start')

    def playbook_on_notify(self, host, handler):
        self._log_event('playbook_on_notify', host=host, handler=handler)

    def playbook_on_no_hosts_matched(self):
        self._log_event('playbook_on_no_hosts_matched')

    def playbook_on_no_hosts_remaining(self):
        self._log_event('playbook_on_no_hosts_remaining')

    def playbook_on_task_start(self, name, is_conditional):
        self._log_event('playbook_on_task_start', name=name,
                        is_conditional=is_conditional)

    def playbook_on_vars_prompt(self, varname, private=True, prompt=None,
                                encrypt=None, confirm=False, salt_size=None,
                                salt=None, default=None):
        self._log_event('playbook_on_vars_prompt', varname=varname,
                        private=private, prompt=prompt, encrypt=encrypt,
                        confirm=confirm, salt_size=salt_size, salt=salt,
                        default=default)

    def playbook_on_setup(self):
        self._log_event('playbook_on_setup')

    def playbook_on_import_for_host(self, host, imported_file):
        # don't care about recording this one
        # self._log_event('playbook_on_import_for_host', host=host,
        #                imported_file=imported_file)
        pass

    def playbook_on_not_import_for_host(self, host, missing_file):
        # don't care about recording this one
        #self._log_event('playbook_on_not_import_for_host', host=host,
        #                missing_file=missing_file)
        pass

    def playbook_on_play_start(self, name):
        # Only play name is passed via callback, get host pattern from the play.
        pattern = getattr(getattr(self, 'play', None), 'hosts', name)
        self._log_event('playbook_on_play_start', name=name, pattern=pattern)

    def playbook_on_stats(self, stats):
        d = {}
        for attr in ('changed', 'dark', 'failures', 'ok', 'processed', 'skipped'):
            d[attr] = getattr(stats, attr)
        self._log_event('playbook_on_stats', **d)
        self._terminate_ssh_control_masters()

    def _terminate_ssh_control_masters(self):
        # Determine if control persist is being used and if any open sockets
        # exist after running the playbook.
        cp_path = os.environ.get('ANSIBLE_SSH_CONTROL_PATH', '')
        if not cp_path:
            return
        cp_dir = os.path.dirname(cp_path)
        if not os.path.exists(cp_dir):
            return
        cp_pattern = os.path.join(cp_dir, 'ansible-ssh-*')
        cp_files = glob.glob(cp_pattern)
        if not cp_files:
            return

        # HACK: If psutil isn't available, sleep and allow the control master
        # processes to timeout and die.
        if not psutil:
            time.sleep(60)

        # Attempt to find any running control master processes.
        username = pwd.getpwuid(os.getuid())[0]
        ssh_cm_procs = []
        for proc in psutil.process_iter():
            try:
                pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline', 'username'])
            except psutil.NoSuchProcess:
                continue
            if pinfo['username'] != username:
                continue
            if pinfo['name'] != 'ssh':
                continue
            for cp_file in cp_files:
                if pinfo['cmdline'] and cp_file in pinfo['cmdline'][0]:
                    ssh_cm_procs.append(proc)
                    break

        # Terminate then kill control master processes.  Workaround older
        # version of psutil that may not have wait_procs implemented.
        for proc in ssh_cm_procs:
            proc.terminate()
        if hasattr(psutil, 'wait_procs'):
            procs_gone, procs_alive = psutil.wait_procs(ssh_cm_procs, timeout=5)
        else:
            procs_gone = []
            procs_alive = ssh_cm_procs[:]
            for x in xrange(5):
                for proc in procs_alive[:]:
                    if not proc.is_running():
                        procs_alive.remove(proc)
                        procs_gone.append(proc)
                if not procs_alive:
                    break
                time.sleep(1)
        for proc in procs_alive:
            proc.kill()
<commit_msg>Support older versions of psutil that don't implement as_dict().<commit_after># Copyright (c) 2014 AnsibleWorks, Inc.
# This file is a utility Ansible plugin that is not part of the AWX or Ansible
# packages.  It does not import any code from either package, nor does its
# license apply to Ansible or AWX.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
#    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.
#
#    Neither the name of the <ORGANIZATION> nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.

# Python
import datetime
import glob
import json
import logging
import os
import pwd
import sys
import urllib
import urlparse
import time
from contextlib import closing

# Requests
import requests

# ZeroMQ
import zmq

# PSUtil
try:
    import psutil
except ImportError:
    psutil = None

class TokenAuth(requests.auth.AuthBase):

    def __init__(self, token):
        self.token = token

    def __call__(self, request):
        request.headers['Authorization'] = 'Token %s' % self.token
        return request

class CallbackModule(object):
    '''
    Callback module for logging ansible-playbook job events via the REST API.
    '''

    # These events should never have an associated play.
    EVENTS_WITHOUT_PLAY = [
        'playbook_on_start',
        'playbook_on_stats',
    ]
    # These events should never have an associated task.
    EVENTS_WITHOUT_TASK = EVENTS_WITHOUT_PLAY + [
        'playbook_on_setup',
        'playbook_on_notify',
        'playbook_on_import_for_host',
        'playbook_on_not_import_for_host',
        'playbook_on_no_hosts_matched',
        'playbook_on_no_hosts_remaining',
    ]

    def __init__(self):
        self.job_id = int(os.getenv('JOB_ID'))
        self.base_url = os.getenv('REST_API_URL', '')
        self.auth_token = os.getenv('REST_API_TOKEN', '')
        self.callback_consumer_port = os.getenv('CALLBACK_CONSUMER_PORT', '')
        self.context = None
        self.socket = None
        self._init_logging()
        self._init_connection()
        self.counter = 0

    def _init_logging(self):
        try:
            self.job_callback_debug = int(os.getenv('JOB_CALLBACK_DEBUG', '0'))
        except ValueError:
            self.job_callback_debug = 0
        self.logger = logging.getLogger('awx.plugins.callback.job_event_callback')
        if self.job_callback_debug >= 2:
            self.logger.setLevel(logging.DEBUG)
        elif self.job_callback_debug >= 1:
            self.logger.setLevel(logging.INFO)
        else:
            self.logger.setLevel(logging.WARNING)
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(levelname)-8s %(process)-8d %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.logger.propagate = False

    def _init_connection(self):
        self.context = None
        self.socket = None

    def _start_connection(self):
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.REQ)
        self.socket.connect(self.callback_consumer_port)

    def _post_job_event_queue_msg(self, event, event_data):
        self.counter += 1
        msg = {
            'job_id': self.job_id,
            'event': event,
            'event_data': event_data,
            'counter': self.counter,
            'created': datetime.datetime.utcnow().isoformat(),
        }

        active_pid = os.getpid()
        if self.job_callback_debug:
            msg.update({
                'pid': active_pid,
            })
        for retry_count in xrange(4):
            try:
                if not hasattr(self, 'connection_pid'):
                    self.connection_pid = active_pid
                if self.connection_pid != active_pid:
                    self._init_connection()
                if self.context is None:
                    self._start_connection()

                self.socket.send_json(msg)
                self.socket.recv()
                return
            except Exception, e:
                self.logger.info('Publish Exception: %r, retry=%d', e,
                                 retry_count, exc_info=True)
                # TODO: Maybe recycle connection here?
                if retry_count >= 3:
                    raise

    def _post_rest_api_event(self, event, event_data):
        data = json.dumps({
            'event': event,
            'event_data': event_data,
        })
        parts = urlparse.urlsplit(self.base_url)
        if parts.username and parts.password:
            auth = (parts.username, parts.password)
        elif self.auth_token:
            auth = TokenAuth(self.auth_token)
        else:
            auth = None
        port = parts.port or (443 if parts.scheme == 'https' else 80)
        url = urlparse.urlunsplit([parts.scheme,
                                   '%s:%d' % (parts.hostname, port),
                                   parts.path, parts.query, parts.fragment])
        url_path = '/api/v1/jobs/%d/job_events/' % self.job_id
        url = urlparse.urljoin(url, url_path)
        headers = {'content-type': 'application/json'}
        response = requests.post(url, data=data, headers=headers, auth=auth)
        response.raise_for_status()

    def _log_event(self, event, **event_data):
        play = getattr(self, 'play', None)
        play_name = getattr(play, 'name', '')
        if play_name and event not in self.EVENTS_WITHOUT_PLAY:
            event_data['play'] = play_name
        task = getattr(self, 'task', None)
        task_name = getattr(task, 'name', '')
        role_name = getattr(task, 'role_name', '')
        if task_name and event not in self.EVENTS_WITHOUT_TASK:
            event_data['task'] = task_name
        if role_name and event not in self.EVENTS_WITHOUT_TASK:
            event_data['role'] = role_name

        if self.callback_consumer_port:
            self._post_job_event_queue_msg(event, event_data)
        else:
            self._post_rest_api_event(event, event_data)

    def on_any(self, *args, **kwargs):
        pass

    def runner_on_failed(self, host, res, ignore_errors=False):
        self._log_event('runner_on_failed', host=host, res=res,
                        ignore_errors=ignore_errors)

    def runner_on_ok(self, host, res):
        self._log_event('runner_on_ok', host=host, res=res)

    def runner_on_error(self, host, msg):
        self._log_event('runner_on_error', host=host, msg=msg)

    def runner_on_skipped(self, host, item=None):
        self._log_event('runner_on_skipped', host=host, item=item)

    def runner_on_unreachable(self, host, res):
        self._log_event('runner_on_unreachable', host=host, res=res)

    def runner_on_no_hosts(self):
        self._log_event('runner_on_no_hosts')

    def runner_on_async_poll(self, host, res, jid, clock):
        self._log_event('runner_on_async_poll', host=host, res=res, jid=jid,
                        clock=clock)

    def runner_on_async_ok(self, host, res, jid):
        self._log_event('runner_on_async_ok', host=host, res=res, jid=jid)

    def runner_on_async_failed(self, host, res, jid):
        self._log_event('runner_on_async_failed', host=host, res=res, jid=jid)

    def runner_on_file_diff(self, host, diff):
        self._log_event('runner_on_file_diff', host=host, diff=diff)

    def playbook_on_start(self):
        self._log_event('playbook_on_start')

    def playbook_on_notify(self, host, handler):
        self._log_event('playbook_on_notify', host=host, handler=handler)

    def playbook_on_no_hosts_matched(self):
        self._log_event('playbook_on_no_hosts_matched')

    def playbook_on_no_hosts_remaining(self):
        self._log_event('playbook_on_no_hosts_remaining')

    def playbook_on_task_start(self, name, is_conditional):
        self._log_event('playbook_on_task_start', name=name,
                        is_conditional=is_conditional)

    def playbook_on_vars_prompt(self, varname, private=True, prompt=None,
                                encrypt=None, confirm=False, salt_size=None,
                                salt=None, default=None):
        self._log_event('playbook_on_vars_prompt', varname=varname,
                        private=private, prompt=prompt, encrypt=encrypt,
                        confirm=confirm, salt_size=salt_size, salt=salt,
                        default=default)

    def playbook_on_setup(self):
        self._log_event('playbook_on_setup')

    def playbook_on_import_for_host(self, host, imported_file):
        # don't care about recording this one
        # self._log_event('playbook_on_import_for_host', host=host,
        #                imported_file=imported_file)
        pass

    def playbook_on_not_import_for_host(self, host, missing_file):
        # don't care about recording this one
        #self._log_event('playbook_on_not_import_for_host', host=host,
        #                missing_file=missing_file)
        pass

    def playbook_on_play_start(self, name):
        # Only play name is passed via callback, get host pattern from the play.
        pattern = getattr(getattr(self, 'play', None), 'hosts', name)
        self._log_event('playbook_on_play_start', name=name, pattern=pattern)

    def playbook_on_stats(self, stats):
        d = {}
        for attr in ('changed', 'dark', 'failures', 'ok', 'processed', 'skipped'):
            d[attr] = getattr(stats, attr)
        self._log_event('playbook_on_stats', **d)
        self._terminate_ssh_control_masters()

    def _terminate_ssh_control_masters(self):
        # Determine if control persist is being used and if any open sockets
        # exist after running the playbook.
        cp_path = os.environ.get('ANSIBLE_SSH_CONTROL_PATH', '')
        if not cp_path:
            return
        cp_dir = os.path.dirname(cp_path)
        if not os.path.exists(cp_dir):
            return
        cp_pattern = os.path.join(cp_dir, 'ansible-ssh-*')
        cp_files = glob.glob(cp_pattern)
        if not cp_files:
            return

        # HACK: If psutil isn't available, sleep and allow the control master
        # processes to timeout and die.
        if not psutil:
            time.sleep(60)

        # Attempt to find any running control master processes.
        username = pwd.getpwuid(os.getuid())[0]
        ssh_cm_procs = []
        for proc in psutil.process_iter():
            try:
                pname = proc.name
                pcmdline = proc.cmdline
                pusername = proc.username
            except psutil.NoSuchProcess:
                continue
            if pusername != username:
                continue
            if pname != 'ssh':
                continue
            for cp_file in cp_files:
                if pcmdline and cp_file in pcmdline[0]:
                    ssh_cm_procs.append(proc)
                    break

        # Terminate then kill control master processes.  Workaround older
        # version of psutil that may not have wait_procs implemented.
        for proc in ssh_cm_procs:
            proc.terminate()
        if hasattr(psutil, 'wait_procs'):
            procs_gone, procs_alive = psutil.wait_procs(ssh_cm_procs, timeout=5)
        else:
            procs_gone = []
            procs_alive = ssh_cm_procs[:]
            for x in xrange(5):
                for proc in procs_alive[:]:
                    if not proc.is_running():
                        procs_alive.remove(proc)
                        procs_gone.append(proc)
                if not procs_alive:
                    break
                time.sleep(1)
        for proc in procs_alive:
            proc.kill()
<|endoftext|>


<commit_before>#!/usr/bin/python3

# Install confirmation with details window

import os.path
import pathlib
import subprocess
import sys
import webbrowser
import tempfile
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit', '3.0')
from gi.repository import Gtk, WebKit
from distutils.version import StrictVersion
from keyman_config.install_kmp import install_kmp, extract_kmp, get_metadata
from keyman_config.list_installed_kmp import get_kmp_version
from keyman_config.kmpmetadata import get_fonts
from keyman_config.welcome import WelcomeView
from keyman_config.uninstall_kmp import uninstall_kmp
from keyman_config.get_kmp import get_download_folder
from keyman_config.check_mime_type import check_mime_type
from keyman_config.accelerators import bind_accelerator, init_accel

class InstallKmpWindow(Gtk.Window):

    def __init__(self, kmpfile, online=False, viewkmp=None):
        print("kmpfile:", kmpfile)
        self.kmpfile = kmpfile
        self.online = online
        self.endonclose = False
        self.viewwindow = viewkmp
        self.accelerators = None
        keyboardid = os.path.basename(os.path.splitext(kmpfile)[0])
        installed_kmp_ver = get_kmp_version(keyboardid)
        if installed_kmp_ver:
            print("installed kmp version", installed_kmp_ver)

        windowtitle = "Installing keyboard/package " + keyboardid
        Gtk.Window.__init__(self, title=windowtitle)
        init_accel(self)

        self.set_border_width(3)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        mainhbox = Gtk.Box()

        with tempfile.TemporaryDirectory() as tmpdirname:
            extract_kmp(kmpfile, tmpdirname)
            info, system, options, keyboards, files = get_metadata(tmpdirname)
            self.kbname = keyboards[0]['name']
            self.checkcontinue = True

            if installed_kmp_ver:
                if info['version']['description'] == installed_kmp_ver:
                    dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
                        Gtk.ButtonsType.YES_NO, "Keyboard is installed already")
                    dialog.format_secondary_text(
                        "The " + self.kbname + " keyboard is already installed at version " + installed_kmp_ver +
                            ". Do you want to uninstall then reinstall it?")
                    response = dialog.run()
                    dialog.destroy()
                    if response == Gtk.ResponseType.YES:
                        print("QUESTION dialog closed by clicking YES button")
                        uninstall_kmp(keyboardid)
                    elif response == Gtk.ResponseType.NO:
                        print("QUESTION dialog closed by clicking NO button")
                        self.checkcontinue = False
                else:
                    try:
                        print("package version", info['version']['description'])
                        print("installed kmp version", installed_kmp_ver)
                        if StrictVersion(info['version']['description']) <= StrictVersion(installed_kmp_ver):
                            dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
                                Gtk.ButtonsType.YES_NO, "Keyboard is installed already")
                            dialog.format_secondary_text(
                                "The " + self.kbname + " keyboard is already installed with a newer version " + installed_kmp_ver +
                                    ". Do you want to uninstall it and install the older version" + info['version']['description'] + "?")
                            response = dialog.run()
                            dialog.destroy()
                            if response == Gtk.ResponseType.YES:
                                print("QUESTION dialog closed by clicking YES button")
                                uninstall_kmp(keyboardid)
                            elif response == Gtk.ResponseType.NO:
                                print("QUESTION dialog closed by clicking NO button")
                                self.checkcontinue = False
                    except:
                        print("exception")
                        pass

            image = Gtk.Image()
            if options and "graphicFile" in options:
                image.set_from_file(os.path.join(tmpdirname, options['graphicFile']))
            else:
                img_default = "/usr/share/keyman/icons/defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "keyman_config/icons/defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "icons/defaultpackage.gif"
                image.set_from_file(img_default)

            mainhbox.pack_start(image, False, False, 0)

            self.page1 = Gtk.Box()
            self.page1.set_border_width(10)

            grid = Gtk.Grid()
            self.page1.add(grid)

            label1 = Gtk.Label()
            label1.set_text("Keyboard layouts:   ")
            label1.set_halign(Gtk.Align.END)
            grid.add(label1)
            prevlabel = label1
            label = Gtk.Label()
            keyboardlayout = ""
            for kb in keyboards:
                if keyboardlayout != "":
                    keyboardlayout = keyboardlayout + "\n"
                keyboardlayout = keyboardlayout + kb['name']
            label.set_text(keyboardlayout)
            label.set_halign(Gtk.Align.START)
            label.set_selectable(True)
            grid.attach_next_to(label, label1, Gtk.PositionType.RIGHT, 1, 1)

            fonts = get_fonts(files)
            if fonts:
                label2 = Gtk.Label()
                # Fonts are optional
                label2.set_text("Fonts:   ")
                label2.set_halign(Gtk.Align.END)
                grid.attach_next_to(label2, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label2
                label = Gtk.Label()
                fontlist = ""
                for font in fonts:
                    if fontlist != "":
                        fontlist = fontlist + "\n"
                    if font['description'][:5] == "Font ":
                        fontdesc = font['description'][5:]
                    else:
                        fontdesc = font['description']
                    fontlist = fontlist + fontdesc
                label.set_text(fontlist)
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label2, Gtk.PositionType.RIGHT, 1, 1)

            label3 = Gtk.Label()
            label3.set_text("Package version:   ")
            label3.set_halign(Gtk.Align.END)
            grid.attach_next_to(label3, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
            prevlabel = label3
            label = Gtk.Label()
            label.set_text(info['version']['description'])
            label.set_halign(Gtk.Align.START)
            label.set_selectable(True)
            grid.attach_next_to(label, label3, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'author' in info:
                label4 = Gtk.Label()
                label4.set_text("Author:   ")
                label4.set_halign(Gtk.Align.END)
                grid.attach_next_to(label4, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label4
                label = Gtk.Label()
                if 'url' in info['author']:
                    label.set_markup("" + info['author']['description'] + "")
                else:
                    label.set_text(info['author']['description'])
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label4, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'website' in info:
                label5 = Gtk.Label()
                # Website is optional and may be a mailto for the author
                label5.set_text("Website:   ")
                label5.set_halign(Gtk.Align.END)
                grid.attach_next_to(label5, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label5
                label = Gtk.Label()
                label.set_markup("" + info['website']['description'] + "")
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label5, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'copyright' in info:
                label6 = Gtk.Label()
                label6.set_text("Copyright:   ")
                label6.set_halign(Gtk.Align.END)
                grid.attach_next_to(label6, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                label = Gtk.Label()
                label.set_text(info['copyright']['description'])
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label6, Gtk.PositionType.RIGHT, 1, 1)

            self.page2 = Gtk.Box()
            s = Gtk.ScrolledWindow()
            webview = WebKit.WebView()
            webview.connect("navigation-policy-decision-requested", self.check)
            webview.connect("mime-type-policy-decision-requested", check_mime_type)

            if options and "readmeFile" in options:
                self.readme = options['readmeFile']
            else:
                self.readme = "readme.htm"
            readme_file = os.path.join(tmpdirname, self.readme)
            if os.path.isfile(readme_file):
                readme_uri = pathlib.Path(readme_file).as_uri()
                webview.load_uri(readme_uri)
                s.add(webview)
                self.page2.pack_start(s, True, True, 0)

                self.notebook = Gtk.Notebook()
                self.notebook.set_tab_pos(Gtk.PositionType.BOTTOM)
                mainhbox.pack_start(self.notebook, True, True, 0)
                self.notebook.append_page(
                    self.page1,
                    Gtk.Label('Details'))
                self.notebook.append_page(
                    self.page2,
                    Gtk.Label('README')
        )
            else:
                mainhbox.pack_start(self.page1, True, True, 0)
        vbox.pack_start(mainhbox, True, True, 0)

        hbox = Gtk.Box(spacing=6)
        vbox.pack_start(hbox, False, False, 0)

        button = Gtk.Button.new_with_mnemonic("_Install")
        button.connect("clicked", self.on_install_clicked)
        hbox.pack_start(button, False, False, 0)

        button = Gtk.Button.new_with_mnemonic("_Cancel")
        button.connect("clicked", self.on_cancel_clicked)
        hbox.pack_end(button, False, False, 0)
        bind_accelerator(self.accelerators, button, '<Control>w')

        self.add(vbox)
        self.resize(635, 270)

    def check(self, view, frame, req, nav, policy):
        uri = req.get_uri()
        if not self.readme in uri:
            webbrowser.open(uri)
            policy.ignore()
            return True
        return False

    def on_install_clicked(self, button):
        print("Installing keyboard")
        install_kmp(self.kmpfile, self.online)
        if self.viewwindow:
            self.viewwindow.refresh_installed_kmp()
        keyboardid = os.path.basename(os.path.splitext(self.kmpfile)[0])
        welcome_file = os.path.join("/usr/local/share/doc/keyman", keyboardid, "welcome.htm")
        if os.path.isfile(welcome_file):
            uri_path = pathlib.Path(welcome_file).as_uri()
            print(uri_path)
            w = WelcomeView(uri_path, self.kbname)
            w.resize(800, 600)
            w.show_all()
        else:
            dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
                Gtk.ButtonsType.OK, "Keyboard " + self.kbname + " installed")
            dialog.run()
            print("INFO dialog closed")
            dialog.destroy()
        if not self.endonclose:
            self.close()

    def on_cancel_clicked(self, button):
        print("Cancel install keyboard")
        if self.endonclose:
            Gtk.main_quit()
        else:
            self.close()

    def connectdestroy(self):
        self.connect("destroy", Gtk.main_quit)
        self.endonclose = True

def main(argv):
    if len(sys.argv) != 2:
        print("install_window.py <kmpfile>")
        sys.exit(2)

    name, ext = os.path.splitext(sys.argv[1])
    if ext != ".kmp":
        print("install_window.py Input file", sys.argv[1], "is not a kmp file.")
        print("install_window.py <kmpfile>")
        sys.exit(2)

    if not os.path.isfile(sys.argv[1]):
        print("install_window.py Keyman kmp file", sys.argv[1], "not found.")
        print("install_window.py <kmpfile>")
        sys.exit(2)

    w = InstallKmpWindow(sys.argv[1])
    w.connectdestroy()
    w.resize(800, 450)
    if w.checkcontinue:
        w.show_all()
        Gtk.main()

if __name__ == "__main__":
	main(sys.argv[1:])
<commit_msg>[linux] further feedback from PR893<commit_after>#!/usr/bin/python3

# Install confirmation with details window

import os.path
import pathlib
import subprocess
import sys
import webbrowser
import tempfile
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit', '3.0')
from gi.repository import Gtk, WebKit
from distutils.version import StrictVersion
from keyman_config.install_kmp import install_kmp, extract_kmp, get_metadata
from keyman_config.list_installed_kmp import get_kmp_version
from keyman_config.kmpmetadata import get_fonts
from keyman_config.welcome import WelcomeView
from keyman_config.uninstall_kmp import uninstall_kmp
from keyman_config.get_kmp import get_download_folder
from keyman_config.check_mime_type import check_mime_type
from keyman_config.accelerators import bind_accelerator, init_accel

class InstallKmpWindow(Gtk.Window):

    def __init__(self, kmpfile, online=False, viewkmp=None):
        print("kmpfile:", kmpfile)
        self.kmpfile = kmpfile
        self.online = online
        self.endonclose = False
        self.viewwindow = viewkmp
        self.accelerators = None
        keyboardid = os.path.basename(os.path.splitext(kmpfile)[0])
        installed_kmp_ver = get_kmp_version(keyboardid)
        if installed_kmp_ver:
            print("installed kmp version", installed_kmp_ver)

        windowtitle = "Installing keyboard/package " + keyboardid
        Gtk.Window.__init__(self, title=windowtitle)
        init_accel(self)

        self.set_border_width(3)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        mainhbox = Gtk.Box()

        with tempfile.TemporaryDirectory() as tmpdirname:
            extract_kmp(kmpfile, tmpdirname)
            info, system, options, keyboards, files = get_metadata(tmpdirname)
            self.kbname = keyboards[0]['name']
            self.checkcontinue = True

            if installed_kmp_ver:
                if info['version']['description'] == installed_kmp_ver:
                    dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
                        Gtk.ButtonsType.YES_NO, "Keyboard is installed already")
                    dialog.format_secondary_text(
                        "The " + self.kbname + " keyboard is already installed at version " + installed_kmp_ver +
                            ". Do you want to uninstall then reinstall it?")
                    response = dialog.run()
                    dialog.destroy()
                    if response == Gtk.ResponseType.YES:
                        print("QUESTION dialog closed by clicking YES button")
                        uninstall_kmp(keyboardid)
                    elif response == Gtk.ResponseType.NO:
                        print("QUESTION dialog closed by clicking NO button")
                        self.checkcontinue = False
                else:
                    try:
                        print("package version", info['version']['description'])
                        print("installed kmp version", installed_kmp_ver)
                        if StrictVersion(info['version']['description']) <= StrictVersion(installed_kmp_ver):
                            dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
                                Gtk.ButtonsType.YES_NO, "Keyboard is installed already")
                            dialog.format_secondary_text(
                                "The " + self.kbname + " keyboard is already installed with a newer version " + installed_kmp_ver +
                                    ". Do you want to uninstall it and install the older version" + info['version']['description'] + "?")
                            response = dialog.run()
                            dialog.destroy()
                            if response == Gtk.ResponseType.YES:
                                print("QUESTION dialog closed by clicking YES button")
                                uninstall_kmp(keyboardid)
                            elif response == Gtk.ResponseType.NO:
                                print("QUESTION dialog closed by clicking NO button")
                                self.checkcontinue = False
                    except:
                        print("exception")
                        pass

            image = Gtk.Image()
            if options and "graphicFile" in options:
                image.set_from_file(os.path.join(tmpdirname, options['graphicFile']))
            else:
                img_default = "/usr/share/keyman/icons/defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "keyman_config/icons/defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "defaultpackage.gif"
                if not os.path.isfile(img_default):
                    img_default = "icons/defaultpackage.gif"
                image.set_from_file(img_default)

            mainhbox.pack_start(image, False, False, 0)

            self.page1 = Gtk.Box()
            self.page1.set_border_width(10)

            grid = Gtk.Grid()
            self.page1.add(grid)

            label1 = Gtk.Label()
            label1.set_text("Keyboard layouts:   ")
            label1.set_halign(Gtk.Align.END)
            grid.add(label1)
            prevlabel = label1
            label = Gtk.Label()
            keyboardlayout = ""
            for kb in keyboards:
                if keyboardlayout != "":
                    keyboardlayout = keyboardlayout + "\n"
                keyboardlayout = keyboardlayout + kb['name']
            label.set_text(keyboardlayout)
            label.set_halign(Gtk.Align.START)
            label.set_selectable(True)
            grid.attach_next_to(label, label1, Gtk.PositionType.RIGHT, 1, 1)

            fonts = get_fonts(files)
            if fonts:
                label2 = Gtk.Label()
                # Fonts are optional
                label2.set_text("Fonts:   ")
                label2.set_halign(Gtk.Align.END)
                grid.attach_next_to(label2, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label2
                label = Gtk.Label()
                fontlist = ""
                for font in fonts:
                    if fontlist != "":
                        fontlist = fontlist + "\n"
                    if font['description'][:5] == "Font ":
                        fontdesc = font['description'][5:]
                    else:
                        fontdesc = font['description']
                    fontlist = fontlist + fontdesc
                label.set_text(fontlist)
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label2, Gtk.PositionType.RIGHT, 1, 1)

            label3 = Gtk.Label()
            label3.set_text("Package version:   ")
            label3.set_halign(Gtk.Align.END)
            grid.attach_next_to(label3, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
            prevlabel = label3
            label = Gtk.Label()
            label.set_text(info['version']['description'])
            label.set_halign(Gtk.Align.START)
            label.set_selectable(True)
            grid.attach_next_to(label, label3, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'author' in info:
                label4 = Gtk.Label()
                label4.set_text("Author:   ")
                label4.set_halign(Gtk.Align.END)
                grid.attach_next_to(label4, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label4
                label = Gtk.Label()
                if 'url' in info['author']:
                    label.set_markup("" + info['author']['description'] + "")
                else:
                    label.set_text(info['author']['description'])
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label4, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'website' in info:
                label5 = Gtk.Label()
                # Website is optional and may be a mailto for the author
                label5.set_text("Website:   ")
                label5.set_halign(Gtk.Align.END)
                grid.attach_next_to(label5, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                prevlabel = label5
                label = Gtk.Label()
                label.set_markup("" + info['website']['description'] + "")
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label5, Gtk.PositionType.RIGHT, 1, 1)

            if info and 'copyright' in info:
                label6 = Gtk.Label()
                label6.set_text("Copyright:   ")
                label6.set_halign(Gtk.Align.END)
                grid.attach_next_to(label6, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)
                label = Gtk.Label()
                label.set_text(info['copyright']['description'])
                label.set_halign(Gtk.Align.START)
                label.set_selectable(True)
                grid.attach_next_to(label, label6, Gtk.PositionType.RIGHT, 1, 1)

            self.page2 = Gtk.Box()
            s = Gtk.ScrolledWindow()
            webview = WebKit.WebView()
            webview.connect("navigation-policy-decision-requested", self.check)
            webview.connect("mime-type-policy-decision-requested", check_mime_type)

            if options and "readmeFile" in options:
                self.readme = options['readmeFile']
            else:
                self.readme = "noreadme"
            readme_file = os.path.join(tmpdirname, self.readme)
            if os.path.isfile(readme_file):
                readme_uri = pathlib.Path(readme_file).as_uri()
                webview.load_uri(readme_uri)
                s.add(webview)
                self.page2.pack_start(s, True, True, 0)

                self.notebook = Gtk.Notebook()
                self.notebook.set_tab_pos(Gtk.PositionType.BOTTOM)
                mainhbox.pack_start(self.notebook, True, True, 0)
                self.notebook.append_page(
                    self.page1,
                    Gtk.Label('Details'))
                self.notebook.append_page(
                    self.page2,
                    Gtk.Label('README')
        )
            else:
                mainhbox.pack_start(self.page1, True, True, 0)
        vbox.pack_start(mainhbox, True, True, 0)

        hbox = Gtk.Box(spacing=6)
        vbox.pack_start(hbox, False, False, 0)

        button = Gtk.Button.new_with_mnemonic("_Install")
        button.connect("clicked", self.on_install_clicked)
        hbox.pack_start(button, False, False, 0)

        button = Gtk.Button.new_with_mnemonic("_Cancel")
        button.connect("clicked", self.on_cancel_clicked)
        hbox.pack_end(button, False, False, 0)
        bind_accelerator(self.accelerators, button, '<Control>w')

        self.add(vbox)
        self.resize(635, 270)

    def check(self, view, frame, req, nav, policy):
        uri = req.get_uri()
        if not self.readme in uri:
            webbrowser.open(uri)
            policy.ignore()
            return True
        return False

    def on_install_clicked(self, button):
        print("Installing keyboard")
        install_kmp(self.kmpfile, self.online)
        if self.viewwindow:
            self.viewwindow.refresh_installed_kmp()
        keyboardid = os.path.basename(os.path.splitext(self.kmpfile)[0])
        welcome_file = os.path.join("/usr/local/share/doc/keyman", keyboardid, "welcome.htm")
        if os.path.isfile(welcome_file):
            uri_path = pathlib.Path(welcome_file).as_uri()
            print(uri_path)
            w = WelcomeView(uri_path, self.kbname)
            w.resize(800, 600)
            w.show_all()
        else:
            dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
                Gtk.ButtonsType.OK, "Keyboard " + self.kbname + " installed")
            dialog.run()
            print("INFO dialog closed")
            dialog.destroy()
        if not self.endonclose:
            self.close()

    def on_cancel_clicked(self, button):
        print("Cancel install keyboard")
        if self.endonclose:
            Gtk.main_quit()
        else:
            self.close()

    def connectdestroy(self):
        self.connect("destroy", Gtk.main_quit)
        self.endonclose = True

def main(argv):
    if len(sys.argv) != 2:
        print("install_window.py <kmpfile>")
        sys.exit(2)

    name, ext = os.path.splitext(sys.argv[1])
    if ext != ".kmp":
        print("install_window.py Input file", sys.argv[1], "is not a kmp file.")
        print("install_window.py <kmpfile>")
        sys.exit(2)

    if not os.path.isfile(sys.argv[1]):
        print("install_window.py Keyman kmp file", sys.argv[1], "not found.")
        print("install_window.py <kmpfile>")
        sys.exit(2)

    w = InstallKmpWindow(sys.argv[1])
    w.connectdestroy()
    w.resize(800, 450)
    if w.checkcontinue:
        w.show_all()
        Gtk.main()

if __name__ == "__main__":
	main(sys.argv[1:])
<|endoftext|>


<commit_before>from   six       import itervalues, string_types
from   .         import errors
from   .normdict import NormalizedDict
from   .scanner  import scan_file, scan_lines, scan_string
from   .types    import lower
from   .util     import unfold

class HeaderParser(object):
    def __init__(self, normalizer=None, body=True):
        self.normalizer = normalizer or lower
        self.body = body
        self.headerdefs = dict()
        self.dests = set()

    def add_header(self, name, *altnames, **kwargs):
        kwargs.setdefault('dest', name)
        hd = HeaderDef(name=name, **kwargs)
        normed = set(map(self.normalizer, (name,) + altnames))
        # Error before modifying anything:
        redefs = [n for n in self.headerdefs if n in normed]
        if redefs:
            raise ValueError('header defined more than once: '+repr(redefs[0]))
        if self.normalizer(hd.dest) in self.dests:
            raise ValueError('destination defined more than once: '
                             + repr(hd.dest))
        for n in normed:
            self.headerdefs[n] = hd
        self.dests.add(self.normalizer(hd.dest))

    def parse_stream(self, headers):
        data = NormalizedDict(normalizer=self.normalizer)
        for k,v in headers:
            if k is None:
                assert data.body is None
                data.body = v
            else:
                try:
                    hd = self.headerdefs[self.normalizer(k)]
                except KeyError:
                    raise errors.UnknownHeaderError(k)
                hd.process_value(data, v)
        for hd in itervalues(self.headerdefs):
            if hd.dest not in data:
                if hd.required:
                    raise errors.MissingHeaderError(hd.name)
                elif hasattr(hd, 'default'):
                    data[hd.dest] = hd.default
        return data

    def parse_file(self, fp):
        return self.parse_stream(scan_file(fp))

    def parse_lines(self, iterable):
        return self.parse_stream(scan_lines(iterable))

    def parse_string(self, s):
        return self.parse_stream(scan_string(s))

class HeaderDef(object):
    def __init__(self, name, dest, type=None, multiple=False, required=False,
                 unfold=False, choices=None, **kwargs):
        if not isinstance(name, string_types):
            raise TypeError('header names must be strings')
        self.name = name
        self.dest = dest
        self.type = type
        self.multiple = bool(multiple)
        self.required = bool(required)
        self.unfold = bool(unfold)
        if choices is not None:
            choices = list(choices)
            if not choices:
                raise ValueError('empty list supplied for choices')
        self.choices = choices
        if 'default' in kwargs:
            if self.required:
                raise ValueError('required and default are mutually exclusive')
            self.default = kwargs.pop('default')
        if kwargs:
            raise TypeError('invalid keyword argument: '
                            + repr(next(iter(kwargs))))

    def process_value(self, data, value):
        if self.unfold:
            value = unfold(value)
        if self.type is not None:
            try:
                value = self.type(value)
            except errors.HeaderTypeError:
                raise
            except Exception as e:
                raise errors.HeaderTypeError(self.name, value, e)
        if self.choices is not None and value not in self.choices:
            raise errors.InvalidChoiceError(self.name, value)
        if self.multiple:
            data.setdefault(self.dest, []).append(value)
        elif self.dest in data:
            raise errors.DuplicateHeaderError(self.name)
        else:
            data[self.dest] = value
<commit_msg>Basic implementation of `add_additional`<commit_after>from   six       import itervalues, string_types
from   .         import errors
from   .normdict import NormalizedDict
from   .scanner  import scan_file, scan_lines, scan_string
from   .types    import lower
from   .util     import unfold

class HeaderParser(object):
    def __init__(self, normalizer=None, body=True):
        self.normalizer = normalizer or lower
        self.body = body
        self.headerdefs = dict()
        self.dests = set()
        self.additional = None
        self.custom_dests = False

    def add_header(self, name, *altnames, **kwargs):
        kwargs.setdefault('dest', name)
        hd = HeaderDef(name=name, **kwargs)
        normed = set(map(self.normalizer, (name,) + altnames))
        # Error before modifying anything:
        redefs = [n for n in self.headerdefs if n in normed]
        if redefs:
            raise ValueError('header defined more than once: '+repr(redefs[0]))
        if self.normalizer(hd.dest) in self.dests:
            raise ValueError('destination defined more than once: '
                             + repr(hd.dest))
        if self.normalizer(hd.dest) not in normed:
            self.custom_dests = True
            if self.additional is not None:
                raise ValueError('add_additional and `dest` are mutually exclusive')
        for n in normed:
            self.headerdefs[n] = hd
        self.dests.add(self.normalizer(hd.dest))

    def add_additional(self, allow=True, **kwargs):
        if allow:
            if self.custom_dests:
                raise ValueError('add_additional and `dest` are mutually exclusive')
            self.additional = HeaderProcessor(**kwargs)
        else:
            self.additional = None

    def parse_stream(self, headers):
        data = NormalizedDict(normalizer=self.normalizer)
        for k,v in headers:
            if k is None:
                assert data.body is None
                data.body = v
            else:
                try:
                    hd = self.headerdefs[self.normalizer(k)]
                except KeyError:
                    if self.additional is not None:
                        self.additional.process(data, k, k, v)
                    else:
                        raise errors.UnknownHeaderError(k)
                else:
                    hd.process_value(data, v)
        for hd in itervalues(self.headerdefs):
            if hd.dest not in data:
                if hd.required:
                    raise errors.MissingHeaderError(hd.name)
                elif hasattr(hd, 'default'):
                    data[hd.dest] = hd.default
        return data

    def parse_file(self, fp):
        return self.parse_stream(scan_file(fp))

    def parse_lines(self, iterable):
        return self.parse_stream(scan_lines(iterable))

    def parse_string(self, s):
        return self.parse_stream(scan_string(s))

class HeaderDef(object):
    def __init__(self, name, dest, required=False, **kwargs):
        if not isinstance(name, string_types):
            raise TypeError('header names must be strings')
        self.name = name
        self.dest = dest
        self.required = bool(required)
        if 'default' in kwargs:
            if self.required:
                raise ValueError('required and default are mutually exclusive')
            self.default = kwargs.pop('default')
        self.proc = HeaderProcessor(**kwargs)

    def process_value(self, data, value):
        self.proc.process(data, self.name, self.dest, value)

class HeaderProcessor(object):
    def __init__(self, type=None, multiple=False, unfold=False, choices=None):
        self.type = type
        self.multiple = bool(multiple)
        self.unfold = bool(unfold)
        if choices is not None:
            choices = list(choices)
            if not choices:
                raise ValueError('empty list supplied for choices')
        self.choices = choices

    def process(self, data, name, dest, value):
        if self.unfold:
            value = unfold(value)
        if self.type is not None:
            try:
                value = self.type(value)
            except errors.HeaderTypeError:
                raise
            except Exception as e:
                raise errors.HeaderTypeError(name, value, e)
        if self.choices is not None and value not in self.choices:
            raise errors.InvalidChoiceError(name, value)
        if self.multiple:
            data.setdefault(dest, []).append(value)
        elif dest in data:
            raise errors.DuplicateHeaderError(name)
        else:
            data[dest] = value
<|endoftext|>


<commit_before>import json
import logging

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.http import HttpResponse, Http404
from django.utils import simplejson
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

from mitxmako.shortcuts import render_to_response, render_to_string
from courseware.courses import get_course_with_access
from courseware.access import has_access

from urllib import urlencode
from operator import methodcaller
from django_comment_client.permissions import check_permissions_by_view
from django_comment_client.utils import merge_dict, extract, strip_none, strip_blank, get_courseware_context

import django_comment_client.utils as utils
import comment_client as cc
import xml.sax.saxutils as saxutils

THREADS_PER_PAGE = 200
INLINE_THREADS_PER_PAGE = 5
PAGES_NEARBY_DELTA = 2

log = logging.getLogger("edx.discussions")

def _general_discussion_id(course_id):
    return course_id.replace('/', '_').replace('.', '_')

def _should_perform_search(request):
    return bool(request.GET.get('text', False) or \
            request.GET.get('tags', False))

def render_accordion(request, course, discussion_id):
    # TODO: Delete if obsolete
    discussion_info = utils.get_categorized_discussion_info(request, course)

    context = {
        'course': course,
        'discussion_info': discussion_info,
        'active': discussion_id,
        'csrf': csrf(request)['csrf_token'],
    }

    return render_to_string('discussion/_accordion.html', context)

def render_discussion(request, course_id, threads, *args, **kwargs):
    discussion_id = kwargs.get('discussion_id')
    user_id = kwargs.get('user_id')
    discussion_type = kwargs.get('discussion_type', 'inline')
    query_params = kwargs.get('query_params', {})

    template = {
        'inline': 'discussion/_inline.html',
        'forum': 'discussion/_forum.html',
        'user': 'discussion/_user_active_threads.html',
    }[discussion_type]

    base_url = {
        'inline': (lambda: reverse('django_comment_client.forum.views.inline_discussion', args=[course_id, discussion_id])),
        'forum': (lambda: reverse('django_comment_client.forum.views.forum_form_discussion', args=[course_id])),
        'user': (lambda: reverse('django_comment_client.forum.views.user_profile', args=[course_id, user_id])),
    }[discussion_type]()

    user_info = cc.User.from_django_user(request.user).to_dict()

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

    if discussion_type != 'inline':
        course = get_course_with_access(request.user, course_id, 'load')

        for thread in threads:
            courseware_context = get_courseware_context(thread, course)
            if courseware_context:
                thread['courseware_location']  = courseware_context['courseware_location']
                thread['courseware_title']  = courseware_context['courseware_title']

    context = {
        #'threads': map(utils.safe_content, threads),   # TODO Delete, this is redundant with discussion_data
        'discussion_id': discussion_id,
        'user_id': user_id,
        'course_id': course_id,
        'request': request,
        'performed_search': _should_perform_search(request),
        'pages_nearby_delta': PAGES_NEARBY_DELTA,
        'discussion_type': discussion_type,
        'base_url': base_url,
        'query_params': strip_blank(strip_none(extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text']))),
        'annotated_content_info': json.dumps(annotated_content_info),
        'discussion_data': json.dumps({ (discussion_id or user_id): map(utils.safe_content, threads) })
    }
    context = dict(context.items() + query_params.items())
    return render_to_string(template, context)

def render_inline_discussion(*args, **kwargs):
    return render_discussion(discussion_type='inline', *args, **kwargs)

def render_forum_discussion(*args, **kwargs):
    return render_discussion(discussion_type='forum', *args, **kwargs)

def render_user_discussion(*args, **kwargs):
    return render_discussion(discussion_type='user', *args, **kwargs)

def get_threads(request, course_id, discussion_id=None, per_page=THREADS_PER_PAGE):
    """
    This may raise cc.utils.CommentClientError or
    cc.utils.CommentClientUnknownError if something goes wrong.
    """

    default_query_params = {
        'page': 1,
        'per_page': per_page,
        'sort_key': 'date',
        'sort_order': 'desc',
        'text': '',
        'tags': '',
        'commentable_id': discussion_id,
        'course_id': course_id,
    }

    if not request.GET.get('sort_key'):
        # If the user did not select a sort key, use their last used sort key
        user = cc.User.from_django_user(request.user)
        user.retrieve()
        # TODO: After the comment service is updated this can just be user.default_sort_key because the service returns the default value
        default_query_params['sort_key'] = user.get('default_sort_key') or default_query_params['sort_key']
    else:
        # If the user clicked a sort key, update their default sort key
        user = cc.User.from_django_user(request.user)
        user.default_sort_key = request.GET.get('sort_key')
        user.save()

    query_params = merge_dict(default_query_params,
                              strip_none(extract(request.GET, ['page', 'sort_key', 'sort_order', 'text', 'tags'])))

    threads, page, num_pages = cc.Thread.search(query_params)

    query_params['page'] = page
    query_params['num_pages'] = num_pages

    return threads, query_params

def inline_discussion(request, course_id, discussion_id):
    """
    Renders JSON for DiscussionModules
    """

    try:
        threads, query_params = get_threads(request, course_id, discussion_id, per_page=INLINE_THREADS_PER_PAGE)
        user_info = cc.User.from_django_user(request.user).to_dict()
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        # TODO (vshnayder): since none of this code seems to be aware of the fact that
        # sometimes things go wrong, I suspect that the js client is also not
        # checking for errors on request.  Check and fix as needed.
        raise Http404

    # TODO: Remove all of this stuff or switch back to server side rendering once templates are mustache again
    #html = render_inline_discussion(request, course_id, threads, discussion_id=discussion_id,  \
    #                                                             query_params=query_params)

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

    return utils.JsonResponse({
#        'html': html,
        'discussion_data': map(utils.safe_content, threads),
        'user_info': user_info,
        'annotated_content_info': annotated_content_info,
        'page': query_params['page'],
        'num_pages': query_params['num_pages']
    })

def forum_form_discussion(request, course_id):
    """
    Renders the main Discussion page, potentially filtered by a search query
    """
    course = get_course_with_access(request.user, course_id, 'load')
    category_map = utils.get_discussion_category_map(course)

    try:
        unsafethreads, query_params = get_threads(request, course_id)   # This might process a search query
        threads = [utils.safe_content(thread) for thread in unsafethreads]
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        raise Http404

    #content = render_forum_discussion(request, course_id, threads, discussion_id=_general_discussion_id(course_id), query_params=query_params)

    user_info = cc.User.from_django_user(request.user).to_dict()

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})
    for thread in threads:
        courseware_context = get_courseware_context(thread, course)
        if courseware_context:
            thread['courseware_location']  = courseware_context['courseware_location']
            thread['courseware_title']  = courseware_context['courseware_title']
    if request.is_ajax():
        return utils.JsonResponse({
            #'html': content,
            'discussion_data': threads,
            'annotated_content_info': annotated_content_info,
        })
    else:
        #recent_active_threads = cc.search_recent_active_threads(
        #    course_id,
        #    recursive=False,
        #    query_params={'follower_id': request.user.id},
        #)

        #trending_tags = cc.search_trending_tags(
        #    course_id,
        #)

        escapedict = {'"': '"'}
        context = {
            'csrf': csrf(request)['csrf_token'],
            'course': course,
            #'content': content,
            #'recent_active_threads': recent_active_threads,
            #'trending_tags': trending_tags,
            'staff_access' : has_access(request.user, course, 'staff'),
            'threads': saxutils.escape(json.dumps(threads),escapedict),
            'user_info': saxutils.escape(json.dumps(user_info),escapedict),
            'annotated_content_info': saxutils.escape(json.dumps(annotated_content_info),escapedict),
            'course_id': course.id,
            'category_map': category_map,
        }
        # print "start rendering.."
        return render_to_response('discussion/index.html', context)

def single_thread(request, course_id, discussion_id, thread_id):

    if request.is_ajax():
        course = get_course_with_access(request.user, course_id, 'load')
        user_info = cc.User.from_django_user(request.user).to_dict()

        try:
            thread = cc.Thread.find(thread_id).retrieve(recursive=True)
        except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
            raise Http404
        courseware_context = get_courseware_context(thread, course)

        annotated_content_info = utils.get_annotated_content_infos(course_id, thread, request.user, user_info=user_info)
        context = {'thread': thread.to_dict(), 'course_id': course_id}
        # TODO: Remove completely or switch back to server side rendering
        html = render_to_string('discussion/_ajax_single_thread.html', context)
        content = utils.safe_content(thread.to_dict())
        if courseware_context:
            content.update(courseware_context)
        return utils.JsonResponse({
            'html': html,
            'content': content,
            'annotated_content_info': annotated_content_info,
        })

    else:
        course = get_course_with_access(request.user, course_id, 'load')
        category_map = utils.get_discussion_category_map(course)
        try:
            threads, query_params = get_threads(request, course_id)
        except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
            raise Http404

        course = get_course_with_access(request.user, course_id, 'load')

        for thread in threads:
            courseware_context = get_courseware_context(thread, course)
            if courseware_context:
                thread['courseware_location']  = courseware_context['courseware_location']
                thread['courseware_title']  = courseware_context['courseware_title']

        #recent_active_threads = cc.search_recent_active_threads(
        #    course_id,
        #    recursive=False,
        #    query_params={'follower_id': request.user.id},
        #)

        #trending_tags = cc.search_trending_tags(
        #    course_id,
        #)

        user_info = cc.User.from_django_user(request.user).to_dict()
        escapedict = {'"': '"'}

        def infogetter(thread):
            return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

        annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

        context = {
            'discussion_id': discussion_id,
            'csrf': csrf(request)['csrf_token'],
            'init': '',
            'user_info': saxutils.escape(json.dumps(user_info),escapedict),
            'annotated_content_info': saxutils.escape(json.dumps(annotated_content_info), escapedict),
            'course': course,
            #'recent_active_threads': recent_active_threads,
            #'trending_tags': trending_tags,
            'course_id': course.id,
            'thread_id': thread_id,
            'threads': saxutils.escape(json.dumps(threads), escapedict),
            'category_map': category_map,
        }

        return render_to_response('discussion/single_thread.html', context)

def user_profile(request, course_id, user_id):

    course = get_course_with_access(request.user, course_id, 'load')
    try:
        profiled_user = cc.User(id=user_id, course_id=course_id)

        query_params['page'] = page
        query_params['num_pages'] = num_pages

        content = render_user_discussion(request, course_id, threads, user_id=user_id, query_params=query_params)

        if request.is_ajax():
            return utils.JsonResponse({
                'html': content,
                'discussion_data': map(utils.safe_content, threads),
            })
        else:
            context = {
                'course': course,
                'user': request.user,
                'django_user': User.objects.get(id=user_id),
                'profiled_user': profiled_user.to_dict(),
                'content': content,
            }

            return render_to_response('discussion/user_profile.html', context)
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        raise Http404
<commit_msg>Add @login_required to forum views so that they redirect to a login page if you're not logged in.<commit_after>import json
import logging

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.http import HttpResponse, Http404
from django.utils import simplejson
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

from mitxmako.shortcuts import render_to_response, render_to_string
from courseware.courses import get_course_with_access
from courseware.access import has_access

from urllib import urlencode
from operator import methodcaller
from django_comment_client.permissions import check_permissions_by_view
from django_comment_client.utils import merge_dict, extract, strip_none, strip_blank, get_courseware_context

import django_comment_client.utils as utils
import comment_client as cc
import xml.sax.saxutils as saxutils

THREADS_PER_PAGE = 200
INLINE_THREADS_PER_PAGE = 5
PAGES_NEARBY_DELTA = 2

log = logging.getLogger("edx.discussions")

def _general_discussion_id(course_id):
    return course_id.replace('/', '_').replace('.', '_')

def _should_perform_search(request):
    return bool(request.GET.get('text', False) or \
            request.GET.get('tags', False))

def render_accordion(request, course, discussion_id):
    # TODO: Delete if obsolete
    discussion_info = utils.get_categorized_discussion_info(request, course)

    context = {
        'course': course,
        'discussion_info': discussion_info,
        'active': discussion_id,
        'csrf': csrf(request)['csrf_token'],
    }

    return render_to_string('discussion/_accordion.html', context)

def render_discussion(request, course_id, threads, *args, **kwargs):
    discussion_id = kwargs.get('discussion_id')
    user_id = kwargs.get('user_id')
    discussion_type = kwargs.get('discussion_type', 'inline')
    query_params = kwargs.get('query_params', {})

    template = {
        'inline': 'discussion/_inline.html',
        'forum': 'discussion/_forum.html',
        'user': 'discussion/_user_active_threads.html',
    }[discussion_type]

    base_url = {
        'inline': (lambda: reverse('django_comment_client.forum.views.inline_discussion', args=[course_id, discussion_id])),
        'forum': (lambda: reverse('django_comment_client.forum.views.forum_form_discussion', args=[course_id])),
        'user': (lambda: reverse('django_comment_client.forum.views.user_profile', args=[course_id, user_id])),
    }[discussion_type]()

    user_info = cc.User.from_django_user(request.user).to_dict()

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

    if discussion_type != 'inline':
        course = get_course_with_access(request.user, course_id, 'load')

        for thread in threads:
            courseware_context = get_courseware_context(thread, course)
            if courseware_context:
                thread['courseware_location']  = courseware_context['courseware_location']
                thread['courseware_title']  = courseware_context['courseware_title']

    context = {
        #'threads': map(utils.safe_content, threads),   # TODO Delete, this is redundant with discussion_data
        'discussion_id': discussion_id,
        'user_id': user_id,
        'course_id': course_id,
        'request': request,
        'performed_search': _should_perform_search(request),
        'pages_nearby_delta': PAGES_NEARBY_DELTA,
        'discussion_type': discussion_type,
        'base_url': base_url,
        'query_params': strip_blank(strip_none(extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text']))),
        'annotated_content_info': json.dumps(annotated_content_info),
        'discussion_data': json.dumps({ (discussion_id or user_id): map(utils.safe_content, threads) })
    }
    context = dict(context.items() + query_params.items())
    return render_to_string(template, context)

def render_inline_discussion(*args, **kwargs):
    return render_discussion(discussion_type='inline', *args, **kwargs)

def render_forum_discussion(*args, **kwargs):
    return render_discussion(discussion_type='forum', *args, **kwargs)

def render_user_discussion(*args, **kwargs):
    return render_discussion(discussion_type='user', *args, **kwargs)

def get_threads(request, course_id, discussion_id=None, per_page=THREADS_PER_PAGE):
    """
    This may raise cc.utils.CommentClientError or
    cc.utils.CommentClientUnknownError if something goes wrong.
    """

    default_query_params = {
        'page': 1,
        'per_page': per_page,
        'sort_key': 'date',
        'sort_order': 'desc',
        'text': '',
        'tags': '',
        'commentable_id': discussion_id,
        'course_id': course_id,
    }

    if not request.GET.get('sort_key'):
        # If the user did not select a sort key, use their last used sort key
        user = cc.User.from_django_user(request.user)
        user.retrieve()
        # TODO: After the comment service is updated this can just be user.default_sort_key because the service returns the default value
        default_query_params['sort_key'] = user.get('default_sort_key') or default_query_params['sort_key']
    else:
        # If the user clicked a sort key, update their default sort key
        user = cc.User.from_django_user(request.user)
        user.default_sort_key = request.GET.get('sort_key')
        user.save()

    query_params = merge_dict(default_query_params,
                              strip_none(extract(request.GET, ['page', 'sort_key', 'sort_order', 'text', 'tags'])))

    threads, page, num_pages = cc.Thread.search(query_params)

    query_params['page'] = page
    query_params['num_pages'] = num_pages

    return threads, query_params

def inline_discussion(request, course_id, discussion_id):
    """
    Renders JSON for DiscussionModules
    """

    try:
        threads, query_params = get_threads(request, course_id, discussion_id, per_page=INLINE_THREADS_PER_PAGE)
        user_info = cc.User.from_django_user(request.user).to_dict()
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        # TODO (vshnayder): since none of this code seems to be aware of the fact that
        # sometimes things go wrong, I suspect that the js client is also not
        # checking for errors on request.  Check and fix as needed.
        raise Http404

    # TODO: Remove all of this stuff or switch back to server side rendering once templates are mustache again
    #html = render_inline_discussion(request, course_id, threads, discussion_id=discussion_id,  \
    #                                                             query_params=query_params)

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

    return utils.JsonResponse({
#        'html': html,
        'discussion_data': map(utils.safe_content, threads),
        'user_info': user_info,
        'annotated_content_info': annotated_content_info,
        'page': query_params['page'],
        'num_pages': query_params['num_pages']
    })

@login_required
def forum_form_discussion(request, course_id):
    """
    Renders the main Discussion page, potentially filtered by a search query
    """
    course = get_course_with_access(request.user, course_id, 'load')
    category_map = utils.get_discussion_category_map(course)

    try:
        unsafethreads, query_params = get_threads(request, course_id)   # This might process a search query
        threads = [utils.safe_content(thread) for thread in unsafethreads]
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        raise Http404

    #content = render_forum_discussion(request, course_id, threads, discussion_id=_general_discussion_id(course_id), query_params=query_params)

    user_info = cc.User.from_django_user(request.user).to_dict()

    def infogetter(thread):
        return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

    annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})
    for thread in threads:
        courseware_context = get_courseware_context(thread, course)
        if courseware_context:
            thread['courseware_location']  = courseware_context['courseware_location']
            thread['courseware_title']  = courseware_context['courseware_title']
    if request.is_ajax():
        return utils.JsonResponse({
            #'html': content,
            'discussion_data': threads,
            'annotated_content_info': annotated_content_info,
        })
    else:
        #recent_active_threads = cc.search_recent_active_threads(
        #    course_id,
        #    recursive=False,
        #    query_params={'follower_id': request.user.id},
        #)

        #trending_tags = cc.search_trending_tags(
        #    course_id,
        #)

        escapedict = {'"': '"'}
        context = {
            'csrf': csrf(request)['csrf_token'],
            'course': course,
            #'content': content,
            #'recent_active_threads': recent_active_threads,
            #'trending_tags': trending_tags,
            'staff_access' : has_access(request.user, course, 'staff'),
            'threads': saxutils.escape(json.dumps(threads),escapedict),
            'user_info': saxutils.escape(json.dumps(user_info),escapedict),
            'annotated_content_info': saxutils.escape(json.dumps(annotated_content_info),escapedict),
            'course_id': course.id,
            'category_map': category_map,
        }
        # print "start rendering.."
        return render_to_response('discussion/index.html', context)

@login_required
def single_thread(request, course_id, discussion_id, thread_id):

    if request.is_ajax():
        course = get_course_with_access(request.user, course_id, 'load')
        user_info = cc.User.from_django_user(request.user).to_dict()

        try:
            thread = cc.Thread.find(thread_id).retrieve(recursive=True)
        except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
            raise Http404
        courseware_context = get_courseware_context(thread, course)

        annotated_content_info = utils.get_annotated_content_infos(course_id, thread, request.user, user_info=user_info)
        context = {'thread': thread.to_dict(), 'course_id': course_id}
        # TODO: Remove completely or switch back to server side rendering
        html = render_to_string('discussion/_ajax_single_thread.html', context)
        content = utils.safe_content(thread.to_dict())
        if courseware_context:
            content.update(courseware_context)
        return utils.JsonResponse({
            'html': html,
            'content': content,
            'annotated_content_info': annotated_content_info,
        })

    else:
        course = get_course_with_access(request.user, course_id, 'load')
        category_map = utils.get_discussion_category_map(course)
        try:
            threads, query_params = get_threads(request, course_id)
        except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
            raise Http404

        course = get_course_with_access(request.user, course_id, 'load')

        for thread in threads:
            courseware_context = get_courseware_context(thread, course)
            if courseware_context:
                thread['courseware_location']  = courseware_context['courseware_location']
                thread['courseware_title']  = courseware_context['courseware_title']

        #recent_active_threads = cc.search_recent_active_threads(
        #    course_id,
        #    recursive=False,
        #    query_params={'follower_id': request.user.id},
        #)

        #trending_tags = cc.search_trending_tags(
        #    course_id,
        #)

        user_info = cc.User.from_django_user(request.user).to_dict()
        escapedict = {'"': '"'}

        def infogetter(thread):
            return utils.get_annotated_content_infos(course_id, thread, request.user, user_info)

        annotated_content_info = reduce(merge_dict, map(infogetter, threads), {})

        context = {
            'discussion_id': discussion_id,
            'csrf': csrf(request)['csrf_token'],
            'init': '',
            'user_info': saxutils.escape(json.dumps(user_info),escapedict),
            'annotated_content_info': saxutils.escape(json.dumps(annotated_content_info), escapedict),
            'course': course,
            #'recent_active_threads': recent_active_threads,
            #'trending_tags': trending_tags,
            'course_id': course.id,
            'thread_id': thread_id,
            'threads': saxutils.escape(json.dumps(threads), escapedict),
            'category_map': category_map,
        }

        return render_to_response('discussion/single_thread.html', context)

@login_required
def user_profile(request, course_id, user_id):

    course = get_course_with_access(request.user, course_id, 'load')
    try:
        profiled_user = cc.User(id=user_id, course_id=course_id)

        query_params['page'] = page
        query_params['num_pages'] = num_pages

        content = render_user_discussion(request, course_id, threads, user_id=user_id, query_params=query_params)

        if request.is_ajax():
            return utils.JsonResponse({
                'html': content,
                'discussion_data': map(utils.safe_content, threads),
            })
        else:
            context = {
                'course': course,
                'user': request.user,
                'django_user': User.objects.get(id=user_id),
                'profiled_user': profiled_user.to_dict(),
                'content': content,
            }

            return render_to_response('discussion/user_profile.html', context)
    except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
        raise Http404
<|endoftext|>


<commit_before>#
# Copyright (c) 2006 rPath, Inc
# All rights reserved
#

from gettext import gettext as _

import raa
import time
import logging
from raa import rpath_error
from raa import constants
from raa.db import schedule, data
from raa.lib import repeatschedules
from raa.modules.raawebplugin import rAAWebPlugin, disablePlugin
import raa.web
from mint import config

log = logging.getLogger('rPath.repoconvert')

class SqliteToPgsql(rAAWebPlugin):
    """
    Takes a sqlite repository and converts it to postgresql
    """

    # Name to be displayed in the side bar.
    displayName = _("PostgreSQL Conversion")

    # Name to be displayed on mouse over in the side bar.
    tooltip = _("Convert your repository to use Postgres")

    def _readConfig(self, repoconfig):
        cfg = config.MintConfig()
        cfg.read(repoconfig)
        return cfg

    def _getConfig(self):
        ret = dict()

        repoCfg = self._readConfig(config.RBUILDER_CONFIG)
        ret['converted'] = (repoCfg.reposDBDriver == 'postgresql')
        ret['finalized'] = self.getPropertyValue('FINALIZED', False)
        if ret['finalized'] and not ret['converted']:
            self.setPropertyValue('raa.hidden', False, data.RDT_BOOL)
            log.warning('Fixing up finalized state')
            self.deletePropertyValue('FINALIZED')
            ret['finalized'] = False

        #Figure out if a job is currently running
        listTasks = raa.web.getWebRoot().execution.getUnfinishedSchedules(
            schedule.typesValid,
            constants.TASKS_UNFINISHED, taskId = self.taskId)
        listTasks.reverse()
        running = False
        for (execId, schedId) in listTasks:
            status = raa.web.getWebRoot().getStatus(schedId)
            statusCode = status['status']
            statusmsg = status['statusmsg']
            if statusCode == constants.TASK_RUNNING:
                running = True
                break
        ret['running'] = running
        if running:
            ret.update(dict(schedId=schedId, status=statusCode, statusmsg=statusmsg))
        return ret

    @raa.web.expose(allow_xmlrpc=True, template="rPath.repoconvert.templates.index")
    def index(self):
        return self._getConfig()

    @raa.web.expose(allow_json=True)
    def convert(self, confirm=False):
        if confirm:
            self.setPropertyValue('FINALIZED', False, data.RDT_BOOL)
            sched = schedule.ScheduleNow()
            schedId = self.schedule(sched)
            return dict(schedId=schedId)
        else:
            return dict(error=_('Conversion not confirmed'))

    @raa.web.expose(allow_json=True)
    def finalize(self, confirm=False):
        if confirm:
            self.setPropertyValue('FINALIZED', True, data.RDT_BOOL)
            # TODO: Clean up the wasted space
            self.setPropertyValue('raa.hidden', True, data.RDT_BOOL)
            return dict(message=_("Conversion finalized"))
        else:
            return dict(error=_('Finalize step not confirmed'))

    def initPlugin(self):
        repoCfg = self._readConfig(config.RBUILDER_CONFIG)
        val = self.getPropertyValue('FINALIZED')
        if repoCfg.reposDBDriver == 'postgresql' and (val==0 or val):
                #val is 0 if this is a fresh install, True if we've
                #already finalized
            # self.setPropertyValue('raa.hidden', True, data.RDT_BOOL)
            self.setPropertyValue('raa.hidden', False, data.RDT_BOOL)
        else:
            self.setPropertyValue('raa.hidden', False, data.RDT_BOOL)
<commit_msg>RBL-3499 remove some debugging code<commit_after>#
# Copyright (c) 2006 rPath, Inc
# All rights reserved
#

from gettext import gettext as _

import raa
import time
import logging
from raa import rpath_error
from raa import constants
from raa.db import schedule, data
from raa.lib import repeatschedules
from raa.modules.raawebplugin import rAAWebPlugin, disablePlugin
import raa.web
from mint import config

log = logging.getLogger('rPath.repoconvert')

class SqliteToPgsql(rAAWebPlugin):
    """
    Takes a sqlite repository and converts it to postgresql
    """

    # Name to be displayed in the side bar.
    displayName = _("PostgreSQL Conversion")

    # Name to be displayed on mouse over in the side bar.
    tooltip = _("Convert your repository to use Postgres")

    def _readConfig(self, repoconfig):
        cfg = config.MintConfig()
        cfg.read(repoconfig)
        return cfg

    def _getConfig(self):
        ret = dict()

        repoCfg = self._readConfig(config.RBUILDER_CONFIG)
        ret['converted'] = (repoCfg.reposDBDriver == 'postgresql')
        ret['finalized'] = self.getPropertyValue('FINALIZED', False)
        if ret['finalized'] and not ret['converted']:
            self.setPropertyValue('raa.hidden', False, data.RDT_BOOL)
            log.warning('Fixing up finalized state')
            self.deletePropertyValue('FINALIZED')
            ret['finalized'] = False

        #Figure out if a job is currently running
        listTasks = raa.web.getWebRoot().execution.getUnfinishedSchedules(
            schedule.typesValid,
            constants.TASKS_UNFINISHED, taskId = self.taskId)
        listTasks.reverse()
        running = False
        for (execId, schedId) in listTasks:
            status = raa.web.getWebRoot().getStatus(schedId)
            statusCode = status['status']
            statusmsg = status['statusmsg']
            if statusCode == constants.TASK_RUNNING:
                running = True
                break
        ret['running'] = running
        if running:
            ret.update(dict(schedId=schedId, status=statusCode, statusmsg=statusmsg))
        return ret

    @raa.web.expose(allow_xmlrpc=True, template="rPath.repoconvert.templates.index")
    def index(self):
        return self._getConfig()

    @raa.web.expose(allow_json=True)
    def convert(self, confirm=False):
        if confirm:
            self.setPropertyValue('FINALIZED', False, data.RDT_BOOL)
            sched = schedule.ScheduleNow()
            schedId = self.schedule(sched)
            return dict(schedId=schedId)
        else:
            return dict(error=_('Conversion not confirmed'))

    @raa.web.expose(allow_json=True)
    def finalize(self, confirm=False):
        if confirm:
            self.setPropertyValue('FINALIZED', True, data.RDT_BOOL)
            # TODO: Clean up the wasted space
            self.setPropertyValue('raa.hidden', True, data.RDT_BOOL)
            return dict(message=_("Conversion finalized"))
        else:
            return dict(error=_('Finalize step not confirmed'))

    def initPlugin(self):
        repoCfg = self._readConfig(config.RBUILDER_CONFIG)
        val = self.getPropertyValue('FINALIZED')
        if repoCfg.reposDBDriver == 'postgresql' and (val==0 or val):
                #val is 0 if this is a fresh install, True if we've
                #already finalized
            self.setPropertyValue('raa.hidden', True, data.RDT_BOOL)
        else:
            self.setPropertyValue('raa.hidden', False, data.RDT_BOOL)
<|endoftext|>