aiohttp-ai-chatbot 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aiohttp_ai_chatbot-1.0.0/LICENSE +21 -0
- aiohttp_ai_chatbot-1.0.0/MANIFEST.in +2 -0
- aiohttp_ai_chatbot-1.0.0/PKG-INFO +127 -0
- aiohttp_ai_chatbot-1.0.0/README.md +96 -0
- aiohttp_ai_chatbot-1.0.0/pyproject.toml +46 -0
- aiohttp_ai_chatbot-1.0.0/setup.cfg +4 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot/__init__.py +6 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot/middleware.py +121 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot/snippet.py +82 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot/utils.py +57 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot.egg-info/PKG-INFO +127 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot.egg-info/SOURCES.txt +16 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot.egg-info/dependency_links.txt +1 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot.egg-info/requires.txt +1 -0
- aiohttp_ai_chatbot-1.0.0/src/aiohttp_ai_chatbot.egg-info/top_level.txt +1 -0
- aiohttp_ai_chatbot-1.0.0/tests/test_middleware.py +312 -0
- aiohttp_ai_chatbot-1.0.0/tests/test_snippet.py +51 -0
- aiohttp_ai_chatbot-1.0.0/tests/test_utils.py +30 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Asyntai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aiohttp-ai-chatbot
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Adds the Asyntai AI chat assistant to aiohttp sites. It answers visitor questions from your own content, in more than 80 languages.
|
|
5
|
+
Author-email: Asyntai <hello@asyntai.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://asyntai.com
|
|
8
|
+
Project-URL: Documentation, https://asyntai.com/documentation/integrations/aiohttp/
|
|
9
|
+
Project-URL: Source, https://github.com/asyntai/aiohttp-ai-chatbot
|
|
10
|
+
Project-URL: Issues, https://github.com/asyntai/aiohttp-ai-chatbot/issues
|
|
11
|
+
Keywords: aiohttp,asyncio,middleware,chatbot,ai,ai-chatbot,live-chat,customer-support,widget
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Environment :: Web Environment
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Framework :: aiohttp
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: aiohttp>=3.8
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# aiohttp-ai-chatbot
|
|
33
|
+
|
|
34
|
+
Adds the [Asyntai](https://asyntai.com) AI chat assistant to an aiohttp site.
|
|
35
|
+
The assistant answers visitor questions from your own content, day and night,
|
|
36
|
+
in more than 80 languages.
|
|
37
|
+
|
|
38
|
+
Free and open source. Works on every Asyntai plan, including the free plan.
|
|
39
|
+
|
|
40
|
+
- Requires Python 3.9 or newer and aiohttp 3.8 or newer
|
|
41
|
+
- Documentation: https://asyntai.com/documentation/integrations/aiohttp/
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
pip install aiohttp-ai-chatbot
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from aiohttp import web
|
|
51
|
+
from aiohttp_ai_chatbot import setup
|
|
52
|
+
|
|
53
|
+
app = web.Application()
|
|
54
|
+
app.router.add_get("/", index)
|
|
55
|
+
setup(app, widget_id="asyntai_ab12cd34")
|
|
56
|
+
|
|
57
|
+
web.run_app(app)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Or pass the middleware yourself:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from aiohttp_ai_chatbot import asyntai_middleware
|
|
64
|
+
|
|
65
|
+
app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
You get the widget ID from the Install page of your
|
|
69
|
+
[Asyntai dashboard](https://asyntai.com/dashboard). You can paste the whole
|
|
70
|
+
snippet; the package keeps only the ID.
|
|
71
|
+
|
|
72
|
+
That is all. The chat button appears on every HTML page of the site. JSON,
|
|
73
|
+
files, streams, websockets and redirects pass through untouched.
|
|
74
|
+
|
|
75
|
+
## Options
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
setup(
|
|
79
|
+
app,
|
|
80
|
+
widget_id="asyntai_ab12cd34", # without it: the ASYNTAI_WIDGET_ID environment variable
|
|
81
|
+
skip_paths=["/admin*"], # the default
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- Leave out `widget_id` to read the `ASYNTAI_WIDGET_ID` environment variable.
|
|
86
|
+
It is read on every request, so you can change it without a code change.
|
|
87
|
+
An empty value switches the chat off.
|
|
88
|
+
- `skip_paths` lists paths that never get the widget. A path that ends in `*`
|
|
89
|
+
also matches everything below it, so `/admin*` covers `/admin` and
|
|
90
|
+
`/admin/users`, but not `/administrator`.
|
|
91
|
+
|
|
92
|
+
The middleware changes complete `web.Response` pages with status 200 and the
|
|
93
|
+
`text/html` content type. A response that uses `enable_compression()` still
|
|
94
|
+
gets the widget, because aiohttp compresses the body after the middleware.
|
|
95
|
+
Files from `add_static` or `web.FileResponse` and responses that you prepare
|
|
96
|
+
and stream yourself are sent as they are.
|
|
97
|
+
|
|
98
|
+
## Placing the widget by hand
|
|
99
|
+
|
|
100
|
+
With aiohttp-jinja2, register the helper once:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
import aiohttp_jinja2
|
|
104
|
+
from aiohttp_ai_chatbot import asyntai_widget
|
|
105
|
+
|
|
106
|
+
env = aiohttp_jinja2.setup(app, loader=...)
|
|
107
|
+
env.globals["asyntai_widget"] = asyntai_widget
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Then put it before the closing body tag:
|
|
111
|
+
|
|
112
|
+
```html
|
|
113
|
+
{{ asyntai_widget() }}
|
|
114
|
+
</body>
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`widget_snippet()` returns the same HTML as a plain string. The middleware
|
|
118
|
+
never adds a second copy to a page that already has one.
|
|
119
|
+
|
|
120
|
+
## How it loads
|
|
121
|
+
|
|
122
|
+
The widget script loads after the page has finished loading, so your page
|
|
123
|
+
draws first and page speed does not change.
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# aiohttp-ai-chatbot
|
|
2
|
+
|
|
3
|
+
Adds the [Asyntai](https://asyntai.com) AI chat assistant to an aiohttp site.
|
|
4
|
+
The assistant answers visitor questions from your own content, day and night,
|
|
5
|
+
in more than 80 languages.
|
|
6
|
+
|
|
7
|
+
Free and open source. Works on every Asyntai plan, including the free plan.
|
|
8
|
+
|
|
9
|
+
- Requires Python 3.9 or newer and aiohttp 3.8 or newer
|
|
10
|
+
- Documentation: https://asyntai.com/documentation/integrations/aiohttp/
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
pip install aiohttp-ai-chatbot
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from aiohttp import web
|
|
20
|
+
from aiohttp_ai_chatbot import setup
|
|
21
|
+
|
|
22
|
+
app = web.Application()
|
|
23
|
+
app.router.add_get("/", index)
|
|
24
|
+
setup(app, widget_id="asyntai_ab12cd34")
|
|
25
|
+
|
|
26
|
+
web.run_app(app)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or pass the middleware yourself:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from aiohttp_ai_chatbot import asyntai_middleware
|
|
33
|
+
|
|
34
|
+
app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
You get the widget ID from the Install page of your
|
|
38
|
+
[Asyntai dashboard](https://asyntai.com/dashboard). You can paste the whole
|
|
39
|
+
snippet; the package keeps only the ID.
|
|
40
|
+
|
|
41
|
+
That is all. The chat button appears on every HTML page of the site. JSON,
|
|
42
|
+
files, streams, websockets and redirects pass through untouched.
|
|
43
|
+
|
|
44
|
+
## Options
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
setup(
|
|
48
|
+
app,
|
|
49
|
+
widget_id="asyntai_ab12cd34", # without it: the ASYNTAI_WIDGET_ID environment variable
|
|
50
|
+
skip_paths=["/admin*"], # the default
|
|
51
|
+
)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
- Leave out `widget_id` to read the `ASYNTAI_WIDGET_ID` environment variable.
|
|
55
|
+
It is read on every request, so you can change it without a code change.
|
|
56
|
+
An empty value switches the chat off.
|
|
57
|
+
- `skip_paths` lists paths that never get the widget. A path that ends in `*`
|
|
58
|
+
also matches everything below it, so `/admin*` covers `/admin` and
|
|
59
|
+
`/admin/users`, but not `/administrator`.
|
|
60
|
+
|
|
61
|
+
The middleware changes complete `web.Response` pages with status 200 and the
|
|
62
|
+
`text/html` content type. A response that uses `enable_compression()` still
|
|
63
|
+
gets the widget, because aiohttp compresses the body after the middleware.
|
|
64
|
+
Files from `add_static` or `web.FileResponse` and responses that you prepare
|
|
65
|
+
and stream yourself are sent as they are.
|
|
66
|
+
|
|
67
|
+
## Placing the widget by hand
|
|
68
|
+
|
|
69
|
+
With aiohttp-jinja2, register the helper once:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import aiohttp_jinja2
|
|
73
|
+
from aiohttp_ai_chatbot import asyntai_widget
|
|
74
|
+
|
|
75
|
+
env = aiohttp_jinja2.setup(app, loader=...)
|
|
76
|
+
env.globals["asyntai_widget"] = asyntai_widget
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Then put it before the closing body tag:
|
|
80
|
+
|
|
81
|
+
```html
|
|
82
|
+
{{ asyntai_widget() }}
|
|
83
|
+
</body>
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`widget_snippet()` returns the same HTML as a plain string. The middleware
|
|
87
|
+
never adds a second copy to a page that already has one.
|
|
88
|
+
|
|
89
|
+
## How it loads
|
|
90
|
+
|
|
91
|
+
The widget script loads after the page has finished loading, so your page
|
|
92
|
+
draws first and page speed does not change.
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
MIT
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "aiohttp-ai-chatbot"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Adds the Asyntai AI chat assistant to aiohttp sites. It answers visitor questions from your own content, in more than 80 languages."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Asyntai", email = "hello@asyntai.com" }]
|
|
14
|
+
keywords = ["aiohttp", "asyncio", "middleware", "chatbot", "ai", "ai-chatbot", "live-chat", "customer-support", "widget"]
|
|
15
|
+
dependencies = ["aiohttp>=3.8"]
|
|
16
|
+
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 5 - Production/Stable",
|
|
19
|
+
"Environment :: Web Environment",
|
|
20
|
+
"Framework :: AsyncIO",
|
|
21
|
+
"Framework :: aiohttp",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
"Programming Language :: Python :: 3",
|
|
25
|
+
"Programming Language :: Python :: 3.9",
|
|
26
|
+
"Programming Language :: Python :: 3.10",
|
|
27
|
+
"Programming Language :: Python :: 3.11",
|
|
28
|
+
"Programming Language :: Python :: 3.12",
|
|
29
|
+
"Programming Language :: Python :: 3.13",
|
|
30
|
+
"Programming Language :: Python :: 3.14",
|
|
31
|
+
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://asyntai.com"
|
|
36
|
+
Documentation = "https://asyntai.com/documentation/integrations/aiohttp/"
|
|
37
|
+
Source = "https://github.com/asyntai/aiohttp-ai-chatbot"
|
|
38
|
+
Issues = "https://github.com/asyntai/aiohttp-ai-chatbot/issues"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.packages.find]
|
|
41
|
+
where = ["src"]
|
|
42
|
+
|
|
43
|
+
[tool.pytest.ini_options]
|
|
44
|
+
asyncio_mode = "auto"
|
|
45
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
46
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Adds the Asyntai AI chat assistant to aiohttp sites."""
|
|
2
|
+
from .middleware import DEFAULT_SKIP_PATHS, asyntai_middleware, setup
|
|
3
|
+
from .snippet import asyntai_widget, widget_snippet
|
|
4
|
+
|
|
5
|
+
__all__ = ['DEFAULT_SKIP_PATHS', 'asyntai_middleware', 'asyntai_widget', 'setup', 'widget_snippet']
|
|
6
|
+
__version__ = '1.0.0'
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Puts the chat widget on every HTML page of an aiohttp site, with no template edit.
|
|
2
|
+
|
|
3
|
+
The middleware only touches complete web.Response objects that carry an HTML
|
|
4
|
+
page with status 200. Everything else passes through untouched: JSON, files
|
|
5
|
+
from add_static or web.FileResponse, prepared streams, websockets and
|
|
6
|
+
redirects.
|
|
7
|
+
"""
|
|
8
|
+
from aiohttp import web
|
|
9
|
+
|
|
10
|
+
from .snippet import MARKER, resolve_widget_id, widget_snippet
|
|
11
|
+
from .utils import clean_script_url
|
|
12
|
+
|
|
13
|
+
BODY_CLOSE = b'</body>'
|
|
14
|
+
|
|
15
|
+
#: Paths the widget never touches by default. A path that ends in * matches
|
|
16
|
+
#: the path itself and everything below it.
|
|
17
|
+
DEFAULT_SKIP_PATHS = ('/admin*',)
|
|
18
|
+
|
|
19
|
+
#: The key under which setup() stores its settings on the application.
|
|
20
|
+
APP_KEY = 'aiohttp_ai_chatbot'
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def path_is_skipped(path, skip_paths):
|
|
24
|
+
"""Answer whether the widget must stay off on this path."""
|
|
25
|
+
for rule in skip_paths:
|
|
26
|
+
if rule.endswith('*'):
|
|
27
|
+
base = rule[:-1].rstrip('/')
|
|
28
|
+
if path == base or path.startswith(base + '/'):
|
|
29
|
+
return True
|
|
30
|
+
elif path == rule:
|
|
31
|
+
return True
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def insert_snippet(body, snippet, charset='utf-8'):
|
|
36
|
+
"""Return the page with the snippet before the last </body>, or None.
|
|
37
|
+
|
|
38
|
+
None means "leave the page as it is": the page has no closing body tag,
|
|
39
|
+
it already carries the widget, or it is not readable text.
|
|
40
|
+
"""
|
|
41
|
+
if MARKER.encode() in body or b'data-asyntai-id' in body:
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
if BODY_CLOSE not in body.lower():
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
html = body.decode(charset)
|
|
49
|
+
encoded_snippet = snippet.encode(charset)
|
|
50
|
+
except (UnicodeError, LookupError):
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
# Split on the last closing tag, so a page that prints the tag inside an
|
|
54
|
+
# example or a code block is left alone.
|
|
55
|
+
index = html.lower().rfind('</body>')
|
|
56
|
+
if index < 0:
|
|
57
|
+
return None
|
|
58
|
+
return html[:index].encode(charset) + encoded_snippet + html[index:].encode(charset)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def asyntai_middleware(widget_id=None, skip_paths=DEFAULT_SKIP_PATHS, script_url=None):
|
|
62
|
+
"""Return an aiohttp middleware that inserts the widget before </body>.
|
|
63
|
+
|
|
64
|
+
widget_id the ID from the Asyntai dashboard; without it, the
|
|
65
|
+
ASYNTAI_WIDGET_ID environment variable (read on every
|
|
66
|
+
request, so the ID can change without a code change)
|
|
67
|
+
skip_paths paths the widget never touches
|
|
68
|
+
script_url change only if Asyntai support asks
|
|
69
|
+
|
|
70
|
+
app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
|
|
71
|
+
"""
|
|
72
|
+
skip = tuple(skip_paths or ())
|
|
73
|
+
|
|
74
|
+
@web.middleware
|
|
75
|
+
async def asyntai_widget_middleware(request, handler):
|
|
76
|
+
response = await handler(request)
|
|
77
|
+
|
|
78
|
+
if request.method == 'HEAD' or path_is_skipped(request.path or '/', skip):
|
|
79
|
+
return response
|
|
80
|
+
|
|
81
|
+
if not resolve_widget_id(widget_id) or not clean_script_url(script_url):
|
|
82
|
+
return response
|
|
83
|
+
|
|
84
|
+
if _can_carry_widget(response):
|
|
85
|
+
snippet = widget_snippet(widget_id, script_url)
|
|
86
|
+
new_body = insert_snippet(response.body, snippet, response.charset or 'utf-8') if snippet else None
|
|
87
|
+
if new_body is not None:
|
|
88
|
+
# The body setter also sets the new Content-Length.
|
|
89
|
+
response.body = new_body
|
|
90
|
+
|
|
91
|
+
return response
|
|
92
|
+
|
|
93
|
+
return asyntai_widget_middleware
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def setup(app, widget_id=None, skip_paths=DEFAULT_SKIP_PATHS, script_url=None):
|
|
97
|
+
"""Add the widget middleware to an application before it starts.
|
|
98
|
+
|
|
99
|
+
from aiohttp_ai_chatbot import setup
|
|
100
|
+
setup(app, widget_id="asyntai_ab12cd34")
|
|
101
|
+
"""
|
|
102
|
+
middleware = asyntai_middleware(widget_id=widget_id, skip_paths=skip_paths, script_url=script_url)
|
|
103
|
+
app.middlewares.append(middleware)
|
|
104
|
+
return middleware
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _can_carry_widget(response):
|
|
108
|
+
# A FileResponse or a hand-made StreamResponse is not a web.Response,
|
|
109
|
+
# and a prepared response has already left; neither can change.
|
|
110
|
+
if not isinstance(response, web.Response) or response.prepared:
|
|
111
|
+
return False
|
|
112
|
+
|
|
113
|
+
if response.status != 200 or response.headers.get('Content-Encoding'):
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
if response.content_type != 'text/html':
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
# A body object (a file, a stream) is sent piece by piece; only plain
|
|
120
|
+
# bytes can be read and changed here.
|
|
121
|
+
return isinstance(response.body, (bytes, bytearray))
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""The HTML that loads the chat widget, for the middleware and for templates."""
|
|
2
|
+
import os
|
|
3
|
+
from html import escape
|
|
4
|
+
|
|
5
|
+
from .utils import clean_script_url, clean_widget_id
|
|
6
|
+
|
|
7
|
+
#: Text that only this package writes. The middleware looks for it, so the
|
|
8
|
+
#: widget is never added twice.
|
|
9
|
+
MARKER = 'asyntai-widget-config'
|
|
10
|
+
|
|
11
|
+
_TEMPLATE = (
|
|
12
|
+
'<div class="' + MARKER + '" data-asyntai-widget="__WIDGET_ID__" '
|
|
13
|
+
'data-asyntai-src="__SCRIPT_URL__" style="display: none"></div>\n'
|
|
14
|
+
'<script>\n'
|
|
15
|
+
' // Loads the Asyntai chat widget after the page has finished loading,\n'
|
|
16
|
+
' // so the site draws first and page speed does not change. The two\n'
|
|
17
|
+
' // values arrive on a data attribute, so nothing is ever written into\n'
|
|
18
|
+
' // the script itself.\n'
|
|
19
|
+
' (function () {\n'
|
|
20
|
+
" var config = document.querySelector('." + MARKER + "');\n"
|
|
21
|
+
' if (!config) { return; }\n'
|
|
22
|
+
'\n'
|
|
23
|
+
" var widgetId = config.getAttribute('data-asyntai-widget') || '';\n"
|
|
24
|
+
" var scriptUrl = config.getAttribute('data-asyntai-src') || '';\n"
|
|
25
|
+
" if (!widgetId || scriptUrl.indexOf('https://') !== 0) { return; }\n"
|
|
26
|
+
'\n'
|
|
27
|
+
' var load = function () {\n'
|
|
28
|
+
" if (document.querySelector('script[data-asyntai-id]')) { return; }\n"
|
|
29
|
+
'\n'
|
|
30
|
+
" var script = document.createElement('script');\n"
|
|
31
|
+
' script.src = scriptUrl;\n'
|
|
32
|
+
' script.async = true;\n'
|
|
33
|
+
" script.setAttribute('data-asyntai-id', widgetId);\n"
|
|
34
|
+
' document.head.appendChild(script);\n'
|
|
35
|
+
' };\n'
|
|
36
|
+
'\n'
|
|
37
|
+
" if (document.readyState === 'complete') {\n"
|
|
38
|
+
' load();\n'
|
|
39
|
+
' } else {\n'
|
|
40
|
+
" window.addEventListener('load', load);\n"
|
|
41
|
+
' }\n'
|
|
42
|
+
' }());\n'
|
|
43
|
+
'</script>\n'
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def resolve_widget_id(widget_id=None):
|
|
48
|
+
"""The given ID, or the ASYNTAI_WIDGET_ID environment variable."""
|
|
49
|
+
if widget_id is None:
|
|
50
|
+
widget_id = os.environ.get('ASYNTAI_WIDGET_ID', '')
|
|
51
|
+
return clean_widget_id(widget_id)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def widget_snippet(widget_id=None, script_url=None):
|
|
55
|
+
"""Return the widget HTML, or an empty string when the chat must stay off.
|
|
56
|
+
|
|
57
|
+
Without a widget_id, the ASYNTAI_WIDGET_ID environment variable is used.
|
|
58
|
+
"""
|
|
59
|
+
clean_id = resolve_widget_id(widget_id)
|
|
60
|
+
clean_url = clean_script_url(script_url)
|
|
61
|
+
if not clean_id or not clean_url:
|
|
62
|
+
return ''
|
|
63
|
+
|
|
64
|
+
return (_TEMPLATE
|
|
65
|
+
.replace('__WIDGET_ID__', escape(clean_id, quote=True))
|
|
66
|
+
.replace('__SCRIPT_URL__', escape(clean_url, quote=True)))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def asyntai_widget(widget_id=None, script_url=None):
|
|
70
|
+
"""Template helper: the same HTML, marked safe for Jinja2.
|
|
71
|
+
|
|
72
|
+
With aiohttp-jinja2, register it once, then write {{ asyntai_widget() }}
|
|
73
|
+
before </body>:
|
|
74
|
+
|
|
75
|
+
aiohttp_jinja2.get_env(app).globals['asyntai_widget'] = asyntai_widget
|
|
76
|
+
"""
|
|
77
|
+
html = widget_snippet(widget_id, script_url)
|
|
78
|
+
try:
|
|
79
|
+
from markupsafe import Markup
|
|
80
|
+
except ImportError: # Jinja2 is optional.
|
|
81
|
+
return html
|
|
82
|
+
return Markup(html)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Reading and checking the two values the widget needs.
|
|
2
|
+
|
|
3
|
+
Every decision the package makes about a configured value lives here, so the
|
|
4
|
+
tests can run it on its own.
|
|
5
|
+
"""
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
DEFAULT_SCRIPT_URL = 'https://widget.asyntai.com/static/js/chat-widget.js'
|
|
9
|
+
|
|
10
|
+
#: Shape of a widget identifier from the Asyntai dashboard.
|
|
11
|
+
ID_PATTERN = re.compile(r'^asyntai_[A-Za-z0-9]{6,64}$')
|
|
12
|
+
|
|
13
|
+
#: The identifier inside a pasted snippet.
|
|
14
|
+
SNIPPET_PATTERN = re.compile(r'data-asyntai-id\s*=\s*["\']([^"\']+)["\']')
|
|
15
|
+
|
|
16
|
+
_HTTPS_PATTERN = re.compile(r'^https://[^\s"\'<>]+$', re.IGNORECASE)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def clean_widget_id(raw):
|
|
20
|
+
"""Return a usable widget identifier, or an empty string.
|
|
21
|
+
|
|
22
|
+
Accepts a bare identifier or the whole snippet from the Asyntai
|
|
23
|
+
dashboard, because people paste the snippet. An empty string means the
|
|
24
|
+
chat stays off, which is how you switch it off again.
|
|
25
|
+
"""
|
|
26
|
+
if not isinstance(raw, str):
|
|
27
|
+
return ''
|
|
28
|
+
|
|
29
|
+
value = raw.strip()
|
|
30
|
+
if not value:
|
|
31
|
+
return ''
|
|
32
|
+
|
|
33
|
+
match = SNIPPET_PATTERN.search(value)
|
|
34
|
+
if match:
|
|
35
|
+
value = match.group(1).strip()
|
|
36
|
+
|
|
37
|
+
return value if ID_PATTERN.match(value) else ''
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def clean_script_url(raw):
|
|
41
|
+
"""Return the script address, or an empty string when the value is bad.
|
|
42
|
+
|
|
43
|
+
Only an https address is accepted, so a bad value can never put a
|
|
44
|
+
javascript: URL on every page of the site. No value means the Asyntai
|
|
45
|
+
address.
|
|
46
|
+
"""
|
|
47
|
+
if raw is None:
|
|
48
|
+
return DEFAULT_SCRIPT_URL
|
|
49
|
+
|
|
50
|
+
if not isinstance(raw, str):
|
|
51
|
+
return ''
|
|
52
|
+
|
|
53
|
+
value = raw.strip()
|
|
54
|
+
if not value:
|
|
55
|
+
return DEFAULT_SCRIPT_URL
|
|
56
|
+
|
|
57
|
+
return value if _HTTPS_PATTERN.match(value) else ''
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aiohttp-ai-chatbot
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Adds the Asyntai AI chat assistant to aiohttp sites. It answers visitor questions from your own content, in more than 80 languages.
|
|
5
|
+
Author-email: Asyntai <hello@asyntai.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://asyntai.com
|
|
8
|
+
Project-URL: Documentation, https://asyntai.com/documentation/integrations/aiohttp/
|
|
9
|
+
Project-URL: Source, https://github.com/asyntai/aiohttp-ai-chatbot
|
|
10
|
+
Project-URL: Issues, https://github.com/asyntai/aiohttp-ai-chatbot/issues
|
|
11
|
+
Keywords: aiohttp,asyncio,middleware,chatbot,ai,ai-chatbot,live-chat,customer-support,widget
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Environment :: Web Environment
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Framework :: aiohttp
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: aiohttp>=3.8
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# aiohttp-ai-chatbot
|
|
33
|
+
|
|
34
|
+
Adds the [Asyntai](https://asyntai.com) AI chat assistant to an aiohttp site.
|
|
35
|
+
The assistant answers visitor questions from your own content, day and night,
|
|
36
|
+
in more than 80 languages.
|
|
37
|
+
|
|
38
|
+
Free and open source. Works on every Asyntai plan, including the free plan.
|
|
39
|
+
|
|
40
|
+
- Requires Python 3.9 or newer and aiohttp 3.8 or newer
|
|
41
|
+
- Documentation: https://asyntai.com/documentation/integrations/aiohttp/
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
pip install aiohttp-ai-chatbot
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from aiohttp import web
|
|
51
|
+
from aiohttp_ai_chatbot import setup
|
|
52
|
+
|
|
53
|
+
app = web.Application()
|
|
54
|
+
app.router.add_get("/", index)
|
|
55
|
+
setup(app, widget_id="asyntai_ab12cd34")
|
|
56
|
+
|
|
57
|
+
web.run_app(app)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Or pass the middleware yourself:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from aiohttp_ai_chatbot import asyntai_middleware
|
|
64
|
+
|
|
65
|
+
app = web.Application(middlewares=[asyntai_middleware("asyntai_ab12cd34")])
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
You get the widget ID from the Install page of your
|
|
69
|
+
[Asyntai dashboard](https://asyntai.com/dashboard). You can paste the whole
|
|
70
|
+
snippet; the package keeps only the ID.
|
|
71
|
+
|
|
72
|
+
That is all. The chat button appears on every HTML page of the site. JSON,
|
|
73
|
+
files, streams, websockets and redirects pass through untouched.
|
|
74
|
+
|
|
75
|
+
## Options
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
setup(
|
|
79
|
+
app,
|
|
80
|
+
widget_id="asyntai_ab12cd34", # without it: the ASYNTAI_WIDGET_ID environment variable
|
|
81
|
+
skip_paths=["/admin*"], # the default
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- Leave out `widget_id` to read the `ASYNTAI_WIDGET_ID` environment variable.
|
|
86
|
+
It is read on every request, so you can change it without a code change.
|
|
87
|
+
An empty value switches the chat off.
|
|
88
|
+
- `skip_paths` lists paths that never get the widget. A path that ends in `*`
|
|
89
|
+
also matches everything below it, so `/admin*` covers `/admin` and
|
|
90
|
+
`/admin/users`, but not `/administrator`.
|
|
91
|
+
|
|
92
|
+
The middleware changes complete `web.Response` pages with status 200 and the
|
|
93
|
+
`text/html` content type. A response that uses `enable_compression()` still
|
|
94
|
+
gets the widget, because aiohttp compresses the body after the middleware.
|
|
95
|
+
Files from `add_static` or `web.FileResponse` and responses that you prepare
|
|
96
|
+
and stream yourself are sent as they are.
|
|
97
|
+
|
|
98
|
+
## Placing the widget by hand
|
|
99
|
+
|
|
100
|
+
With aiohttp-jinja2, register the helper once:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
import aiohttp_jinja2
|
|
104
|
+
from aiohttp_ai_chatbot import asyntai_widget
|
|
105
|
+
|
|
106
|
+
env = aiohttp_jinja2.setup(app, loader=...)
|
|
107
|
+
env.globals["asyntai_widget"] = asyntai_widget
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Then put it before the closing body tag:
|
|
111
|
+
|
|
112
|
+
```html
|
|
113
|
+
{{ asyntai_widget() }}
|
|
114
|
+
</body>
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`widget_snippet()` returns the same HTML as a plain string. The middleware
|
|
118
|
+
never adds a second copy to a page that already has one.
|
|
119
|
+
|
|
120
|
+
## How it loads
|
|
121
|
+
|
|
122
|
+
The widget script loads after the page has finished loading, so your page
|
|
123
|
+
draws first and page speed does not change.
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/aiohttp_ai_chatbot/__init__.py
|
|
6
|
+
src/aiohttp_ai_chatbot/middleware.py
|
|
7
|
+
src/aiohttp_ai_chatbot/snippet.py
|
|
8
|
+
src/aiohttp_ai_chatbot/utils.py
|
|
9
|
+
src/aiohttp_ai_chatbot.egg-info/PKG-INFO
|
|
10
|
+
src/aiohttp_ai_chatbot.egg-info/SOURCES.txt
|
|
11
|
+
src/aiohttp_ai_chatbot.egg-info/dependency_links.txt
|
|
12
|
+
src/aiohttp_ai_chatbot.egg-info/requires.txt
|
|
13
|
+
src/aiohttp_ai_chatbot.egg-info/top_level.txt
|
|
14
|
+
tests/test_middleware.py
|
|
15
|
+
tests/test_snippet.py
|
|
16
|
+
tests/test_utils.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
aiohttp>=3.8
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
aiohttp_ai_chatbot
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from aiohttp import web
|
|
5
|
+
|
|
6
|
+
from aiohttp_ai_chatbot import DEFAULT_SKIP_PATHS, asyntai_middleware, setup
|
|
7
|
+
from aiohttp_ai_chatbot.middleware import insert_snippet, path_is_skipped
|
|
8
|
+
|
|
9
|
+
WIDGET = 'asyntai_ab12cd34'
|
|
10
|
+
PAGE = '<!doctype html><html><head><title>Home</title></head><body><h1>Hello</h1></body></html>'
|
|
11
|
+
# The hidden config element: exactly one per inserted widget.
|
|
12
|
+
MARKER = 'class="asyntai-widget-config"'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def html(text=PAGE, status=200, **kwargs):
|
|
16
|
+
async def handler(request):
|
|
17
|
+
return web.Response(text=text, content_type='text/html', status=status, **kwargs)
|
|
18
|
+
return handler
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def make_app(*routes, **options):
|
|
22
|
+
options.setdefault('widget_id', WIDGET)
|
|
23
|
+
app = web.Application(middlewares=[asyntai_middleware(**options)])
|
|
24
|
+
for method, path, handler in routes:
|
|
25
|
+
if method == 'GET':
|
|
26
|
+
app.router.add_get(path, handler) # also answers HEAD
|
|
27
|
+
else:
|
|
28
|
+
app.router.add_route(method, path, handler)
|
|
29
|
+
return app
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def get_text(client, path, method='GET'):
|
|
33
|
+
response = await client.request(method, path)
|
|
34
|
+
return response, await response.text()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ---------------------------------------------------------------- pages
|
|
38
|
+
|
|
39
|
+
async def test_html_page_gets_widget_once_before_body_close(aiohttp_client):
|
|
40
|
+
client = await aiohttp_client(make_app(('GET', '/', html())))
|
|
41
|
+
response, text = await get_text(client, '/')
|
|
42
|
+
|
|
43
|
+
assert response.status == 200
|
|
44
|
+
assert text.count(MARKER) == 1
|
|
45
|
+
assert f'data-asyntai-widget="{WIDGET}"' in text
|
|
46
|
+
assert text.index(MARKER) < text.rindex('</body>')
|
|
47
|
+
assert text.endswith('</body></html>')
|
|
48
|
+
assert int(response.headers['Content-Length']) == len(text.encode('utf-8'))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def test_upper_case_body_tag_and_last_tag_used(aiohttp_client):
|
|
52
|
+
page = '<html><body><code></body></code><p>x</p></BODY></html>'
|
|
53
|
+
client = await aiohttp_client(make_app(('GET', '/', html(page))))
|
|
54
|
+
_, text = await get_text(client, '/')
|
|
55
|
+
|
|
56
|
+
assert text.count(MARKER) == 1
|
|
57
|
+
assert text.index(MARKER) > text.index('<p>x</p>')
|
|
58
|
+
assert text.endswith('</BODY></html>')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def test_page_without_body_close_is_untouched(aiohttp_client):
|
|
62
|
+
client = await aiohttp_client(make_app(('GET', '/', html('<p>fragment</p>'))))
|
|
63
|
+
_, text = await get_text(client, '/')
|
|
64
|
+
assert text == '<p>fragment</p>'
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def test_page_that_already_has_widget_is_not_doubled(aiohttp_client):
|
|
68
|
+
own = PAGE.replace('</body>', '<script src="x.js" data-asyntai-id="asyntai_zz99yy88"></script></body>')
|
|
69
|
+
client = await aiohttp_client(make_app(('GET', '/', html(own))))
|
|
70
|
+
_, text = await get_text(client, '/')
|
|
71
|
+
assert text == own
|
|
72
|
+
assert MARKER not in text
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def test_charset_is_kept(aiohttp_client):
|
|
76
|
+
page = '<html><body><p>Příliš žluťoučký kůň</p></body></html>'
|
|
77
|
+
|
|
78
|
+
async def handler(request):
|
|
79
|
+
return web.Response(body=page.encode('cp1250'), content_type='text/html', charset='cp1250')
|
|
80
|
+
|
|
81
|
+
client = await aiohttp_client(make_app(('GET', '/', handler)))
|
|
82
|
+
response = await client.get('/')
|
|
83
|
+
raw = await response.read()
|
|
84
|
+
|
|
85
|
+
assert 'charset=cp1250' in response.headers['Content-Type']
|
|
86
|
+
decoded = raw.decode('cp1250')
|
|
87
|
+
assert 'Příliš žluťoučký kůň' in decoded
|
|
88
|
+
assert decoded.count(MARKER) == 1
|
|
89
|
+
assert int(response.headers['Content-Length']) == len(raw)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def test_compressed_response_gets_widget_and_stays_compressed(aiohttp_client):
|
|
93
|
+
async def handler(request):
|
|
94
|
+
response = web.Response(text=PAGE * 50, content_type='text/html')
|
|
95
|
+
response.enable_compression()
|
|
96
|
+
return response
|
|
97
|
+
|
|
98
|
+
client = await aiohttp_client(make_app(('GET', '/', handler)))
|
|
99
|
+
response = await client.get('/', headers={'Accept-Encoding': 'gzip'})
|
|
100
|
+
text = await response.text()
|
|
101
|
+
|
|
102
|
+
assert response.headers.get('Content-Encoding') == 'gzip'
|
|
103
|
+
assert text.count(MARKER) == 1
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def test_pre_compressed_body_is_untouched(aiohttp_client):
|
|
107
|
+
import gzip
|
|
108
|
+
body = gzip.compress(PAGE.encode())
|
|
109
|
+
|
|
110
|
+
async def handler(request):
|
|
111
|
+
return web.Response(body=body, content_type='text/html', headers={'Content-Encoding': 'gzip'})
|
|
112
|
+
|
|
113
|
+
client = await aiohttp_client(make_app(('GET', '/', handler)))
|
|
114
|
+
response = await client.get('/')
|
|
115
|
+
text = await response.text() # the client unpacks the gzip body
|
|
116
|
+
assert MARKER not in text
|
|
117
|
+
assert text == PAGE
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------- left alone
|
|
121
|
+
|
|
122
|
+
async def test_json_is_untouched(aiohttp_client):
|
|
123
|
+
async def handler(request):
|
|
124
|
+
return web.json_response({'body': '</body>'})
|
|
125
|
+
|
|
126
|
+
client = await aiohttp_client(make_app(('GET', '/api', handler)))
|
|
127
|
+
response = await client.get('/api')
|
|
128
|
+
assert await response.json() == {'body': '</body>'}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def test_plain_text_is_untouched(aiohttp_client):
|
|
132
|
+
async def handler(request):
|
|
133
|
+
return web.Response(text='</body>')
|
|
134
|
+
|
|
135
|
+
client = await aiohttp_client(make_app(('GET', '/t', handler)))
|
|
136
|
+
_, text = await get_text(client, '/t')
|
|
137
|
+
assert text == '</body>'
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def test_error_status_is_untouched(aiohttp_client):
|
|
141
|
+
client = await aiohttp_client(make_app(('GET', '/', html(status=500))))
|
|
142
|
+
_, text = await get_text(client, '/')
|
|
143
|
+
assert text == PAGE
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def test_raised_not_found_and_redirect_pass(aiohttp_client):
|
|
147
|
+
async def redirect(request):
|
|
148
|
+
raise web.HTTPFound('/')
|
|
149
|
+
|
|
150
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), ('GET', '/old', redirect)))
|
|
151
|
+
|
|
152
|
+
response = await client.get('/missing')
|
|
153
|
+
assert response.status == 404
|
|
154
|
+
assert MARKER not in await response.text()
|
|
155
|
+
|
|
156
|
+
response = await client.get('/old', allow_redirects=False)
|
|
157
|
+
assert response.status == 302
|
|
158
|
+
assert response.headers['Location'] == '/'
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def test_head_request_is_untouched(aiohttp_client):
|
|
162
|
+
client = await aiohttp_client(make_app(('GET', '/', html())))
|
|
163
|
+
response = await client.head('/')
|
|
164
|
+
assert response.status == 200
|
|
165
|
+
assert int(response.headers['Content-Length']) == len(PAGE.encode())
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def test_static_html_file_is_untouched(aiohttp_client, tmp_path):
|
|
169
|
+
(tmp_path / 'page.html').write_text(PAGE, encoding='utf-8')
|
|
170
|
+
app = make_app()
|
|
171
|
+
app.router.add_static('/static', tmp_path)
|
|
172
|
+
client = await aiohttp_client(app)
|
|
173
|
+
|
|
174
|
+
_, text = await get_text(client, '/static/page.html')
|
|
175
|
+
assert text == PAGE
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def test_prepared_stream_is_untouched(aiohttp_client):
|
|
179
|
+
async def handler(request):
|
|
180
|
+
response = web.StreamResponse(headers={'Content-Type': 'text/html'})
|
|
181
|
+
await response.prepare(request)
|
|
182
|
+
await response.write(PAGE.encode())
|
|
183
|
+
await response.write_eof()
|
|
184
|
+
return response
|
|
185
|
+
|
|
186
|
+
client = await aiohttp_client(make_app(('GET', '/stream', handler)))
|
|
187
|
+
_, text = await get_text(client, '/stream')
|
|
188
|
+
assert text == PAGE
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
async def test_websocket_still_works(aiohttp_client):
|
|
192
|
+
async def handler(request):
|
|
193
|
+
ws = web.WebSocketResponse()
|
|
194
|
+
await ws.prepare(request)
|
|
195
|
+
async for message in ws:
|
|
196
|
+
await ws.send_str('echo:' + message.data)
|
|
197
|
+
await ws.close()
|
|
198
|
+
return ws
|
|
199
|
+
|
|
200
|
+
client = await aiohttp_client(make_app(('GET', '/ws', handler)))
|
|
201
|
+
ws = await client.ws_connect('/ws')
|
|
202
|
+
await ws.send_str('hi')
|
|
203
|
+
assert (await ws.receive()).data == 'echo:hi'
|
|
204
|
+
await ws.close()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ---------------------------------------------------------------- skip paths
|
|
208
|
+
|
|
209
|
+
def test_path_rules():
|
|
210
|
+
assert path_is_skipped('/admin', DEFAULT_SKIP_PATHS)
|
|
211
|
+
assert path_is_skipped('/admin/users', DEFAULT_SKIP_PATHS)
|
|
212
|
+
assert not path_is_skipped('/administrator', DEFAULT_SKIP_PATHS)
|
|
213
|
+
assert not path_is_skipped('/', DEFAULT_SKIP_PATHS)
|
|
214
|
+
assert path_is_skipped('/login', ('/login',))
|
|
215
|
+
assert not path_is_skipped('/login/x', ('/login',))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def test_skip_paths(aiohttp_client):
|
|
219
|
+
client = await aiohttp_client(make_app(
|
|
220
|
+
('GET', '/admin', html()), ('GET', '/admin/x', html()),
|
|
221
|
+
('GET', '/administrator', html()), ('GET', '/login', html()),
|
|
222
|
+
skip_paths=['/admin*', '/login'],
|
|
223
|
+
))
|
|
224
|
+
assert MARKER not in (await get_text(client, '/admin'))[1]
|
|
225
|
+
assert MARKER not in (await get_text(client, '/admin/x'))[1]
|
|
226
|
+
assert MARKER not in (await get_text(client, '/login'))[1]
|
|
227
|
+
assert MARKER in (await get_text(client, '/administrator'))[1]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def test_empty_skip_paths_puts_widget_everywhere(aiohttp_client):
|
|
231
|
+
client = await aiohttp_client(make_app(('GET', '/admin', html()), skip_paths=None))
|
|
232
|
+
assert MARKER in (await get_text(client, '/admin'))[1]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ---------------------------------------------------------------- settings
|
|
236
|
+
|
|
237
|
+
async def test_environment_variable_is_read_per_request(aiohttp_client, monkeypatch):
|
|
238
|
+
monkeypatch.delenv('ASYNTAI_WIDGET_ID', raising=False)
|
|
239
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), widget_id=None))
|
|
240
|
+
|
|
241
|
+
assert MARKER not in (await get_text(client, '/'))[1]
|
|
242
|
+
|
|
243
|
+
monkeypatch.setenv('ASYNTAI_WIDGET_ID', 'asyntai_env12345')
|
|
244
|
+
_, text = await get_text(client, '/')
|
|
245
|
+
assert 'data-asyntai-widget="asyntai_env12345"' in text
|
|
246
|
+
|
|
247
|
+
monkeypatch.setenv('ASYNTAI_WIDGET_ID', '')
|
|
248
|
+
assert MARKER not in (await get_text(client, '/'))[1]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
async def test_pasted_snippet_keeps_only_the_id(aiohttp_client):
|
|
252
|
+
pasted = '<script async src="https://widget.asyntai.com/static/js/chat-widget.js" data-asyntai-id="asyntai_pasted99"></script>'
|
|
253
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), widget_id=pasted))
|
|
254
|
+
_, text = await get_text(client, '/')
|
|
255
|
+
assert 'data-asyntai-widget="asyntai_pasted99"' in text
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@pytest.mark.parametrize('bad', ['', 'nonsense', 'asyntai_<x>', 'asyntai_"onload=', 123])
|
|
259
|
+
async def test_bad_widget_id_keeps_chat_off(aiohttp_client, bad):
|
|
260
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), widget_id=bad))
|
|
261
|
+
_, text = await get_text(client, '/')
|
|
262
|
+
assert text == PAGE
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
async def test_bad_script_url_keeps_chat_off_and_https_url_is_used(aiohttp_client):
|
|
266
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), script_url='javascript:alert(1)'))
|
|
267
|
+
assert MARKER not in (await get_text(client, '/'))[1]
|
|
268
|
+
|
|
269
|
+
client = await aiohttp_client(make_app(('GET', '/', html()), script_url='https://cdn.example.com/w.js'))
|
|
270
|
+
_, text = await get_text(client, '/')
|
|
271
|
+
assert 'data-asyntai-src="https://cdn.example.com/w.js"' in text
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def test_setup_adds_the_middleware(aiohttp_client):
|
|
275
|
+
app = web.Application()
|
|
276
|
+
app.router.add_get('/', html())
|
|
277
|
+
setup(app, widget_id=WIDGET)
|
|
278
|
+
assert len(app.middlewares) == 1
|
|
279
|
+
|
|
280
|
+
client = await aiohttp_client(app)
|
|
281
|
+
assert (await get_text(client, '/'))[1].count(MARKER) == 1
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
async def test_jinja2_helper_with_aiohttp_jinja2(aiohttp_client):
|
|
285
|
+
aiohttp_jinja2 = pytest.importorskip('aiohttp_jinja2')
|
|
286
|
+
jinja2 = pytest.importorskip('jinja2')
|
|
287
|
+
from aiohttp_ai_chatbot import asyntai_widget
|
|
288
|
+
|
|
289
|
+
app = web.Application()
|
|
290
|
+
env = aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
|
|
291
|
+
'page.html': '<html><body>{{ asyntai_widget("' + WIDGET + '") }}</body></html>',
|
|
292
|
+
}))
|
|
293
|
+
env.globals['asyntai_widget'] = asyntai_widget
|
|
294
|
+
setup(app, widget_id=WIDGET)
|
|
295
|
+
|
|
296
|
+
async def handler(request):
|
|
297
|
+
return aiohttp_jinja2.render_template('page.html', request, {})
|
|
298
|
+
|
|
299
|
+
app.router.add_get('/', handler)
|
|
300
|
+
client = await aiohttp_client(app)
|
|
301
|
+
_, text = await get_text(client, '/')
|
|
302
|
+
|
|
303
|
+
# The template already carries the widget, so the middleware adds nothing.
|
|
304
|
+
assert text.count(MARKER) == 1
|
|
305
|
+
assert '<' not in text
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# ---------------------------------------------------------------- helper
|
|
309
|
+
|
|
310
|
+
def test_insert_snippet_bad_charset_returns_none():
|
|
311
|
+
assert insert_snippet(b'<body></body>', 'x', 'no-such-charset') is None
|
|
312
|
+
assert insert_snippet('<body>ž</body>'.encode('utf-8'), 'x', 'ascii') is None
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import shutil
|
|
3
|
+
import subprocess
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from aiohttp_ai_chatbot import asyntai_widget, widget_snippet
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_snippet_carries_id_and_script_url():
|
|
11
|
+
html = widget_snippet('asyntai_ab12cd34')
|
|
12
|
+
assert 'data-asyntai-widget="asyntai_ab12cd34"' in html
|
|
13
|
+
assert 'data-asyntai-src="https://widget.asyntai.com/static/js/chat-widget.js"' in html
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_snippet_is_empty_without_a_good_id(monkeypatch):
|
|
17
|
+
monkeypatch.delenv('ASYNTAI_WIDGET_ID', raising=False)
|
|
18
|
+
assert widget_snippet() == ''
|
|
19
|
+
assert widget_snippet('bad') == ''
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_snippet_reads_the_environment(monkeypatch):
|
|
23
|
+
monkeypatch.setenv('ASYNTAI_WIDGET_ID', 'asyntai_env12345')
|
|
24
|
+
assert 'asyntai_env12345' in widget_snippet()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_template_helper_is_safe_markup():
|
|
28
|
+
markupsafe = pytest.importorskip('markupsafe')
|
|
29
|
+
value = asyntai_widget('asyntai_ab12cd34')
|
|
30
|
+
assert isinstance(value, markupsafe.Markup)
|
|
31
|
+
assert str(markupsafe.escape(value)) == str(value)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_jinja_template_renders_the_widget():
|
|
35
|
+
jinja2 = pytest.importorskip('jinja2')
|
|
36
|
+
env = jinja2.Environment(autoescape=True)
|
|
37
|
+
env.globals['asyntai_widget'] = asyntai_widget
|
|
38
|
+
html = env.from_string('<body>{{ asyntai_widget("asyntai_ab12cd34") }}</body>').render()
|
|
39
|
+
assert '<script>' in html
|
|
40
|
+
assert 'data-asyntai-widget="asyntai_ab12cd34"' in html
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_script_is_valid_javascript(tmp_path):
|
|
44
|
+
node = shutil.which('node')
|
|
45
|
+
if not node:
|
|
46
|
+
pytest.skip('node is not installed')
|
|
47
|
+
script = re.search(r'<script>(.*)</script>', widget_snippet('asyntai_ab12cd34'), re.S).group(1)
|
|
48
|
+
path = tmp_path / 'widget.js'
|
|
49
|
+
path.write_text(script, encoding='utf-8')
|
|
50
|
+
result = subprocess.run([node, '--check', str(path)], capture_output=True, text=True)
|
|
51
|
+
assert result.returncode == 0, result.stderr
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from aiohttp_ai_chatbot.utils import DEFAULT_SCRIPT_URL, clean_script_url, clean_widget_id
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_bare_id_is_kept():
|
|
5
|
+
assert clean_widget_id('asyntai_ab12cd34') == 'asyntai_ab12cd34'
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_id_is_trimmed():
|
|
9
|
+
assert clean_widget_id(' asyntai_ab12cd34 \n') == 'asyntai_ab12cd34'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_id_comes_out_of_a_pasted_snippet():
|
|
13
|
+
snippet = '<script async src="https://widget.asyntai.com/static/js/chat-widget.js" data-asyntai-id="asyntai_ab12cd34"></script>'
|
|
14
|
+
assert clean_widget_id(snippet) == 'asyntai_ab12cd34'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_bad_ids_switch_the_chat_off():
|
|
18
|
+
for raw in ['', ' ', 'hello', 'asyntai_', 'asyntai_ab"><script>', 'asyntai_ab12 cd34', None, 42]:
|
|
19
|
+
assert clean_widget_id(raw) == ''
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_script_url_defaults_to_asyntai():
|
|
23
|
+
assert clean_script_url(None) == DEFAULT_SCRIPT_URL
|
|
24
|
+
assert clean_script_url('') == DEFAULT_SCRIPT_URL
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_only_https_script_urls_are_accepted():
|
|
28
|
+
assert clean_script_url('https://example.com/w.js') == 'https://example.com/w.js'
|
|
29
|
+
for raw in ['http://example.com/w.js', 'javascript:alert(1)', 'https://e.com/a b.js', 'https://e.com/"x', 42]:
|
|
30
|
+
assert clean_script_url(raw) == ''
|