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

import os
import json
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Gio, GdkPixbuf
from random import randint

from helpers import rgb_to_hex, hex_to_rgb

class Coulr(Gtk.Window):

    def __init__(self):
        """Initialize Coulr"""
        Gtk.Window.__init__(self, title="Coulr", border_width=10)
        self.set_size_request(600, 250)

        # Main vars
        self.config = dict()
        self.output_format = "hex"
        self.rgb_color = None
        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

        # Config
        self.config["config_path"] = os.path.expanduser("~") + "/.config/Coulr/"

        # Header bar
        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(True)
        header_bar.props.title = "Coulr"
        header_bar.set_subtitle("Enjoy colors and feel happy !")
        self.set_titlebar(header_bar)

        # Settings button
        menu = Gtk.Menu()
        for menu_label in ["About"]:
            menu_item = Gtk.MenuItem(menu_label)
            menu_item.connect("activate", self.menu_item)
            menu.append(menu_item)
        menu.show_all()
        menu_button = Gtk.MenuButton(popup=menu)
        icon_settings = Gio.ThemedIcon(name="emblem-system-symbolic")
        image_settings = Gtk.Image.new_from_gicon(icon_settings, Gtk.IconSize.BUTTON)
        menu_button.add(image_settings)
        header_bar.pack_end(menu_button)

        # Copy button
        button_copy = Gtk.Button()
        icon_copy = Gio.ThemedIcon(name="edit-copy-symbolic")
        image_copy = Gtk.Image.new_from_gicon(icon_copy, Gtk.IconSize.BUTTON)
        button_copy.add(image_copy)
        button_copy.connect("clicked", self.copy_output)
        header_bar.pack_end(button_copy)

        # Main wrapper
        main_box = Gtk.Grid(column_spacing=6)

        # Second layout level
        layout1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        layout2 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        main_box.attach(layout1, 0, 0, 1, 1)
        main_box.attach(layout2, 1, 0, 1, 1)
        self.add(main_box)

        # Layout 1
        self.notebook_input = Gtk.Notebook()

        # RGB tab
        grid_rgb = Gtk.Grid(row_spacing=6, column_spacing=6, border_width=10)

        # Red spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_r = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_r.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_r, 0, 0, 1, 1)

        # Red slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_r = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_r.set_vexpand(True)
        self.slider_r.set_hexpand(True)
        self.slider_r.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_r, 1, 0, 2, 1)

        # Green spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_g = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_g.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_g, 0, 1, 1, 1)

        # Green slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_g = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_g.set_vexpand(True)
        self.slider_g.set_hexpand(True)
        self.slider_g.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_g, 1, 1, 2, 1)

        # Blue spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_b = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_b.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_b, 0, 2, 1, 1)

        # Blue slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_b = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_b.set_vexpand(True)
        self.slider_b.set_hexpand(True)
        self.slider_b.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_b, 1, 2, 2, 1)

        # Hex tab
        box_hex = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, border_width=10)
        self.entry_hex = Gtk.Entry(max_length=7)
        self.entry_hex.connect("changed", self.hex_entry_changed)
        box_hex.add(self.entry_hex)

        # Lucky tab
        box_luck = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, border_width=10)
        self.button_luck = Gtk.Button("Feel lucky !")
        self.button_luck.connect("clicked", self.luck_button_clicked)
        box_luck.add(self.button_luck)

        self.notebook_input.append_page(grid_rgb, Gtk.Label("RGB"))
        self.notebook_input.append_page(box_hex, Gtk.Label("Hexadecimal"))
        self.notebook_input.append_page(box_luck, Gtk.Label("Lucky mode"))

        # Layout 2
        # Output mode
        self.combo_output = Gtk.ComboBoxText()
        self.combo_output.append("hex", "Hexadecimal")
        self.combo_output.append("rgb", "RGB")
        self.combo_output.set_active(0)
        self.combo_output.connect("changed", self.combo_output_format)

        # Output label
        self.output = Gtk.Label(selectable=True)

        # Preview color with square
        self.square = Gtk.Frame()
        self.square.set_size_request(150, 150)

        layout1.add(self.notebook_input)
        layout2.add(self.square)
        layout2.add(self.combo_output)
        layout2.add(self.output)

        # Initialize color
        try:
            with open(self.config["config_path"] + "save.json", "r") as save_file:
                data = json.load(save_file)
                self.change_color(hex_to_rgb(data["color"].lstrip("#")))
        except EnvironmentError:
            self.change_color((randint(0, 255), randint(0, 255), randint(0, 255)))

    def change_color(self, rgb):
        """Refresh preview and set values of all fields.
        :param rgb: rgb color values
        :type rgb: tuple

        """

        rgba = Gdk.RGBA()
        rgba.parse("rgb({},{},{})".format(*rgb))
        self.square.override_background_color(Gtk.StateType.NORMAL, rgba)

        self.spinbutton_r.set_value(rgb[0])
        self.slider_r.set_value(rgb[0])

        self.slider_g.set_value(rgb[1])
        self.spinbutton_g.set_value(rgb[1])

        self.slider_b.set_value(rgb[2])
        self.spinbutton_b.set_value(rgb[2])

        self.entry_hex.set_text(rgb_to_hex(rgb))

        self.rgb_color = rgb
        self.change_output()

    def change_output(self):
        """Set output field"""
        if self.output_format == "hex":
            output = rgb_to_hex(self.rgb_color)
        elif self.output_format == "rgb":
            output = "rgb({},{},{})".format(*self.rgb_color)

        self.output.set_text(output)

    def rgb_spin_changed(self, event):
        """RGB spinners values changed"""
        spin_red = self.spinbutton_r.get_value_as_int()
        spin_green = self.spinbutton_g.get_value_as_int()
        spin_blue = self.spinbutton_b.get_value_as_int()

        self.change_color((spin_red, spin_green, spin_blue))

    def rgb_slider_moved(self, event):
        """RGB sliders values changed"""
        slider_red = int(self.slider_r.get_value())
        slider_green = int(self.slider_g.get_value())
        slider_blue = int(self.slider_b.get_value())

        self.change_color((slider_red, slider_green, slider_blue))

    def hex_entry_changed(self, event):
        """Hex entry value changed"""
        value = self.entry_hex.get_text().lstrip("#")

        if len(value) == 6:
            rgb = hex_to_rgb(value)
            self.change_color(rgb)

    def luck_button_clicked(self, event):
        """Luck button clicked"""
        self.change_color((randint(0, 255), randint(0, 255), randint(0, 255)))

    def combo_output_format(self, event):
        """Change output format"""
        self.output_format = self.combo_output.get_active_id()
        self.change_output()

    def copy_output(self, event):
        """Copy current output"""
        self.clipboard.set_text(self.output.get_text(), -1)

    def menu_item(self, menu_item):
        """Item menu clicked"""
        label = menu_item.get_label()
        if label == "About":
            self.about_dialog()

    def about_dialog(self):
        """About dialog"""
        about_dialog = Gtk.AboutDialog(self)
        about_dialog.set_program_name("Coulr")
        about_dialog.set_version("1.0.1")
        about_dialog.set_copyright("Hugo Posnic")
        about_dialog.set_comments("Enjoy colors and feel happy !")
        about_dialog.set_website("https://github.com/Huluti/Coulr")
        about_dialog.set_website_label("Github")
        about_dialog.set_authors(["Hugo Posnic"])
        about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(os.path.dirname(os.path.abspath(__file__)) + "/coulr.png"))
        about_dialog.set_license("Coulr is under MIT Licence. \nSee https://github.com/Huluti/Coulr/blob/master/LICENSE")
        about_dialog.set_transient_for(self)
        about_dialog.run()
        about_dialog.destroy()

    def quit_coulr(self, event, data):
        """Save last color then quit app"""
        if not os.path.isdir(self.config["config_path"]):
            os.makedirs(self.config["config_path"])

        try:
            with open(self.config["config_path"] + "save.json", "w") as save_file:
                data = {"color": rgb_to_hex(self.rgb_color)}
                json.dump(data, save_file)
        except EnvironmentError:
            print("Error when trying to set save file.")

        Gtk.main_quit()

win = Coulr()
win.connect("delete-event", win.quit_coulr)
win.show_all()
Gtk.main()
<commit_msg>Center window<commit_after>
#!/usr/bin/env python

import os
import json
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Gio, GdkPixbuf
from random import randint

from helpers import rgb_to_hex, hex_to_rgb

