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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions livekit-api/livekit/api/access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,9 @@ def verify(self, token: str, *, verify_signature: bool = True) -> Claims:
return grant_claims


def camel_to_snake(t: str):
def camel_to_snake(t: str) -> str:
return re.sub(r"(?<!^)(?=[A-Z])", "_", t).lower()


def snake_to_lower_camel(t: str):
def snake_to_lower_camel(t: str) -> str:
return "".join(word.capitalize() if i else word for i, word in enumerate(t.split("_")))
10 changes: 5 additions & 5 deletions livekit-api/livekit/api/livekit_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .sip_service import SipService
from .agent_dispatch_service import AgentDispatchService
from .connector_service import ConnectorService
from typing import Optional
from typing import Any, Optional


class LiveKitAPI:
Expand Down Expand Up @@ -96,21 +96,21 @@ def connector(self) -> ConnectorService:
"""Instance of the ConnectorService"""
return self._connector

async def aclose(self):
async def aclose(self) -> None:
"""Close the API client

Call this before your application exits or when the API client is no longer needed."""
# we do not close custom sessions, that's up to the caller
if not self._custom_session:
if not self._custom_session and self._session is not None:
await self._session.close()

async def __aenter__(self):
async def __aenter__(self) -> "LiveKitAPI":
"""@private

Support for `async with`"""
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
"""@private

Support for `async with`"""
Expand Down
12 changes: 7 additions & 5 deletions livekit-api/tests/test_access_token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime

import pytest # type: ignore
import pytest
from livekit.api import AccessToken, TokenVerifier, VideoGrants, SIPGrants
from livekit.protocol.room import RoomConfiguration
from livekit.protocol.agent_dispatch import RoomAgentDispatch
Expand All @@ -9,7 +9,7 @@
TEST_API_SECRET = "thiskeyistotallyunsafe"


def test_verify_token():
def test_verify_token() -> None:
grants = VideoGrants(room_join=True, room="test_room")
sip = SIPGrants(admin=True)

Expand All @@ -30,11 +30,12 @@ def test_verify_token():
assert claims.metadata == "test_metadata"
assert claims.video == grants
assert claims.sip == sip
assert claims.attributes is not None
assert claims.attributes["key1"] == "value1"
assert claims.attributes["key2"] == "value2"


