コード例 #1
0
def get_ga_custom_values(source, overrides=None, env=None):

    values = {}
    custom_defs = get_setting("x_googleanalytics_custom_definitions")

    if isinstance(source, Mapping):
        overrides = source
        source = None

    for i, custom_def in enumerate(custom_defs):

        if not custom_def.enabled:
            continue

        if overrides is not None and custom_def.identifier:
            value = overrides.get(custom_def.identifier, schema.undefined)
            if value is not schema.undefined:
                key = custom_def.definition_type + str(i + 1)
                value = get_ga_value(value)
                values[key] = value
                continue

        if source is not None and custom_def.applies(source):
            custom_def.apply(source, values, i + 1, env=env)

    return values
コード例 #2
0
def get_ga_value(value, language=None):

    if language is None:
        language = get_setting("x_googleanalytics_language")

    if value is None:
        return ""
    elif isinstance(value, str):
        return escape_ga_string(value)
    elif isinstance(value, bool):
        return translations(value, language=language)
    elif isinstance(value, (int, float, Decimal)):
        return str(value)
    elif isinstance(value, type):
        return escape_ga_string(
            translations(value, language=language) or value.__name__)
    elif isinstance(value, (set, frozenset, SetWrapper)):
        value = list(map(get_ga_value, value))
        value.sort()
        return " ".join(value)
    elif isinstance(value, Iterable):
        return " ".join(get_ga_value(item) for item in value)
    elif isinstance(value, PersistentObject):
        return (u"%s --%d--" % (escape_ga_string(
            translations(
                value, language=language,
                discard_generic_translation=True)), value.id)).strip()
    else:
        raise ValueError("%r is not a valid value for get_ga_value()" % value)
コード例 #3
0
def export_attribute_value(value, language=None):

    if language is None:
        language = get_setting("x_attributes_language")

    if value is None:
        return ""
    elif isinstance(value, str):
        return escape_string(value)
    elif isinstance(value, bool):
        return "1" if value else "0"
    elif isinstance(value, (int, float, Decimal)):
        return str(value)
    elif isinstance(value, type):
        return export_attribute_value([
            translations(cls, language=language) for cls in value.__mro__
            if cls is not Publishable and issubclass(cls, Publishable)
        ])
    elif isinstance(value, (set, frozenset, SetWrapper)):
        value = map(export_attribute_value, value)
        value.sort()
        return " ".join(value)
    elif isinstance(value, Iterable):
        return " ".join(export_attribute_value(item) for item in value)
    elif isinstance(value, PersistentObject):
        return (u"%s --%d--" % (escape_string(
            translations(
                value, language=language,
                discard_generic_translation=True)), value.id)).strip()
    else:
        raise ValueError(
            "%r is not a valid value for export_attribute_value()" % value)
コード例 #4
0
    def get_analytics_script(cls, publishable=None, commands=None):

        config = Configuration.instance

        if publishable is None:
            publishable = app.publishable

        event = cls.declaring_tracker(
            publishable=publishable,
            account=get_setting("x_googleanalytics_account"),
            tracker_parameters={},
            domain=get_setting("x_googleanalytics_domain"),
            template=cls.inclusion_code,
            values={},
            commands=commands or [])

        if not event.account:
            return ""

        commands = event.commands
        parameters = {}

        if event.domain:
            event.tracker_parameters["cookieDomain"] = event.domain

        parameters["create_tracker_command"] = \
            cls._serialize_commands([(
                "create",
                event.account,
                event.tracker_parameters
            )])

        if event.values:
            commands.insert(0, ("set", event.values))

        parameters["initialization"] = (
            "woost.ga.setCustomDefinitions(%s);\n"
            "ga('set', woost.ga.getEventData(document.documentElement));" %
            (json.dumps(
                dict((custom_def.identifier, {
                    "index": i + 1,
                    "type": custom_def.definition_type
                }) for i, custom_def in enumerate(
                    config.x_googleanalytics_custom_definitions)
                     if custom_def.identifier))))
        parameters["commands"] = cls._serialize_commands(commands)
        return event.template % parameters
