furystream 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.
- furystream-1.0.0/.gitignore +8 -0
- furystream-1.0.0/CHANGELOG.md +7 -0
- furystream-1.0.0/LICENSE +21 -0
- furystream-1.0.0/PKG-INFO +123 -0
- furystream-1.0.0/README.md +102 -0
- furystream-1.0.0/examples/django_templatetag.py +24 -0
- furystream-1.0.0/examples/embed_page.py +15 -0
- furystream-1.0.0/examples/files.json +4 -0
- furystream-1.0.0/examples/flask_app.py +27 -0
- furystream-1.0.0/examples/list_files.py +11 -0
- furystream-1.0.0/pyproject.toml +42 -0
- furystream-1.0.0/src/furystream/__init__.py +22 -0
- furystream-1.0.0/src/furystream/__main__.py +5 -0
- furystream-1.0.0/src/furystream/_constants.py +5 -0
- furystream-1.0.0/src/furystream/_transport.py +58 -0
- furystream-1.0.0/src/furystream/cli.py +45 -0
- furystream-1.0.0/src/furystream/client.py +178 -0
- furystream-1.0.0/src/furystream/embed.py +67 -0
- furystream-1.0.0/src/furystream/errors.py +24 -0
- furystream-1.0.0/src/furystream/files.py +33 -0
- furystream-1.0.0/src/furystream/models.py +109 -0
- furystream-1.0.0/src/furystream/py.typed +0 -0
- furystream-1.0.0/tests/test_client.py +137 -0
- furystream-1.0.0/tests/test_embed.py +74 -0
furystream-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anežka Křenková
|
|
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,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: furystream
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Embed FuryStream videos and read your files, stats and balance from Python.
|
|
5
|
+
Project-URL: Homepage, https://github.com/furysdk/furystream-python
|
|
6
|
+
Project-URL: Issues, https://github.com/furysdk/furystream-python/issues
|
|
7
|
+
Author-email: Anežka Křenková <support@furystream.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: embed,furystream,player,video
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# furystream (Python)
|
|
23
|
+
|
|
24
|
+
Put FuryStream videos on your Python website, and optionally read your own files, views and balance.
|
|
25
|
+
|
|
26
|
+
For anyone building a site with Django, Flask, FastAPI or plain scripts. No dependencies, Python 3.9 or newer.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
pip install furystream
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 3-minute start
|
|
35
|
+
|
|
36
|
+
### 1. Embed a video (no API key needed)
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from furystream import embed_iframe, embed_tag
|
|
40
|
+
|
|
41
|
+
print(embed_iframe("abcDEF123456")) # the official player in an iframe
|
|
42
|
+
print(embed_tag("abcDEF123456")) # the <fury-player> tag version
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The file id is checked first. Anything that is not 12 letters and digits raises `InvalidFileIdError`, so nothing unsafe can reach your page. `is_valid_file_id("...")` gives you a yes or no.
|
|
46
|
+
|
|
47
|
+
### 2. List your videos (API key needed)
|
|
48
|
+
|
|
49
|
+
Create a read-only key in your FuryStream account. Give it these scopes: `account:read`, `files:read`, `stats:read`, `earnings:read`. `client.me()` needs `account:read`; without it the call raises an error with status 403. Then:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from furystream import Client
|
|
53
|
+
|
|
54
|
+
client = Client() # reads FURYSTREAM_API_KEY, or Client("fsk_...")
|
|
55
|
+
for f in client.files.iter(): # follows all pages for you
|
|
56
|
+
print(f.file_id, f.title, f.views_total)
|
|
57
|
+
|
|
58
|
+
print(client.files.get("abcDEF123456").title)
|
|
59
|
+
print(client.files.embed("abcDEF123456").iframe_html)
|
|
60
|
+
print(client.stats.summary("2025-01-01", "2025-01-31").views)
|
|
61
|
+
print(client.earnings.balance())
|
|
62
|
+
print(client.me())
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`client.files.list(q=..., status=..., sort=..., limit=1..100, cursor=...)` returns one page with `.data` and `.next_cursor`. `sort` is `-created_at` (newest first, default) or `created_at`. `status` is one of `pending`, `downloading`, `uploading`, `processing`, `ready`, `transcoding`, `failed`, `blocked`, `takedown`. Money amounts in the balance are micro units (1,000,000 = 1.00).
|
|
66
|
+
|
|
67
|
+
Async version (same calls, use `await`):
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from furystream import AsyncClient
|
|
71
|
+
|
|
72
|
+
async def main():
|
|
73
|
+
client = AsyncClient()
|
|
74
|
+
async for f in client.files.iter():
|
|
75
|
+
print(f.title)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Problems raise `FuryStreamError` with `.status` and `.code` (status 0 means the network failed). Keep your key on the server and never print it into a page.
|
|
79
|
+
|
|
80
|
+
### 3. Use it in templates
|
|
81
|
+
|
|
82
|
+
`embed_*` functions return a `SafeString`: a normal string with an `__html__` method. Jinja (Flask) and Django both recognise it and will not escape it a second time. You do not need markupsafe.
|
|
83
|
+
|
|
84
|
+
- Flask / Jinja: `app.add_template_filter(embed_html, "fury_embed")`, then `{{ file_id|fury_embed }}`. See `examples/flask_app.py`.
|
|
85
|
+
- Django: copy `examples/django_templatetag.py` into a `templatetags` folder, then `{% fury_embed video.file_id %}`.
|
|
86
|
+
|
|
87
|
+
### A hand-made list
|
|
88
|
+
|
|
89
|
+
Put your videos in `files.json`:
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
[{ "id": "abcDEF123456", "title": "My first video" }]
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from furystream import load_files
|
|
97
|
+
for item in load_files("files.json"):
|
|
98
|
+
print(item.id, item.title)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Command line
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
python -m furystream embed abcDEF123456
|
|
105
|
+
python -m furystream embed abcDEF123456 --tag
|
|
106
|
+
FURYSTREAM_API_KEY=fsk_... python -m furystream list --all
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
More runnable files are in `examples/`.
|
|
110
|
+
|
|
111
|
+
## FAQ
|
|
112
|
+
|
|
113
|
+
**Do I need an API key to show a video?** No. The key is only for listing files, stats and earnings.
|
|
114
|
+
|
|
115
|
+
**Can the key change my videos?** No. Keys are read-only.
|
|
116
|
+
|
|
117
|
+
**Will an API outage break my page?** Embedding never calls the API. Calls through `Client` raise `FuryStreamError`, which you can catch.
|
|
118
|
+
|
|
119
|
+
**Does it change the player?** No. It only outputs the official embed.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT. Author: Anežka Křenková, support@furystream.com
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# furystream (Python)
|
|
2
|
+
|
|
3
|
+
Put FuryStream videos on your Python website, and optionally read your own files, views and balance.
|
|
4
|
+
|
|
5
|
+
For anyone building a site with Django, Flask, FastAPI or plain scripts. No dependencies, Python 3.9 or newer.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install furystream
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 3-minute start
|
|
14
|
+
|
|
15
|
+
### 1. Embed a video (no API key needed)
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from furystream import embed_iframe, embed_tag
|
|
19
|
+
|
|
20
|
+
print(embed_iframe("abcDEF123456")) # the official player in an iframe
|
|
21
|
+
print(embed_tag("abcDEF123456")) # the <fury-player> tag version
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The file id is checked first. Anything that is not 12 letters and digits raises `InvalidFileIdError`, so nothing unsafe can reach your page. `is_valid_file_id("...")` gives you a yes or no.
|
|
25
|
+
|
|
26
|
+
### 2. List your videos (API key needed)
|
|
27
|
+
|
|
28
|
+
Create a read-only key in your FuryStream account. Give it these scopes: `account:read`, `files:read`, `stats:read`, `earnings:read`. `client.me()` needs `account:read`; without it the call raises an error with status 403. Then:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from furystream import Client
|
|
32
|
+
|
|
33
|
+
client = Client() # reads FURYSTREAM_API_KEY, or Client("fsk_...")
|
|
34
|
+
for f in client.files.iter(): # follows all pages for you
|
|
35
|
+
print(f.file_id, f.title, f.views_total)
|
|
36
|
+
|
|
37
|
+
print(client.files.get("abcDEF123456").title)
|
|
38
|
+
print(client.files.embed("abcDEF123456").iframe_html)
|
|
39
|
+
print(client.stats.summary("2025-01-01", "2025-01-31").views)
|
|
40
|
+
print(client.earnings.balance())
|
|
41
|
+
print(client.me())
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`client.files.list(q=..., status=..., sort=..., limit=1..100, cursor=...)` returns one page with `.data` and `.next_cursor`. `sort` is `-created_at` (newest first, default) or `created_at`. `status` is one of `pending`, `downloading`, `uploading`, `processing`, `ready`, `transcoding`, `failed`, `blocked`, `takedown`. Money amounts in the balance are micro units (1,000,000 = 1.00).
|
|
45
|
+
|
|
46
|
+
Async version (same calls, use `await`):
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from furystream import AsyncClient
|
|
50
|
+
|
|
51
|
+
async def main():
|
|
52
|
+
client = AsyncClient()
|
|
53
|
+
async for f in client.files.iter():
|
|
54
|
+
print(f.title)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Problems raise `FuryStreamError` with `.status` and `.code` (status 0 means the network failed). Keep your key on the server and never print it into a page.
|
|
58
|
+
|
|
59
|
+
### 3. Use it in templates
|
|
60
|
+
|
|
61
|
+
`embed_*` functions return a `SafeString`: a normal string with an `__html__` method. Jinja (Flask) and Django both recognise it and will not escape it a second time. You do not need markupsafe.
|
|
62
|
+
|
|
63
|
+
- Flask / Jinja: `app.add_template_filter(embed_html, "fury_embed")`, then `{{ file_id|fury_embed }}`. See `examples/flask_app.py`.
|
|
64
|
+
- Django: copy `examples/django_templatetag.py` into a `templatetags` folder, then `{% fury_embed video.file_id %}`.
|
|
65
|
+
|
|
66
|
+
### A hand-made list
|
|
67
|
+
|
|
68
|
+
Put your videos in `files.json`:
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
[{ "id": "abcDEF123456", "title": "My first video" }]
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from furystream import load_files
|
|
76
|
+
for item in load_files("files.json"):
|
|
77
|
+
print(item.id, item.title)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Command line
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
python -m furystream embed abcDEF123456
|
|
84
|
+
python -m furystream embed abcDEF123456 --tag
|
|
85
|
+
FURYSTREAM_API_KEY=fsk_... python -m furystream list --all
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
More runnable files are in `examples/`.
|
|
89
|
+
|
|
90
|
+
## FAQ
|
|
91
|
+
|
|
92
|
+
**Do I need an API key to show a video?** No. The key is only for listing files, stats and earnings.
|
|
93
|
+
|
|
94
|
+
**Can the key change my videos?** No. Keys are read-only.
|
|
95
|
+
|
|
96
|
+
**Will an API outage break my page?** Embedding never calls the API. Calls through `Client` raise `FuryStreamError`, which you can catch.
|
|
97
|
+
|
|
98
|
+
**Does it change the player?** No. It only outputs the official embed.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
MIT. Author: Anežka Křenková, support@furystream.com
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Django template tag. Save as <app>/templatetags/furystream_tags.py
|
|
2
|
+
|
|
3
|
+
Template:
|
|
4
|
+
{% load furystream_tags %}
|
|
5
|
+
{% fury_embed video.file_id %}
|
|
6
|
+
{% fury_embed video.file_id "tag" %}
|
|
7
|
+
|
|
8
|
+
``embed_html`` returns a SafeString with ``__html__``, which Django already
|
|
9
|
+
treats as safe, so no ``mark_safe`` is needed. A bad id renders nothing.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from django import template
|
|
13
|
+
|
|
14
|
+
from furystream import InvalidFileIdError, embed_html
|
|
15
|
+
|
|
16
|
+
register = template.Library()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@register.simple_tag
|
|
20
|
+
def fury_embed(file_id, kind="iframe"):
|
|
21
|
+
try:
|
|
22
|
+
return embed_html(file_id, kind)
|
|
23
|
+
except (InvalidFileIdError, ValueError):
|
|
24
|
+
return ""
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Write embed_page.html with every video from files.json. No API key needed."""
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from furystream import embed_iframe, load_files
|
|
7
|
+
|
|
8
|
+
here = Path(__file__).parent
|
|
9
|
+
parts = []
|
|
10
|
+
for item in load_files(here / "files.json"):
|
|
11
|
+
parts.append("<h2>%s</h2>\n%s" % (html.escape(item.title), embed_iframe(item.id)))
|
|
12
|
+
|
|
13
|
+
page = "<!doctype html><meta charset=utf-8><title>Videos</title>\n" + "\n".join(parts)
|
|
14
|
+
(here / "embed_page.html").write_text(page, encoding="utf-8")
|
|
15
|
+
print("Wrote embed_page.html")
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Flask example. Needs Flask (pip install flask). Run: flask --app flask_app run
|
|
2
|
+
|
|
3
|
+
The embed is a SafeString, so Jinja does not escape it again. Only ids that
|
|
4
|
+
pass validation are ever turned into HTML.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from flask import Flask, render_template_string
|
|
10
|
+
|
|
11
|
+
from furystream import embed_html, load_files
|
|
12
|
+
|
|
13
|
+
app = Flask(__name__)
|
|
14
|
+
app.add_template_filter(embed_html, "fury_embed") # {{ file_id|fury_embed }}
|
|
15
|
+
|
|
16
|
+
PAGE = """
|
|
17
|
+
<h1>My videos</h1>
|
|
18
|
+
{% for v in videos %}
|
|
19
|
+
<h2>{{ v.title }}</h2>
|
|
20
|
+
{{ v.id|fury_embed }}
|
|
21
|
+
{% endfor %}
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@app.route("/")
|
|
26
|
+
def index():
|
|
27
|
+
return render_template_string(PAGE, videos=load_files(Path(__file__).with_name("files.json")))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""List your videos. Run: FURYSTREAM_API_KEY=fsk_... python list_files.py"""
|
|
2
|
+
|
|
3
|
+
from furystream import Client, FuryStreamError
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
client = Client() # reads FURYSTREAM_API_KEY
|
|
7
|
+
for f in client.files.iter(limit=50):
|
|
8
|
+
print(f.file_id, f.status, f.title, f.views_total)
|
|
9
|
+
print("Views this month:", client.stats.summary("2025-01-01", "2025-01-31").views)
|
|
10
|
+
except FuryStreamError as err:
|
|
11
|
+
print("Could not reach FuryStream:", err)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "furystream"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Embed FuryStream videos and read your files, stats and balance from Python."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Anežka Křenková", email = "support@furystream.com" }]
|
|
14
|
+
keywords = ["furystream", "video", "embed", "player"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.9",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
dependencies = []
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/furysdk/furystream-python"
|
|
29
|
+
Issues = "https://github.com/furysdk/furystream-python/issues"
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
furystream = "furystream.cli:main"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/furystream"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["src", "tests", "examples", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
testpaths = ["tests"]
|
|
42
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""FuryStream: embed videos and read your files, stats and balance."""
|
|
2
|
+
|
|
3
|
+
from ._constants import VERSION as __version__
|
|
4
|
+
from .client import AsyncClient, Client
|
|
5
|
+
from .embed import (
|
|
6
|
+
SafeString,
|
|
7
|
+
embed_html,
|
|
8
|
+
embed_iframe,
|
|
9
|
+
embed_tag,
|
|
10
|
+
embed_url,
|
|
11
|
+
is_valid_file_id,
|
|
12
|
+
)
|
|
13
|
+
from .errors import FuryStreamError, InvalidFileIdError
|
|
14
|
+
from .files import ManualFile, load_files
|
|
15
|
+
from .models import Balance, EmbedCodes, File, FilePage, StatsSummary
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"AsyncClient", "Client", "SafeString", "embed_html", "embed_iframe", "embed_tag",
|
|
19
|
+
"embed_url", "is_valid_file_id", "FuryStreamError", "InvalidFileIdError",
|
|
20
|
+
"ManualFile", "load_files", "Balance", "EmbedCodes", "File", "FilePage",
|
|
21
|
+
"StatsSummary", "__version__",
|
|
22
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Stdlib HTTP transport. A transport is a callable
|
|
2
|
+
``(method, url, headers, timeout) -> (status, body_bytes)``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
from ._constants import VERSION
|
|
12
|
+
from .errors import FuryStreamError
|
|
13
|
+
|
|
14
|
+
Transport = Callable[[str, str, Dict[str, str], float], Tuple[int, bytes]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def urllib_transport(method: str, url: str, headers: Dict[str, str], timeout: float) -> Tuple[int, bytes]:
|
|
18
|
+
req = urllib.request.Request(url, method=method, headers=headers)
|
|
19
|
+
try:
|
|
20
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 (https only)
|
|
21
|
+
return resp.status, resp.read()
|
|
22
|
+
except urllib.error.HTTPError as exc:
|
|
23
|
+
try:
|
|
24
|
+
return exc.code, exc.read()
|
|
25
|
+
finally:
|
|
26
|
+
exc.close()
|
|
27
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
28
|
+
raise FuryStreamError("network error: %s" % exc, 0, "network_error") from exc
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def request_json(
|
|
32
|
+
transport: Transport,
|
|
33
|
+
url: str,
|
|
34
|
+
api_key: Optional[str],
|
|
35
|
+
timeout: float,
|
|
36
|
+
) -> Any:
|
|
37
|
+
headers = {
|
|
38
|
+
"Accept": "application/json",
|
|
39
|
+
"User-Agent": "furystream-python/%s" % VERSION,
|
|
40
|
+
}
|
|
41
|
+
if api_key:
|
|
42
|
+
headers["Authorization"] = "Bearer " + api_key
|
|
43
|
+
status, body = transport("GET", url, headers, timeout)
|
|
44
|
+
try:
|
|
45
|
+
payload = json.loads(body.decode("utf-8")) if body else None
|
|
46
|
+
except (ValueError, UnicodeDecodeError):
|
|
47
|
+
payload = None
|
|
48
|
+
if status < 200 or status >= 300:
|
|
49
|
+
message = "request failed"
|
|
50
|
+
code = None
|
|
51
|
+
if isinstance(payload, dict):
|
|
52
|
+
message = str(payload.get("detail") or payload.get("title") or payload.get("message") or message)
|
|
53
|
+
raw_code = payload.get("code") or payload.get("type")
|
|
54
|
+
code = str(raw_code) if raw_code else None
|
|
55
|
+
raise FuryStreamError(message, status, code)
|
|
56
|
+
if payload is None:
|
|
57
|
+
raise FuryStreamError("invalid JSON in response", status, "invalid_response")
|
|
58
|
+
return payload
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from ._constants import VERSION
|
|
8
|
+
from .client import Client
|
|
9
|
+
from .embed import embed_html
|
|
10
|
+
from .errors import FuryStreamError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
14
|
+
p = argparse.ArgumentParser(prog="furystream", description="FuryStream helper")
|
|
15
|
+
p.add_argument("--version", action="version", version=VERSION)
|
|
16
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
17
|
+
e = sub.add_parser("embed", help="print the embed code for a file id (no API key needed)")
|
|
18
|
+
e.add_argument("file_id")
|
|
19
|
+
e.add_argument("--tag", action="store_true", help="print the <fury-player> tag instead of the iframe")
|
|
20
|
+
ls = sub.add_parser("list", help="list your files (needs FURYSTREAM_API_KEY)")
|
|
21
|
+
ls.add_argument("--q")
|
|
22
|
+
ls.add_argument("--status")
|
|
23
|
+
ls.add_argument("--limit", type=int, default=20, help="files per request, 1-100")
|
|
24
|
+
ls.add_argument("--all", action="store_true", help="follow all pages")
|
|
25
|
+
args = p.parse_args(argv)
|
|
26
|
+
try:
|
|
27
|
+
if args.cmd == "embed":
|
|
28
|
+
print(embed_html(args.file_id, "tag" if args.tag else "iframe"))
|
|
29
|
+
else:
|
|
30
|
+
files = Client().files
|
|
31
|
+
limit = min(max(args.limit, 1), 100)
|
|
32
|
+
if args.all:
|
|
33
|
+
items = files.iter(q=args.q, status=args.status, limit=limit)
|
|
34
|
+
else:
|
|
35
|
+
items = iter(files.list(q=args.q, status=args.status, limit=limit).data)
|
|
36
|
+
for f in items:
|
|
37
|
+
print("%s\t%s\t%s" % (f.file_id, f.status, f.title))
|
|
38
|
+
except (FuryStreamError, ValueError) as exc:
|
|
39
|
+
print("error: %s" % exc, file=sys.stderr)
|
|
40
|
+
return 1
|
|
41
|
+
return 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if __name__ == "__main__":
|
|
45
|
+
sys.exit(main())
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, AsyncIterator, Dict, Iterator, Optional
|
|
6
|
+
from urllib.parse import quote, urlencode
|
|
7
|
+
|
|
8
|
+
from ._constants import API_BASE
|
|
9
|
+
from ._transport import Transport, request_json, urllib_transport
|
|
10
|
+
from .embed import _check
|
|
11
|
+
from .errors import FuryStreamError
|
|
12
|
+
from .models import Balance, EmbedCodes, File, FilePage, StatsSummary
|
|
13
|
+
|
|
14
|
+
ENV_KEY = "FURYSTREAM_API_KEY"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _file_params(
|
|
18
|
+
q: Optional[str], status: Optional[str], sort: Optional[str], limit: Optional[int], cursor: Optional[str]
|
|
19
|
+
) -> Dict[str, Any]:
|
|
20
|
+
if limit is not None and not 1 <= int(limit) <= 100:
|
|
21
|
+
raise ValueError("limit must be between 1 and 100")
|
|
22
|
+
return {"q": q, "status": status, "sort": sort, "limit": limit, "cursor": cursor}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Files:
|
|
26
|
+
def __init__(self, client: "Client") -> None:
|
|
27
|
+
self._c = client
|
|
28
|
+
|
|
29
|
+
def list(
|
|
30
|
+
self,
|
|
31
|
+
q: Optional[str] = None,
|
|
32
|
+
status: Optional[str] = None,
|
|
33
|
+
sort: Optional[str] = None,
|
|
34
|
+
limit: Optional[int] = None,
|
|
35
|
+
cursor: Optional[str] = None,
|
|
36
|
+
) -> FilePage:
|
|
37
|
+
data = self._c._get("/files", _file_params(q, status, sort, limit, cursor))
|
|
38
|
+
items = data.get("data", []) if isinstance(data, dict) else []
|
|
39
|
+
nxt = data.get("next_cursor") if isinstance(data, dict) else None
|
|
40
|
+
return FilePage([File.from_dict(i) for i in items], nxt or None)
|
|
41
|
+
|
|
42
|
+
def iter(
|
|
43
|
+
self,
|
|
44
|
+
q: Optional[str] = None,
|
|
45
|
+
status: Optional[str] = None,
|
|
46
|
+
sort: Optional[str] = None,
|
|
47
|
+
limit: Optional[int] = None,
|
|
48
|
+
) -> Iterator[File]:
|
|
49
|
+
cursor: Optional[str] = None
|
|
50
|
+
while True:
|
|
51
|
+
page = self.list(q, status, sort, limit, cursor)
|
|
52
|
+
for item in page.data:
|
|
53
|
+
yield item
|
|
54
|
+
if not page.next_cursor or page.next_cursor == cursor:
|
|
55
|
+
return
|
|
56
|
+
cursor = page.next_cursor
|
|
57
|
+
|
|
58
|
+
def get(self, file_id: str) -> File:
|
|
59
|
+
return File.from_dict(self._c._get("/files/" + quote(_check(file_id), safe="")))
|
|
60
|
+
|
|
61
|
+
def embed(self, file_id: str) -> EmbedCodes:
|
|
62
|
+
return EmbedCodes.from_dict(self._c._get("/files/%s/embed" % quote(_check(file_id), safe="")))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _Stats:
|
|
66
|
+
def __init__(self, client: "Client") -> None:
|
|
67
|
+
self._c = client
|
|
68
|
+
|
|
69
|
+
def summary(self, from_: Optional[str] = None, to: Optional[str] = None) -> StatsSummary:
|
|
70
|
+
return StatsSummary.from_dict(self._c._get("/stats/summary", {"from": from_, "to": to}))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _Earnings:
|
|
74
|
+
def __init__(self, client: "Client") -> None:
|
|
75
|
+
self._c = client
|
|
76
|
+
|
|
77
|
+
def balance(self) -> Balance:
|
|
78
|
+
return Balance.from_dict(self._c._get("/earnings/balance"))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Client:
|
|
82
|
+
"""Synchronous, read-only API client. Embedding does not need it."""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self, api_key: Optional[str] = None, timeout: float = 15.0, transport: Optional[Transport] = None
|
|
86
|
+
) -> None:
|
|
87
|
+
self._key = api_key or os.environ.get(ENV_KEY) or None
|
|
88
|
+
self._timeout = timeout
|
|
89
|
+
self._transport: Transport = transport or urllib_transport
|
|
90
|
+
self.files = _Files(self)
|
|
91
|
+
self.stats = _Stats(self)
|
|
92
|
+
self.earnings = _Earnings(self)
|
|
93
|
+
|
|
94
|
+
def __repr__(self) -> str: # never show the key
|
|
95
|
+
return "<Client key=%s>" % ("set" if self._key else "none")
|
|
96
|
+
|
|
97
|
+
def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
98
|
+
if not self._key:
|
|
99
|
+
raise FuryStreamError("an API key is required (argument or %s)" % ENV_KEY, 0, "missing_api_key")
|
|
100
|
+
query = urlencode({k: v for k, v in (params or {}).items() if v is not None})
|
|
101
|
+
url = API_BASE + path + ("?" + query if query else "")
|
|
102
|
+
return request_json(self._transport, url, self._key, self._timeout)
|
|
103
|
+
|
|
104
|
+
def me(self) -> Dict[str, Any]:
|
|
105
|
+
"""The account behind the key. Needs the account:read scope."""
|
|
106
|
+
data = self._get("/me")
|
|
107
|
+
return data if isinstance(data, dict) else {}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _AFiles:
|
|
111
|
+
def __init__(self, c: Client) -> None:
|
|
112
|
+
self._c = c
|
|
113
|
+
|
|
114
|
+
async def list(
|
|
115
|
+
self,
|
|
116
|
+
q: Optional[str] = None,
|
|
117
|
+
status: Optional[str] = None,
|
|
118
|
+
sort: Optional[str] = None,
|
|
119
|
+
limit: Optional[int] = None,
|
|
120
|
+
cursor: Optional[str] = None,
|
|
121
|
+
) -> FilePage:
|
|
122
|
+
return await asyncio.to_thread(self._c.files.list, q, status, sort, limit, cursor)
|
|
123
|
+
|
|
124
|
+
async def iter(
|
|
125
|
+
self,
|
|
126
|
+
q: Optional[str] = None,
|
|
127
|
+
status: Optional[str] = None,
|
|
128
|
+
sort: Optional[str] = None,
|
|
129
|
+
limit: Optional[int] = None,
|
|
130
|
+
) -> AsyncIterator[File]:
|
|
131
|
+
cursor: Optional[str] = None
|
|
132
|
+
while True:
|
|
133
|
+
page = await self.list(q, status, sort, limit, cursor)
|
|
134
|
+
for item in page.data:
|
|
135
|
+
yield item
|
|
136
|
+
if not page.next_cursor or page.next_cursor == cursor:
|
|
137
|
+
return
|
|
138
|
+
cursor = page.next_cursor
|
|
139
|
+
|
|
140
|
+
async def get(self, file_id: str) -> File:
|
|
141
|
+
return await asyncio.to_thread(self._c.files.get, file_id)
|
|
142
|
+
|
|
143
|
+
async def embed(self, file_id: str) -> EmbedCodes:
|
|
144
|
+
return await asyncio.to_thread(self._c.files.embed, file_id)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _AStats:
|
|
148
|
+
def __init__(self, c: Client) -> None:
|
|
149
|
+
self._c = c
|
|
150
|
+
|
|
151
|
+
async def summary(self, from_: Optional[str] = None, to: Optional[str] = None) -> StatsSummary:
|
|
152
|
+
return await asyncio.to_thread(self._c.stats.summary, from_, to)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class _AEarnings:
|
|
156
|
+
def __init__(self, c: Client) -> None:
|
|
157
|
+
self._c = c
|
|
158
|
+
|
|
159
|
+
async def balance(self) -> Balance:
|
|
160
|
+
return await asyncio.to_thread(self._c.earnings.balance)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class AsyncClient:
|
|
164
|
+
"""Async wrapper: runs the same stdlib transport in a worker thread."""
|
|
165
|
+
|
|
166
|
+
def __init__(
|
|
167
|
+
self, api_key: Optional[str] = None, timeout: float = 15.0, transport: Optional[Transport] = None
|
|
168
|
+
) -> None:
|
|
169
|
+
self._client = Client(api_key, timeout, transport)
|
|
170
|
+
self.files = _AFiles(self._client)
|
|
171
|
+
self.stats = _AStats(self._client)
|
|
172
|
+
self.earnings = _AEarnings(self._client)
|
|
173
|
+
|
|
174
|
+
def __repr__(self) -> str:
|
|
175
|
+
return "<AsyncClient key=%s>" % ("set" if self._client._key else "none")
|
|
176
|
+
|
|
177
|
+
async def me(self) -> Dict[str, Any]:
|
|
178
|
+
return await asyncio.to_thread(self._client.me)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Pure embed builders. They never touch the network."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
from ._constants import EMBED_BASE
|
|
10
|
+
from .errors import InvalidFileIdError
|
|
11
|
+
|
|
12
|
+
_ID_RE = re.compile(r"\A[A-Za-z0-9]{12}\Z")
|
|
13
|
+
|
|
14
|
+
IFRAME_ALLOW = "autoplay; fullscreen; picture-in-picture; encrypted-media"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SafeString(str):
|
|
18
|
+
"""A ``str`` that template engines treat as already escaped HTML.
|
|
19
|
+
|
|
20
|
+
It has an ``__html__`` method, the same protocol used by markupsafe
|
|
21
|
+
(Jinja, Flask) and Django, so no extra package is needed.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
__slots__ = ()
|
|
25
|
+
|
|
26
|
+
def __html__(self) -> "SafeString":
|
|
27
|
+
return self
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_valid_file_id(value: object) -> bool:
|
|
31
|
+
return isinstance(value, str) and _ID_RE.match(value) is not None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check(file_id: object) -> str:
|
|
35
|
+
if not is_valid_file_id(file_id):
|
|
36
|
+
raise InvalidFileIdError("invalid FuryStream file id")
|
|
37
|
+
return str(file_id)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def embed_url(file_id: str) -> str:
|
|
41
|
+
return "%s/embed/player?file=%s" % (EMBED_BASE, quote(_check(file_id), safe=""))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def embed_iframe(file_id: str) -> SafeString:
|
|
45
|
+
src = html.escape(embed_url(file_id), quote=True)
|
|
46
|
+
return SafeString(
|
|
47
|
+
'<iframe src="%s" allow="%s" allowfullscreen loading="lazy" '
|
|
48
|
+
'referrerpolicy="origin" style="border:0;width:100%%;aspect-ratio:16/9"></iframe>'
|
|
49
|
+
% (src, IFRAME_ALLOW)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def embed_tag(file_id: str) -> SafeString:
|
|
54
|
+
fid = html.escape(_check(file_id), quote=True)
|
|
55
|
+
return SafeString(
|
|
56
|
+
'<script src="%s/player/embed.js" async></script><fury-player file="%s"></fury-player>'
|
|
57
|
+
% (EMBED_BASE, fid)
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def embed_html(file_id: str, kind: str = "iframe") -> SafeString:
|
|
62
|
+
"""Return the official embed. ``kind`` is ``"iframe"`` or ``"tag"``."""
|
|
63
|
+
if kind == "iframe":
|
|
64
|
+
return embed_iframe(file_id)
|
|
65
|
+
if kind == "tag":
|
|
66
|
+
return embed_tag(file_id)
|
|
67
|
+
raise ValueError('kind must be "iframe" or "tag"')
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FuryStreamError(Exception):
|
|
7
|
+
"""Raised when the API answers with an error or cannot be reached.
|
|
8
|
+
|
|
9
|
+
``status`` is the HTTP status (0 for network problems), ``code`` a short
|
|
10
|
+
machine readable string.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str, status: int = 0, code: Optional[str] = None) -> None:
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.message = message
|
|
16
|
+
self.status = status
|
|
17
|
+
self.code = code or ("network_error" if status == 0 else "http_%d" % status)
|
|
18
|
+
|
|
19
|
+
def __str__(self) -> str:
|
|
20
|
+
return "%s (status=%d, code=%s)" % (self.message, self.status, self.code)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InvalidFileIdError(ValueError):
|
|
24
|
+
"""Raised when a file id does not look like a FuryStream file id."""
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Manual video lists from a local JSON file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from os import PathLike
|
|
8
|
+
from typing import List, Union
|
|
9
|
+
|
|
10
|
+
from .embed import is_valid_file_id
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class ManualFile:
|
|
15
|
+
id: str
|
|
16
|
+
title: str = ""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def load_files(path: Union[str, "PathLike[str]"]) -> List[ManualFile]:
|
|
20
|
+
"""Read ``[{"id": "...", "title": "..."}]``. Raises ValueError on bad entries."""
|
|
21
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
22
|
+
data = json.load(fh)
|
|
23
|
+
if not isinstance(data, list):
|
|
24
|
+
raise ValueError("files.json must contain a list")
|
|
25
|
+
out: List[ManualFile] = []
|
|
26
|
+
for i, item in enumerate(data):
|
|
27
|
+
if not isinstance(item, dict):
|
|
28
|
+
raise ValueError("entry %d is not an object" % i)
|
|
29
|
+
fid = item.get("id", item.get("file_id"))
|
|
30
|
+
if not isinstance(fid, str) or not is_valid_file_id(fid):
|
|
31
|
+
raise ValueError("entry %d has an invalid file id" % i)
|
|
32
|
+
out.append(ManualFile(id=fid, title=str(item.get("title") or "")))
|
|
33
|
+
return out
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field, fields
|
|
4
|
+
from typing import Any, Dict, List, Optional, Type, TypeVar
|
|
5
|
+
|
|
6
|
+
T = TypeVar("T")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _build(cls: Type[T], data: Any, renames: Optional[Dict[str, str]] = None) -> T:
|
|
10
|
+
"""Create a dataclass from a dict, ignoring unknown keys (kept in ``extra``)."""
|
|
11
|
+
if not isinstance(data, dict):
|
|
12
|
+
data = {}
|
|
13
|
+
renames = renames or {}
|
|
14
|
+
names = {f.name for f in fields(cls) if f.name != "extra"} # type: ignore[arg-type]
|
|
15
|
+
kwargs: Dict[str, Any] = {}
|
|
16
|
+
extra: Dict[str, Any] = {}
|
|
17
|
+
for key, value in data.items():
|
|
18
|
+
name = renames.get(key, key)
|
|
19
|
+
if name in names:
|
|
20
|
+
kwargs[name] = value
|
|
21
|
+
else:
|
|
22
|
+
extra[key] = value
|
|
23
|
+
return cls(extra=extra, **kwargs) # type: ignore[call-arg]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class File:
|
|
28
|
+
file_id: str = ""
|
|
29
|
+
title: str = ""
|
|
30
|
+
description: Optional[str] = None # only in files.get
|
|
31
|
+
status: str = "" # pending, downloading, uploading, processing, ready, transcoding, failed, blocked, takedown
|
|
32
|
+
playable: bool = False # only in files.get
|
|
33
|
+
duration_ms: Optional[int] = None
|
|
34
|
+
width: Optional[int] = None
|
|
35
|
+
height: Optional[int] = None
|
|
36
|
+
thumbnail_url: Optional[str] = None
|
|
37
|
+
views_total: int = 0
|
|
38
|
+
embed_url: Optional[str] = None
|
|
39
|
+
created_at: Optional[str] = None
|
|
40
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def from_dict(cls, data: Any) -> "File":
|
|
44
|
+
return _build(cls, data)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class FilePage:
|
|
49
|
+
data: List[File] = field(default_factory=list)
|
|
50
|
+
next_cursor: Optional[str] = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class EmbedCodes:
|
|
55
|
+
file_id: str = ""
|
|
56
|
+
embed_url: str = ""
|
|
57
|
+
iframe_html: str = ""
|
|
58
|
+
player_tag_html: str = ""
|
|
59
|
+
thumbnail_url: Optional[str] = None
|
|
60
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_dict(cls, data: Any) -> "EmbedCodes":
|
|
64
|
+
return _build(cls, data)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class StatsSummary:
|
|
69
|
+
from_: Optional[str] = None
|
|
70
|
+
to: Optional[str] = None
|
|
71
|
+
totals: Dict[str, Any] = field(default_factory=dict)
|
|
72
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def views(self) -> int:
|
|
76
|
+
value = self.totals.get("views", 0) if isinstance(self.totals, dict) else 0
|
|
77
|
+
return value if isinstance(value, int) else 0
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_dict(cls, data: Any) -> "StatsSummary":
|
|
81
|
+
return _build(cls, data, {"from": "from_"})
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class Balance:
|
|
86
|
+
"""Answer of ``GET /earnings/balance``. Amounts are micro units: 1_000_000 = 1.00 of ``currency``."""
|
|
87
|
+
|
|
88
|
+
currency: Optional[str] = None
|
|
89
|
+
pending_micro: int = 0
|
|
90
|
+
available_micro: int = 0
|
|
91
|
+
on_hold_micro: int = 0
|
|
92
|
+
paid_total_micro: int = 0
|
|
93
|
+
requestable_micro: int = 0
|
|
94
|
+
today_estimate_micro: int = 0
|
|
95
|
+
next_release_at: Optional[str] = None
|
|
96
|
+
hold_days: int = 0
|
|
97
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
98
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def available(self) -> float:
|
|
102
|
+
"""Available amount in whole currency units."""
|
|
103
|
+
return self.available_micro / 1_000_000
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def from_dict(cls, data: Any) -> "Balance":
|
|
107
|
+
obj = _build(cls, data)
|
|
108
|
+
obj.raw = dict(data) if isinstance(data, dict) else {}
|
|
109
|
+
return obj
|
|
File without changes
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import unittest
|
|
5
|
+
from unittest import mock
|
|
6
|
+
from urllib.parse import parse_qs, urlparse
|
|
7
|
+
|
|
8
|
+
from furystream import AsyncClient, Client, FuryStreamError
|
|
9
|
+
from furystream.cli import main
|
|
10
|
+
|
|
11
|
+
FID = "abcDEF123456"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FakeTransport:
|
|
15
|
+
def __init__(self, responses):
|
|
16
|
+
self.responses = list(responses)
|
|
17
|
+
self.calls = []
|
|
18
|
+
|
|
19
|
+
def __call__(self, method, url, headers, timeout):
|
|
20
|
+
self.calls.append((method, url, headers))
|
|
21
|
+
status, body = self.responses.pop(0)
|
|
22
|
+
return status, json.dumps(body).encode()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def file_json(fid=FID, **kw):
|
|
26
|
+
d = {"file_id": fid, "title": "T", "status": "ready", "playable": True, "views_total": 5, "new_field": 1}
|
|
27
|
+
d.update(kw)
|
|
28
|
+
return d
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ClientTests(unittest.TestCase):
|
|
32
|
+
def test_list_and_auth_header(self):
|
|
33
|
+
t = FakeTransport([(200, {"data": [file_json()], "next_cursor": None})])
|
|
34
|
+
page = Client("fsk_x", transport=t).files.list(q="a b", limit=5)
|
|
35
|
+
self.assertEqual(page.data[0].file_id, FID)
|
|
36
|
+
self.assertEqual(page.data[0].extra, {"new_field": 1})
|
|
37
|
+
_, url, headers = t.calls[0]
|
|
38
|
+
self.assertEqual(headers["Authorization"], "Bearer fsk_x")
|
|
39
|
+
self.assertTrue(url.startswith("https://api.furystream.com/api/v1/files?"))
|
|
40
|
+
self.assertEqual(parse_qs(urlparse(url).query), {"q": ["a b"], "limit": ["5"]})
|
|
41
|
+
|
|
42
|
+
def test_iter_follows_cursor(self):
|
|
43
|
+
t = FakeTransport([
|
|
44
|
+
(200, {"data": [file_json("aaaaaa1")], "next_cursor": "c2"}),
|
|
45
|
+
(200, {"data": [file_json("bbbbbb2")], "next_cursor": None}),
|
|
46
|
+
])
|
|
47
|
+
ids = [f.file_id for f in Client("k", transport=t).files.iter()]
|
|
48
|
+
self.assertEqual(ids, ["aaaaaa1", "bbbbbb2"])
|
|
49
|
+
self.assertIn("cursor=c2", t.calls[1][1])
|
|
50
|
+
|
|
51
|
+
def test_get_embed_stats_balance_me(self):
|
|
52
|
+
t = FakeTransport([
|
|
53
|
+
(200, file_json()),
|
|
54
|
+
(200, {"file_id": FID, "embed_url": "u", "iframe_html": "i", "player_tag_html": "p", "thumbnail_url": None}),
|
|
55
|
+
(200, {"from": "2025-01-01", "to": "2025-01-31", "totals": {"views": 42}}),
|
|
56
|
+
(200, {"currency": "USD", "available_micro": 1500000, "x": 1}),
|
|
57
|
+
(200, {"id": 1}),
|
|
58
|
+
])
|
|
59
|
+
c = Client("k", transport=t)
|
|
60
|
+
self.assertEqual(c.files.get(FID).title, "T")
|
|
61
|
+
self.assertEqual(c.files.embed(FID).iframe_html, "i")
|
|
62
|
+
s = c.stats.summary("2025-01-01", "2025-01-31")
|
|
63
|
+
self.assertEqual((s.from_, s.views), ("2025-01-01", 42))
|
|
64
|
+
self.assertIn("from=2025-01-01", t.calls[2][1])
|
|
65
|
+
b = c.earnings.balance()
|
|
66
|
+
self.assertEqual((b.currency, b.available_micro, b.available), ("USD", 1500000, 1.5))
|
|
67
|
+
self.assertEqual(c.me(), {"id": 1})
|
|
68
|
+
|
|
69
|
+
def test_error_problem_document(self):
|
|
70
|
+
t = FakeTransport([(403, {"title": "Forbidden", "detail": "scope missing", "code": "insufficient_scope"})])
|
|
71
|
+
with self.assertRaises(FuryStreamError) as cm:
|
|
72
|
+
Client("k", transport=t).me()
|
|
73
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (403, "insufficient_scope"))
|
|
74
|
+
|
|
75
|
+
def test_network_error(self):
|
|
76
|
+
def boom(*a):
|
|
77
|
+
raise FuryStreamError("down", 0)
|
|
78
|
+
|
|
79
|
+
with self.assertRaises(FuryStreamError) as cm:
|
|
80
|
+
Client("k", transport=boom).me()
|
|
81
|
+
self.assertEqual(cm.exception.status, 0)
|
|
82
|
+
|
|
83
|
+
def test_missing_key_and_env(self):
|
|
84
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
85
|
+
with self.assertRaises(FuryStreamError) as cm:
|
|
86
|
+
Client(transport=FakeTransport([])).me()
|
|
87
|
+
self.assertEqual(cm.exception.code, "missing_api_key")
|
|
88
|
+
with mock.patch.dict(os.environ, {"FURYSTREAM_API_KEY": "fsk_env"}):
|
|
89
|
+
t = FakeTransport([(200, {})])
|
|
90
|
+
Client(transport=t).me()
|
|
91
|
+
self.assertEqual(t.calls[0][2]["Authorization"], "Bearer fsk_env")
|
|
92
|
+
|
|
93
|
+
def test_bad_input_never_calls_api(self):
|
|
94
|
+
t = FakeTransport([])
|
|
95
|
+
c = Client("k", transport=t)
|
|
96
|
+
with self.assertRaises(ValueError):
|
|
97
|
+
c.files.get("../etc")
|
|
98
|
+
with self.assertRaises(ValueError):
|
|
99
|
+
c.files.list(limit=500)
|
|
100
|
+
self.assertEqual(t.calls, [])
|
|
101
|
+
|
|
102
|
+
def test_repr_hides_key(self):
|
|
103
|
+
self.assertNotIn("fsk_secret", repr(Client("fsk_secret")))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class AsyncTests(unittest.TestCase):
|
|
107
|
+
def test_async(self):
|
|
108
|
+
async def run():
|
|
109
|
+
t = FakeTransport([
|
|
110
|
+
(200, {"data": [file_json("aaaaaa1")], "next_cursor": "n"}),
|
|
111
|
+
(200, {"data": [file_json("bbbbbb2")]}),
|
|
112
|
+
(200, file_json()),
|
|
113
|
+
])
|
|
114
|
+
c = AsyncClient("k", transport=t)
|
|
115
|
+
ids = [f.file_id async for f in c.files.iter()]
|
|
116
|
+
one = await c.files.get(FID)
|
|
117
|
+
return ids, one.file_id
|
|
118
|
+
|
|
119
|
+
self.assertEqual(asyncio.run(run()), (["aaaaaa1", "bbbbbb2"], FID))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class CliTests(unittest.TestCase):
|
|
123
|
+
def test_embed(self):
|
|
124
|
+
with mock.patch("builtins.print") as p:
|
|
125
|
+
self.assertEqual(main(["embed", FID]), 0)
|
|
126
|
+
self.assertIn("<iframe", p.call_args[0][0])
|
|
127
|
+
|
|
128
|
+
def test_embed_bad_id(self):
|
|
129
|
+
self.assertEqual(main(["embed", "bad id"]), 1)
|
|
130
|
+
|
|
131
|
+
def test_list_without_key(self):
|
|
132
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
133
|
+
self.assertEqual(main(["list"]), 1)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
unittest.main()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
from furystream import (
|
|
7
|
+
InvalidFileIdError, SafeString, embed_html, embed_iframe, embed_tag, is_valid_file_id, load_files,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EmbedTests(unittest.TestCase):
|
|
12
|
+
def test_valid_ids(self):
|
|
13
|
+
self.assertTrue(is_valid_file_id("abcDEF123456"))
|
|
14
|
+
self.assertTrue(is_valid_file_id("a" * 12))
|
|
15
|
+
|
|
16
|
+
def test_invalid_ids(self):
|
|
17
|
+
for bad in ["", "short", "abcdef12345", "abcdef1234567", "a" * 33, 'abc"def123', "abc def123", "abc-def123", "abcdef123456\n", None, 123]:
|
|
18
|
+
self.assertFalse(is_valid_file_id(bad), repr(bad))
|
|
19
|
+
|
|
20
|
+
def test_iframe(self):
|
|
21
|
+
self.assertEqual(
|
|
22
|
+
str(embed_iframe("abcDEF123456")),
|
|
23
|
+
'<iframe src="https://furystream.com/embed/player?file=abcDEF123456" '
|
|
24
|
+
'allow="autoplay; fullscreen; picture-in-picture; encrypted-media" allowfullscreen '
|
|
25
|
+
'loading="lazy" referrerpolicy="origin" '
|
|
26
|
+
'style="border:0;width:100%;aspect-ratio:16/9"></iframe>',
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def test_tag(self):
|
|
30
|
+
self.assertEqual(
|
|
31
|
+
str(embed_tag("abcDEF123456")),
|
|
32
|
+
'<script src="https://furystream.com/player/embed.js" async></script>'
|
|
33
|
+
'<fury-player file="abcDEF123456"></fury-player>',
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def test_rejects_injection(self):
|
|
37
|
+
for fn in (embed_iframe, embed_tag):
|
|
38
|
+
with self.assertRaises(InvalidFileIdError):
|
|
39
|
+
fn('abcdef"><script>alert(1)</script>')
|
|
40
|
+
|
|
41
|
+
def test_safe_string(self):
|
|
42
|
+
out = embed_html("abcDEF123456")
|
|
43
|
+
self.assertIsInstance(out, SafeString)
|
|
44
|
+
self.assertIs(out.__html__(), out)
|
|
45
|
+
|
|
46
|
+
def test_kind(self):
|
|
47
|
+
self.assertIn("fury-player", embed_html("abcDEF123456", "tag"))
|
|
48
|
+
with self.assertRaises(ValueError):
|
|
49
|
+
embed_html("abcDEF123456", "nope")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class LoadFilesTests(unittest.TestCase):
|
|
53
|
+
def _write(self, data):
|
|
54
|
+
fd, path = tempfile.mkstemp(suffix=".json")
|
|
55
|
+
with os.fdopen(fd, "w") as fh:
|
|
56
|
+
json.dump(data, fh)
|
|
57
|
+
self.addCleanup(os.remove, path)
|
|
58
|
+
return path
|
|
59
|
+
|
|
60
|
+
def test_ok(self):
|
|
61
|
+
files = load_files(self._write([{"id": "abcDEF123456", "title": "Hi"}]))
|
|
62
|
+
self.assertEqual((files[0].id, files[0].title), ("abcDEF123456", "Hi"))
|
|
63
|
+
|
|
64
|
+
def test_bad_id(self):
|
|
65
|
+
with self.assertRaises(ValueError):
|
|
66
|
+
load_files(self._write([{"id": "bad id", "title": "x"}]))
|
|
67
|
+
|
|
68
|
+
def test_not_list(self):
|
|
69
|
+
with self.assertRaises(ValueError):
|
|
70
|
+
load_files(self._write({"id": "abcDEF123456"}))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
unittest.main()
|