def test_agent_config():
def test_agent_config() -> None:
token = (
AccessToken(TEST_API_KEY, TEST_API_SECRET)
.with_identity("test_identity")
Expand All @@ -50,6 +51,7 @@ def test_agent_config():
token_verifier = TokenVerifier(TEST_API_KEY, TEST_API_SECRET)
claims = token_verifier.verify(token)
# Verify the decoded claims match
assert claims.room_config is not None
assert claims.room_config.agents[0].agent_name == "test-agent"

# Split token into header.payload.signature
Expand All @@ -74,7 +76,7 @@ def test_agent_config():
assert payload_json["roomConfig"]["agents"][0]["agentName"] == "test-agent"


def test_verify_token_invalid():
def test_verify_token_invalid() -> None:
token = AccessToken(TEST_API_KEY, TEST_API_SECRET).with_identity("test_identity").to_jwt()

token_verifier = TokenVerifier(TEST_API_KEY, "invalid_secret")
Expand All @@ -86,7 +88,7 @@ def test_verify_token_invalid():
token_verifier.verify(token)


def test_verify_token_expired():
def test_verify_token_expired() -> None:
token = (
AccessToken(TEST_API_KEY, TEST_API_SECRET)
.with_identity("test_identity")
Expand Down
8 changes: 4 additions & 4 deletions livekit-api/tests/test_webhook.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import base64
import hashlib

import pytest # type: ignore
import pytest
from livekit.api import AccessToken, TokenVerifier, WebhookReceiver

TEST_API_KEY = "myapikey"
Expand Down Expand Up @@ -45,7 +45,7 @@
"""


def test_webhook_receiver():
def test_webhook_receiver() -> None:
token_verifier = TokenVerifier(TEST_API_KEY, TEST_API_SECRET)
receiver = WebhookReceiver(token_verifier)

Expand All @@ -56,7 +56,7 @@ def test_webhook_receiver():
receiver.receive(TEST_EVENT, jwt)


def test_bad_hash():
def test_bad_hash() -> None:
token_verifier = TokenVerifier(TEST_API_KEY, TEST_API_SECRET)
receiver = WebhookReceiver(token_verifier)

Expand All @@ -68,7 +68,7 @@ def test_bad_hash():
receiver.receive(TEST_EVENT, jwt)


def test_invalid_body():
def test_invalid_body() -> None:
token_verifier = TokenVerifier(TEST_API_KEY, TEST_API_SECRET)
receiver = WebhookReceiver(token_verifier)

Expand Down
8 changes: 4 additions & 4 deletions livekit-rtc/livekit/rtc/_ffi_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
atexit.register(_resource_files.close)


def get_ffi_lib():
def get_ffi_lib() -> ctypes.CDLL:
# allow to override the lib path using an env var
libpath = os.environ.get("LIVEKIT_LIB_PATH", "").strip()
if libpath:
Expand Down Expand Up @@ -92,7 +92,7 @@ def __init__(self, handle: int) -> None:
self.handle = handle
self._disposed = False

def __del__(self):
def __del__(self) -> None:
self.dispose()

@property
Expand Down Expand Up @@ -142,7 +142,7 @@ def unsubscribe(self, queue: Queue[T]) -> None:
break


@ctypes.CFUNCTYPE(None, ctypes.POINTER(ctypes.c_uint8), ctypes.c_size_t)
@ctypes.CFUNCTYPE(None, ctypes.POINTER(ctypes.c_uint8), ctypes.c_size_t) # type: ignore[untyped-decorator]
def ffi_event_callback(
data_ptr: ctypes.POINTER(ctypes.c_uint8), # type: ignore
data_len: ctypes.c_size_t,
Expand Down Expand Up @@ -219,7 +219,7 @@ def __init__(self) -> None:
)

@atexit.register
def _dispose_lk_ffi():
def _dispose_lk_ffi() -> None:
ffi_lib.livekit_ffi_dispose()

@property
Expand Down
10 changes: 5 additions & 5 deletions livekit-rtc/livekit/rtc/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@
from collections import deque
import ctypes
import random
from typing import Callable, Generator, Generic, List, TypeVar
from typing import Any, Callable, Generator, Generic, List, TypeVar

logger = logging.getLogger("livekit")


class classproperty(object):
def __init__(self, f):
self.f = classmethod(f)
def __init__(self, f: Callable[..., Any]) -> None:
self.f: Any = classmethod(f)

def __get__(self, *a):
def __get__(self, *a: Any) -> Any:
return self.f.__get__(*a)()


Expand Down Expand Up @@ -118,7 +118,7 @@ async def join(self) -> None:
_base62_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def generate_random_base62(length=12):
def generate_random_base62(length: int = 12) -> str:
"""
Generate a random base62 encoded string of a specified length.

Expand Down
2 changes: 1 addition & 1 deletion livekit-rtc/livekit/rtc/audio_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def __repr__(self) -> str:
)

@classmethod
def __get_pydantic_core_schema__(cls, *_: Any):
def __get_pydantic_core_schema__(cls, *_: Any) -> Any:
from pydantic_core import core_schema
import base64

Expand Down
4 changes: 2 additions & 2 deletions livekit-rtc/livekit/rtc/audio_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(
num_channels: int = 1,
frame_size_ms: int | None = None,
noise_cancellation: Optional[NoiseCancellationOptions | FrameProcessor[AudioFrame]] = None,
**kwargs,
**kwargs: Any,
) -> None:
"""Initialize an `AudioStream` instance.

Expand Down Expand Up @@ -266,7 +266,7 @@ def _create_owned_stream_from_participant(
resp = FfiClient.instance.request(req)
return resp.audio_stream_from_participant.stream

async def _run(self):
async def _run(self) -> None:
while True:
event = await self._ffi_queue.wait_for(self._is_event)
audio_event: proto_audio_frame.AudioStreamEvent = event.audio_stream_event
Expand Down
22 changes: 12 additions & 10 deletions livekit-rtc/livekit/rtc/data_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ def __init__(
)
self._queue: asyncio.Queue[proto_DataStream.Chunk | None] = asyncio.Queue()

async def _on_chunk_update(self, chunk: proto_DataStream.Chunk):
async def _on_chunk_update(self, chunk: proto_DataStream.Chunk) -> None:
await self._queue.put(chunk)

async def _on_stream_close(self, trailer: proto_DataStream.Trailer):
async def _on_stream_close(self, trailer: proto_DataStream.Trailer) -> None:
self.info.attributes = self.info.attributes or {}
self.info.attributes.update(trailer.attributes)
await self._queue.put(None)
Expand Down Expand Up @@ -114,10 +114,10 @@ def __init__(self, header: proto_DataStream.Header, capacity: int = 0) -> None:
)
self._queue: asyncio.Queue[proto_DataStream.Chunk | None] = asyncio.Queue(capacity)

async def _on_chunk_update(self, chunk: proto_DataStream.Chunk):
async def _on_chunk_update(self, chunk: proto_DataStream.Chunk) -> None:
await self._queue.put(chunk)

async def _on_stream_close(self, trailer: proto_DataStream.Trailer):
async def _on_stream_close(self, trailer: proto_DataStream.Trailer) -> None:
self.info.attributes = self.info.attributes or {}
self.info.attributes.update(trailer.attributes)
await self._queue.put(None)
Expand Down Expand Up @@ -166,7 +166,7 @@ def __init__(
self._sender_identity = sender_identity or self._local_participant.identity
self._closed = False

async def _send_header(self):
async def _send_header(self) -> None:
req = proto_ffi.FfiRequest(
send_stream_header=proto_room.SendStreamHeaderRequest(
header=self._header,
Expand All @@ -188,7 +188,7 @@ async def _send_header(self):
if cb.send_stream_header.error:
raise ConnectionError(cb.send_stream_header.error)

async def _send_chunk(self, chunk: proto_DataStream.Chunk):
async def _send_chunk(self, chunk: proto_DataStream.Chunk) -> None:
if self._closed:
raise RuntimeError(f"Cannot send chunk after stream is closed: {chunk}")
req = proto_ffi.FfiRequest(
Expand All @@ -212,7 +212,7 @@ async def _send_chunk(self, chunk: proto_DataStream.Chunk):
if cb.send_stream_chunk.error:
raise ConnectionError(cb.send_stream_chunk.error)

async def _send_trailer(self, trailer: proto_DataStream.Trailer):
async def _send_trailer(self, trailer: proto_DataStream.Trailer) -> None:
req = proto_ffi.FfiRequest(
send_stream_trailer=proto_room.SendStreamTrailerRequest(
trailer=trailer,
Expand All @@ -233,7 +233,9 @@ async def _send_trailer(self, trailer: proto_DataStream.Trailer):
if cb.send_stream_chunk.error:
raise ConnectionError(cb.send_stream_trailer.error)

async def aclose(self, *, reason: str = "", attributes: Optional[Dict[str, str]] = None):
async def aclose(
self, *, reason: str = "", attributes: Optional[Dict[str, str]] = None
) -> None:
if self._closed:
raise RuntimeError("Stream already closed")
self._closed = True
Expand Down Expand Up @@ -281,7 +283,7 @@ def __init__(
)
self._write_lock = asyncio.Lock()

async def write(self, text: str):
async def write(self, text: str) -> None:
async with self._write_lock:
for chunk in split_utf8(text, STREAM_CHUNK_SIZE):
content = chunk
Expand Down Expand Up @@ -333,7 +335,7 @@ def __init__(
)
self._write_lock = asyncio.Lock()

async def write(self, data: bytes):
async def write(self, data: bytes) -> None:
async with self._write_lock:
chunked_data = [
data[i : i + STREAM_CHUNK_SIZE] for i in range(0, len(data), STREAM_CHUNK_SIZE)
Expand Down
10 changes: 5 additions & 5 deletions livekit-rtc/livekit/rtc/e2ee.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

from dataclasses import dataclass, field
from typing import List, Optional
from typing import List, Optional, cast

from ._ffi_client import FfiClient
from ._proto import e2ee_pb2 as proto_e2ee
Expand Down Expand Up @@ -84,7 +84,7 @@ def export_shared_key(self, key_index: int) -> bytes:
req.e2ee.get_shared_key.key_index = key_index
resp = FfiClient.instance.request(req)
key = resp.e2ee.get_shared_key.key
return key
return cast(bytes, key)

def ratchet_shared_key(self, key_index: int) -> bytes:
"""Ratchets the shared encryption key to a new key.
Expand All @@ -107,7 +107,7 @@ def ratchet_shared_key(self, key_index: int) -> bytes:
resp = FfiClient.instance.request(req)

new_key = resp.e2ee.ratchet_shared_key.new_key
return new_key
return cast(bytes, new_key)

def set_key(self, participant_identity: str, key: bytes, key_index: int) -> None:
"""Sets the encryption key for a specific participant.
Expand Down Expand Up @@ -152,7 +152,7 @@ def export_key(self, participant_identity: str, key_index: int) -> bytes:
req.e2ee.get_key.key_index = key_index
resp = FfiClient.instance.request(req)
key = resp.e2ee.get_key.key
return key
return cast(bytes, key)

def ratchet_key(self, participant_identity: str, key_index: int) -> bytes:
"""Ratchets the encryption key for a specific participant to a new key.
Expand All @@ -176,7 +176,7 @@ def ratchet_key(self, participant_identity: str, key_index: int) -> bytes:

resp = FfiClient.instance.request(req)
new_key = resp.e2ee.ratchet_key.new_key
return new_key
return cast(bytes, new_key)


class FrameCryptor:
Expand Down
6 changes: 3 additions & 3 deletions livekit-rtc/livekit/rtc/event_emitter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import inspect
import asyncio
from typing import Callable, Dict, Set, Optional, Generic, TypeVar
from typing import Any, Callable, Dict, Set, Optional, Generic, TypeVar

from .log import logger

Expand All @@ -14,7 +14,7 @@ def __init__(self) -> None:
"""
self._events: Dict[T_contra, Set[Callable]] = dict()

def emit(self, event: T_contra, *args) -> None:
def emit(self, event: T_contra, *args: Any) -> None:
"""
Trigger all callbacks associated with the given event.

Expand Down Expand Up @@ -104,7 +104,7 @@ def greet_once(name):
"""
if callback is not None:

def once_callback(*args, **kwargs):
def once_callback(*args: Any, **kwargs: Any) -> None:
self.off(event, once_callback)
callback(*args, **kwargs)

Expand Down
Loading
Loading