class Coulr(Gtk.Window):

    def __init__(self):
        """Initialize Coulr"""
        Gtk.Window.__init__(self, title="Coulr", border_width=10)
        self.set_size_request(600, 250)
        self.set_position(Gtk.WindowPosition.CENTER)

        # Main vars
        self.config = dict()
        self.output_format = "hex"
        self.rgb_color = None
        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

        # Config
        self.config["config_path"] = os.path.expanduser("~") + "/.config/Coulr/"

        # Header bar
        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(True)
        header_bar.props.title = "Coulr"
        header_bar.set_subtitle("Enjoy colors and feel happy !")
        self.set_titlebar(header_bar)

        # Settings button
        menu = Gtk.Menu()
        for menu_label in ["About"]:
            menu_item = Gtk.MenuItem(menu_label)
            menu_item.connect("activate", self.menu_item)
            menu.append(menu_item)
        menu.show_all()
        menu_button = Gtk.MenuButton(popup=menu)
        icon_settings = Gio.ThemedIcon(name="emblem-system-symbolic")
        image_settings = Gtk.Image.new_from_gicon(icon_settings, Gtk.IconSize.BUTTON)
        menu_button.add(image_settings)
        header_bar.pack_end(menu_button)

        # Copy button
        button_copy = Gtk.Button()
        icon_copy = Gio.ThemedIcon(name="edit-copy-symbolic")
        image_copy = Gtk.Image.new_from_gicon(icon_copy, Gtk.IconSize.BUTTON)
        button_copy.add(image_copy)
        button_copy.connect("clicked", self.copy_output)
        header_bar.pack_end(button_copy)

        # Main wrapper
        main_box = Gtk.Grid(column_spacing=6)

        # Second layout level
        layout1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        layout2 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        main_box.attach(layout1, 0, 0, 1, 1)
        main_box.attach(layout2, 1, 0, 1, 1)
        self.add(main_box)

        # Layout 1
        self.notebook_input = Gtk.Notebook()

        # RGB tab
        grid_rgb = Gtk.Grid(row_spacing=6, column_spacing=6, border_width=10)

        # Red spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_r = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_r.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_r, 0, 0, 1, 1)

        # Red slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_r = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_r.set_vexpand(True)
        self.slider_r.set_hexpand(True)
        self.slider_r.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_r, 1, 0, 2, 1)

        # Green spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_g = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_g.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_g, 0, 1, 1, 1)

        # Green slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_g = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_g.set_vexpand(True)
        self.slider_g.set_hexpand(True)
        self.slider_g.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_g, 1, 1, 2, 1)

        # Blue spinner
        adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0)
        self.spinbutton_b = Gtk.SpinButton(adjustment=adj)
        self.spinbutton_b.connect("value-changed", self.rgb_spin_changed)
        grid_rgb.attach(self.spinbutton_b, 0, 2, 1, 1)

        # Blue slider
        adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0)
        self.slider_b = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj, draw_value=False)
        self.slider_b.set_vexpand(True)
        self.slider_b.set_hexpand(True)
        self.slider_b.connect("value-changed", self.rgb_slider_moved)
        grid_rgb.attach(self.slider_b, 1, 2, 2, 1)

        # Hex tab
        box_hex = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, border_width=10)
        self.entry_hex = Gtk.Entry(max_length=7)
        self.entry_hex.connect("changed", self.hex_entry_changed)
        box_hex.add(self.entry_hex)

        # Lucky tab
        box_luck = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, border_width=10)
        self.button_luck = Gtk.Button("Feel lucky !")
        self.button_luck.connect("clicked", self.luck_button_clicked)
        box_luck.add(self.button_luck)

        self.notebook_input.append_page(grid_rgb, Gtk.Label("RGB"))
        self.notebook_input.append_page(box_hex, Gtk.Label("Hexadecimal"))
        self.notebook_input.append_page(box_luck, Gtk.Label("Lucky mode"))

        # Layout 2
        # Output mode
        self.combo_output = Gtk.ComboBoxText()
        self.combo_output.append("hex", "Hexadecimal")
        self.combo_output.append("rgb", "RGB")
        self.combo_output.set_active(0)
        self.combo_output.connect("changed", self.combo_output_format)

        # Output label
        self.output = Gtk.Label(selectable=True)

        # Preview color with square
        self.square = Gtk.Frame()
        self.square.set_size_request(150, 150)

        layout1.add(self.notebook_input)
        layout2.add(self.square)
        layout2.add(self.combo_output)
        layout2.add(self.output)

        # Initialize color
        try:
            with open(self.config["config_path"] + "save.json", "r") as save_file:
                data = json.load(save_file)
                self.change_color(hex_to_rgb(data["color"].lstrip("#")))
        except EnvironmentError:
            self.change_color((randint(0, 255), randint(0, 255), randint(0, 255)))

    def change_color(self, rgb):
        """Refresh preview and set values of all fields.
        :param rgb: rgb color values
        :type rgb: tuple

        """

        rgba = Gdk.RGBA()
        rgba.parse("rgb({},{},{})".format(*rgb))
        self.square.override_background_color(Gtk.StateType.NORMAL, rgba)

        self.spinbutton_r.set_value(rgb[0])
        self.slider_r.set_value(rgb[0])

        self.slider_g.set_value(rgb[1])
        self.spinbutton_g.set_value(rgb[1])

        self.slider_b.set_value(rgb[2])
        self.spinbutton_b.set_value(rgb[2])

        self.entry_hex.set_text(rgb_to_hex(rgb))

        self.rgb_color = rgb
        self.change_output()

    def change_output(self):
        """Set output field"""
        if self.output_format == "hex":
            output = rgb_to_hex(self.rgb_color)
        elif self.output_format == "rgb":
            output = "rgb({},{},{})".format(*self.rgb_color)

        self.output.set_text(output)

    def rgb_spin_changed(self, event):
        """RGB spinners values changed"""
        spin_red = self.spinbutton_r.get_value_as_int()
        spin_green = self.spinbutton_g.get_value_as_int()
        spin_blue = self.spinbutton_b.get_value_as_int()

        self.change_color((spin_red, spin_green, spin_blue))

    def rgb_slider_moved(self, event):
        """RGB sliders values changed"""
        slider_red = int(self.slider_r.get_value())
        slider_green = int(self.slider_g.get_value())
        slider_blue = int(self.slider_b.get_value())

        self.change_color((slider_red, slider_green, slider_blue))

    def hex_entry_changed(self, event):
        """Hex entry value changed"""
        value = self.entry_hex.get_text().lstrip("#")

        if len(value) == 6:
            rgb = hex_to_rgb(value)
            self.change_color(rgb)

    def luck_button_clicked(self, event):
        """Luck button clicked"""
        self.change_color((randint(0, 255), randint(0, 255), randint(0, 255)))

    def combo_output_format(self, event):
        """Change output format"""
        self.output_format = self.combo_output.get_active_id()
        self.change_output()

    def copy_output(self, event):
        """Copy current output"""
        self.clipboard.set_text(self.output.get_text(), -1)

    def menu_item(self, menu_item):
        """Item menu clicked"""
        label = menu_item.get_label()
        if label == "About":
            self.about_dialog()

    def about_dialog(self):
        """About dialog"""
        about_dialog = Gtk.AboutDialog(self)
        about_dialog.set_program_name("Coulr")
        about_dialog.set_version("1.0.1")
        about_dialog.set_copyright("Hugo Posnic")
        about_dialog.set_comments("Enjoy colors and feel happy !")
        about_dialog.set_website("https://github.com/Huluti/Coulr")
        about_dialog.set_website_label("Github")
        about_dialog.set_authors(["Hugo Posnic"])
        about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(os.path.dirname(os.path.abspath(__file__)) + "/coulr.png"))
        about_dialog.set_license("Coulr is under MIT Licence. \nSee https://github.com/Huluti/Coulr/blob/master/LICENSE")
        about_dialog.set_transient_for(self)
        about_dialog.run()
        about_dialog.destroy()

    def quit_coulr(self, event, data):
        """Save last color then quit app"""
        if not os.path.isdir(self.config["config_path"]):
            os.makedirs(self.config["config_path"])

        try:
            with open(self.config["config_path"] + "save.json", "w") as save_file:
                data = {"color": rgb_to_hex(self.rgb_color)}
                json.dump(data, save_file)
        except EnvironmentError:
            print("Error when trying to set save file.")

        Gtk.main_quit()

win = Coulr()
win.connect("delete-event", win.quit_coulr)
win.show_all()
Gtk.main()
<|endoftext|>


<commit_before>"""Tests for certbot.crypto_util."""
import logging
import shutil
import tempfile
import unittest

import OpenSSL
import mock
import zope.component

from certbot import errors
from certbot import interfaces
from certbot import le_util
from certbot.tests import test_util

RSA256_KEY = test_util.load_vector('rsa256_key.pem')
RSA512_KEY = test_util.load_vector('rsa512_key.pem')
CERT_PATH = test_util.vector_path('cert.pem')
CERT = test_util.load_vector('cert.pem')
SAN_CERT = test_util.load_vector('cert-san.pem')

class InitSaveKeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_key."""
    def setUp(self):
        logging.disable(logging.CRITICAL)
        zope.component.provideUtility(
            mock.Mock(strict_permissions=True), interfaces.IConfig)
        self.key_dir = tempfile.mkdtemp('key_dir')

    def tearDown(self):
        logging.disable(logging.NOTSET)
        shutil.rmtree(self.key_dir)

    @classmethod
    def _call(cls, key_size, key_dir):
        from certbot.crypto_util import init_save_key
        return init_save_key(key_size, key_dir, 'key-certbot.pem')

    @mock.patch('certbot.crypto_util.make_key')
    def test_success(self, mock_make):
        mock_make.return_value = 'key_pem'
        key = self._call(1024, self.key_dir)
        self.assertEqual(key.pem, 'key_pem')
        self.assertTrue('key-certbot.pem' in key.file)

    @mock.patch('certbot.crypto_util.make_key')
    def test_key_failure(self, mock_make):
        mock_make.side_effect = ValueError
        self.assertRaises(ValueError, self._call, 431, self.key_dir)

class InitSaveCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_csr."""

    def setUp(self):
        zope.component.provideUtility(
            mock.Mock(strict_permissions=True), interfaces.IConfig)
        self.csr_dir = tempfile.mkdtemp('csr_dir')

    def tearDown(self):
        shutil.rmtree(self.csr_dir)

    @mock.patch('certbot.crypto_util.make_csr')
    @mock.patch('certbot.crypto_util.le_util.make_or_verify_dir')
    def test_it(self, unused_mock_verify, mock_csr):
        from certbot.crypto_util import init_save_csr

        mock_csr.return_value = ('csr_pem', 'csr_der')

        csr = init_save_csr(
            mock.Mock(pem='dummy_key'), 'example.com', self.csr_dir,
            'csr-certbot.pem')

        self.assertEqual(csr.data, 'csr_der')
        self.assertTrue('csr-certbot.pem' in csr.file)

class MakeCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.make_csr."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import make_csr
        return make_csr(*args, **kwargs)

    def test_san(self):
        from certbot.crypto_util import get_sans_from_csr
        # TODO: Fails for RSA256_KEY
        csr_pem, csr_der = self._call(
            RSA512_KEY, ['example.com', 'www.example.com'])
        self.assertEqual(
            ['example.com', 'www.example.com'], get_sans_from_csr(csr_pem))
        self.assertEqual(
            ['example.com', 'www.example.com'], get_sans_from_csr(
                csr_der, OpenSSL.crypto.FILETYPE_ASN1))

    def test_must_staple(self):
        # TODO: Fails for RSA256_KEY
        csr_pem, _ = self._call(
            RSA512_KEY, ['example.com', 'www.example.com'], must_staple=True)
        csr = OpenSSL.crypto.load_certificate_request(
            OpenSSL.crypto.FILETYPE_PEM, csr_pem)

        # In pyopenssl 0.13 (used with TOXENV=py26-oldest and py27-oldest), csr
        # objects don't have a get_extensions() method, so we skip this test if
        # the method isn't available.
        if hasattr(csr, 'get_extensions'):
            # NOTE: Ideally we would filter by the TLS Feature OID, but
            # OpenSSL.crypto.X509Extension doesn't give us the extension's raw OID,
            # and the shortname field is just "UNDEF"
            must_staple_exts = [e for e in csr.get_extensions()
                if e.get_data() == "0\x03\x02\x01\x05"]
            self.assertEqual(len(must_staple_exts), 1,
                "Expected exactly one Must Staple extension")

class ValidCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_csr."""

    @classmethod
    def _call(cls, csr):
        from certbot.crypto_util import valid_csr
        return valid_csr(csr)

    def test_valid_pem_true(self):
        self.assertTrue(self._call(test_util.load_vector('csr.pem')))

    def test_valid_pem_san_true(self):
        self.assertTrue(self._call(test_util.load_vector('csr-san.pem')))

    def test_valid_der_false(self):
        self.assertFalse(self._call(test_util.load_vector('csr.der')))

    def test_valid_der_san_false(self):
        self.assertFalse(self._call(test_util.load_vector('csr-san.der')))

    def test_empty_false(self):
        self.assertFalse(self._call(''))

    def test_random_false(self):
        self.assertFalse(self._call('foo bar'))

class CSRMatchesPubkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.csr_matches_pubkey."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import csr_matches_pubkey
        return csr_matches_pubkey(*args, **kwargs)

    def test_valid_true(self):
        self.assertTrue(self._call(
            test_util.load_vector('csr.pem'), RSA512_KEY))

    def test_invalid_false(self):
        self.assertFalse(self._call(
            test_util.load_vector('csr.pem'), RSA256_KEY))

class ImportCSRFileTest(unittest.TestCase):
    """Tests for certbot.certbot_util.import_csr_file."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import import_csr_file
        return import_csr_file(*args, **kwargs)

    def test_der_csr(self):
        csrfile = test_util.vector_path('csr.der')
        data = test_util.load_vector('csr.der')

        self.assertEqual(
            (OpenSSL.crypto.FILETYPE_ASN1,
             le_util.CSR(file=csrfile,
                         data=data,
                         form="der"),
             ["example.com"],),
            self._call(csrfile, data))

    def test_pem_csr(self):
        csrfile = test_util.vector_path('csr.pem')
        data = test_util.load_vector('csr.pem')

        self.assertEqual(
            (OpenSSL.crypto.FILETYPE_PEM,
             le_util.CSR(file=csrfile,
                         data=data,
                         form="pem"),
             ["example.com"],),
            self._call(csrfile, data))

class MakeKeyTest(unittest.TestCase):  # pylint: disable=too-few-public-methods
    """Tests for certbot.crypto_util.make_key."""

    def test_it(self):  # pylint: disable=no-self-use
        from certbot.crypto_util import make_key
        # Do not test larger keys as it takes too long.
        OpenSSL.crypto.load_privatekey(
            OpenSSL.crypto.FILETYPE_PEM, make_key(1024))

class ValidPrivkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_privkey."""

    @classmethod
    def _call(cls, privkey):
        from certbot.crypto_util import valid_privkey
        return valid_privkey(privkey)

    def test_valid_true(self):
        self.assertTrue(self._call(RSA256_KEY))

    def test_empty_false(self):
        self.assertFalse(self._call(''))

    def test_random_false(self):
        self.assertFalse(self._call('foo bar'))

class GetSANsFromCertTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_sans_from_cert."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_sans_from_cert
        return get_sans_from_cert(*args, **kwargs)

    def test_single(self):
        self.assertEqual([], self._call(test_util.load_vector('cert.pem')))

    def test_san(self):
        self.assertEqual(
            ['example.com', 'www.example.com'],
            self._call(test_util.load_vector('cert-san.pem')))

class GetSANsFromCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_sans_from_csr."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_sans_from_csr
        return get_sans_from_csr(*args, **kwargs)

    def test_extract_one_san(self):
        self.assertEqual(['example.com'], self._call(
            test_util.load_vector('csr.pem')))

    def test_extract_two_sans(self):
        self.assertEqual(['example.com', 'www.example.com'], self._call(
            test_util.load_vector('csr-san.pem')))

    def test_extract_six_sans(self):
        self.assertEqual(self._call(test_util.load_vector('csr-6sans.pem')),
                         ["example.com", "example.org", "example.net",
                          "example.info", "subdomain.example.com",
                          "other.subdomain.example.com"])

    def test_parse_non_csr(self):
        self.assertRaises(OpenSSL.crypto.Error, self._call, "hello there")

    def test_parse_no_sans(self):
        self.assertEqual(
            [], self._call(test_util.load_vector('csr-nosans.pem')))

class GetNamesFromCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_names_from_csr."""
    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_names_from_csr
        return get_names_from_csr(*args, **kwargs)

    def test_extract_one_san(self):
        self.assertEqual(['example.com'], self._call(
            test_util.load_vector('csr.pem')))

    def test_extract_two_sans(self):
        self.assertEqual(set(('example.com', 'www.example.com',)), set(
            self._call(test_util.load_vector('csr-san.pem'))))

    def test_extract_six_sans(self):
        self.assertEqual(
            set(self._call(test_util.load_vector('csr-6sans.pem'))),
            set(("example.com", "example.org", "example.net",
                 "example.info", "subdomain.example.com",
                 "other.subdomain.example.com",)))

    def test_parse_non_csr(self):
        self.assertRaises(OpenSSL.crypto.Error, self._call, "hello there")

    def test_parse_no_sans(self):
        self.assertEqual(["example.org"],
                         self._call(test_util.load_vector('csr-nosans.pem')))

class CertLoaderTest(unittest.TestCase):
    """Tests for certbot.crypto_util.pyopenssl_load_certificate"""

    def test_load_valid_cert(self):
        from certbot.crypto_util import pyopenssl_load_certificate

        cert, file_type = pyopenssl_load_certificate(CERT)
        self.assertEqual(cert.digest('sha1'),
                         OpenSSL.crypto.load_certificate(file_type, CERT).digest('sha1'))

    def test_load_invalid_cert(self):
        from certbot.crypto_util import pyopenssl_load_certificate
        bad_cert_data = CERT.replace("BEGIN CERTIFICATE", "ASDFASDFASDF!!!")
        self.assertRaises(
            errors.Error, pyopenssl_load_certificate, bad_cert_data)

class NotBeforeTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notBefore"""

    def test_notBefore(self):
        from certbot.crypto_util import notBefore
        self.assertEqual(notBefore(CERT_PATH).isoformat(),
                         '2014-12-11T22:34:45+00:00')

class NotAfterTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notAfter"""

    def test_notAfter(self):
        from certbot.crypto_util import notAfter
        self.assertEqual(notAfter(CERT_PATH).isoformat(),
                         '2014-12-18T22:34:45+00:00')

if __name__ == '__main__':
    unittest.main()  # pragma: no cover
<commit_msg>Test bad csr<commit_after>"""Tests for certbot.crypto_util."""
import logging
import shutil
import tempfile
import unittest

import OpenSSL
import mock
import zope.component

from certbot import errors
from certbot import interfaces
from certbot import le_util
from certbot.tests import test_util

RSA256_KEY = test_util.load_vector('rsa256_key.pem')
RSA512_KEY = test_util.load_vector('rsa512_key.pem')
CERT_PATH = test_util.vector_path('cert.pem')
CERT = test_util.load_vector('cert.pem')
SAN_CERT = test_util.load_vector('cert-san.pem')

class InitSaveKeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_key."""
    def setUp(self):
        logging.disable(logging.CRITICAL)
        zope.component.provideUtility(
            mock.Mock(strict_permissions=True), interfaces.IConfig)
        self.key_dir = tempfile.mkdtemp('key_dir')

    def tearDown(self):
        logging.disable(logging.NOTSET)
        shutil.rmtree(self.key_dir)

    @classmethod
    def _call(cls, key_size, key_dir):
        from certbot.crypto_util import init_save_key
        return init_save_key(key_size, key_dir, 'key-certbot.pem')

    @mock.patch('certbot.crypto_util.make_key')
    def test_success(self, mock_make):
        mock_make.return_value = 'key_pem'
        key = self._call(1024, self.key_dir)
        self.assertEqual(key.pem, 'key_pem')
        self.assertTrue('key-certbot.pem' in key.file)

    @mock.patch('certbot.crypto_util.make_key')
    def test_key_failure(self, mock_make):
        mock_make.side_effect = ValueError
        self.assertRaises(ValueError, self._call, 431, self.key_dir)

class InitSaveCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_csr."""

    def setUp(self):
        zope.component.provideUtility(
            mock.Mock(strict_permissions=True), interfaces.IConfig)
        self.csr_dir = tempfile.mkdtemp('csr_dir')

    def tearDown(self):
        shutil.rmtree(self.csr_dir)

    @mock.patch('certbot.crypto_util.make_csr')
    @mock.patch('certbot.crypto_util.le_util.make_or_verify_dir')
    def test_it(self, unused_mock_verify, mock_csr):
        from certbot.crypto_util import init_save_csr

        mock_csr.return_value = ('csr_pem', 'csr_der')

        csr = init_save_csr(
            mock.Mock(pem='dummy_key'), 'example.com', self.csr_dir,
            'csr-certbot.pem')

        self.assertEqual(csr.data, 'csr_der')
        self.assertTrue('csr-certbot.pem' in csr.file)

class MakeCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.make_csr."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import make_csr
        return make_csr(*args, **kwargs)

    def test_san(self):
        from certbot.crypto_util import get_sans_from_csr
        # TODO: Fails for RSA256_KEY
        csr_pem, csr_der = self._call(
            RSA512_KEY, ['example.com', 'www.example.com'])
        self.assertEqual(
            ['example.com', 'www.example.com'], get_sans_from_csr(csr_pem))
        self.assertEqual(
            ['example.com', 'www.example.com'], get_sans_from_csr(
                csr_der, OpenSSL.crypto.FILETYPE_ASN1))

    def test_must_staple(self):
        # TODO: Fails for RSA256_KEY
        csr_pem, _ = self._call(
            RSA512_KEY, ['example.com', 'www.example.com'], must_staple=True)
        csr = OpenSSL.crypto.load_certificate_request(
            OpenSSL.crypto.FILETYPE_PEM, csr_pem)

        # In pyopenssl 0.13 (used with TOXENV=py26-oldest and py27-oldest), csr
        # objects don't have a get_extensions() method, so we skip this test if
        # the method isn't available.
        if hasattr(csr, 'get_extensions'):
            # NOTE: Ideally we would filter by the TLS Feature OID, but
            # OpenSSL.crypto.X509Extension doesn't give us the extension's raw OID,
            # and the shortname field is just "UNDEF"
            must_staple_exts = [e for e in csr.get_extensions()
                if e.get_data() == "0\x03\x02\x01\x05"]
            self.assertEqual(len(must_staple_exts), 1,
                "Expected exactly one Must Staple extension")

class ValidCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_csr."""

    @classmethod
    def _call(cls, csr):
        from certbot.crypto_util import valid_csr
        return valid_csr(csr)

    def test_valid_pem_true(self):
        self.assertTrue(self._call(test_util.load_vector('csr.pem')))

    def test_valid_pem_san_true(self):
        self.assertTrue(self._call(test_util.load_vector('csr-san.pem')))

    def test_valid_der_false(self):
        self.assertFalse(self._call(test_util.load_vector('csr.der')))

    def test_valid_der_san_false(self):
        self.assertFalse(self._call(test_util.load_vector('csr-san.der')))

    def test_empty_false(self):
        self.assertFalse(self._call(''))

    def test_random_false(self):
        self.assertFalse(self._call('foo bar'))

class CSRMatchesPubkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.csr_matches_pubkey."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import csr_matches_pubkey
        return csr_matches_pubkey(*args, **kwargs)

    def test_valid_true(self):
        self.assertTrue(self._call(
            test_util.load_vector('csr.pem'), RSA512_KEY))

    def test_invalid_false(self):
        self.assertFalse(self._call(
            test_util.load_vector('csr.pem'), RSA256_KEY))

class ImportCSRFileTest(unittest.TestCase):
    """Tests for certbot.certbot_util.import_csr_file."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import import_csr_file
        return import_csr_file(*args, **kwargs)

    def test_der_csr(self):
        csrfile = test_util.vector_path('csr.der')
        data = test_util.load_vector('csr.der')

        self.assertEqual(
            (OpenSSL.crypto.FILETYPE_ASN1,
             le_util.CSR(file=csrfile,
                         data=data,
                         form="der"),
             ["example.com"],),
            self._call(csrfile, data))

    def test_pem_csr(self):
        csrfile = test_util.vector_path('csr.pem')
        data = test_util.load_vector('csr.pem')

        self.assertEqual(
            (OpenSSL.crypto.FILETYPE_PEM,
             le_util.CSR(file=csrfile,
                         data=data,
                         form="pem"),
             ["example.com"],),
            self._call(csrfile, data))

    def test_bad_csr(self):
        self.assertRaises(errors.Error, self._call,
                          test_util.vector_path('cert.pem'),
                          test_util.load_vector('cert.pem'))

class MakeKeyTest(unittest.TestCase):  # pylint: disable=too-few-public-methods
    """Tests for certbot.crypto_util.make_key."""

    def test_it(self):  # pylint: disable=no-self-use
        from certbot.crypto_util import make_key
        # Do not test larger keys as it takes too long.
        OpenSSL.crypto.load_privatekey(
            OpenSSL.crypto.FILETYPE_PEM, make_key(1024))

class ValidPrivkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_privkey."""

    @classmethod
    def _call(cls, privkey):
        from certbot.crypto_util import valid_privkey
        return valid_privkey(privkey)

    def test_valid_true(self):
        self.assertTrue(self._call(RSA256_KEY))

    def test_empty_false(self):
        self.assertFalse(self._call(''))

    def test_random_false(self):
        self.assertFalse(self._call('foo bar'))

class GetSANsFromCertTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_sans_from_cert."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_sans_from_cert
        return get_sans_from_cert(*args, **kwargs)

    def test_single(self):
        self.assertEqual([], self._call(test_util.load_vector('cert.pem')))

    def test_san(self):
        self.assertEqual(
            ['example.com', 'www.example.com'],
            self._call(test_util.load_vector('cert-san.pem')))

class GetSANsFromCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_sans_from_csr."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_sans_from_csr
        return get_sans_from_csr(*args, **kwargs)

    def test_extract_one_san(self):
        self.assertEqual(['example.com'], self._call(
            test_util.load_vector('csr.pem')))

    def test_extract_two_sans(self):
        self.assertEqual(['example.com', 'www.example.com'], self._call(
            test_util.load_vector('csr-san.pem')))

    def test_extract_six_sans(self):
        self.assertEqual(self._call(test_util.load_vector('csr-6sans.pem')),
                         ["example.com", "example.org", "example.net",
                          "example.info", "subdomain.example.com",
                          "other.subdomain.example.com"])

    def test_parse_non_csr(self):
        self.assertRaises(OpenSSL.crypto.Error, self._call, "hello there")

    def test_parse_no_sans(self):
        self.assertEqual(
            [], self._call(test_util.load_vector('csr-nosans.pem')))

class GetNamesFromCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_names_from_csr."""
    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_names_from_csr
        return get_names_from_csr(*args, **kwargs)

    def test_extract_one_san(self):
        self.assertEqual(['example.com'], self._call(
            test_util.load_vector('csr.pem')))

    def test_extract_two_sans(self):
        self.assertEqual(set(('example.com', 'www.example.com',)), set(
            self._call(test_util.load_vector('csr-san.pem'))))

    def test_extract_six_sans(self):
        self.assertEqual(
            set(self._call(test_util.load_vector('csr-6sans.pem'))),
            set(("example.com", "example.org", "example.net",
                 "example.info", "subdomain.example.com",
                 "other.subdomain.example.com",)))

    def test_parse_non_csr(self):
        self.assertRaises(OpenSSL.crypto.Error, self._call, "hello there")

    def test_parse_no_sans(self):
        self.assertEqual(["example.org"],
                         self._call(test_util.load_vector('csr-nosans.pem')))

class CertLoaderTest(unittest.TestCase):
    """Tests for certbot.crypto_util.pyopenssl_load_certificate"""

    def test_load_valid_cert(self):
        from certbot.crypto_util import pyopenssl_load_certificate

        cert, file_type = pyopenssl_load_certificate(CERT)
        self.assertEqual(cert.digest('sha1'),
                         OpenSSL.crypto.load_certificate(file_type, CERT).digest('sha1'))

    def test_load_invalid_cert(self):
        from certbot.crypto_util import pyopenssl_load_certificate
        bad_cert_data = CERT.replace("BEGIN CERTIFICATE", "ASDFASDFASDF!!!")
        self.assertRaises(
            errors.Error, pyopenssl_load_certificate, bad_cert_data)

class NotBeforeTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notBefore"""

    def test_notBefore(self):
        from certbot.crypto_util import notBefore
        self.assertEqual(notBefore(CERT_PATH).isoformat(),
                         '2014-12-11T22:34:45+00:00')

class NotAfterTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notAfter"""

    def test_notAfter(self):
        from certbot.crypto_util import notAfter
        self.assertEqual(notAfter(CERT_PATH).isoformat(),
                         '2014-12-18T22:34:45+00:00')

if __name__ == '__main__':
    unittest.main()  # pragma: no cover
<|endoftext|>


<commit_before># session_cache.py

# clear cache
# ==================================================

def clear():
	clear_cache()

	import webnotes
	webnotes.response['message'] = "Cache Cleared"

def clear_cache(user=''):
	import webnotes
	try:
		if user:
			webnotes.conn.sql("delete from __SessionCache where user=%s", user)
		else:
			webnotes.conn.sql("delete from __SessionCache")
	except Exception, e:
		if e.args[0]==1146:
			make_cache_table()
		else:
			raise e

# load cache
# ==================================================

def get():
	import webnotes
	import webnotes.defs

	# get country
	country = webnotes.session['data'].get('ipinfo', {}).get('countryName', 'Unknown Country')

	# run patches
	try:
		import webnotes.modules.patch
		webnotes.modules.patch.run()
	except ImportError, e:
		pass # no patches - do nothing

	# check if cache exists
	if not getattr(webnotes.defs,'auto_cache_clear',None):
		cache = load(country)
		if cache:
			return cache

	# if not create it
	sd = build()
	dump(sd, country)

	# update profile from cache
	webnotes.session['data']['profile'] = sd['profile']

	return sd

# load cache
# ==================================================

def load(country):
	import webnotes

	try:
		sd = webnotes.conn.sql("select cache from __SessionCache where user='%s' %s" % (webnotes.session['user'], (country and (" and country='%s'" % country) or '')))
		if sd:
			return eval(sd[0][0])
		else:
			return None
	except Exception, e:
		if e.args[0]==1146:
			make_cache_table()
		else:
			raise e

# make the cache table
# ==================================================

def make_cache_table():
	import webnotes
	webnotes.conn.commit()
	webnotes.conn.sql("create table `__SessionCache` (user VARCHAR(120), country VARCHAR(120), cache LONGTEXT)")
	webnotes.conn.begin()

# dump session to cache
# ==================================================

def dump(sd, country):
	import webnotes
	import webnotes.model.utils

	if sd.get('docs'):
		sd['docs'] = webnotes.model.utils.compress(sd['docs'])

	# delete earlier (?)
	webnotes.conn.sql("delete from __SessionCache where user=%s and country=%s", (webnotes.session['user'], country))

	# make new
	webnotes.conn.sql("insert into `__SessionCache` (user, country, cache) VALUES (%s, %s, %s)", (webnotes.session['user'], country, str(sd)))

# ==================================================

def get_letter_heads():
	import webnotes
	try:
		lh = {}
		ret = webnotes.conn.sql("select name, content from `tabLetter Head` where ifnull(disabled,0)=0")
		for r in ret:
			lh[r[0]] = r[1]
		return lh
	except Exception, e:
		if e.args[0]==1146:
			return {}
		else:
			raise Exception, e

# ==================================================
# load startup.js and startup.css from the modules/startup folder

def load_startup(cp):
	from webnotes.modules import ModuleFile

	try: from webnotes.defs import modules_path
	except ImportError: return

	import os

	cp.startup_code = ModuleFile(os.path.join(modules_path, 'startup', 'startup.js')).get_content()
	cp.startup_css = ModuleFile(os.path.join(modules_path, 'startup', 'startup.css')).get_content()

# build it
# ==================================================