コード例 #5
0
def _should_add_location(record, parent, context):

    # Filter by tree subset
    updated_subset = get_setting("x_locations_updated_subset")
    if updated_subset:
        if not context.get("inside_subset") \
        and context["full_code"] not in updated_subset:
            return False
        else:
            context["inside_subset"] = True

    # Filter by location type
    updated_location_types = get_setting("x_locations_updated_location_types")
    if record["type"] not in updated_location_types:
        return False

    return True
コード例 #6
0
def should_update():

    last_update = Configuration.instance.x_locations_last_update
    if last_update is None:
        return True

    update_frequency = get_setting("x_locations_update_frequency")
    if update_frequency is None:
        return False

    return time() - last_update >= update_frequency * SECONDS_IN_A_DAY
コード例 #7
0
def sync_locations():
    """Populate the locations database with the data provided by the web
    service.
    """
    service_uri = get_setting("x_locations_service_uri")
    text_data = urllib.request.urlopen(service_uri).read()
    json_data = json.loads(text_data)

    for record in json_data:
        _process_record(record)

    Configuration.instance.x_locations_last_update = time()
コード例 #8
0
def get_sentry(dsn: str = None) -> Optional[Sentry]:

    if not dsn:
        dsn = get_setting("x_sentry_dsn")
        if not dsn:
            return None

    try:
        return _instances[dsn]
    except KeyError:
        instance = sentry_class(dsn)
        _instances[dsn] = instance
        return instance
コード例 #9
0
def get_markup():

    container_id = get_setting("x_googletagmananager_container")

    if not container_id:
        return ""
    else:
        return """
            <!-- Google Tag Manager -->
            <noscript><iframe src="//www.googletagmanager.com/ns.html?id=%(container_id)s"
            height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
            <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
            j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
            '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
            })(window,document,'script','dataLayer','%(container_id)s');</script>
            <!-- End Google Tag Manager -->
            """ % {"container_id": container_id}
コード例 #10
0
    def update(self):
        list = List({"api_key": get_setting("x_campaign3_api_key")},
                    self.list_id)
        details = list.details()

        if self.confirmation_success_page:
            confirmation_success_page = \
                self.confirmation_success_page.get_uri(host = "!")
        else:
            confirmation_success_page = None

        if self.unsubscribe_page:
            unsubscribe_page = (self.unsubscribe_page.get_uri(host="!").merge(
                URL(query={"email": "[email]"})))
        else:
            unsubscribe_page = None

        list.update(details.Title,
                    unsubscribe_page,
                    details.ConfirmedOptIn,
                    confirmation_success_page,
                    unsubscribe_setting=details.UnsubscribeSetting)
コード例 #11
0
    def resubscribe(self):
        api_key = get_setting("x_campaign3_api_key")
        cs = CreateSend({"api_key": api_key})
        now = datetime.now()

        for client in cs.clients():
            client = Client({"api_key": api_key}, client.ClientID)

            for list in client.lists():
                subscriber = Subscriber({"api_key": api_key})
                try:
                    response = subscriber.get(list.ListID, self.email)
                except BadRequest:
                    continue

                date = datetime.strptime(response.Date, '%Y-%m-%d %H:%M:%S')
                diff = now - date

                if (response.State != "Active"
                        and (date > now or diff.seconds < self.max_seconds)):
                    response = subscriber.add(list.ListID, self.email,
                                              response.Name, None, True)
                    self.resubscribed_lists.append(list.ListID)
コード例 #12
0
    def _default_validation(self, context):
        """Validation rule for noCaptcha. Checks that the L{response}
        member is valid for the L{public_key} and L{private_key}
        constraints.
        """
        for error in schema.Member._default_validation(self, context):
            yield error

        value = context.value
        if value:
            params = urllib.parse.urlencode({
                "secret":
                get_setting("x_nocaptcha_private_key"),
                "response":
                value,
                "remoteip":
                cherrypy.request.remote.ip
            }).encode("utf-8")

            request = urllib.request.Request(
                url=self.VERIFY_SERVER,
                data=params,
                headers={
                    "Content-type": "application/x-www-form-urlencoded",
                    "User-agent": "Woost noCAPTCHA extension"
                })

            httpresp = urllib.request.urlopen(request)
            return_values = httpresp.read()
            httpresp.close()
            response_json = loads(return_values)

            if not response_json['success']:
                yield NoCaptchaValidationError(context)

        else:
            yield NoCaptchaValidationError(context)