diff --git a/CHANGELOG.md b/CHANGELOG.md index c1fb8c8a..5e4b5a34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Change Log +## 28.3.0 + +* Added: `videos` service to create, list, get, update and delete videos from files in Storage +* Added: `videos.createRendition`, `listRenditions`, `getRendition` and `deleteRendition` to transcode a video into HLS, DASH or CMAF +* Added: `videos.createCaption`, `listCaptions`, `updateCaption` and `deleteCaption` for subtitle tracks +* Added: `getHlsManifest`, `getDashManifest`, `getCmafHlsManifest`, `getCmafDashManifest`, `getCaptionManifest`, `getThumbnail` and `getTimeline` playback URLs, and `listCodecs` +* Added: `project.listVideoProfiles`, `createVideoProfile`, `getVideoProfile`, `updateVideoProfile` and `deleteVideoProfile` +* Added: `Video`, `VideoCodec`, `VideoProfile`, `VideoRendition` and `VideoCaption` models, their list models, and the `VideoCodecId`, `VideoOutput`, `VideoRenditionStatus`, `VideoCaptionStatus` and `VideoTimelineStatus` enums + ## 28.2.0 * Added: `monitors` service to create, list, get, update and delete HTTP, DNS, TCP, SMTP and usage monitors diff --git a/appwrite/client.py b/appwrite/client.py index c12941fb..2541d7d1 100644 --- a/appwrite/client.py +++ b/appwrite/client.py @@ -20,11 +20,11 @@ def __init__(self): self._endpoint = 'https://cloud.appwrite.io/v1' self._global_headers = { 'content-type': '', - 'user-agent': f'AppwritePythonSDK/28.2.0 ({platform.uname().system}; {platform.uname().version}; {platform.uname().machine})', + 'user-agent': f'AppwritePythonSDK/28.3.0 ({platform.uname().system}; {platform.uname().version}; {platform.uname().machine})', 'x-sdk-name': 'Python', 'x-sdk-platform': 'server', 'x-sdk-language': 'python', - 'x-sdk-version': '28.2.0', + 'x-sdk-version': '28.3.0', 'X-Appwrite-Response-Format': '2.7.2', } self._config = {} diff --git a/appwrite/encoders/value_class_encoder.py b/appwrite/encoders/value_class_encoder.py index 5d1c9d31..7879e992 100644 --- a/appwrite/encoders/value_class_encoder.py +++ b/appwrite/encoders/value_class_encoder.py @@ -57,6 +57,7 @@ from ..enums.project_smtp_secure import ProjectSMTPSecure from ..enums.project_email_template_id import ProjectEmailTemplateId from ..enums.project_email_template_locale import ProjectEmailTemplateLocale +from ..enums.video_codec_id import VideoCodecId from ..enums.invalidation_type import InvalidationType from ..enums.status_code import StatusCode from ..enums.proxy_resource_type import ProxyResourceType @@ -69,6 +70,7 @@ from ..enums.password_hash import PasswordHash from ..enums.messaging_provider_type import MessagingProviderType from ..enums.vectors_db_index_type import VectorsDBIndexType +from ..enums.video_output import VideoOutput from ..enums.database_type import DatabaseType from ..enums.database_status import DatabaseStatus from ..enums.attribute_status import AttributeStatus @@ -100,6 +102,9 @@ from ..enums.proxy_rule_status import ProxyRuleStatus from ..enums.proxy_rule_protocol import ProxyRuleProtocol from ..enums.message_status import MessageStatus +from ..enums.video_timeline_status import VideoTimelineStatus +from ..enums.video_rendition_status import VideoRenditionStatus +from ..enums.video_caption_status import VideoCaptionStatus from ..enums.billing_plan_group import BillingPlanGroup from ..enums.domain_transfer_status_enum import DomainTransferStatusEnum from ..enums.waf_rule_action import WafRuleAction @@ -281,6 +286,9 @@ def default(self, o): if isinstance(o, ProjectEmailTemplateLocale): return o.value + if isinstance(o, VideoCodecId): + return o.value + if isinstance(o, InvalidationType): return o.value @@ -317,6 +325,9 @@ def default(self, o): if isinstance(o, VectorsDBIndexType): return o.value + if isinstance(o, VideoOutput): + return o.value + if isinstance(o, DatabaseType): return o.value @@ -410,6 +421,15 @@ def default(self, o): if isinstance(o, MessageStatus): return o.value + if isinstance(o, VideoTimelineStatus): + return o.value + + if isinstance(o, VideoRenditionStatus): + return o.value + + if isinstance(o, VideoCaptionStatus): + return o.value + if isinstance(o, BillingPlanGroup): return o.value diff --git a/appwrite/enums/video_caption_status.py b/appwrite/enums/video_caption_status.py new file mode 100644 index 00000000..53ddc1e2 --- /dev/null +++ b/appwrite/enums/video_caption_status.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class VideoCaptionStatus(Enum): + PENDING = "pending" + STARTED = "started" + READY = "ready" + ERROR = "error" + ABORTED = "aborted" diff --git a/appwrite/enums/video_codec_id.py b/appwrite/enums/video_codec_id.py new file mode 100644 index 00000000..8efc8ecb --- /dev/null +++ b/appwrite/enums/video_codec_id.py @@ -0,0 +1,7 @@ +from enum import Enum + + +class VideoCodecId(Enum): + H264 = "h264" + HEVC = "hevc" + VP9 = "vp9" diff --git a/appwrite/enums/video_output.py b/appwrite/enums/video_output.py new file mode 100644 index 00000000..693b7bd0 --- /dev/null +++ b/appwrite/enums/video_output.py @@ -0,0 +1,7 @@ +from enum import Enum + + +class VideoOutput(Enum): + HLS = "hls" + DASH = "dash" + CMAF = "cmaf" diff --git a/appwrite/enums/video_rendition_status.py b/appwrite/enums/video_rendition_status.py new file mode 100644 index 00000000..8f3328ad --- /dev/null +++ b/appwrite/enums/video_rendition_status.py @@ -0,0 +1,10 @@ +from enum import Enum + + +class VideoRenditionStatus(Enum): + PENDING = "pending" + STARTED = "started" + ENDED = "ended" + READY = "ready" + ERROR = "error" + ABORTED = "aborted" diff --git a/appwrite/enums/video_timeline_status.py b/appwrite/enums/video_timeline_status.py new file mode 100644 index 00000000..94bd9b78 --- /dev/null +++ b/appwrite/enums/video_timeline_status.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class VideoTimelineStatus(Enum): + PENDING = "pending" + STARTED = "started" + READY = "ready" + SKIPPED = "skipped" + ERROR = "error" diff --git a/appwrite/models/__init__.py b/appwrite/models/__init__.py index d93ffe93..cde02c59 100644 --- a/appwrite/models/__init__.py +++ b/appwrite/models/__init__.py @@ -13,6 +13,11 @@ from .file_list import FileList from .bucket_list import BucketList from .resource_token_list import ResourceTokenList +from .video_list import VideoList +from .video_codec_list import VideoCodecList +from .video_profile_list import VideoProfileList +from .video_rendition_list import VideoRenditionList +from .video_caption_list import VideoCaptionList from .team_list import TeamList from .membership_list import MembershipList from .site_list import SiteList @@ -259,6 +264,11 @@ from .insight import Insight from .insight_cta import InsightCTA from .report import Report +from .video import Video +from .video_codec import VideoCodec +from .video_profile import VideoProfile +from .video_rendition import VideoRendition +from .video_caption import VideoCaption from .activity_event import ActivityEvent from .additional_resource import AdditionalResource from .backup_archive import BackupArchive @@ -366,6 +376,11 @@ 'FileList', 'BucketList', 'ResourceTokenList', + 'VideoList', + 'VideoCodecList', + 'VideoProfileList', + 'VideoRenditionList', + 'VideoCaptionList', 'TeamList', 'MembershipList', 'SiteList', @@ -612,6 +627,11 @@ 'Insight', 'InsightCTA', 'Report', + 'Video', + 'VideoCodec', + 'VideoProfile', + 'VideoRendition', + 'VideoCaption', 'ActivityEvent', 'AdditionalResource', 'BackupArchive', diff --git a/appwrite/models/video.py b/appwrite/models/video.py new file mode 100644 index 00000000..c19a8761 --- /dev/null +++ b/appwrite/models/video.py @@ -0,0 +1,149 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.video_timeline_status import VideoTimelineStatus + + +class Video(AppwriteModel): + """ + Video + + Attributes + ---------- + id : str + Video ID. + createdat : str + Video creation time in ISO 8601 format. + updatedat : str + Video update date in ISO 8601 format. + permissions : List[Any] + Video permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + bucketid : str + Storage bucket ID holding the source file. + fileid : str + Source file ID. + name : str + Video name. + size : float + Source file size in bytes. + format : str + Container format. + duration : float + Video duration in milliseconds. + width : float + Video width in pixels. + height : float + Video height in pixels. + aspectratio : str + Video aspect ratio. + videocodec : str + Video codec. + videoformat : str + Video format. + videoformatprofile : str + Video format profile. + videobitrate : float + Video bitrate in bits per second. + videoframerate : float + Video frame rate in frames per second. + videoframeratemode : str + Video frame rate mode. + audiocodec : str + Audio codec. + audioformat : str + Audio format. + audiobitrate : float + Audio bitrate in bits per second. + audiosamplerate : float + Audio sample rate in hertz. + timelinestatus : VideoTimelineStatus + Thumbnail timeline job status: one of `pending`, `started`, `ready`, `skipped` (source has no video track) or `error`. + timelineerror : str + Why the timeline job failed. Empty unless `timelineStatus` is `error`. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + permissions: List[Any] = Field(..., alias='$permissions') + bucketid: str = Field(..., alias='bucketId') + fileid: str = Field(..., alias='fileId') + name: str = Field(..., alias='name') + size: float = Field(..., alias='size') + format: str = Field(..., alias='format') + duration: float = Field(..., alias='duration') + width: float = Field(..., alias='width') + height: float = Field(..., alias='height') + aspectratio: str = Field(..., alias='aspectRatio') + videocodec: str = Field(..., alias='videoCodec') + videoformat: str = Field(..., alias='videoFormat') + videoformatprofile: str = Field(..., alias='videoFormatProfile') + videobitrate: float = Field(..., alias='videoBitRate') + videoframerate: float = Field(..., alias='videoFrameRate') + videoframeratemode: str = Field(..., alias='videoFrameRateMode') + audiocodec: str = Field(..., alias='audioCodec') + audioformat: str = Field(..., alias='audioFormat') + audiobitrate: float = Field(..., alias='audioBitRate') + audiosamplerate: float = Field(..., alias='audioSampleRate') + timelinestatus: VideoTimelineStatus = Field(..., alias='timelineStatus') + timelineerror: str = Field(..., alias='timelineError') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if '$permissions' not in data and 'permissions' not in data: + data['$permissions'] = [] + if 'bucketId' not in data and 'bucketid' not in data: + data['bucketId'] = '' + if 'fileId' not in data and 'fileid' not in data: + data['fileId'] = '' + if 'name' not in data: + data['name'] = '' + if 'size' not in data: + data['size'] = 0 + if 'format' not in data: + data['format'] = '' + if 'duration' not in data: + data['duration'] = 0 + if 'width' not in data: + data['width'] = 0 + if 'height' not in data: + data['height'] = 0 + if 'aspectRatio' not in data and 'aspectratio' not in data: + data['aspectRatio'] = '' + if 'videoCodec' not in data and 'videocodec' not in data: + data['videoCodec'] = '' + if 'videoFormat' not in data and 'videoformat' not in data: + data['videoFormat'] = '' + if 'videoFormatProfile' not in data and 'videoformatprofile' not in data: + data['videoFormatProfile'] = '' + if 'videoBitRate' not in data and 'videobitrate' not in data: + data['videoBitRate'] = 0 + if 'videoFrameRate' not in data and 'videoframerate' not in data: + data['videoFrameRate'] = 0 + if 'videoFrameRateMode' not in data and 'videoframeratemode' not in data: + data['videoFrameRateMode'] = '' + if 'audioCodec' not in data and 'audiocodec' not in data: + data['audioCodec'] = '' + if 'audioFormat' not in data and 'audioformat' not in data: + data['audioFormat'] = '' + if 'audioBitRate' not in data and 'audiobitrate' not in data: + data['audioBitRate'] = 0 + if 'audioSampleRate' not in data and 'audiosamplerate' not in data: + data['audioSampleRate'] = 0 + if 'timelineStatus' not in data and 'timelinestatus' not in data: + data['timelineStatus'] = 'pending' + if 'timelineError' not in data and 'timelineerror' not in data: + data['timelineError'] = '' + return data diff --git a/appwrite/models/video_caption.py b/appwrite/models/video_caption.py new file mode 100644 index 00000000..386c2f8b --- /dev/null +++ b/appwrite/models/video_caption.py @@ -0,0 +1,94 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.video_caption_status import VideoCaptionStatus + + +class VideoCaption(AppwriteModel): + """ + Video caption + + Attributes + ---------- + id : str + Caption ID. + createdat : str + Caption creation time in ISO 8601 format. + updatedat : str + Caption update date in ISO 8601 format. + videoid : str + Video ID. + bucketid : str + Storage bucket ID holding the caption file. + fileid : str + Caption file ID. + name : str + Caption display name. + language : str + Caption ISO 639-2 language code. + default : bool + Is this the default caption track? + embedded : bool + Was this track auto-extracted from the source container? Extracted tracks have no backing file; extraction runs once per video, so a deleted extracted track is not re-created. + targetduration : float + Longest segment duration in seconds. + status : VideoCaptionStatus + Packaging status: one of `pending`, `started`, `ready`, `error` or `aborted`. + error : str + Why the caption failed or was aborted. Empty unless `status` is `error` or `aborted`. + size : float + Stored caption size in bytes. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + videoid: str = Field(..., alias='videoId') + bucketid: str = Field(..., alias='bucketId') + fileid: str = Field(..., alias='fileId') + name: str = Field(..., alias='name') + language: str = Field(..., alias='language') + default: bool = Field(..., alias='default') + embedded: bool = Field(..., alias='embedded') + targetduration: float = Field(..., alias='targetDuration') + status: VideoCaptionStatus = Field(..., alias='status') + error: str = Field(..., alias='error') + size: float = Field(..., alias='size') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'videoId' not in data and 'videoid' not in data: + data['videoId'] = '' + if 'bucketId' not in data and 'bucketid' not in data: + data['bucketId'] = '' + if 'fileId' not in data and 'fileid' not in data: + data['fileId'] = '' + if 'name' not in data: + data['name'] = '' + if 'language' not in data: + data['language'] = '' + if 'default' not in data: + data['default'] = False + if 'embedded' not in data: + data['embedded'] = False + if 'targetDuration' not in data and 'targetduration' not in data: + data['targetDuration'] = 0 + if 'status' not in data: + data['status'] = 'pending' + if 'error' not in data: + data['error'] = '' + if 'size' not in data: + data['size'] = 0 + return data diff --git a/appwrite/models/video_caption_list.py b/appwrite/models/video_caption_list.py new file mode 100644 index 00000000..4030b287 --- /dev/null +++ b/appwrite/models/video_caption_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .video_caption import VideoCaption + + +class VideoCaptionList(AppwriteModel): + """ + Video Captions List + + Attributes + ---------- + total : float + Total number of captions that matched your query. + captions : List[VideoCaption] + List of captions. + """ + + total: float = Field(..., alias='total') + captions: List[VideoCaption] = Field(..., alias='captions') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'captions' not in data: + data['captions'] = [] + return data diff --git a/appwrite/models/video_codec.py b/appwrite/models/video_codec.py new file mode 100644 index 00000000..e6ece380 --- /dev/null +++ b/appwrite/models/video_codec.py @@ -0,0 +1,39 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.video_output import VideoOutput + + +class VideoCodec(AppwriteModel): + """ + Video codec + + Attributes + ---------- + id : str + Codec ID. + name : str + Codec display name. + outputs : List[VideoOutput] + Streaming output formats this codec may be packaged into. + """ + + id: str = Field(..., alias='$id') + name: str = Field(..., alias='name') + outputs: List[VideoOutput] = Field(..., alias='outputs') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if 'name' not in data: + data['name'] = '' + if 'outputs' not in data: + data['outputs'] = [] + return data diff --git a/appwrite/models/video_codec_list.py b/appwrite/models/video_codec_list.py new file mode 100644 index 00000000..16b6cb85 --- /dev/null +++ b/appwrite/models/video_codec_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .video_codec import VideoCodec + + +class VideoCodecList(AppwriteModel): + """ + Video Codecs List + + Attributes + ---------- + total : float + Total number of codecs that matched your query. + codecs : List[VideoCodec] + List of codecs. + """ + + total: float = Field(..., alias='total') + codecs: List[VideoCodec] = Field(..., alias='codecs') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'codecs' not in data: + data['codecs'] = [] + return data diff --git a/appwrite/models/video_list.py b/appwrite/models/video_list.py new file mode 100644 index 00000000..fbabf294 --- /dev/null +++ b/appwrite/models/video_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .video import Video + + +class VideoList(AppwriteModel): + """ + Videos List + + Attributes + ---------- + total : float + Total number of videos that matched your query. + videos : List[Video] + List of videos. + """ + + total: float = Field(..., alias='total') + videos: List[Video] = Field(..., alias='videos') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'videos' not in data: + data['videos'] = [] + return data diff --git a/appwrite/models/video_profile.py b/appwrite/models/video_profile.py new file mode 100644 index 00000000..111d2493 --- /dev/null +++ b/appwrite/models/video_profile.py @@ -0,0 +1,69 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.video_codec_id import VideoCodecId + + +class VideoProfile(AppwriteModel): + """ + Video profile + + Attributes + ---------- + id : str + Video profile ID. + createdat : str + Video profile creation time in ISO 8601 format. + updatedat : str + Video profile update date in ISO 8601 format. + name : str + Video profile name. + codec : VideoCodecId + Video encode codec: one of `h264`, `hevc`, or `vp9`. + videobitrate : float + Target video bitrate in bits per second. + audiobitrate : float + Target audio bitrate in bits per second. + width : float + Target video width in pixels. + height : float + Target video height in pixels. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + name: str = Field(..., alias='name') + codec: VideoCodecId = Field(..., alias='codec') + videobitrate: float = Field(..., alias='videoBitRate') + audiobitrate: float = Field(..., alias='audioBitRate') + width: float = Field(..., alias='width') + height: float = Field(..., alias='height') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'name' not in data: + data['name'] = '' + if 'codec' not in data: + data['codec'] = 'h264' + if 'videoBitRate' not in data and 'videobitrate' not in data: + data['videoBitRate'] = 0 + if 'audioBitRate' not in data and 'audiobitrate' not in data: + data['audioBitRate'] = 0 + if 'width' not in data: + data['width'] = 0 + if 'height' not in data: + data['height'] = 0 + return data diff --git a/appwrite/models/video_profile_list.py b/appwrite/models/video_profile_list.py new file mode 100644 index 00000000..6040d738 --- /dev/null +++ b/appwrite/models/video_profile_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .video_profile import VideoProfile + + +class VideoProfileList(AppwriteModel): + """ + Video Profiles List + + Attributes + ---------- + total : float + Total number of profiles that matched your query. + profiles : List[VideoProfile] + List of profiles. + """ + + total: float = Field(..., alias='total') + profiles: List[VideoProfile] = Field(..., alias='profiles') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'profiles' not in data: + data['profiles'] = [] + return data diff --git a/appwrite/models/video_rendition.py b/appwrite/models/video_rendition.py new file mode 100644 index 00000000..c10cdbd4 --- /dev/null +++ b/appwrite/models/video_rendition.py @@ -0,0 +1,121 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.video_rendition_status import VideoRenditionStatus +from ..enums.video_output import VideoOutput +from ..enums.video_codec_id import VideoCodecId + + +class VideoRendition(AppwriteModel): + """ + Video rendition + + Attributes + ---------- + id : str + Rendition ID. + createdat : str + Rendition creation time in ISO 8601 format. + updatedat : str + Rendition update date in ISO 8601 format. + videoid : str + Video ID. + profileid : str + Video profile ID this rendition was encoded against. + name : str + Rendition name, derived from its dimensions and bitrate. + startedat : str + Transcoding start time in ISO 8601 format. + endedat : str + Transcoding end time in ISO 8601 format. + width : float + Rendition width in pixels. + height : float + Rendition height in pixels. + videobitrate : float + Video bitrate in bits per second. + audiobitrate : float + Audio bitrate in bits per second. + targetduration : float + Longest segment duration in seconds. + status : VideoRenditionStatus + Transcoding status: one of `pending`, `started`, `ended`, `ready`, `error` or `aborted`. + error : str + Why the rendition failed or was aborted. Empty unless `status` is `error` or `aborted`. + progress : float + Transcoding progress as a percentage, from 0 to 100. + output : VideoOutput + Streaming output format: `hls`, `dash`, or `cmaf`. + codec : VideoCodecId + Video encode codec snapshotted from the profile at create time: one of `h264`, `hevc`, or `vp9`. + size : float + Stored rendition size in bytes. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + videoid: str = Field(..., alias='videoId') + profileid: str = Field(..., alias='profileId') + name: str = Field(..., alias='name') + startedat: str = Field(..., alias='startedAt') + endedat: str = Field(..., alias='endedAt') + width: float = Field(..., alias='width') + height: float = Field(..., alias='height') + videobitrate: float = Field(..., alias='videoBitRate') + audiobitrate: float = Field(..., alias='audioBitRate') + targetduration: float = Field(..., alias='targetDuration') + status: VideoRenditionStatus = Field(..., alias='status') + error: str = Field(..., alias='error') + progress: float = Field(..., alias='progress') + output: VideoOutput = Field(..., alias='output') + codec: VideoCodecId = Field(..., alias='codec') + size: float = Field(..., alias='size') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'videoId' not in data and 'videoid' not in data: + data['videoId'] = '' + if 'profileId' not in data and 'profileid' not in data: + data['profileId'] = '' + if 'name' not in data: + data['name'] = '' + if 'startedAt' not in data and 'startedat' not in data: + data['startedAt'] = '' + if 'endedAt' not in data and 'endedat' not in data: + data['endedAt'] = '' + if 'width' not in data: + data['width'] = 0 + if 'height' not in data: + data['height'] = 0 + if 'videoBitRate' not in data and 'videobitrate' not in data: + data['videoBitRate'] = 0 + if 'audioBitRate' not in data and 'audiobitrate' not in data: + data['audioBitRate'] = 0 + if 'targetDuration' not in data and 'targetduration' not in data: + data['targetDuration'] = 0 + if 'status' not in data: + data['status'] = 'pending' + if 'error' not in data: + data['error'] = '' + if 'progress' not in data: + data['progress'] = 0 + if 'output' not in data: + data['output'] = 'hls' + if 'codec' not in data: + data['codec'] = 'h264' + if 'size' not in data: + data['size'] = 0 + return data diff --git a/appwrite/models/video_rendition_list.py b/appwrite/models/video_rendition_list.py new file mode 100644 index 00000000..db376ee0 --- /dev/null +++ b/appwrite/models/video_rendition_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .video_rendition import VideoRendition + + +class VideoRenditionList(AppwriteModel): + """ + Video Renditions List + + Attributes + ---------- + total : float + Total number of renditions that matched your query. + renditions : List[VideoRendition] + List of renditions. + """ + + total: float = Field(..., alias='total') + renditions: List[VideoRendition] = Field(..., alias='renditions') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'renditions' not in data: + data['renditions'] = [] + return data diff --git a/appwrite/services/project.py b/appwrite/services/project.py index 9d39f3b5..141bf09f 100644 --- a/appwrite/services/project.py +++ b/appwrite/services/project.py @@ -127,6 +127,9 @@ from ..models.email_template import EmailTemplate from ..models.variable_list import VariableList from ..models.variable import Variable +from ..models.video_profile_list import VideoProfileList +from ..enums.video_codec_id import VideoCodecId +from ..models.video_profile import VideoProfile T = TypeVar('T') @@ -7635,3 +7638,270 @@ def delete_variable( ) return response + + def list_video_profiles( + self, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> VideoProfileList: + """ + Get a list of video profiles in the current project (`GET /v1/project/videos/profiles`). Every profile is returned regardless of codec. Filter with `queries`, for example `Query.equal('codec', ['h264'])` for one encode ladder, or on `name`, `width`, `height`, `videoBitRate` and `audioBitRate`. Search with `Query.search()` on the `search` attribute. + + Parameters + ---------- + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, codec, width, height, videoBitRate, audioBitRate, search + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + VideoProfileList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/project/videos/profiles' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoProfileList) + + def create_video_profile( + self, + profile_id: str, + name: str, + video_bit_rate: float, + audio_bit_rate: float, + width: float, + height: float, + codec: Optional[VideoCodecId] = None, + ) -> VideoProfile: + """ + Create a video profile (`POST /v1/project/videos/profiles`) describing an encoding target: output dimensions, video/audio bitrates, and encode codec. Only codecs enabled on this instance are accepted; the default is `h264`. A disabled codec is rejected. Creating a profile with the same width, height, bitrates, and codec fails with `video_profile_already_exists`. Bitrates are in bits per second and must be multiples of 1000. Renditions are encoded against a profile. + + Parameters + ---------- + profile_id : str + Video profile ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Video profile name. + video_bit_rate : float + Target video bitrate in bits per second. Must be a multiple of 1000. + audio_bit_rate : float + Target audio bitrate in bits per second. Must be a multiple of 1000. + width : float + Target video width in pixels. Must be an even number. + height : float + Target video height in pixels. Must be an even number. + codec : Optional[VideoCodecId] + Video encode codec. Codecs not enabled on this instance are rejected. Defaults to `h264`. + Returns + ------- + VideoProfile + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/project/videos/profiles' + api_params = {} + if profile_id is None: + raise AppwriteException('Missing required parameter: "profile_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if video_bit_rate is None: + raise AppwriteException('Missing required parameter: "video_bit_rate"') + if audio_bit_rate is None: + raise AppwriteException('Missing required parameter: "audio_bit_rate"') + if width is None: + raise AppwriteException('Missing required parameter: "width"') + if height is None: + raise AppwriteException('Missing required parameter: "height"') + api_params['profileId'] = self._normalize_value(profile_id) + api_params['name'] = self._normalize_value(name) + api_params['videoBitRate'] = self._normalize_value(video_bit_rate) + api_params['audioBitRate'] = self._normalize_value(audio_bit_rate) + api_params['width'] = self._normalize_value(width) + api_params['height'] = self._normalize_value(height) + if codec is not None: + api_params['codec'] = self._normalize_value(codec) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoProfile) + + def get_video_profile( + self, + profile_id: str, + ) -> VideoProfile: + """ + Get a video profile by its unique ID (`GET /v1/project/videos/profiles/:profileId`). + + Parameters + ---------- + profile_id : str + Video profile unique ID. + Returns + ------- + VideoProfile + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/project/videos/profiles/{profileId}' + api_params = {} + if profile_id is None or profile_id == '': + raise AppwriteException('Missing required parameter: "profile_id"') + api_path = api_path.replace('{profileId}', self._encode_path(profile_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoProfile) + + def update_video_profile( + self, + profile_id: str, + name: Optional[str] = None, + video_bit_rate: Optional[float] = None, + audio_bit_rate: Optional[float] = None, + width: Optional[float] = None, + height: Optional[float] = None, + ) -> VideoProfile: + """ + Update a video profile by its unique ID (`PATCH /v1/project/videos/profiles/:profileId`). Existing renditions are not re-encoded. Changing the profile onto the same width, height, bitrates, and codec as another profile fails with `video_profile_already_exists`. + + Parameters + ---------- + profile_id : str + Video profile unique ID. + name : Optional[str] + Video profile name. + video_bit_rate : Optional[float] + Target video bitrate in bits per second. Must be a multiple of 1000. + audio_bit_rate : Optional[float] + Target audio bitrate in bits per second. Must be a multiple of 1000. + width : Optional[float] + Target video width in pixels. Must be an even number. + height : Optional[float] + Target video height in pixels. Must be an even number. + Returns + ------- + VideoProfile + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/project/videos/profiles/{profileId}' + api_params = {} + if profile_id is None or profile_id == '': + raise AppwriteException('Missing required parameter: "profile_id"') + api_path = api_path.replace('{profileId}', self._encode_path(profile_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if video_bit_rate is not None: + api_params['videoBitRate'] = self._normalize_value(video_bit_rate) + if audio_bit_rate is not None: + api_params['audioBitRate'] = self._normalize_value(audio_bit_rate) + if width is not None: + api_params['width'] = self._normalize_value(width) + if height is not None: + api_params['height'] = self._normalize_value(height) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoProfile) + + def delete_video_profile( + self, + profile_id: str, + ) -> Dict[str, Any]: + """ + Delete a video profile by its unique ID (`DELETE /v1/project/videos/profiles/:profileId`). Renditions already encoded against it are left in place. + + Parameters + ---------- + profile_id : str + Video profile unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/project/videos/profiles/{profileId}' + api_params = {} + if profile_id is None or profile_id == '': + raise AppwriteException('Missing required parameter: "profile_id"') + api_path = api_path.replace('{profileId}', self._encode_path(profile_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response diff --git a/appwrite/services/videos.py b/appwrite/services/videos.py new file mode 100644 index 00000000..db6074e9 --- /dev/null +++ b/appwrite/services/videos.py @@ -0,0 +1,1076 @@ +from ..service import Service +from urllib.parse import quote +from typing import Any, Dict, List, Optional, Union +from ..exception import AppwriteException +from appwrite.utils.deprecated import deprecated +from ..models.video_list import VideoList +from ..models.video import Video +from ..models.video_codec_list import VideoCodecList +from ..models.video_caption_list import VideoCaptionList +from ..models.video_caption import VideoCaption +from ..enums.video_output import VideoOutput +from ..models.video_rendition_list import VideoRenditionList +from ..models.video_rendition import VideoRendition +from ..enums.image_format import ImageFormat + + +class Videos(Service): + + def __init__(self, client) -> None: + super(Videos, self).__init__(client) + + def list( + self, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> VideoList: + """ + Get a list of videos in the current project. Sessions receive only videos they can read according to each video's `$permissions`. API keys and admins receive the full project catalog. Playback uses the same document read ACL plus the `videos.play` (or `videos.read`) scope: a guest can stream a video that grants `read("any")` or `read("guests")` even though guests lack `videos.read` and will not see it in this list. + + Parameters + ---------- + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: bucketId, fileId, name, size, format, duration, width, height, videoCodec, videoBitRate, audioCodec, audioBitRate, search + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + VideoList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoList) + + def create( + self, + video_id: str, + bucket_id: str, + file_id: str, + name: Optional[str] = None, + permissions: Optional[List[str]] = None, + ) -> Video: + """ + Create a video resource from an existing file in a storage bucket. The source file must be a video or audio file, and the caller must be able to read that file. Creating a video stores the document and queues timeline generation. The worker downloads the source, probes metadata, extracts embedded captions once, and deletes its working copy when finished. Sources with a video track also get a thumbnail timeline. Call create-rendition to package a streaming output. + + An optional `name` defaults to the source file name. An optional `permissions` array sets the video document ACL (list, get, update, delete, manage child resources, and playback). By default, only the current user is granted all permissions; API keys and admins create with empty permissions when omitted. Guests with `videos.play` can stream when the video grants them read (`read("any")` or `read("guests")`). + + Uploaded caption files stay listed alongside auto-extracted tracks for the same language; when the current default is an auto-extracted track with that code, the upload takes the default flag. + + Parameters + ---------- + video_id : str + Video ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + bucket_id : str + Storage bucket unique ID holding the source file. + file_id : str + Source file unique ID. + name : Optional[str] + Video name. Defaults to the source file name. Max length: 2048 chars. + permissions : Optional[List[str]] + An array of permission strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + Returns + ------- + Video + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos' + api_params = {} + if video_id is None: + raise AppwriteException('Missing required parameter: "video_id"') + if bucket_id is None: + raise AppwriteException('Missing required parameter: "bucket_id"') + if file_id is None: + raise AppwriteException('Missing required parameter: "file_id"') + api_params['videoId'] = self._normalize_value(video_id) + api_params['bucketId'] = self._normalize_value(bucket_id) + api_params['fileId'] = self._normalize_value(file_id) + if name is not None: + api_params['name'] = self._normalize_value(name) + if permissions is not None: + api_params['permissions'] = self._normalize_value(permissions) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Video) + + def list_codecs( + self, + ) -> VideoCodecList: + """ + Get a list of video encode codecs enabled on this instance. Each codec includes the output formats it may be packaged into. + Returns + ------- + VideoCodecList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/codecs' + api_params = {} + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoCodecList) + + def get( + self, + video_id: str, + ) -> Video: + """ + Get a video by its unique ID. This endpoint response returns a JSON object with the video metadata. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + Video + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Video) + + def update( + self, + video_id: str, + name: Optional[str] = None, + permissions: Optional[List[str]] = None, + ) -> Video: + """ + Update a video's name, permissions, or both. Only the fields you pass are changed: omit `name` to keep the current name and `permissions` to keep the current ACL. The caller must hold update permission on the video document. The source file cannot be replaced; delete the video and create a new one to point at a different file. + + Parameters + ---------- + video_id : str + Video unique ID. + name : Optional[str] + Video name. Max length: 2048 chars. + permissions : Optional[List[str]] + An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + Returns + ------- + Video + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if permissions is not None: + api_params['permissions'] = self._normalize_value(permissions) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Video) + + def delete( + self, + video_id: str, + ) -> Dict[str, Any]: + """ + Delete a video by its unique ID. This also removes every rendition, caption, preview and transcoded artifact derived from it. Fails with `video_rendition_in_progress` while a rendition is started or ended, unless that rendition has not been updated within the rendition retention window. Fails with `video_timeline_in_progress` while the video's timeline is being generated, unless the video has not been updated within the same window. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response + + def list_captions( + self, + video_id: str, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> VideoCaptionList: + """ + Get a list of all the caption tracks attached to a video. You can use the query params to filter your results. + + Parameters + ---------- + video_id : str + Video unique ID. + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, language, default, status, size, bucketId, fileId + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + VideoCaptionList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/captions' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoCaptionList) + + def create_caption( + self, + video_id: str, + bucket_id: str, + file_id: str, + name: str, + language: str, + default: Optional[bool] = None, + ) -> VideoCaption: + """ + Add a caption track to a video from a WebVTT or SubRip file in a storage bucket. The file is normalised to WebVTT and segmented in the background. Subscribe to `videos.[videoId].captions.[captionId].update` for `started`, `ready`, and `error` status changes instead of only polling the caption document. + + Uploaded tracks are listed alongside auto-extracted embedded tracks (`embedded: true`). When the current default is an auto-extracted track for the same language code, the upload takes the default flag so players pick the authored file first. Auto-extracted tracks are never removed automatically — delete a track explicitly to remove it. Extraction runs once per video, so a deleted extracted track is not re-created. + + Parameters + ---------- + video_id : str + Video unique ID. + bucket_id : str + Storage bucket unique ID holding the caption file. + file_id : str + Caption file unique ID. + name : str + Caption display name. Allowed characters: a-z, A-Z, 0-9, space, and - . , ( ) _ ' + language : str + Caption ISO 639-2 three-letter language code. + default : Optional[bool] + Make this the default caption track for the video. + Returns + ------- + VideoCaption + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/captions' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if bucket_id is None: + raise AppwriteException('Missing required parameter: "bucket_id"') + if file_id is None: + raise AppwriteException('Missing required parameter: "file_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if language is None: + raise AppwriteException('Missing required parameter: "language"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_params['bucketId'] = self._normalize_value(bucket_id) + api_params['fileId'] = self._normalize_value(file_id) + api_params['name'] = self._normalize_value(name) + api_params['language'] = self._normalize_value(language) + if default is not None: + api_params['default'] = self._normalize_value(default) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoCaption) + + def update_caption( + self, + video_id: str, + caption_id: str, + bucket_id: Optional[str] = None, + file_id: Optional[str] = None, + name: Optional[str] = None, + language: Optional[str] = None, + default: Optional[bool] = None, + ) -> VideoCaption: + """ + Update a caption track by its unique ID. Pass only `name`, `language`, and/or `default` to retag an extracted track (for example `und` → `heb` for Hebrew) without replacing the file. Changing `bucketId`/`fileId` re-packages the track in the background. + + Parameters + ---------- + video_id : str + Video unique ID. + caption_id : str + Caption unique ID. + bucket_id : Optional[str] + Storage bucket unique ID holding the caption file. Omit together with fileId to only update name, language, or default. + file_id : Optional[str] + Caption file unique ID. Omit together with bucketId to only update name, language, or default. + name : Optional[str] + Caption display name. Allowed characters: a-z, A-Z, 0-9, space, and - . , ( ) _ ' + language : Optional[str] + Caption ISO 639-2 three-letter language code (for example `heb` for Hebrew). + default : Optional[bool] + Make this the default caption track for the video. Omit to leave unchanged. + Returns + ------- + VideoCaption + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/captions/{captionId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if caption_id is None or caption_id == '': + raise AppwriteException('Missing required parameter: "caption_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{captionId}', self._encode_path(caption_id)) + if bucket_id is not None: + api_params['bucketId'] = self._normalize_value(bucket_id) + if file_id is not None: + api_params['fileId'] = self._normalize_value(file_id) + if name is not None: + api_params['name'] = self._normalize_value(name) + if language is not None: + api_params['language'] = self._normalize_value(language) + if default is not None: + api_params['default'] = self._normalize_value(default) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoCaption) + + def delete_caption( + self, + video_id: str, + caption_id: str, + ) -> Dict[str, Any]: + """ + Delete a caption track by its unique ID, along with its packaged segments. + + Parameters + ---------- + video_id : str + Video unique ID. + caption_id : str + Caption unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/captions/{captionId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if caption_id is None or caption_id == '': + raise AppwriteException('Missing required parameter: "caption_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{captionId}', self._encode_path(caption_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response + + def get_cmaf_hls_manifest( + self, + video_id: str, + ) -> bytes: + """ + Get the top-level streaming manifest for a video output: an HLS master playlist (`master.m3u8`) or a DASH MPD (`master.mpd`). Hand this URL to a player to begin adaptive playback. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. A video with `read("any")` or `read("guests")` is playable without a session. + + For CMAF renditions, use `getCmafHlsManifest` or `getCmafDashManifest`. Both masters point at the same fMP4 segment set. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/outputs/cmaf/master.m3u8' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response + + def get_cmaf_dash_manifest( + self, + video_id: str, + ) -> bytes: + """ + Get the top-level streaming manifest for a video output: an HLS master playlist (`master.m3u8`) or a DASH MPD (`master.mpd`). Hand this URL to a player to begin adaptive playback. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. A video with `read("any")` or `read("guests")` is playable without a session. + + For CMAF renditions, use `getCmafHlsManifest` or `getCmafDashManifest`. Both masters point at the same fMP4 segment set. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/outputs/cmaf/master.mpd' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response + + def get_dash_manifest( + self, + video_id: str, + ) -> bytes: + """ + Get the top-level streaming manifest for a video output: an HLS master playlist (`master.m3u8`) or a DASH MPD (`master.mpd`). Hand this URL to a player to begin adaptive playback. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. A video with `read("any")` or `read("guests")` is playable without a session. + + For CMAF renditions, use `getCmafHlsManifest` or `getCmafDashManifest`. Both masters point at the same fMP4 segment set. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/outputs/dash/master.mpd' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response + + def get_hls_manifest( + self, + video_id: str, + ) -> bytes: + """ + Get the top-level streaming manifest for a video output: an HLS master playlist (`master.m3u8`) or a DASH MPD (`master.mpd`). Hand this URL to a player to begin adaptive playback. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. A video with `read("any")` or `read("guests")` is playable without a session. + + For CMAF renditions, use `getCmafHlsManifest` or `getCmafDashManifest`. Both masters point at the same fMP4 segment set. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/outputs/hls/master.m3u8' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response + + def get_caption_manifest( + self, + video_id: str, + output: VideoOutput, + caption_id: str, + ) -> bytes: + """ + Get the playable caption resource for a video output: an HLS captions playlist, or the WebVTT file itself for DASH. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. + + Parameters + ---------- + video_id : str + Video unique ID. + output : VideoOutput + Streaming output format. + caption_id : str + Caption unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/outputs/{output}/captions/{captionId}/manifest' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if output is None: + raise AppwriteException('Missing required parameter: "output"') + if caption_id is None or caption_id == '': + raise AppwriteException('Missing required parameter: "caption_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{output}', self._encode_path(output)) + api_path = api_path.replace('{captionId}', self._encode_path(caption_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response + + def list_renditions( + self, + video_id: str, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> VideoRenditionList: + """ + Get a list of all the renditions of a video. You can use the query params to filter your results. + + Parameters + ---------- + video_id : str + Video unique ID. + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: profileId, name, status, output, codec, width, height, videoBitRate, audioBitRate, size, startedAt, endedAt + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + VideoRenditionList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/renditions' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoRenditionList) + + def create_rendition( + self, + video_id: str, + profile_id: str, + output: VideoOutput, + ) -> VideoRendition: + """ + Request a new rendition of a video, encoded against a video profile and packaged for HLS, DASH, or CMAF. The rendition is created immediately with a `pending` status and transcoded in the background; poll it or subscribe to realtime events to follow its progress. The worker downloads the source file for this job, probes metadata and extracts embedded captions when needed, then deletes the working copy when the job ends. + + The profile codec must be enabled on this instance. A disabled codec fails with `video_codec_disabled`. + + Each video may have only one rendition per profile and output combination. Creating a duplicate fails with `video_rendition_already_exists`. After an encode fails or is aborted, delete the rendition and create it again. The same profile may still be encoded for different outputs (for example HLS and DASH). + + A video accepts 10 rendition creates per hour. The next create returns `general_rate_limit_exceeded`. + + CMAF packs shared fMP4 segments once and exposes both HLS (`/outputs/cmaf/master.m3u8`) and DASH (`/outputs/cmaf/master.mpd`) masters for the same encode. + + Renditions can only be created from the Console or a server SDK with an API key that has the `videos.write` scope. Each encode spends the project's compute, so client sessions receive `user_unauthorized`. + + Parameters + ---------- + video_id : str + Video unique ID. + profile_id : str + Video profile unique ID to encode against. + output : VideoOutput + Streaming output format to package as. + Returns + ------- + VideoRendition + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/renditions' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if profile_id is None: + raise AppwriteException('Missing required parameter: "profile_id"') + if output is None: + raise AppwriteException('Missing required parameter: "output"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_params['profileId'] = self._normalize_value(profile_id) + api_params['output'] = self._normalize_value(output) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoRendition) + + def get_rendition( + self, + video_id: str, + rendition_id: str, + ) -> VideoRendition: + """ + Get a rendition by its unique ID, including its current transcoding status and progress. + + Parameters + ---------- + video_id : str + Video unique ID. + rendition_id : str + Rendition unique ID. + Returns + ------- + VideoRendition + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/renditions/{renditionId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if rendition_id is None or rendition_id == '': + raise AppwriteException('Missing required parameter: "rendition_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{renditionId}', self._encode_path(rendition_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=VideoRendition) + + def delete_rendition( + self, + video_id: str, + rendition_id: str, + ) -> Dict[str, Any]: + """ + Delete a rendition by its unique ID, along with its packaged segments and transcoded output. Fails with `video_rendition_in_progress` while the rendition is started or ended, unless it has not been updated within the rendition retention window. + + Parameters + ---------- + video_id : str + Video unique ID. + rendition_id : str + Rendition unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/renditions/{renditionId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if rendition_id is None or rendition_id == '': + raise AppwriteException('Missing required parameter: "rendition_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{renditionId}', self._encode_path(rendition_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response + + def get_thumbnail( + self, + video_id: str, + thumbnail_id: str, + width: Optional[float] = None, + height: Optional[float] = None, + output: Optional[ImageFormat] = None, + ) -> bytes: + """ + Get a single thumbnail sheet from a video's timeline as an image. You can resize the returned image and choose its output format. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. + + Parameters + ---------- + video_id : str + Video unique ID. + thumbnail_id : str + Thumbnail unique ID. + width : Optional[float] + Resize thumbnail image width, in pixels. + height : Optional[float] + Resize thumbnail image height, in pixels. + output : Optional[ImageFormat] + Output format type (jpeg, jpg, png, gif and webp). + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/thumbnails/{thumbnailId}' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + if thumbnail_id is None or thumbnail_id == '': + raise AppwriteException('Missing required parameter: "thumbnail_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + api_path = api_path.replace('{thumbnailId}', self._encode_path(thumbnail_id)) + if width is not None: + api_params['width'] = self._normalize_value(width) + if height is not None: + api_params['height'] = self._normalize_value(height) + if output is not None: + api_params['output'] = self._normalize_value(output) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'image/*', + }, + api_params, + ) + + return response + + def get_timeline( + self, + video_id: str, + ) -> bytes: + """ + Get the WebVTT thumbnail timeline for a video, used to render scrubbing thumbnails in a player. Timeline generation is queued when the video is created. Subscribe to `videos.[videoId].timelines.update` for probe and terminal updates, or poll this endpoint until it returns a WebVTT document. Audio-only sources produce no timeline and this endpoint returns `video_timelines_not_found`. + + Guests can request this URL when they hold `videos.play` (or `videos.read`) **and** the video document grants them read. A video with `read("any")` or `read("guests")` is playable without a session. + + Parameters + ---------- + video_id : str + Video unique ID. + Returns + ------- + bytes + Response as bytes + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/videos/{videoId}/timeline' + api_params = {} + if video_id is None or video_id == '': + raise AppwriteException('Missing required parameter: "video_id"') + api_path = api_path.replace('{videoId}', self._encode_path(video_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': '*/*', + }, + api_params, + ) + + return response diff --git a/docs/examples/project/create-video-profile.md b/docs/examples/project/create-video-profile.md new file mode 100644 index 00000000..26afad95 --- /dev/null +++ b/docs/examples/project/create-video-profile.md @@ -0,0 +1,25 @@ +```python +from appwrite.client import Client +from appwrite.services.project import Project +from appwrite.models import VideoProfile +from appwrite.enums.video_codec_id import VideoCodecId + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +project = Project(client) + +result: VideoProfile = project.create_video_profile( + profile_id = '', + name = '', + video_bit_rate = 32000, + audio_bit_rate = 32000, + width = 16, + height = 16, + codec = VideoCodecId.H264 # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/project/delete-video-profile.md b/docs/examples/project/delete-video-profile.md new file mode 100644 index 00000000..f0afc471 --- /dev/null +++ b/docs/examples/project/delete-video-profile.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.project import Project + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +project = Project(client) + +result = project.delete_video_profile( + profile_id = '' +) +``` diff --git a/docs/examples/project/get-video-profile.md b/docs/examples/project/get-video-profile.md new file mode 100644 index 00000000..b2497343 --- /dev/null +++ b/docs/examples/project/get-video-profile.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.project import Project +from appwrite.models import VideoProfile + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +project = Project(client) + +result: VideoProfile = project.get_video_profile( + profile_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/project/list-video-profiles.md b/docs/examples/project/list-video-profiles.md new file mode 100644 index 00000000..3e2575e9 --- /dev/null +++ b/docs/examples/project/list-video-profiles.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.project import Project +from appwrite.models import VideoProfileList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +project = Project(client) + +result: VideoProfileList = project.list_video_profiles( + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/project/update-video-profile.md b/docs/examples/project/update-video-profile.md new file mode 100644 index 00000000..04962a57 --- /dev/null +++ b/docs/examples/project/update-video-profile.md @@ -0,0 +1,23 @@ +```python +from appwrite.client import Client +from appwrite.services.project import Project +from appwrite.models import VideoProfile + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +project = Project(client) + +result: VideoProfile = project.update_video_profile( + profile_id = '', + name = '', # optional + video_bit_rate = 32000, # optional + audio_bit_rate = 32000, # optional + width = 16, # optional + height = 16 # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/create-caption.md b/docs/examples/videos/create-caption.md new file mode 100644 index 00000000..4cffc847 --- /dev/null +++ b/docs/examples/videos/create-caption.md @@ -0,0 +1,23 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoCaption + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoCaption = videos.create_caption( + video_id = '', + bucket_id = '', + file_id = '', + name = '', + language = 'aar', + default = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/create-rendition.md b/docs/examples/videos/create-rendition.md new file mode 100644 index 00000000..69c65bd3 --- /dev/null +++ b/docs/examples/videos/create-rendition.md @@ -0,0 +1,21 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoRendition +from appwrite.enums.video_output import VideoOutput + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +videos = Videos(client) + +result: VideoRendition = videos.create_rendition( + video_id = '', + profile_id = '', + output = VideoOutput.HLS +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/create.md b/docs/examples/videos/create.md new file mode 100644 index 00000000..9b399e63 --- /dev/null +++ b/docs/examples/videos/create.md @@ -0,0 +1,24 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import Video +from appwrite.permission import Permission +from appwrite.role import Role + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: Video = videos.create( + video_id = '', + bucket_id = '', + file_id = '', + name = '', # optional + permissions = [Permission.read(Role.any())] # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/delete-caption.md b/docs/examples/videos/delete-caption.md new file mode 100644 index 00000000..7099c83c --- /dev/null +++ b/docs/examples/videos/delete-caption.md @@ -0,0 +1,16 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result = videos.delete_caption( + video_id = '', + caption_id = '' +) +``` diff --git a/docs/examples/videos/delete-rendition.md b/docs/examples/videos/delete-rendition.md new file mode 100644 index 00000000..d5f25f37 --- /dev/null +++ b/docs/examples/videos/delete-rendition.md @@ -0,0 +1,16 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result = videos.delete_rendition( + video_id = '', + rendition_id = '' +) +``` diff --git a/docs/examples/videos/delete.md b/docs/examples/videos/delete.md new file mode 100644 index 00000000..a4d7082d --- /dev/null +++ b/docs/examples/videos/delete.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result = videos.delete( + video_id = '' +) +``` diff --git a/docs/examples/videos/get-caption-manifest.md b/docs/examples/videos/get-caption-manifest.md new file mode 100644 index 00000000..779e6e35 --- /dev/null +++ b/docs/examples/videos/get-caption-manifest.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.enums.video_output import VideoOutput + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_caption_manifest( + video_id = '', + output = VideoOutput.HLS, + caption_id = '' +) +``` diff --git a/docs/examples/videos/get-cmaf-dash-manifest.md b/docs/examples/videos/get-cmaf-dash-manifest.md new file mode 100644 index 00000000..e6e39a05 --- /dev/null +++ b/docs/examples/videos/get-cmaf-dash-manifest.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_cmaf_dash_manifest( + video_id = '' +) +``` diff --git a/docs/examples/videos/get-cmaf-hls-manifest.md b/docs/examples/videos/get-cmaf-hls-manifest.md new file mode 100644 index 00000000..c77325dc --- /dev/null +++ b/docs/examples/videos/get-cmaf-hls-manifest.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_cmaf_hls_manifest( + video_id = '' +) +``` diff --git a/docs/examples/videos/get-dash-manifest.md b/docs/examples/videos/get-dash-manifest.md new file mode 100644 index 00000000..20d6b6ed --- /dev/null +++ b/docs/examples/videos/get-dash-manifest.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_dash_manifest( + video_id = '' +) +``` diff --git a/docs/examples/videos/get-hls-manifest.md b/docs/examples/videos/get-hls-manifest.md new file mode 100644 index 00000000..bfb7056d --- /dev/null +++ b/docs/examples/videos/get-hls-manifest.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_hls_manifest( + video_id = '' +) +``` diff --git a/docs/examples/videos/get-rendition.md b/docs/examples/videos/get-rendition.md new file mode 100644 index 00000000..ed4e8341 --- /dev/null +++ b/docs/examples/videos/get-rendition.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoRendition + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoRendition = videos.get_rendition( + video_id = '', + rendition_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/get-thumbnail.md b/docs/examples/videos/get-thumbnail.md new file mode 100644 index 00000000..ee6c3cd7 --- /dev/null +++ b/docs/examples/videos/get-thumbnail.md @@ -0,0 +1,20 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.enums.image_format import ImageFormat + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_thumbnail( + video_id = '', + thumbnail_id = '', + width = 0, # optional + height = 0, # optional + output = ImageFormat.JPG # optional +) +``` diff --git a/docs/examples/videos/get-timeline.md b/docs/examples/videos/get-timeline.md new file mode 100644 index 00000000..0bb3cbb5 --- /dev/null +++ b/docs/examples/videos/get-timeline.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: bytes = videos.get_timeline( + video_id = '' +) +``` diff --git a/docs/examples/videos/get.md b/docs/examples/videos/get.md new file mode 100644 index 00000000..6f2b5e13 --- /dev/null +++ b/docs/examples/videos/get.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import Video + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: Video = videos.get( + video_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/list-captions.md b/docs/examples/videos/list-captions.md new file mode 100644 index 00000000..4a70caa7 --- /dev/null +++ b/docs/examples/videos/list-captions.md @@ -0,0 +1,20 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoCaptionList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoCaptionList = videos.list_captions( + video_id = '', + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/list-codecs.md b/docs/examples/videos/list-codecs.md new file mode 100644 index 00000000..a422b19e --- /dev/null +++ b/docs/examples/videos/list-codecs.md @@ -0,0 +1,16 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoCodecList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoCodecList = videos.list_codecs() + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/list-renditions.md b/docs/examples/videos/list-renditions.md new file mode 100644 index 00000000..d7f7d3a9 --- /dev/null +++ b/docs/examples/videos/list-renditions.md @@ -0,0 +1,20 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoRenditionList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoRenditionList = videos.list_renditions( + video_id = '', + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/list.md b/docs/examples/videos/list.md new file mode 100644 index 00000000..49b10584 --- /dev/null +++ b/docs/examples/videos/list.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoList = videos.list( + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/update-caption.md b/docs/examples/videos/update-caption.md new file mode 100644 index 00000000..76a5cf82 --- /dev/null +++ b/docs/examples/videos/update-caption.md @@ -0,0 +1,24 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import VideoCaption + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: VideoCaption = videos.update_caption( + video_id = '', + caption_id = '', + bucket_id = '', # optional + file_id = '', # optional + name = '', # optional + language = 'aar', # optional + default = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/videos/update.md b/docs/examples/videos/update.md new file mode 100644 index 00000000..5328fe52 --- /dev/null +++ b/docs/examples/videos/update.md @@ -0,0 +1,22 @@ +```python +from appwrite.client import Client +from appwrite.services.videos import Videos +from appwrite.models import Video +from appwrite.permission import Permission +from appwrite.role import Role + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_session('') # The user session to authenticate with + +videos = Videos(client) + +result: Video = videos.update( + video_id = '', + name = '', # optional + permissions = [Permission.read(Role.any())] # optional +) + +print(result.model_dump()) +``` diff --git a/pyproject.toml b/pyproject.toml index 4713d396..cdfa7013 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "appwrite" -version = "28.2.0" +version = "28.3.0" description = "Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API" readme = "README.md" requires-python = ">=3.10" diff --git a/setup.py b/setup.py index 48c46c7f..2496447b 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setuptools.setup( name='appwrite', packages=setuptools.find_packages(), - version='28.2.0', + version='28.3.0', license='BSD-3-Clause', description='Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API', long_description=long_description, @@ -18,7 +18,7 @@ maintainer='Appwrite Team', maintainer_email='team@appwrite.io', url='https://appwrite.io/support', - download_url='https://github.com/appwrite/sdk-for-python/archive/28.2.0.tar.gz', + download_url='https://github.com/appwrite/sdk-for-python/archive/28.3.0.tar.gz', install_requires=[ 'requests>=2.34.2,<3', 'urllib3>=2.8.0,<3', diff --git a/test/services/test_project.py b/test/services/test_project.py index 7173a31d..27750a6d 100644 --- a/test/services/test_project.py +++ b/test/services/test_project.py @@ -6120,3 +6120,188 @@ def test_delete_variable(self, m): sent = json.loads(request.body or '{}') self.assertEqual(sent, {}) self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_list_video_profiles(self, m): + data = { + "total": 5.0, + "profiles": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.project.list_video_profiles( + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/project/videos/profiles', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_video_profile(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "360p", + "codec": "h264", + "videoBitRate": 890000.0, + "audioBitRate": 64000.0, + "width": 640.0, + "height": 360.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.project.create_video_profile( + '', + '', + 1, + 1, + 1, + 1, + codec='h264', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/project/videos/profiles', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'profileId': '', + 'name': '', + 'videoBitRate': 1, + 'audioBitRate': 1, + 'width': 1, + 'height': 1, + 'codec': 'h264', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get_video_profile(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "360p", + "codec": "h264", + "videoBitRate": 890000.0, + "audioBitRate": 64000.0, + "width": 640.0, + "height": 360.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.project.get_video_profile( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/project/videos/profiles/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_video_profile(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "360p", + "codec": "h264", + "videoBitRate": 890000.0, + "audioBitRate": 64000.0, + "width": 640.0, + "height": 360.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.project.update_video_profile( + '', + name='', + video_bit_rate=1, + audio_bit_rate=1, + width=1, + height=1, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/project/videos/profiles/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'videoBitRate': 1, + 'audioBitRate': 1, + 'width': 1, + 'height': 1, + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_video_profile(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.project.delete_video_profile( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/project/videos/profiles/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) diff --git a/test/services/test_videos.py b/test/services/test_videos.py new file mode 100644 index 00000000..4eb54226 --- /dev/null +++ b/test/services/test_videos.py @@ -0,0 +1,752 @@ +import json +import re +import requests_mock +import unittest +from urllib.parse import parse_qs, unquote, urlsplit + +from appwrite.client import Client +from appwrite.input_file import InputFile +from appwrite.models import * +from appwrite.services.videos import Videos + + +class VideosServiceTest(unittest.TestCase): + + def setUp(self): + self.client = Client() + self.videos = Videos(self.client) + + @requests_mock.Mocker() + def test_list(self, m): + data = { + "total": 5.0, + "videos": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.list( + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "$permissions": [], + "bucketId": "5e5ea5c16897e", + "fileId": "d5fg5ehg1c168g7c", + "name": "Product demo", + "size": 23647142.0, + "format": "MPEG-4", + "duration": 92810.0, + "width": 960.0, + "height": 544.0, + "aspectRatio": "16:9", + "videoCodec": "h264", + "videoFormat": "AVC", + "videoFormatProfile": "Baseline@L3.1", + "videoBitRate": 564790.0, + "videoFrameRate": 29.97, + "videoFrameRateMode": "CFR", + "audioCodec": "aac", + "audioFormat": "AAC", + "audioBitRate": 127999.0, + "audioSampleRate": 48000.0, + "timelineStatus": "ready", + "timelineError": "The requested file is not a valid video or audio file (ffprobe: Invalid data found when processing input)", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.create( + '', + '', + '', + name='', + permissions=[], + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'videoId': '', + 'bucketId': '', + 'fileId': '', + 'name': '', + 'permissions': [], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_list_codecs(self, m): + data = { + "total": 5.0, + "codecs": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.list_codecs() + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos/codecs', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "$permissions": [], + "bucketId": "5e5ea5c16897e", + "fileId": "d5fg5ehg1c168g7c", + "name": "Product demo", + "size": 23647142.0, + "format": "MPEG-4", + "duration": 92810.0, + "width": 960.0, + "height": 544.0, + "aspectRatio": "16:9", + "videoCodec": "h264", + "videoFormat": "AVC", + "videoFormatProfile": "Baseline@L3.1", + "videoBitRate": 564790.0, + "videoFrameRate": 29.97, + "videoFrameRateMode": "CFR", + "audioCodec": "aac", + "audioFormat": "AAC", + "audioBitRate": 127999.0, + "audioSampleRate": 48000.0, + "timelineStatus": "ready", + "timelineError": "The requested file is not a valid video or audio file (ffprobe: Invalid data found when processing input)", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.get( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "$permissions": [], + "bucketId": "5e5ea5c16897e", + "fileId": "d5fg5ehg1c168g7c", + "name": "Product demo", + "size": 23647142.0, + "format": "MPEG-4", + "duration": 92810.0, + "width": 960.0, + "height": 544.0, + "aspectRatio": "16:9", + "videoCodec": "h264", + "videoFormat": "AVC", + "videoFormatProfile": "Baseline@L3.1", + "videoBitRate": 564790.0, + "videoFrameRate": 29.97, + "videoFrameRateMode": "CFR", + "audioCodec": "aac", + "audioFormat": "AAC", + "audioBitRate": 127999.0, + "audioSampleRate": 48000.0, + "timelineStatus": "ready", + "timelineError": "The requested file is not a valid video or audio file (ffprobe: Invalid data found when processing input)", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.update( + '', + name='', + permissions=[], + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'permissions': [], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.delete( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_list_captions(self, m): + data = { + "total": 5.0, + "captions": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.list_captions( + '', + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//captions', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_caption(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "videoId": "5e5ea5c16897e", + "bucketId": "d5fg5ehg1c168g7c", + "fileId": "c5fg5emg1c168grr", + "name": "English", + "language": "eng", + "default": True, + "embedded": True, + "targetDuration": 93, + "status": "ready", + "error": "Caption is not a proper .srt file (Invalid timestamp delimiter at line 2)", + "size": 4096.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.create_caption( + '', + '', + '', + '', + 'aar', + default=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//captions', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'bucketId': '', + 'fileId': '', + 'name': '', + 'language': 'aar', + 'default': False, + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_caption(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "videoId": "5e5ea5c16897e", + "bucketId": "d5fg5ehg1c168g7c", + "fileId": "c5fg5emg1c168grr", + "name": "English", + "language": "eng", + "default": True, + "embedded": True, + "targetDuration": 93, + "status": "ready", + "error": "Caption is not a proper .srt file (Invalid timestamp delimiter at line 2)", + "size": 4096.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.update_caption( + '', + '', + bucket_id='', + file_id='', + name='', + language='aar', + default=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//captions/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'bucketId': '', + 'fileId': '', + 'name': '', + 'language': 'aar', + 'default': False, + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_caption(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.delete_caption( + '', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//captions/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_cmaf_hls_manifest(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_cmaf_hls_manifest( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//outputs/cmaf/master.m3u8', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_cmaf_dash_manifest(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_cmaf_dash_manifest( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//outputs/cmaf/master.mpd', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_dash_manifest(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_dash_manifest( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//outputs/dash/master.mpd', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_hls_manifest(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_hls_manifest( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//outputs/hls/master.m3u8', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_caption_manifest(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_caption_manifest( + '', + 'hls', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//outputs/hls/captions//manifest', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_list_renditions(self, m): + data = { + "total": 5.0, + "renditions": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.list_renditions( + '', + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//renditions', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_rendition(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "videoId": "5e5ea5c16897e", + "profileId": "d5fg5ehg1c168g7c", + "name": "1280X720@3679", + "startedAt": "2020-10-15T06:38:00.000+00:00", + "endedAt": "2020-10-15T06:38:00.000+00:00", + "width": 1280.0, + "height": 720.0, + "videoBitRate": 3551000.0, + "audioBitRate": 128000.0, + "targetDuration": 6.006, + "status": "ready", + "error": "The requested file is not a valid video or audio file (ffprobe: Invalid data found when processing input)", + "progress": 88.0, + "output": "hls", + "codec": "h264", + "size": 18350080.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.create_rendition( + '', + '', + 'hls', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//renditions', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'profileId': '', + 'output': 'hls', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get_rendition(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "videoId": "5e5ea5c16897e", + "profileId": "d5fg5ehg1c168g7c", + "name": "1280X720@3679", + "startedAt": "2020-10-15T06:38:00.000+00:00", + "endedAt": "2020-10-15T06:38:00.000+00:00", + "width": 1280.0, + "height": 720.0, + "videoBitRate": 3551000.0, + "audioBitRate": 128000.0, + "targetDuration": 6.006, + "status": "ready", + "error": "The requested file is not a valid video or audio file (ffprobe: Invalid data found when processing input)", + "progress": 88.0, + "output": "hls", + "codec": "h264", + "size": 18350080.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.get_rendition( + '', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//renditions/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_rendition(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.videos.delete_rendition( + '', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//renditions/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_thumbnail(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_thumbnail( + '', + '', + width=1, + height=1, + output='jpg', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//thumbnails/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'width': ['1'], + 'height': ['1'], + 'output': ['jpg'], + }, + ) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_get_timeline(self, m): + data = bytearray() + headers = {'Content-Type': 'application/octet-stream'} + m.request( + 'GET', + requests_mock.ANY, + body=data, + headers=headers, + ) + response = self.videos.get_timeline( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/videos//timeline', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response, data)