def build():
	sd = {}

	import webnotes
	import webnotes.model
	import webnotes.model.doc
	import webnotes.model.doctype
	import webnotes.widgets.page
	import webnotes.widgets.menus
	import webnotes.profile
	import webnotes.defs

	sql = webnotes.conn.sql

	webnotes.conn.begin()
	sd['profile'] = webnotes.user.load_profile()

	doclist = []
	doclist += webnotes.model.doc.get('Control Panel')
	cp = doclist[0]
	load_startup(cp)

	doclist += webnotes.model.doctype.get('Event')
	doclist += webnotes.model.doctype.get('Search Criteria')
	home_page = webnotes.user.get_home_page()

	if home_page:
		doclist += webnotes.widgets.page.get(home_page)

	sd['account_name'] = cp.account_id or ''
	sd['sysdefaults'] = webnotes.utils.get_defaults()
	sd['n_online'] = int(sql("SELECT COUNT(DISTINCT user) FROM tabSessions")[0][0] or 0)
	sd['docs'] = doclist
	sd['letter_heads'] = get_letter_heads()
	sd['home_page'] = home_page or ''
	sd['start_items'] = webnotes.widgets.menus.get_menu_items()
	if webnotes.session['data'].get('ipinfo'):
		sd['ipinfo'] = webnotes.session['data']['ipinfo']

	webnotes.session['data']['profile'] = sd['profile']
	sd['dt_labels'] = webnotes.model.get_dt_labels()
	webnotes.conn.commit()

	return sd
<commit_msg>fix to session cache<commit_after># session_cache.py

# clear cache
# ==================================================

def clear():
	clear_cache()

	import webnotes
	webnotes.response['message'] = "Cache Cleared"

def clear_cache(user=''):
	import webnotes
	try:
		if user:
			webnotes.conn.sql("delete from __SessionCache where user=%s", user)
		else:
			webnotes.conn.sql("delete from __SessionCache")
	except Exception, e:
		if e.args[0]==1146:
			make_cache_table()
		else:
			raise e

# load cache
# ==================================================

def get():
	import webnotes
	import webnotes.defs

	# get country
	country = webnotes.session['data'].get('ipinfo', {}).get('countryName', 'Unknown Country')

	# run patches
	try:
		import webnotes.modules.patch
		webnotes.modules.patch.run()
	except ImportError, e:
		pass # no patches - do nothing

	# check if cache exists
	if not getattr(webnotes.defs,'auto_cache_clear',None):
		cache = load(country)
		if cache:
			return cache

	# if not create it
	sd = build()
	dump(sd, country)

	# update profile from cache
	webnotes.session['data']['profile'] = sd['profile']

	return sd

# load cache
# ==================================================

def load(country):
	import webnotes

	try:
		sd = webnotes.conn.sql("select cache from __SessionCache where user='%s' %s" % (webnotes.session['user'], (country and (" and country='%s'" % country) or '')))
		if sd:
			return eval(sd[0][0])
		else:
			return None
	except Exception, e:
		if e.args[0]==1146:
			make_cache_table()
		else:
			raise e

# make the cache table
# ==================================================

def make_cache_table():
	import webnotes
	webnotes.conn.commit()
	webnotes.conn.sql("create table `__SessionCache` (user VARCHAR(120), country VARCHAR(120), cache LONGTEXT)")
	webnotes.conn.begin()

# dump session to cache
# ==================================================

def dump(sd, country):
	import webnotes
	import webnotes.model.utils

	if sd.get('docs'):
		sd['docs'] = webnotes.model.utils.compress(sd['docs'])

	# delete earlier (?)
	webnotes.conn.sql("delete from __SessionCache where user=%s and country=%s", (webnotes.session['user'], country))

	# make new
	webnotes.conn.sql("insert into `__SessionCache` (user, country, cache) VALUES (%s, %s, %s)", (webnotes.session['user'], country, str(sd)))

# ==================================================

def get_letter_heads():
	import webnotes
	try:
		lh = {}
		ret = webnotes.conn.sql("select name, content from `tabLetter Head` where ifnull(disabled,0)=0")
		for r in ret:
			lh[r[0]] = r[1]
		return lh
	except Exception, e:
		if e.args[0]==1146:
			return {}
		else:
			raise Exception, e

# ==================================================
# load startup.js and startup.css from the modules/startup folder

def load_startup(cp):
	from webnotes.modules import ModuleFile

	try: from webnotes.defs import modules_path
	except ImportError: return

	import os

	cp.startup_code = ModuleFile(os.path.join(modules_path, 'startup', 'startup.js')).load_content()
	cp.startup_css = ModuleFile(os.path.join(modules_path, 'startup', 'startup.css')).load_content()

# build it
# ==================================================

def build():
	sd = {}

	import webnotes
	import webnotes.model
	import webnotes.model.doc
	import webnotes.model.doctype
	import webnotes.widgets.page
	import webnotes.widgets.menus
	import webnotes.profile
	import webnotes.defs

	sql = webnotes.conn.sql

	webnotes.conn.begin()
	sd['profile'] = webnotes.user.load_profile()

	doclist = []
	doclist += webnotes.model.doc.get('Control Panel')
	cp = doclist[0]
	load_startup(cp)

	doclist += webnotes.model.doctype.get('Event')
	doclist += webnotes.model.doctype.get('Search Criteria')
	home_page = webnotes.user.get_home_page()

	if home_page:
		doclist += webnotes.widgets.page.get(home_page)

	sd['account_name'] = cp.account_id or ''
	sd['sysdefaults'] = webnotes.utils.get_defaults()
	sd['n_online'] = int(sql("SELECT COUNT(DISTINCT user) FROM tabSessions")[0][0] or 0)
	sd['docs'] = doclist
	sd['letter_heads'] = get_letter_heads()
	sd['home_page'] = home_page or ''
	sd['start_items'] = webnotes.widgets.menus.get_menu_items()
	if webnotes.session['data'].get('ipinfo'):
		sd['ipinfo'] = webnotes.session['data']['ipinfo']

	webnotes.session['data']['profile'] = sd['profile']
	sd['dt_labels'] = webnotes.model.get_dt_labels()
	webnotes.conn.commit()

	return sd
<|endoftext|>


<commit_before># Copyright (c) 2008 Participatory Culture Foundation
# See LICENSE for details.

import datetime
import mimetypes
import urllib
import urlparse

import feedparser
from django.core.mail import send_mail
from django.conf import settings
from django.http import (
    Http404, HttpResponseRedirect, HttpResponse, HttpResponseBadRequest)
from django.template import loader, Context

from channelguide import util, cache
from channelguide.guide import filetypes
from channelguide.guide.forms.share import ShareForm
from channelguide.guide.models import (Channel, Item)
from channelguide.guide.views import playback

# Custom exceptions for this module
class Error(Exception): pass
class FeedFetchingError(Error): pass

class FakeItem(object):
    def __init__(self, url, name=None, description=None,
                 date=None, thumbnail_url=None):
        self.url = url
        self.name = name
        self.description = description
        self.date = date
        self.thumbnail_url = thumbnail_url

        self.fake = True

        self.mime_type = filetypes.guessMimeType(self.url)

    def thumb(self):
        return util.mark_safe(
            '' % (
                self.thumbnail_url, self.name.replace('"', "'")))

    def get_url(self):
        pass

class FakeChannel(object):
    def __init__(self, name, description, url, website_url, thumbnail_url):
        self.name = name
        self.description = description
        self.url = url
        self.website_url = website_url
        self.thumbnail_url = thumbnail_url

        # Things required by the template that should be left empty
        self.categories = []
        self.tags = []
        self.hi_def = False

        self.fake = True

    def get_subscribe_hit_url(self):
        return self.get_url() + '/subscribe-hit'

    def get_subscription_url(self):
        if self.url:
            return util.get_subscription_url(
                self.url, trackback=self.get_subscribe_hit_url())
        else:
            return util.get_subscription_url(
                self.website_url, type='site',
                trackback=self.get_subscribe_hit_url())

    def website_link(self):
        url_label = self.website_url
        url_label = util.chop_prefix(url_label, 'http://')
        url_label = util.chop_prefix(url_label, 'https://')
        url_label = util.chop_prefix(url_label, 'www.')
        return util.make_link(self.website_url, url_label)

    def thumb_url_245_164(self):
        return self.thumbnail_url

def get_channels_and_items(feed_url, connection):
    feed_key = 'share_feed-' + feed_url
    items_key = 'share_feed_items-' + feed_url

    # check the cache.  If not...
    cached_channel = cache.client.get(feed_key)
    cached_items = cache.client.get(items_key)
    if cached_channel:
        channel = cached_channel
        items = cached_items
    else:
        # check to see if we have that feed in our database...
        channels = Channel.query().where(url=feed_url).execute(connection)
        if channels:
            channel = channels[0]
            cache.client.set(feed_key, channel)

            item_query = Item.query(channel_id=channel.id).join('channel')
            item_query = item_query.order_by('date', desc=True).limit(4)
            items = item_query.execute(connection)
            cache.client.set(items_key, items)
        else:
            ## parse the feed
            parsed = feedparser.parse(feed_url)

            #ok, so this doesn't work...
            if hasattr(parsed, 'status') and parsed.status != 200:
                raise FeedFetchingError("Got a non-200 status while parsing feed")

            ## generate fake channel
            if parsed.feed.has_key('thumbnail'):
                thumbnail_url = parsed.feed.thumbnail.href
            else:
                thumbnail_url = \
                    settings.STATIC_BASE_URL + 'images/generic_feed_thumb.png'

            channel = FakeChannel(
                parsed.feed.get('title'),
                parsed.feed.get('subtitle'),
                feed_url,
                parsed.feed.get('link'),
                thumbnail_url)

            items = []
            # why not limit the number of items here to 4?
            # Because we might need to check to see if a particular
            # item is in this feed if it's being faked...
            for entry in parsed.entries:
                item = FakeItem(
                    entry.link,
                    entry.title,
                    entry.summary,
                    datetime.datetime(*entry.updated_parsed[:7]),
                    thumbnail_url) # just use whatever thumbnail the channel has?
                items.append(item)

            cache.client.set(feed_key, channel)
            cache.client.set(items_key, items)

    return channel, items

def share_feed(request):
    try:
        feed_url = str(request.GET['feed_url'])
    except KeyError:
        return HttpResponse("you must supply a feed_url")

    try:
        channel, items = get_channels_and_items(feed_url, request.connection)
    except FeedFetchingError:
        return HttpResponse("This feed appears to be dead.")

    if isinstance(channel, Channel):
        return HttpResponseRedirect('/feeds/%s?share=true' % channel.id)

    share_links = util.get_share_links(channel.url, channel.name)

    return util.render_to_response(
        request, 'show-channel.html',
        {'channel': channel,
         'items': items[:4],
         'feed_url': feed_url,
         'share_type': 'feed',
         'share_links': share_links})

