Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions ci/check-environment-variable-names.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ $ErrorActionPreference = 'Stop'
$script:Prefix = '_51DEGREES_'

# Names GitHub, the operating system, Python, pytest and Flask define. Any
# name starting GITHUB_ is GitHub's.
# name starting GITHUB_ is GitHub's, and GitHub sets CI on every runner.
$script:PlatformNames = @(
'FLASK_APP', 'PATH', 'PSModulePath', 'PYTEST_ADDOPTS', 'PYTHON_GIL',
'CI', 'FLASK_APP', 'PATH', 'PSModulePath', 'PYTEST_ADDOPTS', 'PYTHON_GIL',
'PYTHONPATH', 'TEMP', 'TMP', 'TMPDIR')
$script:PlatformPrefixes = @('GITHUB_')

Expand Down
2 changes: 1 addition & 1 deletion device-detection/fiftyone_devicedetection/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def read(file_name):
python_requires=">=3.10",
packages=["fiftyone_devicedetection"],
package_dir={"": "src"},
install_requires=["fiftyone_devicedetection_shared", "fiftyone_devicedetection_cloud", "fiftyone_devicedetection_onpremise"],
install_requires=["fiftyone_devicedetection_shared", "fiftyone_devicedetection_cloud>=4.6.3", "fiftyone_devicedetection_onpremise"],
license="EUPL-1.2",
classifiers=[
"Development Status :: 5 - Production/Stable",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import CloudRequestEngine
from fiftyone_pipeline_cloudrequestengine.browserderived import BrowserDerivedCloud
from fiftyone_devicedetection_cloud.devicedetection_cloud import DeviceDetectionCloud
from fiftyone_devicedetection_onpremise.devicedetection_onpremise import DeviceDetectionOnPremise
from fiftyone_devicedetection_shared.utils import merge_two_dicts
Expand Down Expand Up @@ -169,6 +170,10 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs):
request_engine.set_cache(settings["cache"])

self.add(request_engine)
# browserderived carries the browser tests that come with
# HumanConfidence. They are JavaScript properties, which the
# client script runs.
self.add(BrowserDerivedCloud())
device = DeviceDetectionCloud()

