chainlit 1.1.300rc1__py3-none-any.whl → 1.1.300rc2__py3-none-any.whl
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.
Potentially problematic release.
This version of chainlit might be problematic. Click here for more details.
- chainlit/copilot/dist/index.js +75 -75
- chainlit/data/dynamodb.py +586 -0
- chainlit/frontend/dist/assets/{DailyMotion-acaf0251.js → DailyMotion-875f8ae4.js} +1 -1
- chainlit/frontend/dist/assets/{Facebook-7e85d6cd.js → Facebook-5a236c6a.js} +1 -1
- chainlit/frontend/dist/assets/{FilePlayer-548ab948.js → FilePlayer-139fc89f.js} +1 -1
- chainlit/frontend/dist/assets/{Kaltura-63c33135.js → Kaltura-091e82f4.js} +1 -1
- chainlit/frontend/dist/assets/{Mixcloud-553956db.js → Mixcloud-2a11761c.js} +1 -1
- chainlit/frontend/dist/assets/{Mux-823ded93.js → Mux-e9439155.js} +1 -1
- chainlit/frontend/dist/assets/{Preview-47f5b210.js → Preview-4a1f503b.js} +1 -1
- chainlit/frontend/dist/assets/{SoundCloud-e5e98e65.js → SoundCloud-56125978.js} +1 -1
- chainlit/frontend/dist/assets/{Streamable-14812f3b.js → Streamable-9aff4ba5.js} +1 -1
- chainlit/frontend/dist/assets/{Twitch-3e4a9570.js → Twitch-ea748d1d.js} +1 -1
- chainlit/frontend/dist/assets/{Vidyard-63580b33.js → Vidyard-8106a931.js} +1 -1
- chainlit/frontend/dist/assets/{Vimeo-1c2b5c4c.js → Vimeo-1f0b6b55.js} +1 -1
- chainlit/frontend/dist/assets/{Wistia-3dc1d7c3.js → Wistia-c18b0bba.js} +1 -1
- chainlit/frontend/dist/assets/{YouTube-d92466dc.js → YouTube-9114d4e0.js} +1 -1
- chainlit/frontend/dist/assets/{index-53c62926.css → index-67745611.css} +1 -1
- chainlit/frontend/dist/assets/{index-89bf1895.js → index-b8523620.js} +7 -7
- chainlit/frontend/dist/assets/{react-plotly-691f8eab.js → react-plotly-68456fe1.js} +1 -1
- chainlit/frontend/dist/index.html +2 -2
- chainlit/oauth_providers.py +56 -0
- chainlit/socket.py +4 -1
- {chainlit-1.1.300rc1.dist-info → chainlit-1.1.300rc2.dist-info}/METADATA +1 -1
- {chainlit-1.1.300rc1.dist-info → chainlit-1.1.300rc2.dist-info}/RECORD +26 -25
- {chainlit-1.1.300rc1.dist-info → chainlit-1.1.300rc2.dist-info}/WHEEL +0 -0
- {chainlit-1.1.300rc1.dist-info → chainlit-1.1.300rc2.dist-info}/entry_points.txt +0 -0
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import random
|
|
6
|
+
from dataclasses import asdict
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
|
9
|
+
|
|
10
|
+
import aiofiles
|
|
11
|
+
import aiohttp
|
|
12
|
+
import boto3 # type: ignore
|
|
13
|
+
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer
|
|
14
|
+
from chainlit.context import context
|
|
15
|
+
from chainlit.data import BaseDataLayer, BaseStorageClient, queue_until_user_message
|
|
16
|
+
from chainlit.element import ElementDict
|
|
17
|
+
from chainlit.logger import logger
|
|
18
|
+
from chainlit.step import StepDict
|
|
19
|
+
from chainlit.types import (
|
|
20
|
+
Feedback,
|
|
21
|
+
PageInfo,
|
|
22
|
+
PaginatedResponse,
|
|
23
|
+
Pagination,
|
|
24
|
+
ThreadDict,
|
|
25
|
+
ThreadFilter,
|
|
26
|
+
)
|
|
27
|
+
from chainlit.user import PersistedUser, User
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from chainlit.element import Element
|
|
31
|
+
from mypy_boto3_dynamodb import DynamoDBClient
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_logger = logger.getChild("DynamoDB")
|
|
35
|
+
_logger.setLevel(logging.WARNING)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DynamoDBDataLayer(BaseDataLayer):
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
table_name: str,
|
|
43
|
+
client: Optional["DynamoDBClient"] = None,
|
|
44
|
+
storage_provider: Optional[BaseStorageClient] = None,
|
|
45
|
+
user_thread_limit: int = 10,
|
|
46
|
+
):
|
|
47
|
+
if client:
|
|
48
|
+
self.client = client
|
|
49
|
+
else:
|
|
50
|
+
region_name = os.environ.get("AWS_REGION", "us-east-1")
|
|
51
|
+
self.client = boto3.client("dynamodb", region_name=region_name) # type: ignore
|
|
52
|
+
|
|
53
|
+
self.table_name = table_name
|
|
54
|
+
self.storage_provider = storage_provider
|
|
55
|
+
self.user_thread_limit = user_thread_limit
|
|
56
|
+
|
|
57
|
+
self._type_deserializer = TypeDeserializer()
|
|
58
|
+
self._type_serializer = TypeSerializer()
|
|
59
|
+
|
|
60
|
+
def _get_current_timestamp(self) -> str:
|
|
61
|
+
return datetime.now().isoformat() + "Z"
|
|
62
|
+
|
|
63
|
+
def _serialize_item(self, item: Dict[str, Any]) -> Dict[str, Any]:
|
|
64
|
+
return {
|
|
65
|
+
key: self._type_serializer.serialize(value) for key, value in item.items()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def _deserialize_item(self, item: Dict[str, Any]) -> Dict[str, Any]:
|
|
69
|
+
return {
|
|
70
|
+
key: self._type_deserializer.deserialize(value)
|
|
71
|
+
for key, value in item.items()
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def _update_item(self, key: Dict[str, Any], updates: Dict[str, Any]):
|
|
75
|
+
update_expr: List[str] = []
|
|
76
|
+
expression_attribute_names = {}
|
|
77
|
+
expression_attribute_values = {}
|
|
78
|
+
|
|
79
|
+
for index, (attr, value) in enumerate(updates.items()):
|
|
80
|
+
if not value:
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
k, v = f"#{index}", f":{index}"
|
|
84
|
+
update_expr.append(f"{k} = {v}")
|
|
85
|
+
expression_attribute_names[k] = attr
|
|
86
|
+
expression_attribute_values[v] = value
|
|
87
|
+
|
|
88
|
+
self.client.update_item(
|
|
89
|
+
TableName=self.table_name,
|
|
90
|
+
Key=self._serialize_item(key),
|
|
91
|
+
UpdateExpression="SET " + ", ".join(update_expr),
|
|
92
|
+
ExpressionAttributeNames=expression_attribute_names,
|
|
93
|
+
ExpressionAttributeValues=self._serialize_item(expression_attribute_values),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
async def get_user(self, identifier: str) -> Optional["PersistedUser"]:
|
|
97
|
+
_logger.info("DynamoDB: get_user identifier=%s", identifier)
|
|
98
|
+
|
|
99
|
+
response = self.client.get_item(
|
|
100
|
+
TableName=self.table_name,
|
|
101
|
+
Key={
|
|
102
|
+
"PK": {"S": f"USER#{identifier}"},
|
|
103
|
+
"SK": {"S": "USER"},
|
|
104
|
+
},
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if "Item" not in response:
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
user = self._deserialize_item(response["Item"])
|
|
111
|
+
|
|
112
|
+
return PersistedUser(
|
|
113
|
+
id=user["id"],
|
|
114
|
+
identifier=user["identifier"],
|
|
115
|
+
createdAt=user["createdAt"],
|
|
116
|
+
metadata=user["metadata"],
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
async def create_user(self, user: "User") -> Optional["PersistedUser"]:
|
|
120
|
+
_logger.info("DynamoDB: create_user user.identifier=%s", user.identifier)
|
|
121
|
+
|
|
122
|
+
ts = self._get_current_timestamp()
|
|
123
|
+
metadata: Dict[Any, Any] = user.metadata # type: ignore
|
|
124
|
+
|
|
125
|
+
item = {
|
|
126
|
+
"PK": f"USER#{user.identifier}",
|
|
127
|
+
"SK": "USER",
|
|
128
|
+
"id": user.identifier,
|
|
129
|
+
"identifier": user.identifier,
|
|
130
|
+
"metadata": metadata,
|
|
131
|
+
"createdAt": ts,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
self.client.put_item(
|
|
135
|
+
TableName=self.table_name,
|
|
136
|
+
Item=self._serialize_item(item),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
return PersistedUser(
|
|
140
|
+
id=user.identifier,
|
|
141
|
+
identifier=user.identifier,
|
|
142
|
+
createdAt=ts,
|
|
143
|
+
metadata=metadata,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
async def delete_feedback(self, feedback_id: str) -> bool:
|
|
147
|
+
_logger.info("DynamoDB: delete_feedback feedback_id=%s", feedback_id)
|
|
148
|
+
|
|
149
|
+
# feedback id = THREAD#{thread_id}::STEP#{step_id}
|
|
150
|
+
thread_id, step_id = feedback_id.split("::")
|
|
151
|
+
thread_id = thread_id.strip("THREAD#")
|
|
152
|
+
step_id = step_id.strip("STEP#")
|
|
153
|
+
|
|
154
|
+
self.client.update_item(
|
|
155
|
+
TableName=self.table_name,
|
|
156
|
+
Key={
|
|
157
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
158
|
+
"SK": {"S": f"STEP#{step_id}"},
|
|
159
|
+
},
|
|
160
|
+
UpdateExpression="REMOVE #feedback",
|
|
161
|
+
ExpressionAttributeNames={"#feedback": "feedback"},
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
async def upsert_feedback(self, feedback: Feedback) -> str:
|
|
167
|
+
_logger.info(
|
|
168
|
+
"DynamoDB: upsert_feedback thread=%s step=%s value=%s",
|
|
169
|
+
feedback.threadId,
|
|
170
|
+
feedback.forId,
|
|
171
|
+
feedback.value,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
if not feedback.forId:
|
|
175
|
+
raise ValueError(
|
|
176
|
+
"DynamoDB datalayer expects value for feedback.threadId got None"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
feedback.id = f"THREAD#{feedback.threadId}::STEP#{feedback.forId}"
|
|
180
|
+
searialized_feedback = self._type_serializer.serialize(asdict(feedback))
|
|
181
|
+
|
|
182
|
+
self.client.update_item(
|
|
183
|
+
TableName=self.table_name,
|
|
184
|
+
Key={
|
|
185
|
+
"PK": {"S": f"THREAD#{feedback.threadId}"},
|
|
186
|
+
"SK": {"S": f"STEP#{feedback.forId}"},
|
|
187
|
+
},
|
|
188
|
+
UpdateExpression="SET #feedback = :feedback",
|
|
189
|
+
ExpressionAttributeNames={"#feedback": "feedback"},
|
|
190
|
+
ExpressionAttributeValues={":feedback": searialized_feedback},
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
return feedback.id
|
|
194
|
+
|
|
195
|
+
@queue_until_user_message()
|
|
196
|
+
async def create_element(self, element: "Element"):
|
|
197
|
+
_logger.info(
|
|
198
|
+
"DynamoDB: create_element thread=%s step=%s type=%s",
|
|
199
|
+
element.thread_id,
|
|
200
|
+
element.for_id,
|
|
201
|
+
element.type,
|
|
202
|
+
)
|
|
203
|
+
_logger.debug("DynamoDB: create_element: %s", element.to_dict())
|
|
204
|
+
|
|
205
|
+
if not element.for_id:
|
|
206
|
+
return
|
|
207
|
+
|
|
208
|
+
if not self.storage_provider:
|
|
209
|
+
_logger.warning(
|
|
210
|
+
"DynamoDB: create_element error. No storage_provider is configured!"
|
|
211
|
+
)
|
|
212
|
+
return
|
|
213
|
+
|
|
214
|
+
content: Optional[Union[bytes, str]] = None
|
|
215
|
+
|
|
216
|
+
if element.content:
|
|
217
|
+
content = element.content
|
|
218
|
+
|
|
219
|
+
elif element.path:
|
|
220
|
+
_logger.debug("DynamoDB: create_element reading file %s", element.path)
|
|
221
|
+
async with aiofiles.open(element.path, "rb") as f:
|
|
222
|
+
content = await f.read()
|
|
223
|
+
|
|
224
|
+
elif element.url:
|
|
225
|
+
_logger.debug("DynamoDB: create_element http %s", element.url)
|
|
226
|
+
async with aiohttp.ClientSession() as session:
|
|
227
|
+
async with session.get(element.url) as response:
|
|
228
|
+
if response.status == 200:
|
|
229
|
+
content = await response.read()
|
|
230
|
+
else:
|
|
231
|
+
raise ValueError(
|
|
232
|
+
f"Failed to read content from {element.url} status {response.status}",
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
else:
|
|
236
|
+
raise ValueError("Element url, path or content must be provided")
|
|
237
|
+
|
|
238
|
+
if content is None:
|
|
239
|
+
raise ValueError("Content is None, cannot upload file")
|
|
240
|
+
|
|
241
|
+
if not element.mime:
|
|
242
|
+
element.mime = "application/octet-stream"
|
|
243
|
+
|
|
244
|
+
context_user = context.session.user
|
|
245
|
+
user_folder = getattr(context_user, "id", "unknown")
|
|
246
|
+
file_object_key = f"{user_folder}/{element.thread_id}/{element.id}"
|
|
247
|
+
|
|
248
|
+
uploaded_file = await self.storage_provider.upload_file(
|
|
249
|
+
object_key=file_object_key,
|
|
250
|
+
data=content,
|
|
251
|
+
mime=element.mime,
|
|
252
|
+
overwrite=True,
|
|
253
|
+
)
|
|
254
|
+
if not uploaded_file:
|
|
255
|
+
raise ValueError(
|
|
256
|
+
"DynamoDB Error: create_element, Failed to persist data in storage_provider",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
element_dict: Dict[str, Any] = element.to_dict() # type: ignore
|
|
260
|
+
element_dict.update(
|
|
261
|
+
{
|
|
262
|
+
"PK": f"THREAD#{element.thread_id}",
|
|
263
|
+
"SK": f"ELEMENT#{element.id}",
|
|
264
|
+
"url": uploaded_file.get("url"),
|
|
265
|
+
"objectKey": uploaded_file.get("object_key"),
|
|
266
|
+
}
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
self.client.put_item(
|
|
270
|
+
TableName=self.table_name,
|
|
271
|
+
Item=self._serialize_item(element_dict),
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
async def get_element(
|
|
275
|
+
self, thread_id: str, element_id: str
|
|
276
|
+
) -> Optional["ElementDict"]:
|
|
277
|
+
_logger.info(
|
|
278
|
+
"DynamoDB: get_element thread=%s element=%s", thread_id, element_id
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
response = self.client.get_item(
|
|
282
|
+
TableName=self.table_name,
|
|
283
|
+
Key={
|
|
284
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
285
|
+
"SK": {"S": f"ELEMENT#{element_id}"},
|
|
286
|
+
},
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
if "Item" not in response:
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
return self._deserialize_item(response["Item"]) # type: ignore
|
|
293
|
+
|
|
294
|
+
@queue_until_user_message()
|
|
295
|
+
async def delete_element(self, element_id: str, thread_id: Optional[str] = None):
|
|
296
|
+
thread_id = context.session.thread_id
|
|
297
|
+
_logger.info(
|
|
298
|
+
"DynamoDB: delete_element thread=%s element=%s", thread_id, element_id
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
self.client.delete_item(
|
|
302
|
+
TableName=self.table_name,
|
|
303
|
+
Key={
|
|
304
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
305
|
+
"SK": {"S": f"ELEMENT#{element_id}"},
|
|
306
|
+
},
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
@queue_until_user_message()
|
|
310
|
+
async def create_step(self, step_dict: "StepDict"):
|
|
311
|
+
_logger.info(
|
|
312
|
+
"DynamoDB: create_step thread=%s step=%s",
|
|
313
|
+
step_dict.get("threadId"),
|
|
314
|
+
step_dict.get("id"),
|
|
315
|
+
)
|
|
316
|
+
_logger.debug("DynamoDB: create_step: %s", step_dict)
|
|
317
|
+
|
|
318
|
+
item = dict(step_dict)
|
|
319
|
+
item.update(
|
|
320
|
+
{
|
|
321
|
+
# ignore type, dynamo needs these so we want to fail if not set
|
|
322
|
+
"PK": f"THREAD#{step_dict['threadId']}", # type: ignore
|
|
323
|
+
"SK": f"STEP#{step_dict['id']}", # type: ignore
|
|
324
|
+
}
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
self.client.put_item(
|
|
328
|
+
TableName=self.table_name,
|
|
329
|
+
Item=self._serialize_item(item),
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
@queue_until_user_message()
|
|
333
|
+
async def update_step(self, step_dict: "StepDict"):
|
|
334
|
+
_logger.info(
|
|
335
|
+
"DynamoDB: update_step thread=%s step=%s",
|
|
336
|
+
step_dict.get("threadId"),
|
|
337
|
+
step_dict.get("id"),
|
|
338
|
+
)
|
|
339
|
+
_logger.debug("DynamoDB: update_step: %s", step_dict)
|
|
340
|
+
|
|
341
|
+
self._update_item(
|
|
342
|
+
key={
|
|
343
|
+
# ignore type, dynamo needs these so we want to fail if not set
|
|
344
|
+
"PK": f"THREAD#{step_dict['threadId']}", # type: ignore
|
|
345
|
+
"SK": f"STEP#{step_dict['id']}", # type: ignore
|
|
346
|
+
},
|
|
347
|
+
updates=step_dict, # type: ignore
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
@queue_until_user_message()
|
|
351
|
+
async def delete_step(self, step_id: str):
|
|
352
|
+
thread_id = context.session.thread_id
|
|
353
|
+
_logger.info("DynamoDB: delete_feedback thread=%s step=%s", thread_id, step_id)
|
|
354
|
+
|
|
355
|
+
self.client.delete_item(
|
|
356
|
+
TableName=self.table_name,
|
|
357
|
+
Key={
|
|
358
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
359
|
+
"SK": {"S": f"STEP#{step_id}"},
|
|
360
|
+
},
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
async def get_thread_author(self, thread_id: str) -> str:
|
|
364
|
+
_logger.info("DynamoDB: get_thread_author thread=%s", thread_id)
|
|
365
|
+
|
|
366
|
+
response = self.client.get_item(
|
|
367
|
+
TableName=self.table_name,
|
|
368
|
+
Key={
|
|
369
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
370
|
+
"SK": {"S": "THREAD"},
|
|
371
|
+
},
|
|
372
|
+
ProjectionExpression="userId",
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
if "Item" not in response:
|
|
376
|
+
raise ValueError(f"Author not found for thread_id {thread_id}")
|
|
377
|
+
|
|
378
|
+
item = self._deserialize_item(response["Item"])
|
|
379
|
+
return item["userId"]
|
|
380
|
+
|
|
381
|
+
async def delete_thread(self, thread_id: str):
|
|
382
|
+
_logger.info("DynamoDB: delete_thread thread=%s", thread_id)
|
|
383
|
+
|
|
384
|
+
thread = await self.get_thread(thread_id)
|
|
385
|
+
if not thread:
|
|
386
|
+
return
|
|
387
|
+
|
|
388
|
+
items: List[Any] = thread["steps"]
|
|
389
|
+
if thread["elements"]:
|
|
390
|
+
items.extend(thread["elements"])
|
|
391
|
+
|
|
392
|
+
delete_requests = []
|
|
393
|
+
for item in items:
|
|
394
|
+
key = self._serialize_item({"PK": item["PK"], "SK": item["SK"]})
|
|
395
|
+
req = {"DeleteRequest": {"Key": key}}
|
|
396
|
+
delete_requests.append(req)
|
|
397
|
+
|
|
398
|
+
BATCH_ITEM_SIZE = 25 # pylint: disable=invalid-name
|
|
399
|
+
for i in range(0, len(delete_requests), BATCH_ITEM_SIZE):
|
|
400
|
+
chunk = delete_requests[i : i + BATCH_ITEM_SIZE] # noqa: E203
|
|
401
|
+
response = self.client.batch_write_item(
|
|
402
|
+
RequestItems={
|
|
403
|
+
self.table_name: chunk, # type: ignore
|
|
404
|
+
}
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
backoff_time = 1
|
|
408
|
+
while "UnprocessedItems" in response and response["UnprocessedItems"]:
|
|
409
|
+
backoff_time *= 2
|
|
410
|
+
# Cap the backoff time at 32 seconds & add jitter
|
|
411
|
+
delay = min(backoff_time, 32) + random.uniform(0, 1)
|
|
412
|
+
await asyncio.sleep(delay)
|
|
413
|
+
|
|
414
|
+
response = self.client.batch_write_item(
|
|
415
|
+
RequestItems=response["UnprocessedItems"]
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
self.client.delete_item(
|
|
419
|
+
TableName=self.table_name,
|
|
420
|
+
Key={
|
|
421
|
+
"PK": {"S": f"THREAD#{thread_id}"},
|
|
422
|
+
"SK": {"S": "THREAD"},
|
|
423
|
+
},
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
async def list_threads(
|
|
427
|
+
self, pagination: "Pagination", filters: "ThreadFilter"
|
|
428
|
+
) -> "PaginatedResponse[ThreadDict]":
|
|
429
|
+
_logger.info("DynamoDB: list_threads filters.userId=%s", filters.userId)
|
|
430
|
+
|
|
431
|
+
if filters.feedback:
|
|
432
|
+
_logger.warning("DynamoDB: filters on feedback not supported")
|
|
433
|
+
|
|
434
|
+
paginated_response: PaginatedResponse[ThreadDict] = PaginatedResponse(
|
|
435
|
+
data=[],
|
|
436
|
+
pageInfo=PageInfo(
|
|
437
|
+
hasNextPage=False, startCursor=pagination.cursor, endCursor=None
|
|
438
|
+
),
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
query_args: Dict[str, Any] = {
|
|
442
|
+
"TableName": self.table_name,
|
|
443
|
+
"IndexName": "UserThread",
|
|
444
|
+
"ScanIndexForward": False,
|
|
445
|
+
"Limit": self.user_thread_limit,
|
|
446
|
+
"KeyConditionExpression": "#UserThreadPK = :pk",
|
|
447
|
+
"ExpressionAttributeNames": {
|
|
448
|
+
"#UserThreadPK": "UserThreadPK",
|
|
449
|
+
},
|
|
450
|
+
"ExpressionAttributeValues": {
|
|
451
|
+
":pk": {"S": f"USER#{filters.userId}"},
|
|
452
|
+
},
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if pagination.cursor:
|
|
456
|
+
query_args["ExclusiveStartKey"] = json.loads(pagination.cursor)
|
|
457
|
+
|
|
458
|
+
if filters.search:
|
|
459
|
+
query_args["FilterExpression"] = "contains(#name, :search)"
|
|
460
|
+
query_args["ExpressionAttributeNames"]["#name"] = "name"
|
|
461
|
+
query_args["ExpressionAttributeValues"][":search"] = {"S": filters.search}
|
|
462
|
+
|
|
463
|
+
response = self.client.query(**query_args) # type: ignore
|
|
464
|
+
|
|
465
|
+
if "LastEvaluatedKey" in response:
|
|
466
|
+
paginated_response.pageInfo.hasNextPage = True
|
|
467
|
+
paginated_response.pageInfo.endCursor = json.dumps(
|
|
468
|
+
response["LastEvaluatedKey"]
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
for item in response["Items"]:
|
|
472
|
+
deserialized_item: Dict[str, Any] = self._deserialize_item(item)
|
|
473
|
+
thread = ThreadDict( # type: ignore
|
|
474
|
+
id=deserialized_item["PK"].strip("THREAD#"),
|
|
475
|
+
createdAt=deserialized_item["UserThreadSK"].strip("TS#"),
|
|
476
|
+
name=deserialized_item["name"],
|
|
477
|
+
)
|
|
478
|
+
paginated_response.data.append(thread)
|
|
479
|
+
|
|
480
|
+
return paginated_response
|
|
481
|
+
|
|
482
|
+
async def get_thread(self, thread_id: str) -> "Optional[ThreadDict]":
|
|
483
|
+
_logger.info("DynamoDB: get_thread thread=%s", thread_id)
|
|
484
|
+
|
|
485
|
+
# Get all thread records
|
|
486
|
+
thread_items: List[Any] = []
|
|
487
|
+
|
|
488
|
+
cursor: Dict[str, Any] = {}
|
|
489
|
+
while True:
|
|
490
|
+
response = self.client.query(
|
|
491
|
+
TableName=self.table_name,
|
|
492
|
+
KeyConditionExpression="#pk = :pk",
|
|
493
|
+
ExpressionAttributeNames={"#pk": "PK"},
|
|
494
|
+
ExpressionAttributeValues={":pk": {"S": f"THREAD#{thread_id}"}},
|
|
495
|
+
**cursor,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
deserialized_items = map(self._deserialize_item, response["Items"])
|
|
499
|
+
thread_items.extend(deserialized_items)
|
|
500
|
+
|
|
501
|
+
if "LastEvaluatedKey" not in response:
|
|
502
|
+
break
|
|
503
|
+
cursor["ExclusiveStartKey"] = response["LastEvaluatedKey"]
|
|
504
|
+
|
|
505
|
+
if len(thread_items) == 0:
|
|
506
|
+
return None
|
|
507
|
+
|
|
508
|
+
# process accordingly
|
|
509
|
+
thread_dict: Optional[ThreadDict] = None
|
|
510
|
+
steps = []
|
|
511
|
+
elements = []
|
|
512
|
+
|
|
513
|
+
for item in thread_items:
|
|
514
|
+
if item["SK"] == "THREAD":
|
|
515
|
+
thread_dict = item
|
|
516
|
+
|
|
517
|
+
elif item["SK"].startswith("ELEMENT"):
|
|
518
|
+
elements.append(item)
|
|
519
|
+
|
|
520
|
+
elif item["SK"].startswith("STEP"):
|
|
521
|
+
if "feedback" in item: # Decimal is not json serializable
|
|
522
|
+
item["feedback"]["value"] = int(item["feedback"]["value"])
|
|
523
|
+
steps.append(item)
|
|
524
|
+
|
|
525
|
+
if not thread_dict:
|
|
526
|
+
if len(thread_items) > 0:
|
|
527
|
+
_logger.warning(
|
|
528
|
+
"DynamoDB: found orphaned items for thread=%s", thread_id
|
|
529
|
+
)
|
|
530
|
+
return None
|
|
531
|
+
|
|
532
|
+
steps.sort(key=lambda i: i["createdAt"])
|
|
533
|
+
thread_dict.update(
|
|
534
|
+
{
|
|
535
|
+
"steps": steps,
|
|
536
|
+
"elements": elements,
|
|
537
|
+
}
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
return thread_dict
|
|
541
|
+
|
|
542
|
+
async def update_thread(
|
|
543
|
+
self,
|
|
544
|
+
thread_id: str,
|
|
545
|
+
name: Optional[str] = None,
|
|
546
|
+
user_id: Optional[str] = None,
|
|
547
|
+
metadata: Optional[Dict] = None,
|
|
548
|
+
tags: Optional[List[str]] = None,
|
|
549
|
+
):
|
|
550
|
+
_logger.info("DynamoDB: update_thread thread=%s userId=%s", thread_id, user_id)
|
|
551
|
+
_logger.debug(
|
|
552
|
+
"DynamoDB: update_thread name=%s tags=%s metadata=%s", name, tags, metadata
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
ts = self._get_current_timestamp()
|
|
556
|
+
|
|
557
|
+
item = {
|
|
558
|
+
# GSI: UserThread
|
|
559
|
+
"UserThreadSK": f"TS#{ts}",
|
|
560
|
+
#
|
|
561
|
+
"id": thread_id,
|
|
562
|
+
"createdAt": ts,
|
|
563
|
+
"name": name,
|
|
564
|
+
"userId": user_id,
|
|
565
|
+
"userIdentifier": user_id,
|
|
566
|
+
"tags": tags,
|
|
567
|
+
"metadata": metadata,
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
if user_id:
|
|
571
|
+
# user_id may be None on subsequent calls, don't update UserThreadPK to "USER#{None}"
|
|
572
|
+
item["UserThreadPK"] = f"USER#{user_id}"
|
|
573
|
+
|
|
574
|
+
self._update_item(
|
|
575
|
+
key={
|
|
576
|
+
"PK": f"THREAD#{thread_id}",
|
|
577
|
+
"SK": "THREAD",
|
|
578
|
+
},
|
|
579
|
+
updates=item,
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
async def delete_user_session(self, id: str) -> bool:
|
|
583
|
+
return True # Not sure why documentation wants this
|
|
584
|
+
|
|
585
|
+
async def build_debug_url(self) -> str:
|
|
586
|
+
return ""
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as P,r as v,u as D,a as O}from"./index-
|
|
1
|
+
import{g as P,r as v,u as D,a as O}from"./index-b8523620.js";function b(t,e){for(var r=0;r<e.length;r++){const o=e[r];if(typeof o!="string"&&!Array.isArray(o)){for(const a in o)if(a!=="default"&&!(a in t)){const i=Object.getOwnPropertyDescriptor(o,a);i&&Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:()=>o[a]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var M=Object.create,s=Object.defineProperty,w=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,j=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty,E=(t,e,r)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,A=(t,e)=>{for(var r in e)s(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of S(e))!T.call(t,a)&&a!==r&&s(t,a,{get:()=>e[a],enumerable:!(o=w(e,a))||o.enumerable});return t},L=(t,e,r)=>(r=t!=null?M(j(t)):{},h(e||!t||!t.__esModule?s(r,"default",{value:t,enumerable:!0}):r,t)),C=t=>h(s({},"__esModule",{value:!0}),t),n=(t,e,r)=>(E(t,typeof e!="symbol"?e+"":e,r),r),d={};A(d,{default:()=>p});var _=C(d),c=L(v),l=D,f=O;const x="https://api.dmcdn.net/all.js",N="DM",K="dmAsyncInit";class p extends c.Component{constructor(){super(...arguments),n(this,"callPlayer",l.callPlayer),n(this,"onDurationChange",()=>{const e=this.getDuration();this.props.onDuration(e)}),n(this,"mute",()=>{this.callPlayer("setMuted",!0)}),n(this,"unmute",()=>{this.callPlayer("setMuted",!1)}),n(this,"ref",e=>{this.container=e})}componentDidMount(){this.props.onMount&&this.props.onMount(this)}load(e){const{controls:r,config:o,onError:a,playing:i}=this.props,[,y]=e.match(f.MATCH_URL_DAILYMOTION);if(this.player){this.player.load(y,{start:(0,l.parseStartTime)(e),autoplay:i});return}(0,l.getSDK)(x,N,K,u=>u.player).then(u=>{if(!this.container)return;const g=u.player;this.player=new g(this.container,{width:"100%",height:"100%",video:y,params:{controls:r,autoplay:this.props.playing,mute:this.props.muted,start:(0,l.parseStartTime)(e),origin:window.location.origin,...o.params},events:{apiready:this.props.onReady,seeked:()=>this.props.onSeek(this.player.currentTime),video_end:this.props.onEnded,durationchange:this.onDurationChange,pause:this.props.onPause,playing:this.props.onPlay,waiting:this.props.onBuffer,error:m=>a(m)}})},a)}play(){this.callPlayer("play")}pause(){this.callPlayer("pause")}stop(){}seekTo(e,r=!0){this.callPlayer("seek",e),r||this.pause()}setVolume(e){this.callPlayer("setVolume",e)}getDuration(){return this.player.duration||null}getCurrentTime(){return this.player.currentTime}getSecondsLoaded(){return this.player.bufferedTime}render(){const{display:e}=this.props,r={width:"100%",height:"100%",display:e};return c.default.createElement("div",{style:r},c.default.createElement("div",{ref:this.ref}))}}n(p,"displayName","DailyMotion");n(p,"canPlay",f.canPlay.dailymotion);n(p,"loopOnEnded",!0);const R=P(_),I=b({__proto__:null,default:R},[_]);export{I as D};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as _,r as g,u as P,a as m}from"./index-
|
|
1
|
+
import{g as _,r as g,u as P,a as m}from"./index-b8523620.js";function v(t,e){for(var r=0;r<e.length;r++){const a=e[r];if(typeof a!="string"&&!Array.isArray(a)){for(const s in a)if(s!=="default"&&!(s in t)){const p=Object.getOwnPropertyDescriptor(a,s);p&&Object.defineProperty(t,s,p.get?p:{enumerable:!0,get:()=>a[s]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var O=Object.create,i=Object.defineProperty,D=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,S=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,I=(t,e,r)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,k=(t,e)=>{for(var r in e)i(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of E(e))!j.call(t,s)&&s!==r&&i(t,s,{get:()=>e[s],enumerable:!(a=D(e,s))||a.enumerable});return t},w=(t,e,r)=>(r=t!=null?O(S(t)):{},h(e||!t||!t.__esModule?i(r,"default",{value:t,enumerable:!0}):r,t)),F=t=>h(i({},"__esModule",{value:!0}),t),o=(t,e,r)=>(I(t,typeof e!="symbol"?e+"":e,r),r),b={};k(b,{default:()=>l});var d=F(b),u=w(g),n=P,x=m;const c="https://connect.facebook.net/en_US/sdk.js",y="FB",f="fbAsyncInit",L="facebook-player-";class l extends u.Component{constructor(){super(...arguments),o(this,"callPlayer",n.callPlayer),o(this,"playerID",this.props.config.playerId||`${L}${(0,n.randomString)()}`),o(this,"mute",()=>{this.callPlayer("mute")}),o(this,"unmute",()=>{this.callPlayer("unmute")})}componentDidMount(){this.props.onMount&&this.props.onMount(this)}load(e,r){if(r){(0,n.getSDK)(c,y,f).then(a=>a.XFBML.parse());return}(0,n.getSDK)(c,y,f).then(a=>{a.init({appId:this.props.config.appId,xfbml:!0,version:this.props.config.version}),a.Event.subscribe("xfbml.render",s=>{this.props.onLoaded()}),a.Event.subscribe("xfbml.ready",s=>{s.type==="video"&&s.id===this.playerID&&(this.player=s.instance,this.player.subscribe("startedPlaying",this.props.onPlay),this.player.subscribe("paused",this.props.onPause),this.player.subscribe("finishedPlaying",this.props.onEnded),this.player.subscribe("startedBuffering",this.props.onBuffer),this.player.subscribe("finishedBuffering",this.props.onBufferEnd),this.player.subscribe("error",this.props.onError),this.props.muted?this.callPlayer("mute"):this.callPlayer("unmute"),this.props.onReady(),document.getElementById(this.playerID).querySelector("iframe").style.visibility="visible")})})}play(){this.callPlayer("play")}pause(){this.callPlayer("pause")}stop(){}seekTo(e,r=!0){this.callPlayer("seek",e),r||this.pause()}setVolume(e){this.callPlayer("setVolume",e)}getDuration(){return this.callPlayer("getDuration")}getCurrentTime(){return this.callPlayer("getCurrentPosition")}getSecondsLoaded(){return null}render(){const{attributes:e}=this.props.config,r={width:"100%",height:"100%"};return u.default.createElement("div",{style:r,id:this.playerID,className:"fb-video","data-href":this.props.url,"data-autoplay":this.props.playing?"true":"false","data-allowfullscreen":"true","data-controls":this.props.controls?"true":"false",...e})}}o(l,"displayName","Facebook");o(l,"canPlay",x.canPlay.facebook);o(l,"loopOnEnded",!0);const M=_(d),B=v({__proto__:null,default:M},[d]);export{B as F};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as b,r as _,u as O,a as A}from"./index-
|
|
1
|
+
import{g as b,r as _,u as O,a as A}from"./index-b8523620.js";function R(s,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const n in i)if(n!=="default"&&!(n in s)){const l=Object.getOwnPropertyDescriptor(i,n);l&&Object.defineProperty(s,n,l.get?l:{enumerable:!0,get:()=>i[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}var I=Object.create,u=Object.defineProperty,D=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyNames,M=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty,U=(s,e,t)=>e in s?u(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,N=(s,e)=>{for(var t in e)u(s,t,{get:e[t],enumerable:!0})},E=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of w(e))!k.call(s,n)&&n!==t&&u(s,n,{get:()=>e[n],enumerable:!(i=D(e,n))||i.enumerable});return s},j=(s,e,t)=>(t=s!=null?I(M(s)):{},E(e||!s||!s.__esModule?u(t,"default",{value:s,enumerable:!0}):t,s)),H=s=>E(u({},"__esModule",{value:!0}),s),r=(s,e,t)=>(U(s,typeof e!="symbol"?e+"":e,t),t),m={};N(m,{default:()=>P});var g=H(m),c=j(_),a=O,d=A;const y=typeof navigator<"u",F=y&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,v=y&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||F)&&!window.MSStream,V=y&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)&&!window.MSStream,T="https://cdn.jsdelivr.net/npm/hls.js@VERSION/dist/hls.min.js",C="Hls",B="https://cdnjs.cloudflare.com/ajax/libs/dashjs/VERSION/dash.all.min.js",x="dashjs",K="https://cdn.jsdelivr.net/npm/flv.js@VERSION/dist/flv.min.js",G="flvjs",X=/www\.dropbox\.com\/.+/,f=/https:\/\/watch\.cloudflarestream\.com\/([a-z0-9]+)/,W="https://videodelivery.net/{id}/manifest/video.m3u8";class P extends c.Component{constructor(){super(...arguments),r(this,"onReady",(...e)=>this.props.onReady(...e)),r(this,"onPlay",(...e)=>this.props.onPlay(...e)),r(this,"onBuffer",(...e)=>this.props.onBuffer(...e)),r(this,"onBufferEnd",(...e)=>this.props.onBufferEnd(...e)),r(this,"onPause",(...e)=>this.props.onPause(...e)),r(this,"onEnded",(...e)=>this.props.onEnded(...e)),r(this,"onError",(...e)=>this.props.onError(...e)),r(this,"onPlayBackRateChange",e=>this.props.onPlaybackRateChange(e.target.playbackRate)),r(this,"onEnablePIP",(...e)=>this.props.onEnablePIP(...e)),r(this,"onDisablePIP",e=>{const{onDisablePIP:t,playing:i}=this.props;t(e),i&&this.play()}),r(this,"onPresentationModeChange",e=>{if(this.player&&(0,a.supportsWebKitPresentationMode)(this.player)){const{webkitPresentationMode:t}=this.player;t==="picture-in-picture"?this.onEnablePIP(e):t==="inline"&&this.onDisablePIP(e)}}),r(this,"onSeek",e=>{this.props.onSeek(e.target.currentTime)}),r(this,"mute",()=>{this.player.muted=!0}),r(this,"unmute",()=>{this.player.muted=!1}),r(this,"renderSourceElement",(e,t)=>typeof e=="string"?c.default.createElement("source",{key:t,src:e}):c.default.createElement("source",{key:t,...e})),r(this,"renderTrack",(e,t)=>c.default.createElement("track",{key:t,...e})),r(this,"ref",e=>{this.player&&(this.prevPlayer=this.player),this.player=e})}componentDidMount(){this.props.onMount&&this.props.onMount(this),this.addListeners(this.player);const e=this.getSource(this.props.url);e&&(this.player.src=e),(v||this.props.config.forceDisableHls)&&this.player.load()}componentDidUpdate(e){this.shouldUseAudio(this.props)!==this.shouldUseAudio(e)&&(this.removeListeners(this.prevPlayer,e.url),this.addListeners(this.player)),this.props.url!==e.url&&!(0,a.isMediaStream)(this.props.url)&&!(this.props.url instanceof Array)&&(this.player.srcObject=null)}componentWillUnmount(){this.player.removeAttribute("src"),this.removeListeners(this.player),this.hls&&this.hls.destroy()}addListeners(e){const{url:t,playsinline:i}=this.props;e.addEventListener("play",this.onPlay),e.addEventListener("waiting",this.onBuffer),e.addEventListener("playing",this.onBufferEnd),e.addEventListener("pause",this.onPause),e.addEventListener("seeked",this.onSeek),e.addEventListener("ended",this.onEnded),e.addEventListener("error",this.onError),e.addEventListener("ratechange",this.onPlayBackRateChange),e.addEventListener("enterpictureinpicture",this.onEnablePIP),e.addEventListener("leavepictureinpicture",this.onDisablePIP),e.addEventListener("webkitpresentationmodechanged",this.onPresentationModeChange),this.shouldUseHLS(t)||e.addEventListener("canplay",this.onReady),i&&(e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline",""),e.setAttribute("x5-playsinline",""))}removeListeners(e,t){e.removeEventListener("canplay",this.onReady),e.removeEventListener("play",this.onPlay),e.removeEventListener("waiting",this.onBuffer),e.removeEventListener("playing",this.onBufferEnd),e.removeEventListener("pause",this.onPause),e.removeEventListener("seeked",this.onSeek),e.removeEventListener("ended",this.onEnded),e.removeEventListener("error",this.onError),e.removeEventListener("ratechange",this.onPlayBackRateChange),e.removeEventListener("enterpictureinpicture",this.onEnablePIP),e.removeEventListener("leavepictureinpicture",this.onDisablePIP),e.removeEventListener("webkitpresentationmodechanged",this.onPresentationModeChange),this.shouldUseHLS(t)||e.removeEventListener("canplay",this.onReady)}shouldUseAudio(e){return e.config.forceVideo||e.config.attributes.poster?!1:d.AUDIO_EXTENSIONS.test(e.url)||e.config.forceAudio}shouldUseHLS(e){return V&&this.props.config.forceSafariHLS||this.props.config.forceHLS?!0:v||this.props.config.forceDisableHls?!1:d.HLS_EXTENSIONS.test(e)||f.test(e)}shouldUseDASH(e){return d.DASH_EXTENSIONS.test(e)||this.props.config.forceDASH}shouldUseFLV(e){return d.FLV_EXTENSIONS.test(e)||this.props.config.forceFLV}load(e){const{hlsVersion:t,hlsOptions:i,dashVersion:n,flvVersion:l}=this.props.config;if(this.hls&&this.hls.destroy(),this.dash&&this.dash.reset(),this.shouldUseHLS(e)&&(0,a.getSDK)(T.replace("VERSION",t),C).then(o=>{if(this.hls=new o(i),this.hls.on(o.Events.MANIFEST_PARSED,()=>{this.props.onReady()}),this.hls.on(o.Events.ERROR,(h,p)=>{this.props.onError(h,p,this.hls,o)}),f.test(e)){const h=e.match(f)[1];this.hls.loadSource(W.replace("{id}",h))}else this.hls.loadSource(e);this.hls.attachMedia(this.player),this.props.onLoaded()}),this.shouldUseDASH(e)&&(0,a.getSDK)(B.replace("VERSION",n),x).then(o=>{this.dash=o.MediaPlayer().create(),this.dash.initialize(this.player,e,this.props.playing),this.dash.on("error",this.props.onError),parseInt(n)<3?this.dash.getDebug().setLogToBrowserConsole(!1):this.dash.updateSettings({debug:{logLevel:o.Debug.LOG_LEVEL_NONE}}),this.props.onLoaded()}),this.shouldUseFLV(e)&&(0,a.getSDK)(K.replace("VERSION",l),G).then(o=>{this.flv=o.createPlayer({type:"flv",url:e}),this.flv.attachMediaElement(this.player),this.flv.on(o.Events.ERROR,(h,p)=>{this.props.onError(h,p,this.flv,o)}),this.flv.load(),this.props.onLoaded()}),e instanceof Array)this.player.load();else if((0,a.isMediaStream)(e))try{this.player.srcObject=e}catch{this.player.src=window.URL.createObjectURL(e)}}play(){const e=this.player.play();e&&e.catch(this.props.onError)}pause(){this.player.pause()}stop(){this.player.removeAttribute("src"),this.dash&&this.dash.reset()}seekTo(e,t=!0){this.player.currentTime=e,t||this.pause()}setVolume(e){this.player.volume=e}enablePIP(){this.player.requestPictureInPicture&&document.pictureInPictureElement!==this.player?this.player.requestPictureInPicture():(0,a.supportsWebKitPresentationMode)(this.player)&&this.player.webkitPresentationMode!=="picture-in-picture"&&this.player.webkitSetPresentationMode("picture-in-picture")}disablePIP(){document.exitPictureInPicture&&document.pictureInPictureElement===this.player?document.exitPictureInPicture():(0,a.supportsWebKitPresentationMode)(this.player)&&this.player.webkitPresentationMode!=="inline"&&this.player.webkitSetPresentationMode("inline")}setPlaybackRate(e){try{this.player.playbackRate=e}catch(t){this.props.onError(t)}}getDuration(){if(!this.player)return null;const{duration:e,seekable:t}=this.player;return e===1/0&&t.length>0?t.end(t.length-1):e}getCurrentTime(){return this.player?this.player.currentTime:null}getSecondsLoaded(){if(!this.player)return null;const{buffered:e}=this.player;if(e.length===0)return 0;const t=e.end(e.length-1),i=this.getDuration();return t>i?i:t}getSource(e){const t=this.shouldUseHLS(e),i=this.shouldUseDASH(e),n=this.shouldUseFLV(e);if(!(e instanceof Array||(0,a.isMediaStream)(e)||t||i||n))return X.test(e)?e.replace("www.dropbox.com","dl.dropboxusercontent.com"):e}render(){const{url:e,playing:t,loop:i,controls:n,muted:l,config:o,width:h,height:p}=this.props,L=this.shouldUseAudio(this.props)?"audio":"video",S={width:h==="auto"?h:"100%",height:p==="auto"?p:"100%"};return c.default.createElement(L,{ref:this.ref,src:this.getSource(e),style:S,preload:"auto",autoPlay:t||void 0,controls:n,muted:l,loop:i,...o.attributes},e instanceof Array&&e.map(this.renderSourceElement),o.tracks.map(this.renderTrack))}}r(P,"displayName","FilePlayer");r(P,"canPlay",d.canPlay.file);const z=b(g),J=R({__proto__:null,default:z},[g]);export{J as F};
|