def share_item(request):
    # check to see if we have that item in our database...
    # If so
    #   use that item
    # else
    #   let's create a "fake" item to preview
    # render that item preview
    try:
        file_url = str(request.GET['file_url'])
    except KeyError:
        return HttpResponse("you must supply a file_url")

    feed_url = request.GET.get('feed_url')
    webpage_url = request.GET.get('webpage_url')
    item_name = request.GET.get('item_name')

    item = None
    next = None
    previous = None

    if webpage_url:
        webpage_url = str(webpage_url)

    if feed_url:
        feed_url = str(feed_url)
        try:
            channel, channel_items = get_channels_and_items(
                feed_url, request.connection)
        except FeedFetchingError:
            return HttpResponse("This feed appears to be dead.")

        # see if we have that item in the feed
        ## if it's a fake feed check the full list of items
        if isinstance(channel, FakeChannel):
            i = 0
            for this_item in channel_items:
                if this_item.url == file_url:
                    item = this_item
                    break
                i += 1
            if item:
                if i != 0:
                    previous = channel_items[i - 1]
                if len(channel_items) != i + 1:
                    next = channel_items[i + 1]

        ## if it's a real feed do a query
        else:
            # do a query for this item
            item_query = Item.query(channel_id=channel.id, url=file_url)
            item_query = item_query.join('channel')
            item_query = item_query.order_by('date', desc=True).limit(1)
            items = item_query.execute(request.connection)
            if items:
                item = items[0]

    if isinstance(item, Item):
        return HttpResponseRedirect('/items/%s?share=true' % item.id)

    ## if we don't have an item at this point, we need to generate
    ## a fake one.  It won't have much useful info though...
    if not item:
        if not item_name:
            subpath = urlparse.urlsplit(file_url)[3]
            if subpath:
                item_name = subpath.split('/')[-1]

            else:
                item_name = file_url

        item = FakeItem(file_url, item_name)

    # get the sharing info
    share_links = util.get_share_links(item.url, item.name)

    # render the page
    return util.render_to_response(
        request, 'playback.html',
        {'item': item,
         'channel': channel,
         'previous': previous,
         'next': next,
         'embed': util.mark_safe(playback.embed_code(item)),
         'feed_url': feed_url,
         'webpage_url': webpage_url,
         'item_name': item_name,
         'share_type': 'item',
         'share_links': share_links})

def email(request):
    share_form = ShareForm(request.POST)

    if not share_form.is_valid():
        return util.render_to_response(
            request, 'share-form.html',
            {'share_form': share_form,
             'share_type': share_form.data.get('share_type'),
             'feed_url': share_form.data.get('feed_url'),
             'file_url': share_form.data.get('file_url'),
             'item_url': share_form.data.get('item_url')})

    # construct the email to send out from a template
    if share_form.cleaned_data['share_type'] == 'feed':
        title = _(u'%(from_email)s wants to share a video feed with you') % {
            'from_email': share_form.cleaned_data['from_email']}
    else:
        title = _(u'%(from_email)s wants to share a video with you') % {
            'from_email': share_form.cleaned_data['from_email']}

    email_template = loader.get_template('guide/share-email.txt')
    email_body = email_template.render(Context(share_form.cleaned_data))

    send_mail(
        title, email_body,
        share_form.cleaned_data['from_email'],
        share_form.cleaned_data['recipients'],
        fail_silently=False)

    return util.render_to_response(
        request, 'share-email-success.html', {})
<commit_msg>Switching over to the miroguide-specific mail sending stuffs<commit_after># Copyright (c) 2008 Participatory Culture Foundation
# See LICENSE for details.

import datetime
import mimetypes
import urllib
import urlparse

import feedparser
from django.conf import settings
from django.http import (
    Http404, HttpResponseRedirect, HttpResponse, HttpResponseBadRequest)
from django.template import loader, Context

from channelguide import util, cache
from channelguide.guide import filetypes
from channelguide.guide.forms.share import ShareForm
from channelguide.guide.models import (Channel, Item)
from channelguide.guide.views import playback

# Custom exceptions for this module
class Error(Exception): pass
class FeedFetchingError(Error): pass

class FakeItem(object):
    def __init__(self, url, name=None, description=None,
                 date=None, thumbnail_url=None):
        self.url = url
        self.name = name
        self.description = description
        self.date = date
        self.thumbnail_url = thumbnail_url

        self.fake = True

        self.mime_type = filetypes.guessMimeType(self.url)

    def thumb(self):
        return util.mark_safe(
            '' % (
                self.thumbnail_url, self.name.replace('"', "'")))

    def get_url(self):
        pass

class FakeChannel(object):
    def __init__(self, name, description, url, website_url, thumbnail_url):
        self.name = name
        self.description = description
        self.url = url
        self.website_url = website_url
        self.thumbnail_url = thumbnail_url

        # Things required by the template that should be left empty
        self.categories = []
        self.tags = []
        self.hi_def = False

        self.fake = True

    def get_subscribe_hit_url(self):
        return self.get_url() + '/subscribe-hit'

    def get_subscription_url(self):
        if self.url:
            return util.get_subscription_url(
                self.url, trackback=self.get_subscribe_hit_url())
        else:
            return util.get_subscription_url(
                self.website_url, type='site',
                trackback=self.get_subscribe_hit_url())

    def website_link(self):
        url_label = self.website_url
        url_label = util.chop_prefix(url_label, 'http://')
        url_label = util.chop_prefix(url_label, 'https://')
        url_label = util.chop_prefix(url_label, 'www.')
        return util.make_link(self.website_url, url_label)

    def thumb_url_245_164(self):
        return self.thumbnail_url

def get_channels_and_items(feed_url, connection):
    feed_key = 'share_feed-' + feed_url
    items_key = 'share_feed_items-' + feed_url

    # check the cache.  If not...
    cached_channel = cache.client.get(feed_key)
    cached_items = cache.client.get(items_key)
    if cached_channel:
        channel = cached_channel
        items = cached_items
    else:
        # check to see if we have that feed in our database...
        channels = Channel.query().where(url=feed_url).execute(connection)
        if channels:
            channel = channels[0]
            cache.client.set(feed_key, channel)

            item_query = Item.query(channel_id=channel.id).join('channel')
            item_query = item_query.order_by('date', desc=True).limit(4)
            items = item_query.execute(connection)
            cache.client.set(items_key, items)
        else:
            ## parse the feed
            parsed = feedparser.parse(feed_url)

            #ok, so this doesn't work...
            if hasattr(parsed, 'status') and parsed.status != 200:
                raise FeedFetchingError("Got a non-200 status while parsing feed")

            ## generate fake channel
            if parsed.feed.has_key('thumbnail'):
                thumbnail_url = parsed.feed.thumbnail.href
            else:
                thumbnail_url = \
                    settings.STATIC_BASE_URL + 'images/generic_feed_thumb.png'

            channel = FakeChannel(
                parsed.feed.get('title'),
                parsed.feed.get('subtitle'),
                feed_url,
                parsed.feed.get('link'),
                thumbnail_url)

            items = []
            # why not limit the number of items here to 4?
            # Because we might need to check to see if a particular
            # item is in this feed if it's being faked...
            for entry in parsed.entries:
                item = FakeItem(
                    entry.link,
                    entry.title,
                    entry.summary,
                    datetime.datetime(*entry.updated_parsed[:7]),
                    thumbnail_url) # just use whatever thumbnail the channel has?
                items.append(item)

            cache.client.set(feed_key, channel)
            cache.client.set(items_key, items)

    return channel, items

def share_feed(request):
    try:
        feed_url = str(request.GET['feed_url'])
    except KeyError:
        return HttpResponse("you must supply a feed_url")

    try:
        channel, items = get_channels_and_items(feed_url, request.connection)
    except FeedFetchingError:
        return HttpResponse("This feed appears to be dead.")

    if isinstance(channel, Channel):
        return HttpResponseRedirect('/feeds/%s?share=true' % channel.id)

    share_links = util.get_share_links(channel.url, channel.name)

    return util.render_to_response(
        request, 'show-channel.html',
        {'channel': channel,
         'items': items[:4],
         'feed_url': feed_url,
         'share_type': 'feed',
         'share_links': share_links})

def share_item(request):
    # check to see if we have that item in our database...
    # If so
    #   use that item
    # else
    #   let's create a "fake" item to preview
    # render that item preview
    try:
        file_url = str(request.GET['file_url'])
    except KeyError:
        return HttpResponse("you must supply a file_url")

    feed_url = request.GET.get('feed_url')
    webpage_url = request.GET.get('webpage_url')
    item_name = request.GET.get('item_name')

    item = None
    next = None
    previous = None

    if webpage_url:
        webpage_url = str(webpage_url)

    if feed_url:
        feed_url = str(feed_url)
        try:
            channel, channel_items = get_channels_and_items(
                feed_url, request.connection)
        except FeedFetchingError:
            return HttpResponse("This feed appears to be dead.")

        # see if we have that item in the feed
        ## if it's a fake feed check the full list of items
        if isinstance(channel, FakeChannel):
            i = 0
            for this_item in channel_items:
                if this_item.url == file_url:
                    item = this_item
                    break
                i += 1
            if item:
                if i != 0:
                    previous = channel_items[i - 1]
                if len(channel_items) != i + 1:
                    next = channel_items[i + 1]

        ## if it's a real feed do a query
        else:
            # do a query for this item
            item_query = Item.query(channel_id=channel.id, url=file_url)
            item_query = item_query.join('channel')
            item_query = item_query.order_by('date', desc=True).limit(1)
            items = item_query.execute(request.connection)
            if items:
                item = items[0]

    if isinstance(item, Item):
        return HttpResponseRedirect('/items/%s?share=true' % item.id)

    ## if we don't have an item at this point, we need to generate
    ## a fake one.  It won't have much useful info though...
    if not item:
        if not item_name:
            subpath = urlparse.urlsplit(file_url)[3]
            if subpath:
                item_name = subpath.split('/')[-1]

            else:
                item_name = file_url

        item = FakeItem(file_url, item_name)

    # get the sharing info
    share_links = util.get_share_links(item.url, item.name)

    # render the page
    return util.render_to_response(
        request, 'playback.html',
        {'item': item,
         'channel': channel,
         'previous': previous,
         'next': next,
         'embed': util.mark_safe(playback.embed_code(item)),
         'feed_url': feed_url,
         'webpage_url': webpage_url,
         'item_name': item_name,
         'share_type': 'item',
         'share_links': share_links})