self.add(device)
Expand Down
2 changes: 2 additions & 0 deletions device-detection/fiftyone_devicedetection_cloud/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ fd.process()
print(fd.device.ismobile.value())
```

The builder also adds a `BrowserDerivedCloud` engine after the cloud request engine. HumanConfidence comes with browser tests, and the engine puts them into the FlowData as JavaScript properties. The client script your server serves then runs them. The engine works from the cloud request engine's response and makes no request of its own.

For more in-depth examples, check out the [examples](https://51degrees.com/device-detection-python/examples.html?utm_source=pypi&utm_medium=package&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_cloud&utm_term=from-pypi) page in the documentation.

### From GitHub
Expand Down
2 changes: 1 addition & 1 deletion device-detection/fiftyone_devicedetection_cloud/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def read(file_name):
# profile results of this package are built on.
"fiftyone_pipeline_core>=4.5.44",
# The release this package is built and tested with.
"fiftyone_pipeline_cloudrequestengine>=4.5.45",
"fiftyone_pipeline_cloudrequestengine>=4.6.3",
],
license="EUPL-1.2",
classifiers=[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@
from __future__ import absolute_import
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import CloudRequestEngine
from fiftyone_pipeline_cloudrequestengine.browserderived import BrowserDerivedCloud
from .devicedetection_cloud import DeviceDetectionCloud
from fiftyone_devicedetection_shared.utils import merge_two_dicts

class DeviceDetectionCloudPipelineBuilder(PipelineBuilder):
"""!
The Device Detection Pipeline Builder allows you to easily
Construct a pipeline containing the device detection cloud engine
Construct a pipeline containing the device detection cloud engine.
It also adds the browserderived cloud engine after the Cloud Request
Engine, which puts the browser tests into the FlowData as JavaScript
properties for the client script to run.

Internal function for getting evidence keys used by cloud engines

Expand Down Expand Up @@ -91,5 +95,9 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs):
request_engine.set_cache(settings["cache"])

self.add(request_engine)
# A request for HumanConfidence gets browser tests back as
# JavaScript properties of browserderived, and the client script
# runs them.
self.add(BrowserDerivedCloud())
self.add(DeviceDetectionCloud())

Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************
"""!
Tests that a pipeline from the Device Detection Cloud Pipeline Builder has
the browserderived cloud engine after the Cloud Request Engine. The user
adds nothing, the browser tests are in the FlowData as JavaScript
properties, and the only request made is the Cloud Request Engine's one.
The names are made up. No network connection or resource key is needed.
"""

import json
import unittest
from unittest.mock import Mock

from requests import Response

from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient

from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder


class StandInCloud(RequestClient):
"""!
A stand in for the cloud service that counts every request. It has a
browser test with a made-up name and the JavaScript type.
"""

def __init__(self):
self.requests = []

def request(self, type, url, content, originHeader, timeout_seconds=None):
self.requests.append(url)
if "accessibleProperties" in url:
body = {"Products": {
"device": {"Properties": [
{"Name": "IsMobile", "Type": "Boolean"}]},
"browserderived": {"Properties": [
{"Name": "Q7Hx2b", "Type": "JavaScript"}]}}}
elif "evidencekeys" in url:
body = ["header.user-agent", "query.user-agent"]
else:
body = {"device": {"ismobile": False},
"browserderived": {"q7hx2b": "window.q7=1;"}}
response = Mock(spec=Response)
response.status_code = 200
response.text = json.dumps(body)
response.content = response.text.encode("utf-8")
response.json = lambda: json.loads(response.text)
return response


class BuilderBrowserTestsTests(unittest.TestCase):

def test_a_cloud_pipeline_carries_the_browser_tests(self):
cloud = StandInCloud()
pipeline = DeviceDetectionCloudPipelineBuilder(
resource_key="a-resource-key", http_client=cloud).build()
self.addCleanup(pipeline.close)

keys = [element.datakey for element in pipeline.flow_elements]
self.assertEqual(keys.index("cloud") + 1,
keys.index("browserderived"))
properties = pipeline.get_element("browserderived").get_properties()
self.assertEqual("JavaScript", properties["q7hx2b"]["type"])

before = len(cloud.requests)
data = pipeline.create_flowdata()
data.evidence.add("header.user-agent", "Mozilla/5.0")
data.process()
self.assertEqual("window.q7=1;",
data.get("browserderived").get("q7hx2b").value())
self.assertIn("browserderived.q7hx2b",
data.get("jsonbundler").get("json")[
"javascriptProperties"])
self.assertEqual(1, len(cloud.requests) - before,
"one request, the data request, and no other")
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ def test_missing_property_service_element_not_found(self):

result = str(raised.exception)
self.assertIn("notpresent", result)
self.assertIn("['device']", result)
self.assertIn("https://51degrees.com/documentation/_services__cloud__resource_keys.html", result)

def test_engine_init_performance(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************
"""
The Device Detection builder is tested here, as the
fiftyone_devicedetection package has no tests of its own.

Given a resource key, the builder adds the browserderived cloud engine
after the Cloud Request Engine by itself. The browser tests then reach the
FlowData as JavaScript properties, and the pipeline makes the Cloud Request
Engine's one request and no other. Browser test names are made up. Runs
with no network connection and no resource key.
"""

import json
import unittest
from unittest.mock import Mock

from requests import Response

from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient

from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder


class StandInCloud(RequestClient):
"""
Answers as the cloud service would, with a single browser test typed
JavaScript under a made-up name. Keeps a count of the requests.
"""

def __init__(self):
self.requests = []

def request(self, type, url, content, originHeader, timeout_seconds=None):
self.requests.append(url)
if "accessibleProperties" in url:
body = {"Products": {
"device": {"Properties": [
{"Name": "IsMobile", "Type": "Boolean"}]},
"browserderived": {"Properties": [
{"Name": "Q7Hx2b", "Type": "JavaScript"}]}}}
elif "evidencekeys" in url:
body = ["header.user-agent", "query.user-agent"]
else:
body = {"device": {"ismobile": False},
"browserderived": {"q7hx2b": "window.q7=1;"}}
response = Mock(spec=Response)
response.status_code = 200
response.text = json.dumps(body)
response.content = response.text.encode("utf-8")
response.json = lambda: json.loads(response.text)
return response


class BuilderBrowserTestsTests(unittest.TestCase):

def test_a_cloud_pipeline_carries_the_browser_tests(self):
cloud = StandInCloud()
pipeline = DeviceDetectionPipelineBuilder(
resource_key="a-resource-key", http_client=cloud).build()
self.addCleanup(pipeline.close)

keys = [element.datakey for element in pipeline.flow_elements]
self.assertEqual(keys.index("cloud") + 1,
keys.index("browserderived"))
self.assertLess(keys.index("browserderived"), keys.index("device"))

before = len(cloud.requests)
data = pipeline.create_flowdata()
data.evidence.add("header.user-agent", "Mozilla/5.0")
data.process()
self.assertEqual("window.q7=1;",
data.get("browserderived").get("q7hx2b").value())
self.assertEqual(1, len(cloud.requests) - before,
"one request, the data request, and no other")
8 changes: 8 additions & 0 deletions pipeline/fiftyone_pipeline_cloudrequestengine/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ client script's complete handlers run later than they otherwise would, by the
time the tests take and one more request. A page can read the first
response's properties sooner through its change handlers.

The `browserderived` element's JavaScript properties are the browser
tests. The client script your server serves runs them once a
`BrowserDerivedCloud` engine
(`fiftyone_pipeline_cloudrequestengine.browserderived`) follows the
`CloudRequestEngine` in the pipeline. The device detection cloud pipeline
builders add that engine for you. If you build the pipeline another way,
add it there yourself.

Where a page sets a Content Security Policy, it must allow these for the
browser tests to run. Otherwise HumanConfidenceSource stays `Passive`.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************

from .cloudengine import CloudEngine


class BrowserDerivedCloud(CloudEngine):

"""!
Cloud engine for the "browserderived" section of the cloud response,
whose properties are available as flowdata.browserderived.

The section is read as every cloud engine reads its own, and each
property takes its type from the Cloud Request Engine's accessible
properties. Properties whose metadata gives the JavaScript type are
the browser tests that come with HumanConfidence. The JSON bundler
lists those and the client script runs them. The cloud service can
return any number of them under any names, and none is written here.

A key without the browserderived product logs no warning, because the
browser tests only come with a request that names HumanConfidence.
"""

def __init__(self):
super(BrowserDerivedCloud, self).__init__()
self.datakey = "browserderived"
self.warns_on_missing_product = False
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ def __init__(self):

# Whether set_cache has logged that this engine ignores a cache.
self._cache_ignored_logged = False
# Whether to log a key that carries no properties for this engine.
# Set it False in an engine whose product only comes with some
# requests.
self.warns_on_missing_product = True

def get_evidence_key_filter(self):

Expand Down Expand Up @@ -219,7 +223,8 @@ def _load_properties(self, log):
# at all. That is not a configuration error, so the engine has
# no properties and the missing product is logged here, once.
if not self.datakey in carried:
log("warning", "The key in use does not include access to any properties under the engine with key " + self.datakey + " that was added to the pipeline. For more details on resource keys, see our explainer: https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=comment&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-src-fiftyone_pipeline_cloudrequestengine-cloudengine.py&utm_term=engine-properties-not-accessible " + "Available engine data keys are: " + str([e for e in carried]))
if getattr(self, "warns_on_missing_product", True):
log("warning", "The key in use does not include access to any properties under the engine with key " + self.datakey + " that was added to the pipeline. For more details on resource keys, see our explainer: https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=comment&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-src-fiftyone_pipeline_cloudrequestengine-cloudengine.py&utm_term=engine-properties-not-accessible " + "Available engine data keys are: " + str([e for e in carried]))
self.properties = {}
else:
self.properties = carried[self.datakey]
Expand Down
Loading
Loading