diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e4b5a34..b65fe39b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Change Log +## 28.4.0 + +* Added: `analytics` service to create, list, get, update and delete analytics properties +* Added: `analytics.createEvent` to send events from a server, with `userId`, `ip` and `userAgent` overrides for API keys with the `analytics.write` scope +* Added: `analytics.listMetrics` to query visitors, sessions, views and events over time or broken down by a dimension +* Added: `analytics.listAnnotations`, `createAnnotation`, `getAnnotation`, `updateAnnotation` and `deleteAnnotation` +* Added: `AnalyticsProperty`, `AnalyticsAnnotation` and `AnalyticsMetric` models, their list models, and the `AnalyticsDimension`, `AnalyticsInterval` and `AnalyticsPropertyType` enums + ## 28.3.0 * Added: `videos` service to create, list, get, update and delete videos from files in Storage diff --git a/appwrite/client.py b/appwrite/client.py index 2541d7d1..1f6992d0 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.3.0 ({platform.uname().system}; {platform.uname().version}; {platform.uname().machine})', + 'user-agent': f'AppwritePythonSDK/28.4.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.3.0', + 'x-sdk-version': '28.4.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 7879e992..9c0f7750 100644 --- a/appwrite/encoders/value_class_encoder.py +++ b/appwrite/encoders/value_class_encoder.py @@ -4,6 +4,9 @@ from ..enums.authentication_factor import AuthenticationFactor from ..enums.id_token_provider import IdTokenProvider from ..enums.o_auth_provider import OAuthProvider +from ..enums.analytics_property_type import AnalyticsPropertyType +from ..enums.analytics_interval import AnalyticsInterval +from ..enums.analytics_dimension import AnalyticsDimension from ..enums.browser import Browser from ..enums.credit_card import CreditCard from ..enums.flag import Flag @@ -127,6 +130,15 @@ def default(self, o): if isinstance(o, OAuthProvider): return o.value + if isinstance(o, AnalyticsPropertyType): + return o.value + + if isinstance(o, AnalyticsInterval): + return o.value + + if isinstance(o, AnalyticsDimension): + return o.value + if isinstance(o, Browser): return o.value diff --git a/appwrite/enums/analytics_dimension.py b/appwrite/enums/analytics_dimension.py new file mode 100644 index 00000000..f5f0f60d --- /dev/null +++ b/appwrite/enums/analytics_dimension.py @@ -0,0 +1,30 @@ +from enum import Enum + + +class AnalyticsDimension(Enum): + COUNTRY = "country" + REGION = "region" + CITY = "city" + BROWSER = "browser" + BROWSERVERSION = "browserVersion" + OPERATINGSYSTEM = "operatingSystem" + OPERATINGSYSTEMVERSION = "operatingSystemVersion" + DEVICE = "device" + SCREENSIZE = "screenSize" + REFERRERSOURCE = "referrerSource" + CHANNEL = "channel" + UTMSOURCE = "utmSource" + UTMMEDIUM = "utmMedium" + UTMCAMPAIGN = "utmCampaign" + UTMCONTENT = "utmContent" + UTMTERM = "utmTerm" + PAGE = "page" + HOSTNAME = "hostname" + ENTRYPAGE = "entryPage" + EXITPAGE = "exitPage" + TRAFFICTYPE = "trafficType" + BOTNAME = "botName" + BOTCATEGORY = "botCategory" + USERID = "userId" + EVENTNAME = "eventName" + PROPS = "props" diff --git a/appwrite/enums/analytics_interval.py b/appwrite/enums/analytics_interval.py new file mode 100644 index 00000000..4bf6f552 --- /dev/null +++ b/appwrite/enums/analytics_interval.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class AnalyticsInterval(Enum): + ONE_HOUR = "1h" + ONE_DAY = "1d" + ONE_WEEK = "1w" + ONE_MONTH = "1m" diff --git a/appwrite/enums/analytics_property_type.py b/appwrite/enums/analytics_property_type.py new file mode 100644 index 00000000..7df29fc7 --- /dev/null +++ b/appwrite/enums/analytics_property_type.py @@ -0,0 +1,7 @@ +from enum import Enum + + +class AnalyticsPropertyType(Enum): + WEB = "web" + MOBILE = "mobile" + AGENT = "agent" diff --git a/appwrite/models/__init__.py b/appwrite/models/__init__.py index cde02c59..e5322bd9 100644 --- a/appwrite/models/__init__.py +++ b/appwrite/models/__init__.py @@ -271,6 +271,10 @@ from .video_caption import VideoCaption from .activity_event import ActivityEvent from .additional_resource import AdditionalResource +from .analytics_annotation import AnalyticsAnnotation +from .analytics_metric import AnalyticsMetric +from .analytics_metric_list import AnalyticsMetricList +from .analytics_property import AnalyticsProperty from .backup_archive import BackupArchive from .dedicated_database_backup import DedicatedDatabaseBackup from .dedicated_database_backup_list import DedicatedDatabaseBackupList @@ -346,6 +350,8 @@ from .oauth2_consent_list import Oauth2ConsentList from .oauth2_consent_token_list import Oauth2ConsentTokenList from .activity_event_list import ActivityEventList +from .analytics_property_list import AnalyticsPropertyList +from .analytics_annotation_list import AnalyticsAnnotationList from .backup_archive_list import BackupArchiveList from .backup_policy_list import BackupPolicyList from .backup_restoration_list import BackupRestorationList @@ -634,6 +640,10 @@ 'VideoCaption', 'ActivityEvent', 'AdditionalResource', + 'AnalyticsAnnotation', + 'AnalyticsMetric', + 'AnalyticsMetricList', + 'AnalyticsProperty', 'BackupArchive', 'DedicatedDatabaseBackup', 'DedicatedDatabaseBackupList', @@ -709,6 +719,8 @@ 'Oauth2ConsentList', 'Oauth2ConsentTokenList', 'ActivityEventList', + 'AnalyticsPropertyList', + 'AnalyticsAnnotationList', 'BackupArchiveList', 'BackupPolicyList', 'BackupRestorationList', diff --git a/appwrite/models/analytics_annotation.py b/appwrite/models/analytics_annotation.py new file mode 100644 index 00000000..36937c9a --- /dev/null +++ b/appwrite/models/analytics_annotation.py @@ -0,0 +1,58 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel + + +class AnalyticsAnnotation(AppwriteModel): + """ + AnalyticsAnnotation + + Attributes + ---------- + id : str + Annotation ID. + createdat : str + Annotation creation date in ISO 8601 format. + updatedat : str + Annotation update date in ISO 8601 format. + propertyid : str + ID of the analytics property the annotation belongs to. + date : str + Point in time the annotation marks, in ISO 8601 format. + content : str + Annotation text. + userid : str + ID of the user who created the annotation. Empty when it was created with an API key. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + propertyid: str = Field(..., alias='propertyId') + date: str = Field(..., alias='date') + content: str = Field(..., alias='content') + userid: str = Field(..., alias='userId') + + @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 'propertyId' not in data and 'propertyid' not in data: + data['propertyId'] = '' + if 'date' not in data: + data['date'] = '' + if 'content' not in data: + data['content'] = '' + if 'userId' not in data and 'userid' not in data: + data['userId'] = '' + return data diff --git a/appwrite/models/analytics_annotation_list.py b/appwrite/models/analytics_annotation_list.py new file mode 100644 index 00000000..62439d48 --- /dev/null +++ b/appwrite/models/analytics_annotation_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 .analytics_annotation import AnalyticsAnnotation + + +class AnalyticsAnnotationList(AppwriteModel): + """ + Analytics annotations list + + Attributes + ---------- + total : float + Total number of annotations that matched your query. + annotations : List[AnalyticsAnnotation] + List of annotations. + """ + + total: float = Field(..., alias='total') + annotations: List[AnalyticsAnnotation] = Field(..., alias='annotations') + + @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 'annotations' not in data: + data['annotations'] = [] + return data diff --git a/appwrite/models/analytics_metric.py b/appwrite/models/analytics_metric.py new file mode 100644 index 00000000..0cda0c2e --- /dev/null +++ b/appwrite/models/analytics_metric.py @@ -0,0 +1,68 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel + + +class AnalyticsMetric(AppwriteModel): + """ + AnalyticsMetric + + Attributes + ---------- + value : Optional[str] + Dimension value this row covers. Null when no dimension was requested, empty when the dimension could not be derived for those events. + date : Optional[str] + Start of the time bucket this row covers, in ISO 8601. Null when no interval was requested. + visitors : float + Unique visitors in the requested range. + sessions : float + Unique sessions in the requested range. + pageviews : Optional[float] + Total page and screen view events (events named "pageview" or "screen_view") in the requested range. The flat aggregate and the time series compute it; null on breakdown rows. + events : float + Total events in the requested range. + users : Optional[float] + Unique identified users in the requested range. Anonymous events are not counted. Null on entry and exit page breakdown rows. + visits : Optional[float] + Total sessions with activity in the requested range. Only the flat aggregate computes it; null on breakdown and time-series rows. + bouncerate : Optional[float] + Share of bounced visits, as a percentage; a visit is a bounce unless it records two or more page or screen views, at least one interaction, or ten seconds or more of activity. An interaction is any event that is neither a view nor automatic measurement such as "app_foregrounded", "engagement_time" or "scroll_depth". Only the flat aggregate computes it; null on breakdown and time-series rows. + visitduration : Optional[float] + Average session length in seconds, measured first event to last event. Single-event sessions count as 0. Only the flat aggregate computes it; null on breakdown and time-series rows. + viewspervisit : Optional[float] + Average pageviews per session (pageviews divided by visits). Only the flat aggregate computes it; null on breakdown and time-series rows. + scrolldepth : Optional[float] + Average scroll depth across events, as a percentage. Only the flat aggregate computes it; null on breakdown and time-series rows. + engagementtime : Optional[float] + Average engaged time per session in seconds, counting only foreground time. Sessions that reported no engagement are excluded. Only the flat aggregate computes it; null on breakdown and time-series rows. + """ + + value: Optional[str] = Field(default=None, alias='value') + date: Optional[str] = Field(default=None, alias='date') + visitors: float = Field(..., alias='visitors') + sessions: float = Field(..., alias='sessions') + pageviews: Optional[float] = Field(default=None, alias='pageviews') + events: float = Field(..., alias='events') + users: Optional[float] = Field(default=None, alias='users') + visits: Optional[float] = Field(default=None, alias='visits') + bouncerate: Optional[float] = Field(default=None, alias='bounceRate') + visitduration: Optional[float] = Field(default=None, alias='visitDuration') + viewspervisit: Optional[float] = Field(default=None, alias='viewsPerVisit') + scrolldepth: Optional[float] = Field(default=None, alias='scrollDepth') + engagementtime: Optional[float] = Field(default=None, alias='engagementTime') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'visitors' not in data: + data['visitors'] = 0 + if 'sessions' not in data: + data['sessions'] = 0 + if 'events' not in data: + data['events'] = 0 + return data diff --git a/appwrite/models/analytics_metric_list.py b/appwrite/models/analytics_metric_list.py new file mode 100644 index 00000000..2dd7ea40 --- /dev/null +++ b/appwrite/models/analytics_metric_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 .analytics_metric import AnalyticsMetric + + +class AnalyticsMetricList(AppwriteModel): + """ + AnalyticsMetricList + + Attributes + ---------- + total : float + Total number of metric rows returned. + metrics : List[AnalyticsMetric] + Metric rows: one per time bucket, one per dimension value, or a single row for the flat aggregate. + """ + + total: float = Field(..., alias='total') + metrics: List[AnalyticsMetric] = Field(..., alias='metrics') + + @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 'metrics' not in data: + data['metrics'] = [] + return data diff --git a/appwrite/models/analytics_property.py b/appwrite/models/analytics_property.py new file mode 100644 index 00000000..21a383c0 --- /dev/null +++ b/appwrite/models/analytics_property.py @@ -0,0 +1,79 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.analytics_property_type import AnalyticsPropertyType + + +class AnalyticsProperty(AppwriteModel): + """ + AnalyticsProperty + + Attributes + ---------- + id : str + Analytics property ID. + createdat : str + Property creation date in ISO 8601 format. + updatedat : str + Property update date in ISO 8601 format. + name : str + Human-readable name of the tracked website or application. + domain : str + Primary domain being tracked (e.g. example.com). May be empty for mobile and agent properties. + enabled : bool + Whether tracking is currently active. + allowedorigins : List[Any] + List of origins allowed to send tracking events. Use ["*"] to allow all. Managed by Appwrite for a property linked to a site, following the site's production domains. + type : AnalyticsPropertyType + Kind of product this property tracks. Decides which dashboard panels apply. + identifyusers : bool + Whether events sent from a signed-in client session record that user's ID. + accessedat : str + Most recent event date in ISO 8601 format. This attribute is only updated again after 24 hours. + firstaccessedat : str + First event date in ISO 8601 format. Empty until the property receives its first event. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + name: str = Field(..., alias='name') + domain: str = Field(..., alias='domain') + enabled: bool = Field(..., alias='enabled') + allowedorigins: List[Any] = Field(..., alias='allowedOrigins') + type: AnalyticsPropertyType = Field(..., alias='type') + identifyusers: bool = Field(..., alias='identifyUsers') + accessedat: str = Field(..., alias='accessedAt') + firstaccessedat: str = Field(..., alias='firstAccessedAt') + + @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 'domain' not in data: + data['domain'] = '' + if 'enabled' not in data: + data['enabled'] = True + if 'allowedOrigins' not in data and 'allowedorigins' not in data: + data['allowedOrigins'] = ['*'] + if 'type' not in data: + data['type'] = 'web' + if 'identifyUsers' not in data and 'identifyusers' not in data: + data['identifyUsers'] = False + if 'accessedAt' not in data and 'accessedat' not in data: + data['accessedAt'] = '' + if 'firstAccessedAt' not in data and 'firstaccessedat' not in data: + data['firstAccessedAt'] = '' + return data diff --git a/appwrite/models/analytics_property_list.py b/appwrite/models/analytics_property_list.py new file mode 100644 index 00000000..571f2337 --- /dev/null +++ b/appwrite/models/analytics_property_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 .analytics_property import AnalyticsProperty + + +class AnalyticsPropertyList(AppwriteModel): + """ + Analytics properties list + + Attributes + ---------- + total : float + Total number of properties that matched your query. + properties : List[AnalyticsProperty] + List of properties. + """ + + total: float = Field(..., alias='total') + properties: List[AnalyticsProperty] = Field(..., alias='properties') + + @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 'properties' not in data: + data['properties'] = [] + return data diff --git a/appwrite/services/analytics.py b/appwrite/services/analytics.py new file mode 100644 index 00000000..8dc45836 --- /dev/null +++ b/appwrite/services/analytics.py @@ -0,0 +1,757 @@ +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.analytics_property_list import AnalyticsPropertyList +from ..enums.analytics_property_type import AnalyticsPropertyType +from ..models.analytics_property import AnalyticsProperty +from ..models.analytics_annotation_list import AnalyticsAnnotationList +from ..models.analytics_annotation import AnalyticsAnnotation +from ..enums.analytics_interval import AnalyticsInterval +from ..enums.analytics_dimension import AnalyticsDimension +from ..models.analytics_metric_list import AnalyticsMetricList + + +class Analytics(Service): + + def __init__(self, client) -> None: + super(Analytics, self).__init__(client) + + def list_properties( + self, + queries: Optional[List[str]] = None, + search: Optional[str] = None, + total: Optional[bool] = None, + ) -> AnalyticsPropertyList: + """ + List analytics properties for the current project. + + 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, domain, enabled, type + search : Optional[str] + Search term to filter your list results. Matches the property ID, name and domain. Max length: 256 chars. + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + AnalyticsPropertyList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if search is not None: + api_params['search'] = self._normalize_value(search) + 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=AnalyticsPropertyList) + + def create_property( + self, + property_id: str, + name: str, + domain: Optional[str] = None, + enabled: Optional[bool] = None, + allowed_origins: Optional[List[str]] = None, + identify_users: Optional[bool] = None, + type: Optional[AnalyticsPropertyType] = None, + ) -> AnalyticsProperty: + """ + Create a new analytics property to track a website or application. + + Parameters + ---------- + property_id : str + Unique ID. Choose a custom ID or generate a random ID with `ID.unique()`. Max length is 36 chars. + name : str + Human-readable name for this property. + domain : Optional[str] + Primary domain to track (e.g. example.com). May be empty for mobile and agent properties. + enabled : Optional[bool] + Whether the property accepts events. Events sent to a disabled property are rejected as not found. + allowed_origins : Optional[List[str]] + Allowed origins for tracking. Use ["*"] to allow all. + identify_users : Optional[bool] + Record the signed-in user's ID on events sent from a client session, so traffic can be broken down and counted by user. Off by default. + type : Optional[AnalyticsPropertyType] + Kind of product this property tracks. Only changes which panels the dashboard shows; ingestion accepts the same events for every type. + Returns + ------- + AnalyticsProperty + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties' + api_params = {} + if property_id is None: + raise AppwriteException('Missing required parameter: "property_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + api_params['propertyId'] = self._normalize_value(property_id) + api_params['name'] = self._normalize_value(name) + if domain is not None: + api_params['domain'] = self._normalize_value(domain) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if allowed_origins is not None: + api_params['allowedOrigins'] = self._normalize_value(allowed_origins) + if identify_users is not None: + api_params['identifyUsers'] = self._normalize_value(identify_users) + if type is not None: + api_params['type'] = self._normalize_value(type) + + 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=AnalyticsProperty) + + def get_property( + self, + property_id: str, + ) -> AnalyticsProperty: + """ + Get an analytics property by ID. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + Returns + ------- + AnalyticsProperty + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_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=AnalyticsProperty) + + def update_property( + self, + property_id: str, + name: Optional[str] = None, + domain: Optional[str] = None, + enabled: Optional[bool] = None, + allowed_origins: Optional[List[str]] = None, + identify_users: Optional[bool] = None, + type: Optional[AnalyticsPropertyType] = None, + ) -> AnalyticsProperty: + """ + Update an analytics property. Only the attributes you pass are changed; omitted attributes keep their current value. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + name : Optional[str] + Human-readable name for this property. + domain : Optional[str] + Primary domain to track (e.g. example.com). Pass an empty string to clear it. + enabled : Optional[bool] + Whether the property accepts events. Events sent to a disabled property are rejected as not found. + allowed_origins : Optional[List[str]] + Allowed origins for tracking. Use ["*"] to allow all. On a property linked to a site, Appwrite manages this list: it is rewritten from the site's production domains whenever they change. + identify_users : Optional[bool] + Record the signed-in user's ID on events sent from a client session, so traffic can be broken down and counted by user. + type : Optional[AnalyticsPropertyType] + Kind of product this property tracks. Only changes which panels the dashboard shows; stored events are kept. + Returns + ------- + AnalyticsProperty + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if domain is not None: + api_params['domain'] = self._normalize_value(domain) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if allowed_origins is not None: + api_params['allowedOrigins'] = self._normalize_value(allowed_origins) + if identify_users is not None: + api_params['identifyUsers'] = self._normalize_value(identify_users) + if type is not None: + api_params['type'] = self._normalize_value(type) + + 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=AnalyticsProperty) + + def delete_property( + self, + property_id: str, + ) -> Dict[str, Any]: + """ + Delete an analytics property along with every event and session collected for it. This cannot be undone. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_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_annotations( + self, + property_id: str, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> AnalyticsAnnotationList: + """ + List the annotations of an analytics property. Filter on `date` to fetch the annotations inside a chart's time range. + + Parameters + ---------- + property_id : str + Analytics property 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: date + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + AnalyticsAnnotationList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/annotations' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_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=AnalyticsAnnotationList) + + def create_annotation( + self, + property_id: str, + annotation_id: str, + date: str, + content: str, + ) -> AnalyticsAnnotation: + """ + Create an annotation that marks a point in time on an analytics property's charts. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + annotation_id : str + Unique ID. Choose a custom ID or generate a random ID with `ID.unique()`. Max length is 36 chars. + date : str + Point in time the annotation marks, in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + content : str + Annotation text. Max length: 512 chars. + Returns + ------- + AnalyticsAnnotation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/annotations' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + if annotation_id is None: + raise AppwriteException('Missing required parameter: "annotation_id"') + if date is None: + raise AppwriteException('Missing required parameter: "date"') + if content is None: + raise AppwriteException('Missing required parameter: "content"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + api_params['annotationId'] = self._normalize_value(annotation_id) + api_params['date'] = self._normalize_value(date) + api_params['content'] = self._normalize_value(content) + + 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=AnalyticsAnnotation) + + def get_annotation( + self, + property_id: str, + annotation_id: str, + ) -> AnalyticsAnnotation: + """ + Get an analytics annotation by ID. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + annotation_id : str + Annotation unique ID. + Returns + ------- + AnalyticsAnnotation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/annotations/{annotationId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + if annotation_id is None or annotation_id == '': + raise AppwriteException('Missing required parameter: "annotation_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + api_path = api_path.replace('{annotationId}', self._encode_path(annotation_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=AnalyticsAnnotation) + + def update_annotation( + self, + property_id: str, + annotation_id: str, + date: Optional[str] = None, + content: Optional[str] = None, + ) -> AnalyticsAnnotation: + """ + Update an analytics annotation. Only the attributes you pass are changed; omitted attributes keep their current value. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + annotation_id : str + Annotation unique ID. + date : Optional[str] + Point in time the annotation marks, in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + content : Optional[str] + Annotation text. Max length: 512 chars. + Returns + ------- + AnalyticsAnnotation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/annotations/{annotationId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + if annotation_id is None or annotation_id == '': + raise AppwriteException('Missing required parameter: "annotation_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + api_path = api_path.replace('{annotationId}', self._encode_path(annotation_id)) + if date is not None: + api_params['date'] = self._normalize_value(date) + if content is not None: + api_params['content'] = self._normalize_value(content) + + 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=AnalyticsAnnotation) + + def delete_annotation( + self, + property_id: str, + annotation_id: str, + ) -> Dict[str, Any]: + """ + Delete an analytics annotation. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + annotation_id : str + Annotation unique ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/annotations/{annotationId}' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + if annotation_id is None or annotation_id == '': + raise AppwriteException('Missing required parameter: "annotation_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + api_path = api_path.replace('{annotationId}', self._encode_path(annotation_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 create_event( + self, + property_id: str, + name: str, + url: str, + domain: Optional[str] = None, + referrer: Optional[str] = None, + screen_width: Optional[float] = None, + session_hash: Optional[str] = None, + scroll_depth: Optional[float] = None, + engagement_time: Optional[float] = None, + props: Optional[List[str]] = None, + user_id: Optional[str] = None, + ip: Optional[str] = None, + user_agent: Optional[str] = None, + interactive: Optional[bool] = None, + ) -> Dict[str, Any]: + """ + Send a tracking event from a browser, native app, or server-side SDK. + + Parameters + ---------- + property_id : str + Analytics property ID. + name : str + Event name. "pageview" and "screen_view" are counted as views, every other name is a custom event. + url : str + Full page URL or screen identifier. + domain : Optional[str] + Hostname (e.g. example.com). + referrer : Optional[str] + Referrer URL. + screen_width : Optional[float] + Viewport width in CSS pixels. + session_hash : Optional[str] + Optional session hash (provided by SDK). + scroll_depth : Optional[float] + Scroll depth percentage 0-100. + engagement_time : Optional[float] + Engagement time in seconds, 0-4294967295. + props : Optional[List[str]] + Custom string properties as a flat key=value list (max 32 entries, alternating key,value). + user_id : Optional[str] + Override user ID. Pass an opaque ID, not personal data such as an email. Requires API-key auth with analytics.write scope. + ip : Optional[str] + Override IP address. Requires API-key auth with analytics.write scope. + user_agent : Optional[str] + Override user agent. Requires API-key auth with analytics.write scope. + interactive : Optional[bool] + Whether this event is a visitor interaction that ends a bounce. Set false for telemetry such as heartbeats or background syncs. Defaults to true for custom events and false for the automatic engagement, scroll and app lifecycle events. Ignored for views. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/events' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if url is None: + raise AppwriteException('Missing required parameter: "url"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + api_params['name'] = self._normalize_value(name) + api_params['url'] = self._normalize_value(url) + if domain is not None: + api_params['domain'] = self._normalize_value(domain) + if referrer is not None: + api_params['referrer'] = self._normalize_value(referrer) + if screen_width is not None: + api_params['screenWidth'] = self._normalize_value(screen_width) + if session_hash is not None: + api_params['sessionHash'] = self._normalize_value(session_hash) + if scroll_depth is not None: + api_params['scrollDepth'] = self._normalize_value(scroll_depth) + if engagement_time is not None: + api_params['engagementTime'] = self._normalize_value(engagement_time) + if props is not None: + api_params['props'] = self._normalize_value(props) + if user_id is not None: + api_params['userId'] = self._normalize_value(user_id) + if ip is not None: + api_params['ip'] = self._normalize_value(ip) + if user_agent is not None: + api_params['userAgent'] = self._normalize_value(user_agent) + if interactive is not None: + api_params['interactive'] = self._normalize_value(interactive) + + 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 response + + def list_metrics( + self, + property_id: str, + queries: Optional[List[str]] = None, + interval: Optional[AnalyticsInterval] = None, + dimensions: Optional[List[AnalyticsDimension]] = None, + prop_key: Optional[str] = None, + date_range: Optional[str] = None, + start_at: Optional[str] = None, + end_at: Optional[str] = None, + limit: Optional[float] = None, + total: Optional[bool] = None, + ) -> AnalyticsMetricList: + """ + Read analytics metrics (visitors, sessions, pageviews, events, bounceRate, …) for a property over a date range. + + **Three response shapes**, chosen by `dimensions[]` and `interval`: + - Neither: one row aggregating the whole window, with `value` and `date` null. Only this shape carries `visits`, `bounceRate`, `visitDuration`, `viewsPerVisit`, `scrollDepth` and `engagementTime`. + - `dimensions[]`: one row per dimension value, ranked by visitors, with `value` set and `date` null. + - `interval`: one row per time bucket in chronological order, with `date` set and `value` null. + + `pageviews` is carried by the flat aggregate and by `interval`, but not by a breakdown. + + `userId` and `users` cover identified traffic only: events sent with an API key's `userId`, or from a signed-in session on a property with `identifyUsers` on. A `userId` breakdown leaves out anonymous events; returned values are the project's user IDs. + + Custom event props: `dimensions[]=props` ranks the prop keys seen in the window, and adding `propKey` ranks the values of that one key. `queries[]` filters on a prop's value with the `props.` attribute, e.g. `equal("props.plan", ["pro"])`. + + Combining `dimensions[]` with `interval` is not supported yet. `queries[]` filters the underlying events using standard Utopia query syntax. + + Parameters + ---------- + property_id : str + Analytics property unique ID. + queries : Optional[List[str]] + Up to 10 filter queries in Utopia syntax. Allowed attributes: country, region, city, browser, browserVersion, operatingSystem, operatingSystemVersion, device, screenSize, referrerSource, channel, utmSource, utmMedium, utmCampaign, utmContent, utmTerm, page, hostname, trafficType, botName, botCategory, userId, eventName, and `props.` for a custom prop. page, userId, eventName and `props.` are only accepted alongside `interval`, or with a breakdown on a dimension other than entryPage, exitPage. Allowed methods: equal, notEqual, contains, startsWith, endsWith. Example: `queries[]=equal("country", ["US"])`. + interval : Optional[AnalyticsInterval] + Time bucket size. Omit (null) for a flat aggregate over the whole window. Allowed: 1h, 1d, 1w, 1m. + dimensions : Optional[List[AnalyticsDimension]] + Dimension to break the metrics down by. One at most for now; the parameter is a list so that cap can be raised without a breaking change. Allowed: country, region, city, browser, browserVersion, operatingSystem, operatingSystemVersion, device, screenSize, referrerSource, channel, utmSource, utmMedium, utmCampaign, utmContent, utmTerm, page, hostname, entryPage, exitPage, trafficType, botName, botCategory, userId, eventName, props. + prop_key : Optional[str] + Custom prop key whose values to rank, with `dimensions[]=props`. Omit to rank the prop keys themselves. + date_range : Optional[str] + Date range shorthand (e.g. 7d, 30d). Ignored for any bound you supply explicitly via startAt/endAt. + start_at : Optional[str] + Explicit window start in ISO 8601. Defaults to endAt minus dateRange. + end_at : Optional[str] + Explicit window end in ISO 8601. Defaults to the current time. + limit : Optional[float] + Maximum number of ranked values to return. + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + AnalyticsMetricList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/analytics/properties/{propertyId}/metrics' + api_params = {} + if property_id is None or property_id == '': + raise AppwriteException('Missing required parameter: "property_id"') + api_path = api_path.replace('{propertyId}', self._encode_path(property_id)) + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if dimensions is not None: + api_params['dimensions'] = self._normalize_value(dimensions) + if prop_key is not None: + api_params['propKey'] = self._normalize_value(prop_key) + if date_range is not None: + api_params['dateRange'] = self._normalize_value(date_range) + if start_at is not None: + api_params['startAt'] = self._normalize_value(start_at) + if end_at is not None: + api_params['endAt'] = self._normalize_value(end_at) + if limit is not None: + api_params['limit'] = self._normalize_value(limit) + 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=AnalyticsMetricList) diff --git a/docs/examples/analytics/create-annotation.md b/docs/examples/analytics/create-annotation.md new file mode 100644 index 00000000..e0c03816 --- /dev/null +++ b/docs/examples/analytics/create-annotation.md @@ -0,0 +1,21 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsAnnotation + +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 + +analytics = Analytics(client) + +result: AnalyticsAnnotation = analytics.create_annotation( + property_id = '', + annotation_id = '', + date = '2020-10-15T06:38:00.000+00:00', + content = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/create-event.md b/docs/examples/analytics/create-event.md new file mode 100644 index 00000000..61471e03 --- /dev/null +++ b/docs/examples/analytics/create-event.md @@ -0,0 +1,28 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics + +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 + +analytics = Analytics(client) + +result = analytics.create_event( + property_id = '', + name = '', + url = 'https://example.com', + domain = '', # optional + referrer = '', # optional + screen_width = None, # optional + session_hash = '', # optional + scroll_depth = 0, # optional + engagement_time = 0, # optional + props = [], # optional + user_id = '', # optional + ip = '', # optional + user_agent = '', # optional + interactive = False # optional +) +``` diff --git a/docs/examples/analytics/create-property.md b/docs/examples/analytics/create-property.md new file mode 100644 index 00000000..c7df387c --- /dev/null +++ b/docs/examples/analytics/create-property.md @@ -0,0 +1,25 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsProperty +from appwrite.enums.analytics_property_type import AnalyticsPropertyType + +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 + +analytics = Analytics(client) + +result: AnalyticsProperty = analytics.create_property( + property_id = '', + name = '', + domain = '', # optional + enabled = False, # optional + allowed_origins = [], # optional + identify_users = False, # optional + type = AnalyticsPropertyType.WEB # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/delete-annotation.md b/docs/examples/analytics/delete-annotation.md new file mode 100644 index 00000000..9dc47fdf --- /dev/null +++ b/docs/examples/analytics/delete-annotation.md @@ -0,0 +1,16 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics + +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 + +analytics = Analytics(client) + +result = analytics.delete_annotation( + property_id = '', + annotation_id = '' +) +``` diff --git a/docs/examples/analytics/delete-property.md b/docs/examples/analytics/delete-property.md new file mode 100644 index 00000000..caaf97b1 --- /dev/null +++ b/docs/examples/analytics/delete-property.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics + +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 + +analytics = Analytics(client) + +result = analytics.delete_property( + property_id = '' +) +``` diff --git a/docs/examples/analytics/get-annotation.md b/docs/examples/analytics/get-annotation.md new file mode 100644 index 00000000..c742392c --- /dev/null +++ b/docs/examples/analytics/get-annotation.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsAnnotation + +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 + +analytics = Analytics(client) + +result: AnalyticsAnnotation = analytics.get_annotation( + property_id = '', + annotation_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/get-property.md b/docs/examples/analytics/get-property.md new file mode 100644 index 00000000..d8ffc6b6 --- /dev/null +++ b/docs/examples/analytics/get-property.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsProperty + +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 + +analytics = Analytics(client) + +result: AnalyticsProperty = analytics.get_property( + property_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/list-annotations.md b/docs/examples/analytics/list-annotations.md new file mode 100644 index 00000000..8ee871fc --- /dev/null +++ b/docs/examples/analytics/list-annotations.md @@ -0,0 +1,20 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsAnnotationList + +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 + +analytics = Analytics(client) + +result: AnalyticsAnnotationList = analytics.list_annotations( + property_id = '', + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/list-metrics.md b/docs/examples/analytics/list-metrics.md new file mode 100644 index 00000000..92154edd --- /dev/null +++ b/docs/examples/analytics/list-metrics.md @@ -0,0 +1,29 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsMetricList +from appwrite.enums.analytics_interval import AnalyticsInterval +from appwrite.enums.analytics_dimension import AnalyticsDimension + +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 + +analytics = Analytics(client) + +result: AnalyticsMetricList = analytics.list_metrics( + property_id = '', + queries = [], # optional + interval = AnalyticsInterval.ONE_HOUR, # optional + dimensions = [AnalyticsDimension.COUNTRY], # optional + prop_key = '', # optional + date_range = '', # optional + start_at = '2020-10-15T06:38:00.000+00:00', # optional + end_at = '2020-10-15T06:38:00.000+00:00', # optional + limit = 1, # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/list-properties.md b/docs/examples/analytics/list-properties.md new file mode 100644 index 00000000..c1fe9c15 --- /dev/null +++ b/docs/examples/analytics/list-properties.md @@ -0,0 +1,20 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsPropertyList + +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 + +analytics = Analytics(client) + +result: AnalyticsPropertyList = analytics.list_properties( + queries = [], # optional + search = '', # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/update-annotation.md b/docs/examples/analytics/update-annotation.md new file mode 100644 index 00000000..256b4e22 --- /dev/null +++ b/docs/examples/analytics/update-annotation.md @@ -0,0 +1,21 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsAnnotation + +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 + +analytics = Analytics(client) + +result: AnalyticsAnnotation = analytics.update_annotation( + property_id = '', + annotation_id = '', + date = '2020-10-15T06:38:00.000+00:00', # optional + content = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/analytics/update-property.md b/docs/examples/analytics/update-property.md new file mode 100644 index 00000000..df83bc3f --- /dev/null +++ b/docs/examples/analytics/update-property.md @@ -0,0 +1,25 @@ +```python +from appwrite.client import Client +from appwrite.services.analytics import Analytics +from appwrite.models import AnalyticsProperty +from appwrite.enums.analytics_property_type import AnalyticsPropertyType + +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 + +analytics = Analytics(client) + +result: AnalyticsProperty = analytics.update_property( + property_id = '', + name = '', # optional + domain = '', # optional + enabled = False, # optional + allowed_origins = [], # optional + identify_users = False, # optional + type = AnalyticsPropertyType.WEB # optional +) + +print(result.model_dump()) +``` diff --git a/pyproject.toml b/pyproject.toml index cdfa7013..42b2d757 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "appwrite" -version = "28.3.0" +version = "28.4.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 2496447b..c5829a9c 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setuptools.setup( name='appwrite', packages=setuptools.find_packages(), - version='28.3.0', + version='28.4.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.3.0.tar.gz', + download_url='https://github.com/appwrite/sdk-for-python/archive/28.4.0.tar.gz', install_requires=[ 'requests>=2.34.2,<3', 'urllib3>=2.8.0,<3', diff --git a/test/services/test_analytics.py b/test/services/test_analytics.py new file mode 100644 index 00000000..4b45013f --- /dev/null +++ b/test/services/test_analytics.py @@ -0,0 +1,481 @@ +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.analytics import Analytics + + +class AnalyticsServiceTest(unittest.TestCase): + + def setUp(self): + self.client = Client() + self.analytics = Analytics(self.client) + + @requests_mock.Mocker() + def test_list_properties(self, m): + data = { + "total": 5.0, + "properties": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.list_properties( + queries=[], + search='', + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'search': [''], + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_property(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "enabled": True, + "allowedOrigins": [], + "type": "web", + "identifyUsers": True, + "accessedAt": "2020-10-15T06:38:00.000+00:00", + "firstAccessedAt": "2020-10-15T06:38:00.000+00:00", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.create_property( + '', + '', + domain='', + enabled=False, + allowed_origins=[], + identify_users=False, + type='web', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'propertyId': '', + 'name': '', + 'domain': '', + 'enabled': False, + 'allowedOrigins': [], + 'identifyUsers': False, + 'type': 'web', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get_property(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "enabled": True, + "allowedOrigins": [], + "type": "web", + "identifyUsers": True, + "accessedAt": "2020-10-15T06:38:00.000+00:00", + "firstAccessedAt": "2020-10-15T06:38:00.000+00:00", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.get_property( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_property(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "My Website", + "domain": "example.com", + "enabled": True, + "allowedOrigins": [], + "type": "web", + "identifyUsers": True, + "accessedAt": "2020-10-15T06:38:00.000+00:00", + "firstAccessedAt": "2020-10-15T06:38:00.000+00:00", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.update_property( + '', + name='', + domain='', + enabled=False, + allowed_origins=[], + identify_users=False, + type='web', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'domain': '', + 'enabled': False, + 'allowedOrigins': [], + 'identifyUsers': False, + 'type': 'web', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_property(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.delete_property( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_list_annotations(self, m): + data = { + "total": 5.0, + "annotations": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.list_annotations( + '', + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//annotations', + ) + 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_annotation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "propertyId": "5e5ea5c16897e", + "date": "2020-10-15T06:38:00.000+00:00", + "content": "Launched the new pricing page", + "userId": "5e5ea5c16897e", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.create_annotation( + '', + '', + '2020-10-15T06:38:00.000+00:00', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//annotations', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'annotationId': '', + 'date': '2020-10-15T06:38:00.000+00:00', + 'content': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get_annotation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "propertyId": "5e5ea5c16897e", + "date": "2020-10-15T06:38:00.000+00:00", + "content": "Launched the new pricing page", + "userId": "5e5ea5c16897e", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.get_annotation( + '', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//annotations/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_annotation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "propertyId": "5e5ea5c16897e", + "date": "2020-10-15T06:38:00.000+00:00", + "content": "Launched the new pricing page", + "userId": "5e5ea5c16897e", + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.update_annotation( + '', + '', + date='2020-10-15T06:38:00.000+00:00', + content='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//annotations/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'date': '2020-10-15T06:38:00.000+00:00', + 'content': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_annotation(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.delete_annotation( + '', + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//annotations/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_create_event(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.create_event( + '', + '', + 'https://example.com', + domain='', + referrer='', + screen_width=1, + session_hash='', + scroll_depth=1, + engagement_time=1, + props=[], + user_id='', + ip='', + user_agent='', + interactive=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//events', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'url': 'https://example.com', + 'domain': '', + 'referrer': '', + 'screenWidth': 1, + 'sessionHash': '', + 'scrollDepth': 1, + 'engagementTime': 1, + 'props': [], + 'userId': '', + 'ip': '', + 'userAgent': '', + 'interactive': False, + }, + ) + self.assertEqual(response, data) + + @requests_mock.Mocker() + def test_list_metrics(self, m): + data = { + "total": 30.0, + "metrics": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.analytics.list_metrics( + '', + queries=[], + interval='1h', + dimensions=[], + prop_key='', + date_range='', + start_at='2020-10-15T06:38:00.000+00:00', + end_at='2020-10-15T06:38:00.000+00:00', + limit=1, + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/analytics/properties//metrics', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'interval': ['1h'], + 'propKey': [''], + 'dateRange': [''], + 'startAt': ['2020-10-15T06:38:00.000+00:00'], + 'endAt': ['2020-10-15T06:38:00.000+00:00'], + 'limit': ['1'], + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data)