def email(request):
    share_form = ShareForm(request.POST)

    if not share_form.is_valid():
        return util.render_to_response(
            request, 'share-form.html',
            {'share_form': share_form,
             'share_type': share_form.data.get('share_type'),
             'feed_url': share_form.data.get('feed_url'),
             'file_url': share_form.data.get('file_url'),
             'item_url': share_form.data.get('item_url')})

    # construct the email to send out from a template
    if share_form.cleaned_data['share_type'] == 'feed':
        title = _(u'%(from_email)s wants to share a video feed with you') % {
            'from_email': share_form.cleaned_data['from_email']}
    else:
        title = _(u'%(from_email)s wants to share a video with you') % {
            'from_email': share_form.cleaned_data['from_email']}

    email_template = loader.get_template('guide/share-email.txt')
    email_body = email_template.render(Context(share_form.cleaned_data))

    util.send_mail(
        title, email_body,
        share_form.cleaned_data['recipients'],
        #share_form.cleaned_data['from_email'],
        break_lines=False)

    return util.render_to_response(
        request, 'share-email-success.html', {})
<|endoftext|>


<commit_before># Copyright (c) 2008 Participatory Culture Foundation
# See LICENSE for details.

import datetime
import urllib
import urlparse

import feedparser
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.template import loader, Context
from django.utils.translation import gettext as _

from channelguide import util, cache
from channelguide.guide import filetypes
from channelguide.guide.forms.share import ShareForm
from channelguide.guide.models import (Channel, Item)
from channelguide.guide.views import playback

# Custom exceptions for this module
class Error(Exception): pass
class FeedFetchingError(Error): pass

class FakeItem(object):
    def __init__(self, url, name=None, description=None,
                 date=None, thumbnail_url=None):
        self.url = url
        self.name = name
        self.description = description
        self.date = date
        self.thumbnail_url = thumbnail_url

        self.fake = True

        self.mime_type = filetypes.guessMimeType(self.url)

    def thumb(self):
        return util.mark_safe(
            '' % (
                self.thumbnail_url, self.name.replace('"', "'")))

    def get_url(self):
        pass

class FakeChannel(object):
    def __init__(self, name, description, url, website_url, thumbnail_url):
        self.name = name
        self.description = description
        self.url = url
        self.website_url = website_url
        self.thumbnail_url = thumbnail_url

        # Things required by the template that should be left empty
        self.categories = []
        self.tags = []
        self.hi_def = False

        self.fake = True

    def get_subscribe_hit_url(self):
        return self.get_url() + '/subscribe-hit'

    def get_subscription_url(self):
        if self.url:
            return util.get_subscription_url(
                self.url, trackback=self.get_subscribe_hit_url())
        else:
            return util.get_subscription_url(
                self.website_url, type='site',
                trackback=self.get_subscribe_hit_url())

    def website_link(self):
        url_label = self.website_url
        url_label = util.chop_prefix(url_label, 'http://')
        url_label = util.chop_prefix(url_label, 'https://')
        url_label = util.chop_prefix(url_label, 'www.')
        return util.make_link(self.website_url, url_label)

    def thumb_url_245_164(self):
        return self.thumbnail_url

def get_channels_and_items(feed_url, connection):
    feed_key = 'share_feed-' + feed_url
    items_key = 'share_feed_items-' + feed_url

    # check the cache.  If not...
    cached_channel = cache.client.get(feed_key)
    cached_items = cache.client.get(items_key)
    if cached_channel:
        channel = cached_channel
        items = cached_items
    else:
        # check to see if we have that feed in our database...
        channels = Channel.query().where(url=feed_url).execute(connection)
        if channels:
            channel = channels[0]
            cache.client.set(feed_key, channel)

            item_query = Item.query(channel_id=channel.id).join('channel')
            item_query = item_query.order_by('date', desc=True).limit(4)
            items = item_query.execute(connection)
            cache.client.set(items_key, items)
        else:
            ## parse the feed
            parsed = feedparser.parse(feed_url)

            #ok, so this doesn't work...
            if hasattr(parsed, 'status') and parsed.status != 200:
                raise FeedFetchingError("Got a non-200 status while parsing feed")

            if parsed.bozo: # this didn't work either
                raise FeedFetchingError('Feed is unparsable')

            ## generate fake channel
            thumbnail_url = (
                settings.STATIC_BASE_URL + 'images/generic_feed_thumb.png')

            channel = FakeChannel(
                parsed.feed.get('title'),
                parsed.feed.get('subtitle'),
                feed_url,
                parsed.feed.get('link'),
                thumbnail_url)

            items = []
            # why not limit the number of items here to 4?
            # Because we might need to check to see if a particular
            # item is in this feed if it's being faked...
            for entry in parsed.entries:
                updated_datetime = None
                if entry.get('updated_parsed'):
                    updated_datetime = datetime.datetime(*entry.updated_parsed[:7])
                item = FakeItem(
                    entry.link,
                    entry.title,
                    entry.summary,
                    updated_datetime,
                    thumbnail_url) # just use whatever thumbnail the channel has?
                items.append(item)

            cache.client.set(feed_key, channel)
            cache.client.set(items_key, items)

    return channel, items

def share_feed(request):
    try:
        feed_url = str(request.GET['feed_url'])
    except KeyError:
        return HttpResponse("you must supply a feed_url")

    try:
        channel, items = get_channels_and_items(feed_url, request.connection)
    except FeedFetchingError:
        return HttpResponse("This feed appears to be dead.")

    if isinstance(channel, Channel):
        return HttpResponseRedirect('/feeds/%s?share=true' % channel.id)

    share_url = urlparse.urljoin(
        settings.BASE_URL_FULL,
        '/share/feed/?feed_url=%s&share=false' % urllib.quote(feed_url))

    share_links = None
    share_button_url = None
    if request.GET.get('share') == 'false':
        share_button_url = urlparse.urljoin(
            settings.BASE_URL_FULL,
            '/share/feed/?feed_url=%s' % urllib.quote(feed_url))
    else:
        share_links = util.get_share_links(share_url, channel.name)

    return util.render_to_response(
        request, 'show-channel.html',
        {'channel': channel,
         'items': items[:4],
         'feed_url': feed_url,
         'share_url': share_url,
         'share_button_url': share_button_url,
         'share_type': 'feed',
         'google_analytics_ua': None,
         'share_links': share_links})

def share_item(request):
    # check to see if we have that item in our database...
    # If so
    #   use that item
    # else
    #   let's create a "fake" item to preview
    # render that item preview
    try:
        file_url = str(request.GET['file_url'])
    except KeyError:
        return HttpResponse("you must supply a file_url")

    feed_url = request.GET.get('feed_url')
    webpage_url = request.GET.get('webpage_url')
    item_name = request.GET.get('item_name')

    item = None
    next = None
    previous = None

    if webpage_url:
        webpage_url = str(webpage_url)

    if feed_url:
        feed_url = str(feed_url)
        try:
            channel, channel_items = get_channels_and_items(
                feed_url, request.connection)
        except FeedFetchingError:
            channel = None
            feed_url = None

        # see if we have that item in the feed
        ## if it's a fake feed check the full list of items
        if isinstance(channel, FakeChannel):
            i = 0
            for this_item in channel_items:
                if this_item.url == file_url:
                    item = this_item
                    break
                i += 1
            if item:
                if i != 0:
                    previous = channel_items[i - 1]
                if len(channel_items) != i + 1:
                    next = channel_items[i + 1]

        ## if it's a real feed do a query
        elif channel is not None:
            # do a query for this item
            item_query = Item.query(channel_id=channel.id, url=file_url)
            item_query = item_query.join('channel')
            item_query = item_query.order_by('date', desc=True).limit(1)
            items = item_query.execute(request.connection)
            if items:
                item = items[0]
    else:
        channel = None

    if isinstance(item, Item):
        return HttpResponseRedirect('/items/%s?share=true' % item.id)

    ## if we don't have an item at this point, we need to generate
    ## a fake one.  It won't have much useful info though...
    if not item:
        if not item_name:
            subpath = urlparse.urlsplit(file_url)[3]
            if subpath:
                item_name = subpath.split('/')[-1]

            else:
                item_name = file_url

        item = FakeItem(file_url, item_name)

    # get the sharing info
    get_params = {'file_url': file_url, 'share': 'false'}
    if feed_url:
        get_params['feed_url'] = feed_url
    if webpage_url:
        get_params['webpage_url'] = webpage_url
    if item_name:
        get_params['item_name'] = feed_url

    share_url = urlparse.urljoin(
        settings.BASE_URL_FULL,
        '/share/item/?%s' % urllib.urlencode(get_params))

    share_links = None
    share_button_url = None
    if request.GET.get('share') == 'false':
        get_params.pop('share')
        share_button_url = urlparse.urljoin(
            settings.BASE_URL_FULL,
            '/share/item/?%s' % urllib.urlencode(get_params))
    else:
        share_links = util.get_share_links(share_url, item.name)

    # render the page
    return util.render_to_response(
        request, 'playback.html',
        {'item': item,
         'channel': channel,
         'previous': previous,
         'next': next,
         'embed': util.mark_safe(playback.embed_code(item)),
         'feed_url': feed_url,
         'webpage_url': webpage_url,
         'item_name': item_name,
         'file_url': file_url,
         'share_url': share_url,
         'share_button_url': share_button_url,
         'share_type': 'item',
         'google_analytics_ua': None,
         'share_links': share_links})

def email(request):
    share_form = ShareForm(request.POST)

    if not share_form.is_valid():
        return util.render_to_response(
            request, 'share-form.html',
            {'share_form': share_form,
             'share_type': share_form.data.get('share_type'),
             'feed_url': share_form.data.get('feed_url'),
             'file_url': share_form.data.get('file_url'),
             'share_url': share_form.data.get('share_url'),
             'item_url': share_form.data.get('item_url')})

    # construct the email to send out from a template
    if share_form.cleaned_data['share_type'] == 'feed':
        title = _(u'%(from_email)s wants to share a video feed with you') % {
            'from_email': share_form.cleaned_data['from_email']}
    else:
        title = _(u'%(from_email)s wants to share a video with you') % {
            'from_email': share_form.cleaned_data['from_email']}

    email_template = loader.get_template('guide/share-email.txt')
    email_body = email_template.render(Context(share_form.cleaned_data))

    util.send_mail(
        title, email_body,
        share_form.cleaned_data['recipients'],
        #share_form.cleaned_data['from_email'],
        break_lines=False)

    return util.render_to_response(
        request, 'share-email-success.html', {})
<commit_msg>Using the guide/ prefix for non-html templates doesn't work when html templates have been "optimized"<commit_after># Copyright (c) 2008 Participatory Culture Foundation
# See LICENSE for details.

import datetime
import urllib
import urlparse

import feedparser
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.template import loader, Context
from django.utils.translation import gettext as _

from channelguide import util, cache
from channelguide.guide import filetypes
from channelguide.guide.forms.share import ShareForm
from channelguide.guide.models import (Channel, Item)
from channelguide.guide.views import playback

# Custom exceptions for this module
class Error(Exception): pass
class FeedFetchingError(Error): pass

class FakeItem(object):
    def __init__(self, url, name=None, description=None,
                 date=None, thumbnail_url=None):
        self.url = url
        self.name = name
        self.description = description
        self.date = date
        self.thumbnail_url = thumbnail_url

        self.fake = True

        self.mime_type = filetypes.guessMimeType(self.url)

    def thumb(self):
        return util.mark_safe(
            '' % (
                self.thumbnail_url, self.name.replace('"', "'")))

    def get_url(self):
        pass

class FakeChannel(object):
    def __init__(self, name, description, url, website_url, thumbnail_url):
        self.name = name
        self.description = description
        self.url = url
        self.website_url = website_url
        self.thumbnail_url = thumbnail_url

        # Things required by the template that should be left empty
        self.categories = []
        self.tags = []
        self.hi_def = False

        self.fake = True

    def get_subscribe_hit_url(self):
        return self.get_url() + '/subscribe-hit'

    def get_subscription_url(self):
        if self.url:
            return util.get_subscription_url(
                self.url, trackback=self.get_subscribe_hit_url())
        else:
            return util.get_subscription_url(
                self.website_url, type='site',
                trackback=self.get_subscribe_hit_url())

    def website_link(self):
        url_label = self.website_url
        url_label = util.chop_prefix(url_label, 'http://')
        url_label = util.chop_prefix(url_label, 'https://')
        url_label = util.chop_prefix(url_label, 'www.')
        return util.make_link(self.website_url, url_label)

    def thumb_url_245_164(self):
        return self.thumbnail_url

def get_channels_and_items(feed_url, connection):
    feed_key = 'share_feed-' + feed_url
    items_key = 'share_feed_items-' + feed_url

    # check the cache.  If not...
    cached_channel = cache.client.get(feed_key)
    cached_items = cache.client.get(items_key)
    if cached_channel:
        channel = cached_channel
        items = cached_items
    else:
        # check to see if we have that feed in our database...
        channels = Channel.query().where(url=feed_url).execute(connection)
        if channels:
            channel = channels[0]
            cache.client.set(feed_key, channel)

            item_query = Item.query(channel_id=channel.id).join('channel')
            item_query = item_query.order_by('date', desc=True).limit(4)
            items = item_query.execute(connection)
            cache.client.set(items_key, items)
        else:
            ## parse the feed
            parsed = feedparser.parse(feed_url)

            #ok, so this doesn't work...
            if hasattr(parsed, 'status') and parsed.status != 200:
                raise FeedFetchingError("Got a non-200 status while parsing feed")

            if parsed.bozo: # this didn't work either
                raise FeedFetchingError('Feed is unparsable')

            ## generate fake channel
            thumbnail_url = (
                settings.STATIC_BASE_URL + 'images/generic_feed_thumb.png')

            channel = FakeChannel(
                parsed.feed.get('title'),
                parsed.feed.get('subtitle'),
                feed_url,
                parsed.feed.get('link'),
                thumbnail_url)

            items = []
            # why not limit the number of items here to 4?
            # Because we might need to check to see if a particular
            # item is in this feed if it's being faked...
            for entry in parsed.entries:
                updated_datetime = None
                if entry.get('updated_parsed'):
                    updated_datetime = datetime.datetime(*entry.updated_parsed[:7])
                item = FakeItem(
                    entry.link,
                    entry.title,
                    entry.summary,
                    updated_datetime,
                    thumbnail_url) # just use whatever thumbnail the channel has?
                items.append(item)

            cache.client.set(feed_key, channel)
            cache.client.set(items_key, items)

    return channel, items

def share_feed(request):
    try:
        feed_url = str(request.GET['feed_url'])
    except KeyError:
        return HttpResponse("you must supply a feed_url")

    try:
        channel, items = get_channels_and_items(feed_url, request.connection)
    except FeedFetchingError:
        return HttpResponse("This feed appears to be dead.")

    if isinstance(channel, Channel):
        return HttpResponseRedirect('/feeds/%s?share=true' % channel.id)

    share_url = urlparse.urljoin(
        settings.BASE_URL_FULL,
        '/share/feed/?feed_url=%s&share=false' % urllib.quote(feed_url))

    share_links = None
    share_button_url = None
    if request.GET.get('share') == 'false':
        share_button_url = urlparse.urljoin(
            settings.BASE_URL_FULL,
            '/share/feed/?feed_url=%s' % urllib.quote(feed_url))
    else:
        share_links = util.get_share_links(share_url, channel.name)

    return util.render_to_response(
        request, 'show-channel.html',
        {'channel': channel,
         'items': items[:4],
         'feed_url': feed_url,
         'share_url': share_url,
         'share_button_url': share_button_url,
         'share_type': 'feed',
         'google_analytics_ua': None,
         'share_links': share_links})

def share_item(request):
    # check to see if we have that item in our database...
    # If so
    #   use that item
    # else
    #   let's create a "fake" item to preview
    # render that item preview
    try:
        file_url = str(request.GET['file_url'])
    except KeyError:
        return HttpResponse("you must supply a file_url")

    feed_url = request.GET.get('feed_url')
    webpage_url = request.GET.get('webpage_url')
    item_name = request.GET.get('item_name')

    item = None
    next = None
    previous = None

    if webpage_url:
        webpage_url = str(webpage_url)

    if feed_url:
        feed_url = str(feed_url)
        try:
            channel, channel_items = get_channels_and_items(
                feed_url, request.connection)
        except FeedFetchingError:
            channel = None
            feed_url = None

        # see if we have that item in the feed
        ## if it's a fake feed check the full list of items
        if isinstance(channel, FakeChannel):
            i = 0
            for this_item in channel_items:
                if this_item.url == file_url:
                    item = this_item
                    break
                i += 1
            if item:
                if i != 0:
                    previous = channel_items[i - 1]
                if len(channel_items) != i + 1:
                    next = channel_items[i + 1]

        ## if it's a real feed do a query
        elif channel is not None:
            # do a query for this item
            item_query = Item.query(channel_id=channel.id, url=file_url)
            item_query = item_query.join('channel')
            item_query = item_query.order_by('date', desc=True).limit(1)
            items = item_query.execute(request.connection)
            if items:
                item = items[0]
    else:
        channel = None

    if isinstance(item, Item):
        return HttpResponseRedirect('/items/%s?share=true' % item.id)

    ## if we don't have an item at this point, we need to generate
    ## a fake one.  It won't have much useful info though...
    if not item:
        if not item_name:
            subpath = urlparse.urlsplit(file_url)[3]
            if subpath:
                item_name = subpath.split('/')[-1]

            else:
                item_name = file_url

        item = FakeItem(file_url, item_name)

    # get the sharing info
    get_params = {'file_url': file_url, 'share': 'false'}
    if feed_url:
        get_params['feed_url'] = feed_url
    if webpage_url:
        get_params['webpage_url'] = webpage_url
    if item_name:
        get_params['item_name'] = feed_url

    share_url = urlparse.urljoin(
        settings.BASE_URL_FULL,
        '/share/item/?%s' % urllib.urlencode(get_params))

    share_links = None
    share_button_url = None
    if request.GET.get('share') == 'false':
        get_params.pop('share')
        share_button_url = urlparse.urljoin(
            settings.BASE_URL_FULL,
            '/share/item/?%s' % urllib.urlencode(get_params))
    else:
        share_links = util.get_share_links(share_url, item.name)

    # render the page
    return util.render_to_response(
        request, 'playback.html',
        {'item': item,
         'channel': channel,
         'previous': previous,
         'next': next,
         'embed': util.mark_safe(playback.embed_code(item)),
         'feed_url': feed_url,
         'webpage_url': webpage_url,
         'item_name': item_name,
         'file_url': file_url,
         'share_url': share_url,
         'share_button_url': share_button_url,
         'share_type': 'item',
         'google_analytics_ua': None,
         'share_links': share_links})

def email(request):
    share_form = ShareForm(request.POST)

    if not share_form.is_valid():
        return util.render_to_response(
            request, 'share-form.html',
            {'share_form': share_form,
             'share_type': share_form.data.get('share_type'),
             'feed_url': share_form.data.get('feed_url'),
             'file_url': share_form.data.get('file_url'),
             'share_url': share_form.data.get('share_url'),
             'item_url': share_form.data.get('item_url')})

    # construct the email to send out from a template
    if share_form.cleaned_data['share_type'] == 'feed':
        title = _(u'%(from_email)s wants to share a video feed with you') % {
            'from_email': share_form.cleaned_data['from_email']}
    else:
        title = _(u'%(from_email)s wants to share a video with you') % {
            'from_email': share_form.cleaned_data['from_email']}

    email_template = loader.get_template('share-email.txt')
    email_body = email_template.render(Context(share_form.cleaned_data))

    util.send_mail(
        title, email_body,
        share_form.cleaned_data['recipients'],
        #share_form.cleaned_data['from_email'],
        break_lines=False)

    return util.render_to_response(
        request, 'share-email-success.html', {})
<|endoftext|>


<commit_before>import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CanvasStoryArchive.archive.settings")
django.setup()

from stories.models import Story, RelatedStories

stories1 = Story.objects.all()

for object in stories1:
    set1 = []
    set1sum = []
    for nouns in object.nouns.all():
        set1.append(nouns.noun)
        set1sum.append(nouns.noun_count)
    stories2 = Story.objects.exclude(id=object.id)
    for object2 in stories2:
        set2 = []
        for nouns2 in object2.nouns.all():
            set2.append(nouns2.noun)
        matches = set(set1) & set(set2)
        matchcount = len(matches)
        if matchcount != 0:
            pct = float(matchcount/len(set1))
            scr = float(pct * sum(set1sum))
            #rs = RelatedStories.objects.create(story1=object, story2=object2, percent=pct, score=scr)
            print pct, scr
        else:
            continue
        set2 = []
    set1=[]
    set1sum=[]

            <commit_msg>removing nouncounts script because it doesn't do anything (the sauce is in the management command)<commit_after><|endoftext|>