Merge pull request #771 from appwrite/feat-messaging-sdk

Use enum and SDK methods
This commit is contained in:
Torsten Dittmann authored and GitHub committed 2024-02-08 10:24:42 +01:00
commit be09ddece1
111 files changed
+1384 -1793

No files matched your search

@@ -1,12 +1,14 @@
<script lang="ts">
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { CreditCard } from '@appwrite.io/console';
export let brand: string;
export let width = 23;
export let height = 16;
function getCreditCardImage(brand: string, width = 46, height = 32) {
if (!brand) return '';
if (!isValueOfStringEnum(CreditCard, brand)) return '';
return sdk.forConsole.avatars.getCreditCard(brand, width, height).toString();
}
</script>
+8 -7
View File
@@ -60,13 +60,14 @@
{#if icon}
<span class={`icon-${icon} u-margin-inline-start-auto`} aria-hidden="true" />
{/if}
{/if}
{#if imageIcon}
<img
class="u-margin-inline-start-auto"
style:--p-text-size="1.25rem"
src={`${base}/icons/${$app.themeInUse}/color/${imageIcon}.svg`}
alt={imageIcon} />
{#if imageIcon}
<img
class="u-margin-inline-start-auto"
style:max-inline-size="1.25rem"
style:max-block-size="1.25rem"
src={`${base}/icons/${$app.themeInUse}/color/${imageIcon}.svg`}
alt={imageIcon} />
{/if}
{/if}
</div>
</label>
+1
View File
@@ -51,6 +51,7 @@ export enum Dependencies {
CONSOLE_VARIABLES = 'dependency:console_variables',
MESSAGING_PROVIDERS = 'dependency:messaging_providers',
MESSAGING_PROVIDER = 'dependency:messaging_provider',
MESSAGING_MESSAGES = 'dependency:messaging_messages',
MESSAGING_MESSAGE = 'dependency:messaging_message',
MESSAGING_TOPICS = 'dependency:messaging_topics',
MESSAGING_TOPIC = 'dependency:messaging_topic',
+3
View File
@@ -1,5 +1,7 @@
<script lang="ts">
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { Flag } from '@appwrite.io/console';
export let flag: string;
export let name: string = flag;
export let width = 40;
@@ -9,6 +11,7 @@
export { classes as class };
export function getFlag(country: string, width: number, height: number, quality: number) {
if (!isValueOfStringEnum(Flag, country)) return '';
let flag = sdk.forProject.avatars
.getFlag(country, width * 2, height * 2, quality)
?.toString();
+2
View File
@@ -6,6 +6,7 @@
export let id: string;
export let selectedIds: string[] = [];
export let disabled: boolean = false;
let el: HTMLInputElement;
const handleClick = (e: Event) => {
@@ -35,6 +36,7 @@
id="select-{id}"
wrapperTag="div"
checked={selectedIds.includes(id)}
{disabled}
on:click={handleClick} />
</TableCell>
+3 -3
View File
@@ -4,7 +4,7 @@
export function periodToDates(period: UsagePeriods): {
start: string;
end: string;
period: '1h' | '1d';
period: ProjectUsageRange;
} {
const start = new Date();
switch (period) {
@@ -26,7 +26,7 @@
return {
start: start.toISOString(),
end: end.toISOString(),
period: period === '24h' ? '1h' : '1d'
period: period === '24h' ? ProjectUsageRange.OneHour : ProjectUsageRange.OneDay
};
}
@@ -62,7 +62,7 @@
import { BarChart } from '$lib/charts';
import { formatNumberWithCommas } from '$lib/helpers/numbers';
import { Card, SecondaryTabs, SecondaryTabsItem, Heading } from '$lib/components';
import type { Models } from '@appwrite.io/console';
import { ProjectUsageRange, type Models } from '@appwrite.io/console';
import { page } from '$app/stores';
type MetricMetadata = {
+2 -9
View File
@@ -1,10 +1,3 @@
<script context="module" lang="ts">
export enum ProxyTypes {
API = 'api',
FUNCTION = 'function'
}
</script>
<script lang="ts">
import { DropList, DropListItem, Empty, Heading, Modal, Trim } from '$lib/components';
import {
@@ -22,14 +15,14 @@
import { toLocaleDate } from '$lib/helpers/date';
import { wizard } from '$lib/stores/wizard';
import type { Dependencies } from '$lib/constants';
import type { Models } from '@appwrite.io/console';
import type { Models, ResourceType } from '@appwrite.io/console';
import Create from './create.svelte';
import Delete from './delete.svelte';
import Retry from './wizard/retry.svelte';
import { Pill } from '$lib/elements';
export let rules: Models.ProxyRuleList;
export let type: ProxyTypes;
export let type: ResourceType;
export let dependency: Dependencies;
let showDomainsDropdown = [];
+1 -1
View File
@@ -1,2 +1,2 @@
export { default as ProxyRulesPage, ProxyTypes } from './index.svelte';
export { default as ProxyRulesPage } from './index.svelte';
export { default as Retry } from './wizard/retry.svelte';
+2 -2
View File
@@ -6,9 +6,9 @@
import { sdk } from '$lib/stores/sdk';
import { isSelfHosted } from '$lib/system';
import { func } from '$routes/console/project-[project]/functions/function-[function]/store';
import { ProxyTypes } from '../index.svelte';
import { domain, typeStore } from './store';
import { consoleVariables } from '$routes/console/store';
import { ResourceType } from '@appwrite.io/console';
let error = null;
const isDomainsEnabled = $consoleVariables?._APP_DOMAIN_ENABLED === true;
@@ -22,7 +22,7 @@
$domain = await sdk.forProject.proxy.createRule(
$domain.domain,
$typeStore,
$typeStore === ProxyTypes.FUNCTION ? $func.$id : undefined
$typeStore === ResourceType.Function ? $func.$id : undefined
);
trackEvent(Submit.DomainCreate);
+2 -3
View File
@@ -1,8 +1,7 @@
import type { Models } from '@appwrite.io/console';
import type { Models, ResourceType } from '@appwrite.io/console';
import { writable } from 'svelte/store';
import type { ProxyTypes } from '../index.svelte';
import type { Dependencies } from '$lib/constants';
export const domain = writable<Partial<Models.ProxyRule>>({ $id: '', domain: '' });
export const typeStore = writable<ProxyTypes>();
export const typeStore = writable<ResourceType>();
export const dependencyStore = writable<Dependencies>();
+1 -1
View File
@@ -448,7 +448,7 @@ export class Billing {
);
}
async listInvoices(organizationId: string, queries: Query[] = []): Promise<InvoiceList> {
async listInvoices(organizationId: string, queries: string[] = []): Promise<InvoiceList> {
const path = `/organizations/${organizationId}/invoices`;
const params = {
organizationId,
+9 -9
View File
@@ -1,9 +1,9 @@
import { writable } from 'svelte/store';
import type { Models } from '@appwrite.io/console';
import { type Models, AuthMethod as AuthMethodEnum } from '@appwrite.io/console';
export type AuthMethod = {
label: string;
method: string;
method: AuthMethodEnum;
value: boolean | null;
};
@@ -11,37 +11,37 @@ const setAuthMethod = (project: Models.Project): AuthMethod[] => {
return [
{
label: 'Email/Password',
method: 'email-password',
method: AuthMethodEnum.Emailpassword,
value: project?.authEmailPassword
},
{
label: 'Phone',
method: 'phone',
method: AuthMethodEnum.Phone,
value: project?.authPhone
},
{
label: 'Magic URL',
method: 'magic-url',
method: AuthMethodEnum.Magicurl,
value: project?.authUsersAuthMagicURL
},
{
label: 'Email OTP',
method: 'email-otp',
method: AuthMethodEnum.Emailotp,
value: project?.authEmailOtp
},
{
label: 'Anonymous',
method: 'anonymous',
method: AuthMethodEnum.Anonymous,
value: project?.authAnonymous
},
{
label: 'Team Invites',
method: 'invites',
method: AuthMethodEnum.Invites,
value: project?.authInvites
},
{
label: 'JWT',
method: 'jwt',
method: AuthMethodEnum.Jwt,
value: project?.authJWT
}
];
+21 -31
View File
@@ -1,9 +1,9 @@
import { writable } from 'svelte/store';
import type { Models } from '@appwrite.io/console';
import { APIService, type Models } from '@appwrite.io/console';
export type Service = {
label: string;
method: string;
method: APIService;
value: boolean | null;
};
@@ -12,62 +12,52 @@ function createServices() {
list: [
{
label: 'Account',
method: 'account',
method: APIService.Account,
value: null
},
{
label: 'Avatars',
method: 'avatars',
method: APIService.Avatars,
value: null
},
{
label: 'Databases',
method: 'databases',
method: APIService.Databases,
value: null
},
{
label: 'Functions',
method: 'functions',
method: APIService.Functions,
value: null
},
{
label: 'Health',
method: 'health',
method: APIService.Health,
value: null
},
{
label: 'Locale',
method: 'locale',
method: APIService.Locale,
value: null
},
{
label: 'Storage',
method: 'storage',
method: APIService.Storage,
value: null
},
{
label: 'Teams',
method: 'teams',
method: APIService.Teams,
value: null
},
{
label: 'Users',
method: 'users',
method: APIService.Users,
value: null
},
{
label: 'GraphQL',
method: 'graphql',
value: null
},
{
label: 'VCS',
method: 'vcs',
value: null
},
{
label: 'Proxy',
method: 'proxy',
method: APIService.Graphql,
value: null
}
]
@@ -80,47 +70,47 @@ function createServices() {
const list = [
{
label: 'Account',
method: 'account',
method: APIService.Account,
value: project.serviceStatusForAccount
},
{
label: 'Avatars',
method: 'avatars',
method: APIService.Avatars,
value: project.serviceStatusForAvatars
},
{
label: 'Databases',
method: 'databases',
method: APIService.Databases,
value: project.serviceStatusForDatabases
},
{
label: 'Functions',
method: 'functions',
method: APIService.Functions,
value: project.serviceStatusForFunctions
},
{
label: 'Health',
method: 'health',
method: APIService.Health,
value: project.serviceStatusForHealth
},
{
label: 'Locale',
method: 'locale',
method: APIService.Locale,
value: project.serviceStatusForLocale
},
{
label: 'Storage',
method: 'storage',
method: APIService.Storage,
value: project.serviceStatusForStorage
},
{
label: 'Teams',
method: 'teams',
method: APIService.Teams,
value: project.serviceStatusForTeams
},
{
label: 'Users',
method: 'users',
method: APIService.Users,
value: project.serviceStatusForUsers
}
];
+2
View File
@@ -10,6 +10,7 @@ import {
Functions,
Health,
Locale,
Messaging,
Migrations,
Project,
Project as ProjectApi,
@@ -38,6 +39,7 @@ const sdkForProject = {
functions: new Functions(clientProject),
health: new Health(clientProject),
locale: new Locale(clientProject),
messaging: new Messaging(clientProject),
project: new Project(clientProject),
projectApi: new ProjectApi(clientProject),
storage: new Storage(clientProject),
@@ -11,9 +11,14 @@
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
async function createGitHubInstallation() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
$func.$id,
$func.name,
+5 -1
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { ID } from '@appwrite.io/console';
import { ID, Runtime } from '@appwrite.io/console';
import { Wizard } from '$lib/layout';
import type { WizardStepsType } from '$lib/layout/wizard.svelte';
import { sdk } from '$lib/stores/sdk';
@@ -13,9 +13,13 @@
import ExecuteAccess from './steps/executeAccess.svelte';
import GitConfiguration from './steps/gitConfiguration.svelte';
import FunctionConfiguration from './steps/functionConfiguration.svelte';
import { isValueOfStringEnum } from '$lib/helpers/types';
async function create() {
try {
if (!isValueOfStringEnum(Runtime, $createFunction.runtime)) {
throw new Error(`Invalid runtime: ${$createFunction.runtime}`);
}
const response = await sdk.forProject.functions.create(
$createFunction.$id || ID.unique(),
$createFunction.name,
@@ -1,5 +1,5 @@
<script lang="ts">
import { ID } from '@appwrite.io/console';
import { ID, Runtime } from '@appwrite.io/console';
import { Wizard } from '$lib/layout';
import type { WizardStepsType } from '$lib/layout/wizard.svelte';
import { sdk } from '$lib/stores/sdk';
@@ -19,9 +19,13 @@
import Details from './steps/details.svelte';
import Configuration from './steps/configuration.svelte';
import ExecuteAccess from './steps/executeAccess.svelte';
import { isValueOfStringEnum } from '$lib/helpers/types';
async function create() {
try {
if (!isValueOfStringEnum(Runtime, $createFunction.runtime)) {
throw new Error(`Invalid runtime: ${$createFunction.runtime}`);
}
const response = await sdk.forProject.functions.create(
$createFunction.$id || ID.unique(),
$createFunction.name,
@@ -1,5 +1,5 @@
<script lang="ts">
import { ID } from '@appwrite.io/console';
import { ID, Runtime } from '@appwrite.io/console';
import { Wizard } from '$lib/layout';
import type { WizardStepsType } from '$lib/layout/wizard.svelte';
import { sdk } from '$lib/stores/sdk';
@@ -16,9 +16,13 @@
import CreateRepository from './steps/createRepository.svelte';
import TemplateVariables from './steps/templateVariables.svelte';
import { scopes } from '$lib/constants';
import { isValueOfStringEnum } from '$lib/helpers/types';
async function create() {
try {
if (!isValueOfStringEnum(Runtime, $templateConfig.runtime)) {
throw new Error(`Invalid runtime: ${$templateConfig.runtime}`);
}
const runtimeDetail = $template.runtimes.find(
(r) => r.name === $templateConfig.runtime
);
@@ -15,15 +15,18 @@
import { sdk } from '$lib/stores/sdk';
import { goto, invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import type { Models } from '@appwrite.io/console';
import { Browser, type Models } from '@appwrite.io/console';
import type { PageData } from './$types';
import { Submit, trackEvent } from '$lib/actions/analytics';
import { base } from '$app/paths';
import { isValueOfStringEnum } from '$lib/helpers/types';
export let data: PageData;
function getBrowser(clientCode: string) {
return sdk.forConsole.avatars.getBrowser(clientCode, 40, 40);
const code = clientCode.toLowerCase();
if (!isValueOfStringEnum(Browser, code)) return '';
return sdk.forProject.avatars.getBrowser(code, 40, 40);
}
async function logout(session: Models.Session) {
@@ -62,16 +65,24 @@
</TableHeader>
<TableBody>
{#each data.sessions.sessions as session}
{@const browser = getBrowser(session.clientCode)}
<TableRow>
<TableCell title="Client">
<div class="u-flex u-gap-12 u-cross-center">
{#if session.clientName}
<div class="avatar is-small">
<img
height="20"
width="20"
src={getBrowser(session.clientCode).toString()}
alt={session.clientName} />
{#if browser}
<img
height="20"
width="20"
src={getBrowser(session.clientCode).toString()}
alt={session.clientName} />
{:else}
<span
class="icon-globe-alt"
style="font-size: 20px"
aria-hidden="true" />
{/if}
</div>
<Trim>
{session.clientName}
@@ -25,7 +25,7 @@
import { sdk } from '$lib/stores/sdk';
import { loading } from '$routes/store';
import type { Models } from '@appwrite.io/console';
import { ID } from '@appwrite.io/console';
import { ID, Region } from '@appwrite.io/console';
import { openImportWizard } from '../project-[project]/settings/migrations/(import)';
import { readOnly } from '$lib/stores/billing';
import type { RegionList } from '$lib/sdk/billing';
@@ -105,7 +105,7 @@
ID.unique(),
`Imported project ${new Date().toISOString()}`,
$page.params.organization,
'default'
Region.Default
);
trackEvent(Submit.ProjectCreate, {
teamId: $page.params.organization
@@ -6,7 +6,7 @@
import { InputText, Button, FormList } from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { ID } from '@appwrite.io/console';
import { ID, Region } from '@appwrite.io/console';
import { createEventDispatcher } from 'svelte';
export let show = false;
@@ -25,7 +25,7 @@
id ?? ID.unique(),
name,
teamId,
'default'
Region.Default
);
dispatch('created', project);
trackEvent(Submit.ProjectCreate, {
@@ -15,6 +15,8 @@
import deepEqual from 'deep-equal';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { Box } from '$lib/components';
import { TemplateLocale, TemplateType } from '@appwrite.io/console';
import { isValueOfStringEnum } from '$lib/helpers/types';
export let loading = false;
let openResetModal = false;
@@ -29,6 +31,13 @@
});
return;
}
if (!isValueOfStringEnum(TemplateType, $emailTemplate.type)) {
throw new Error(`Invalid template type: ${$emailTemplate.type}`);
}
if (!isValueOfStringEnum(TemplateLocale, $emailTemplate.locale)) {
throw new Error(`Invalid template locale: ${$emailTemplate.locale}`);
}
try {
switch ($emailTemplate.type) {
case 'invitation':
@@ -1,9 +1,11 @@
import { invalidate } from '$app/navigation';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { Dependencies } from '$lib/constants';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { addNotification } from '$lib/stores/notifications';
import type { Provider } from '$lib/stores/oauth-providers';
import { sdk } from '$lib/stores/sdk';
import { OAuthProvider } from '@appwrite.io/console';
type Args = {
projectId: string;
@@ -26,6 +28,9 @@ export async function updateOAuth({
enabled
}: Args): Promise<Return> {
try {
if (!isValueOfStringEnum(OAuthProvider, provider.key)) {
throw new Error(`Invalid OAuth2 provider: ${provider.key}`);
}
await sdk.forConsole.projects.updateOAuth2(
projectId,
provider.key,
@@ -1,18 +1,15 @@
import type { Metric, UsageUsers } from '$lib/sdk/usage';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { UserUsageRange } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
const { period } = params;
const period = isValueOfStringEnum(UserUsageRange, params.period)
? params.period
: UserUsageRange.ThirtyDays;
try {
const response = (await sdk.forProject.users.getUsage(
period ?? '30d'
)) as unknown as UsageUsers;
return {
usersTotal: response.usersTotal,
users: response.users as Metric[]
};
return sdk.forProject.users.getUsage(period);
} catch (e) {
throw error(e.code, e.message);
}
@@ -11,8 +11,10 @@
TableHeader,
TableRow
} from '$lib/elements/table';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Container, ContainerHeader } from '$lib/layout';
import { sdk } from '$lib/stores/sdk';
import { Browser } from '@appwrite.io/console';
import DeleteAllSessions from '../deleteAllSessions.svelte';
import DeleteSessions from '../deleteSession.svelte';
import type { PageData } from './$types';
@@ -23,8 +25,11 @@
let showDeleteAll = false;
let selectedSessionId: string;
const getBrowser = (clientCode: string) =>
sdk.forProject.avatars.getBrowser(clientCode, 40, 40);
function getBrowser(clientCode: string) {
const code = clientCode.toLowerCase();
if (!isValueOfStringEnum(Browser, code)) return '';
return sdk.forProject.avatars.getBrowser(code, 40, 40);
}
</script>
<Container>
@@ -46,15 +51,23 @@
</TableHeader>
<TableBody>
{#each data.sessions.sessions as session}
{@const browser = getBrowser(session.clientCode)}
<TableRow>
<TableCell title="Client">
<div class="u-flex u-gap-12 u-cross-center">
<div class="avatar">
<img
height="20"
width="20"
src={getBrowser(session.clientCode).toString()}
alt={session.clientName} />
{#if browser}
<img
height="20"
width="20"
src={getBrowser(session.clientCode).toString()}
alt={session.clientName} />
{:else}
<span
class="icon-globe-alt"
style="font-size: 20px"
aria-hidden="true" />
{/if}
</div>
<p class="text">
{session.clientName}
@@ -1,9 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import { Button } from '$lib/elements/forms';
import {
Empty,
EmptySearch,
PaginationWithLimit,
Heading,
ViewSelector,
@@ -93,7 +91,7 @@
total={data.targets.total} />
{:else if $hasPageQueries}
<EmptyFilter resource="targets" />
{:else if data.search}
<!-- {:else if data.search}
<EmptySearch>
<div class="u-text-center">
<b>Sorry, we couldn't find '{data.search}'</b>
@@ -104,7 +102,7 @@
href={`/console/project-${$page.params.project}/auth/user-${$page.params.user}/targets`}>
Clear Search
</Button>
</EmptySearch>
</EmptySearch> -->
{:else}
<!-- TODO: update docs link -->
<Empty
@@ -1,60 +1,33 @@
import { queries, queryParamToMap } from '$lib/components/filters';
import { Dependencies, PAGE_LIMIT } from '$lib/constants';
import { getLimit, getPage, getQuery, getSearch, pageToOffset } from '$lib/helpers/load';
import { getLimit, getPage, getQuery, pageToOffset } from '$lib/helpers/load';
import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params, url, route, depends }) => {
depends(Dependencies.USER_TARGETS);
const page = getPage(url);
const limit = getLimit(url, route, PAGE_LIMIT);
const offset = pageToOffset(page, limit);
const search = getSearch(url);
const query = getQuery(url);
const parsedQueries = queryParamToMap(query || '[]');
queries.set(parsedQueries);
const payload = {
queries: [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]
};
if (search) {
payload['search'] = search;
}
// TODO: remove when the API is ready with data
// This allows us to mock w/ data and when search returns 0 results
const targets: { targets: Models.Target[]; total: number } = await sdk.forProject.client.call(
'GET',
new URL(`${sdk.forProject.client.config.endpoint}/users/${params.user}/targets`),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
payload
);
const targets = await sdk.forProject.users.listTargets(params.user, [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]);
const promisesById: Record<string, Promise<Models.Provider>> = {};
targets.targets.forEach((target) => {
if (target.providerId && !promisesById[target.providerId]) {
promisesById[target.providerId] = sdk.forProject.client.call(
'GET',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/${target.providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
promisesById[target.providerId] = sdk.forProject.messaging.getProvider(
target.providerId
);
}
});
@@ -71,7 +44,6 @@ export const load: PageLoad = async ({ params, url, route, depends }) => {
return {
offset,
limit,
search,
query,
targets,
providersById
@@ -9,12 +9,11 @@
import InputEmail from '$lib/elements/forms/inputEmail.svelte';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { ProviderTypes } from '$routes/console/project-[project]/messaging/providerType.svelte';
import { ID } from '@appwrite.io/console';
import { ID, MessagingProviderType } from '@appwrite.io/console';
export let show = false;
let providerType = ProviderTypes.Push;
let providerType = MessagingProviderType.Push;
let identifier = '';
let name = '';
let providerId = '';
@@ -22,38 +21,20 @@
let showCustomId = false;
const providerTypeOptions = [
{ label: 'Push', value: ProviderTypes.Push },
{ label: 'Email', value: ProviderTypes.Email },
{ label: 'SMS', value: ProviderTypes.Sms }
{ label: 'Push', value: MessagingProviderType.Push },
{ label: 'Email', value: MessagingProviderType.Email },
{ label: 'SMS', value: MessagingProviderType.Sms }
];
const create = async () => {
try {
const payload = {
targetId: id ? id : ID.unique(),
await sdk.forProject.users.createTarget(
$page.params.user,
id ? id : ID.unique(),
providerType,
identifier
};
if (providerId) {
payload['providerId'] = providerId;
}
if (name) {
payload['name'] = name;
}
await sdk.forProject.client.call(
'POST',
new URL(
`${sdk.forProject.client.config.endpoint}/users/${$page.params.user}/targets`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
payload
identifier,
providerId ?? undefined,
name ?? undefined
);
show = false;
addNotification({
@@ -78,7 +59,7 @@
// Ensure values are reset when modal is opened
$: if (show) {
showCustomId = false;
providerType = ProviderTypes.Push;
providerType = MessagingProviderType.Push;
identifier = '';
name = '';
providerId = '';
@@ -97,7 +78,7 @@
label="Provider Type"
bind:value={providerType}
options={providerTypeOptions} />
{#if providerType === ProviderTypes.Push}
{#if providerType === MessagingProviderType.Push}
<InputText
id="provider-id"
label="Provider ID"
@@ -116,14 +97,14 @@
placeholder="Enter target name"
bind:value={name}
required />
{:else if providerType === ProviderTypes.Email}
{:else if providerType === MessagingProviderType.Email}
<InputEmail
id="identifier"
label="Identifier"
placeholder="Enter email"
bind:value={identifier}
required />
{:else if providerType === ProviderTypes.Sms}
{:else if providerType === MessagingProviderType.Sms}
<InputPhone
id="identifier"
label="Identifier"
@@ -15,9 +15,7 @@
import type { PageData } from './$types';
import { columns } from './store';
import { toLocaleDateTime } from '$lib/helpers/date';
import ProviderType, {
ProviderTypes
} from '$routes/console/project-[project]/messaging/providerType.svelte';
import ProviderType from '$routes/console/project-[project]/messaging/providerType.svelte';
import Provider from '$routes/console/project-[project]/messaging/provider.svelte';
import { sdk } from '$lib/stores/sdk';
import { page } from '$app/stores';
@@ -25,6 +23,7 @@
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
import { invalidate } from '$app/navigation';
import { MessagingProviderType } from '@appwrite.io/console';
export let data: PageData;
@@ -35,21 +34,9 @@
async function handleDelete() {
showDelete = false;
async function deleteTarget(id: string) {
await sdk.forProject.client.call(
'DELETE',
new URL(
`${sdk.forProject.client.config.endpoint}/users/${$page.params.user}/targets/${id}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
}
const promises = selectedIds.map((id) => deleteTarget(id));
const promises = selectedIds.map((id) =>
sdk.forProject.users.deleteTarget($page.params.user, id)
);
try {
await Promise.all(promises);
@@ -103,7 +90,7 @@
{/key}
{:else if column.id === 'target'}
<TableCell title={column.title}>
{#if target.providerType === ProviderTypes.Push}
{#if target.providerType === MessagingProviderType.Push}
{target.name}
{:else}
{target.identifier}
@@ -17,25 +17,12 @@
let error = '';
onMount(async () => {
// TODO: Remove type cast when console SDK is updated
labels = [...($user as unknown as { labels: string[] }).labels];
labels = [...$user.labels];
});
async function updateLabels() {
try {
// TODO: Use SDK method when console SDK is updated
// await sdk.forProject.users.updateLabels($user.$id, labels);
const path = `/users/${$user.$id}/labels`;
await sdk.forProject.client.call(
'PUT',
new URL(sdk.forConsole.client.config.endpoint + path),
{
'content-type': 'application/json'
},
{
labels: labels
}
);
await sdk.forProject.users.updateLabels($user.$id, labels);
await invalidate(Dependencies.USER);
isDisabled = true;
@@ -1,5 +1,5 @@
<script context="module" lang="ts">
import { Query, type Models } from '@appwrite.io/console';
import { Query, type Models, RelationshipType, RelationMutate } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
export async function submitRelationship(
@@ -8,6 +8,12 @@
_key: string,
data: Partial<Models.AttributeRelationship>
) {
if (!isValueOfStringEnum(RelationshipType, data.relationType)) {
throw new Error(`Invalid relationship type: ${data.relationType}`);
}
if (!isValueOfStringEnum(RelationMutate, data.onDelete)) {
throw new Error(`Invalid on delete: ${data.onDelete}`);
}
await sdk.forProject.databases.createRelationshipAttribute(
databaseId,
collectionId,
@@ -25,6 +31,9 @@
collectionId: string,
data: Partial<Models.AttributeRelationship>
) {
if (!isValueOfStringEnum(RelationMutate, data.onDelete)) {
throw new Error(`Invalid on delete: ${data.onDelete}`);
}
await sdk.forProject.databases.updateRelationshipAttribute(
databaseId,
collectionId,
@@ -44,6 +53,7 @@
import arrowTwo from './arrow-two.svg';
import { camelize } from '$lib/helpers/string';
import { SelectSearchItem } from '$lib/elements';
import { isValueOfStringEnum } from '$lib/helpers/types';
// Props
export let data: Models.AttributeRelationship;
@@ -9,6 +9,7 @@
import { remove } from '$lib/helpers/array';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { IndexType } from '@appwrite.io/console';
import { isRelationship } from '../document-[document]/attributes/store';
import { indexes, type Attributes } from '../store';
import { collection } from '../store';
@@ -22,11 +23,11 @@
let error: string;
let key = `index_${$indexes.length + 1}`;
let types = [
{ value: 'key', label: 'Key' },
{ value: 'unique', label: 'Unique' },
{ value: 'fulltext', label: 'FullText' }
{ value: IndexType.Key, label: 'Key' },
{ value: IndexType.Unique, label: 'Unique' },
{ value: IndexType.Fulltext, label: 'FullText' }
];
let selectedType = 'key';
let selectedType = IndexType.Key;
let attributeOptions = $collection.attributes
.filter((attribute) => !isRelationship(attribute))
@@ -41,7 +42,7 @@
attributeList = externalAttribute
? [{ value: externalAttribute.key, order: 'ASC' }]
: [{ value: '', order: 'ASC' }];
selectedType = 'key';
selectedType = IndexType.Key;
key = `index_${$indexes.length + 1}`;
}
@@ -1,16 +1,11 @@
import type { Metric, UsageCollection } from '$lib/sdk/usage';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { DatabaseUsageRange } from '@appwrite.io/console';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params }) => {
const response = (await sdk.forProject.databases.getCollectionUsage(
params.database,
params.collection,
params.period ?? '30d'
)) as unknown as UsageCollection;
return {
documentsTotal: response.documentsTotal,
documents: response.documents as Metric[]
};
const period = isValueOfStringEnum(DatabaseUsageRange, params.period)
? params.period
: DatabaseUsageRange.ThirtyDays;
return sdk.forProject.databases.getCollectionUsage(params.database, params.collection, period);
};
@@ -1,15 +1,11 @@
import type { Metric, UsageDatabase } from '$lib/sdk/usage';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { DatabaseUsageRange } from '@appwrite.io/console';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params }) => {
const response = (await sdk.forProject.databases.getDatabaseUsage(
params.database,
params.period ?? '30d'
)) as unknown as UsageDatabase;
return {
collectionsTotal: response.collectionsTotal,
collections: response.collections as Metric[]
};
const period = isValueOfStringEnum(DatabaseUsageRange, params.period)
? params.period
: DatabaseUsageRange.ThirtyDays;
return sdk.forProject.databases.getDatabaseUsage(params.database, period);
};
@@ -1,18 +1,15 @@
import type { Metric, UsageDatabases } from '$lib/sdk/usage';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { sdk } from '$lib/stores/sdk';
import { DatabaseUsageRange } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
const { period } = params;
const period = isValueOfStringEnum(DatabaseUsageRange, params.period)
? params.period
: DatabaseUsageRange.ThirtyDays;
try {
const response = (await sdk.forProject.databases.getUsage(
period ?? '30d'
)) as unknown as UsageDatabases;
return {
databasesTotal: response.databasesTotal,
databases: response.databases as Metric[]
};
return sdk.forProject.databases.getUsage(period);
} catch (e) {
throw error(e.code, e.message);
}
@@ -16,7 +16,8 @@
import { base } from '$app/paths';
import { page } from '$app/stores';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { ID } from '@appwrite.io/console';
import { ID, Runtime } from '@appwrite.io/console';
import { isValueOfStringEnum } from '$lib/helpers/types';
const projectId = $page.params.project;
@@ -26,6 +27,9 @@
async function create() {
try {
if (!isValueOfStringEnum(Runtime, $createFunction.runtime)) {
throw new Error(`Invalid runtime: ${$createFunction.runtime}`);
}
const response = await sdk.forProject.functions.create(
$createFunction.id ?? ID.unique(),
$createFunction.name,
@@ -1,8 +1,9 @@
<script lang="ts">
import { Container } from '$lib/layout';
import type { PageData } from './$types';
import { ProxyRulesPage, ProxyTypes } from '$lib/pages/domains';
import { ProxyRulesPage } from '$lib/pages/domains';
import { Dependencies } from '$lib/constants';
import { ResourceType } from '@appwrite.io/console';
export let data: PageData;
</script>
@@ -10,7 +11,7 @@
<Container>
<ProxyRulesPage
rules={data.rules}
type={ProxyTypes.FUNCTION}
type={ResourceType.Function}
dependency={Dependencies.FUNCTION_DOMAINS}>
<svelte:fragment slot="heading">Domains</svelte:fragment>
</ProxyRulesPage>
@@ -1,15 +1,14 @@
import { Dependencies } from '$lib/constants';
import { sdk } from '$lib/stores/sdk';
import { Query } from '@appwrite.io/console';
import { Query, ResourceType } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import { ProxyTypes } from '$lib/pages/domains/index.svelte';
export const load: PageLoad = async ({ depends, params }) => {
depends(Dependencies.FUNCTION_DOMAINS);
return {
rules: await sdk.forProject.proxy.listRules([
Query.equal('resourceType', ProxyTypes.FUNCTION),
Query.equal('resourceType', ResourceType.Function),
Query.equal('resourceId', params.function)
])
};
@@ -15,23 +15,23 @@
import Label from '$lib/elements/forms/label.svelte';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { ExecutionMethod, type Models } from '@appwrite.io/console';
export let selectedFunction: Models.Function = null;
let path = '/';
let method = 'GET';
let method = ExecutionMethod.GET;
let body = '';
let headers: [string, string][] = [['', '']];
let error: string = null;
const methodOptions = [
{ label: 'GET', value: 'GET' },
{ label: 'POST', value: 'POST' },
{ label: 'PUT', value: 'PUT' },
{ label: 'PATCH', value: 'PATCH' },
{ label: 'DELETE', value: 'DELETE' },
{ label: 'OPTIONS', value: 'OPTIONS' }
{ label: 'GET', value: ExecutionMethod.GET },
{ label: 'POST', value: ExecutionMethod.POST },
{ label: 'PUT', value: ExecutionMethod.PUT },
{ label: 'PATCH', value: ExecutionMethod.PATCH },
{ label: 'DELETE', value: ExecutionMethod.DELETE },
{ label: 'OPTIONS', value: ExecutionMethod.OPTIONS }
];
let show = false;
@@ -9,6 +9,8 @@
import { sdk } from '$lib/stores/sdk';
import { createEventDispatcher } from 'svelte';
import { func } from '../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
export let show = false;
const functionId = $page.params.function;
@@ -18,6 +20,9 @@
const handleSubmit = async () => {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -8,12 +8,13 @@
import { timeFromNow, toLocaleDateTime } from '$lib/helpers/date';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { Runtime, type Models } from '@appwrite.io/console';
import { func, repositories } from '../store';
import { invalidate } from '$app/navigation';
import InputSelectSearch from '$lib/elements/forms/inputSelectSearch.svelte';
import { sortBranches } from './updateConfiguration.svelte';
import { installations } from '$lib/wizards/functions/store';
import { isValueOfStringEnum } from '$lib/helpers/types';
export let show: boolean;
@@ -48,6 +49,9 @@
async function handleSubmit() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -36,7 +36,7 @@
} from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { Runtime, type Models } from '@appwrite.io/console';
import { func } from '../store';
import GitInstallationModal from '$routes/console/project-[project]/settings/GitInstallationModal.svelte';
import GitConfigurationModal from './gitConfigurationModal.svelte';
@@ -50,6 +50,7 @@
import { installations } from '$lib/wizards/functions/store';
import { isSelfHosted } from '$lib/system';
import { consoleVariables } from '$routes/console/store';
import { isValueOfStringEnum } from '$lib/helpers/types';
const functionId = $page.params.function;
const isVcsEnabled = $consoleVariables?._APP_VCS_ENABLED === true;
@@ -114,6 +115,9 @@
async function updateConfiguration() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -19,6 +19,8 @@
import { Button } from '$lib/elements/forms';
import DropList from '$lib/components/dropList.svelte';
import DropListItem from '$lib/components/dropListItem.svelte';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
const eventSet: Writable<Set<string>> = writable(new Set($func.events));
@@ -29,6 +31,9 @@
async function updateEvents() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -11,6 +11,8 @@
import { project } from '$routes/console/project-[project]/store';
import { onMount } from 'svelte';
import { func } from '../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
let functionLogging: boolean = null;
@@ -21,6 +23,9 @@
async function updateLogging() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -9,6 +9,8 @@
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { func } from '../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
let functionName: string = null;
@@ -19,6 +21,9 @@
async function updateName() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
functionName,
@@ -11,6 +11,8 @@
import { func } from '../store';
import { Roles } from '$lib/components/permissions';
import { symmetricDifference } from '$lib/helpers/array';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
@@ -23,6 +25,9 @@
async function updatePermissions() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -11,6 +11,8 @@
import { func } from '../store';
import InputSelect from '$lib/elements/forms/inputSelect.svelte';
import { runtimesList } from '../../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
let runtime: string = null;
@@ -29,6 +31,9 @@
async function updateRuntime() {
try {
if (!isValueOfStringEnum(Runtime, runtime)) {
throw new Error(`Invalid runtime: ${runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -9,6 +9,8 @@
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { func } from '../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
let functionSchedule: string = null;
@@ -19,6 +21,9 @@
async function updateSchedule() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -9,6 +9,8 @@
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { func } from '../store';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { Runtime } from '@appwrite.io/console';
const functionId = $page.params.function;
let timeout: number = null;
@@ -19,6 +21,9 @@
async function updateTimeout() {
try {
if (!isValueOfStringEnum(Runtime, $func.runtime)) {
throw new Error(`Invalid runtime: ${$func.runtime}`);
}
await sdk.forProject.functions.update(
functionId,
$func.name,
@@ -1,19 +1,15 @@
import type { Metric, UsageFunctions } from '$lib/sdk/usage';
import { sdk } from '$lib/stores/sdk';
import { FunctionUsageRange } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { isValueOfStringEnum } from '$lib/helpers/types';
export const load: PageLoad = async ({ params }) => {
try {
const response = (await sdk.forProject.functions.getFunctionUsage(
params.function,
params.period ?? '30d'
)) as unknown as UsageFunctions;
return {
executionsTotal: response.executionsTotal,
executions: response.executions as Metric[]
};
const period = isValueOfStringEnum(FunctionUsageRange, params.period)
? params.period
: FunctionUsageRange.ThirtyDays;
return sdk.forProject.functions.getFunctionUsage(params.function, period);
} catch (e) {
throw error(e.code, e.message);
}
@@ -8,6 +8,7 @@
FloatingActionBar,
Heading,
Id,
Modal,
PaginationWithLimit,
SearchQuery,
ViewSelector
@@ -27,16 +28,23 @@
} from '$lib/elements/table';
import { toLocaleDateTime } from '$lib/helpers/date';
import { Container } from '$lib/layout';
import { MessageType, MessagingProviderType } from '@appwrite.io/console';
import type { PageData } from './$types';
import CreateMessageDropdown from './createMessageDropdown.svelte';
import FailedModal from './failedModal.svelte';
import MessageStatusPill from './messageStatusPill.svelte';
import ProviderType, { ProviderTypes } from './providerType.svelte';
import ProviderType from './providerType.svelte';
import { columns, showCreate } from './store';
import { sdk } from '$lib/stores/sdk';
import { invalidate } from '$app/navigation';
import { trackEvent, Submit, trackError } from '$lib/actions/analytics';
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
export let data: PageData;
let selected: string[] = [];
let showDelete = false;
let deleting = false;
let showFailed = false;
let errors: string[] = [];
let showCreateDropdownMobile = false;
@@ -45,7 +53,32 @@
const project = $page.params.project;
$: console.log(showDelete);
async function handleDelete() {
showDelete = false;
const promises = selected.map((id) => sdk.forProject.messaging.delete(id));
try {
await Promise.all(promises);
trackEvent(Submit.MessagingMessageDelete, {
total: selected.length
});
addNotification({
type: 'success',
message: `${selected.length} message${selected.length > 1 ? 's' : ''} deleted`
});
} catch (error) {
addNotification({
type: 'error',
message: error.message
});
trackError(error, Submit.MessagingMessageDelete);
} finally {
invalidate(Dependencies.MESSAGING_MESSAGES);
selected = [];
showDelete = false;
}
}
</script>
<Container>
@@ -105,7 +138,10 @@
{#each data.messages.messages as message (message.$id)}
<TableRowLink
href={`${base}/console/project-${project}/messaging/message-${message.$id}`}>
<TableCellCheck bind:selectedIds={selected} id={message.$id} />
<TableCellCheck
bind:selectedIds={selected}
id={message.$id}
disabled={message.status === MessageType.Processing} />
{#each $columns as column (column.id)}
{#if column.show}
@@ -117,11 +153,11 @@
{/key}
{:else if column.id === 'message'}
<TableCellText title={column.title} width={column.width}>
{#if message.providerType === ProviderTypes.Push}
{#if message.providerType === MessagingProviderType.Push}
{message.data.title}
{:else if message.providerType === ProviderTypes.Sms}
{:else if message.providerType === MessagingProviderType.Sms}
{message.data.content}
{:else if message.providerType === ProviderTypes.Email}
{:else if message.providerType === MessagingProviderType.Email}
{message.data.subject}
{:else}
Invalid provider
@@ -175,7 +211,6 @@
<div class="u-flex u-cross-center u-gap-8">
<Button text on:click={() => (selected = [])}>Cancel</Button>
<!-- TODO: handle delete -->
<Button secondary on:click={() => (showDelete = true)}>
<p>Delete</p>
</Button>
@@ -248,3 +283,21 @@
</Container>
<FailedModal bind:show={showFailed} {errors} />
<Modal
title="Delete messages"
icon="exclamation"
state="warning"
bind:show={showDelete}
onSubmit={handleDelete}
headerDivider={false}
closable={!deleting}>
<p class="text" data-private>
Are you sure you want to delete <b>{selected.length}</b>
{selected.length > 1 ? 'messages' : 'message'}?
</p>
<svelte:fragment slot="footer">
<Button text on:click={() => (showDelete = false)} disabled={deleting}>Cancel</Button>
<Button secondary submit disabled={deleting}>Delete</Button>
</svelte:fragment>
</Modal>
@@ -1,5 +1,5 @@
import { queries, queryParamToMap } from '$lib/components/filters';
import { CARD_LIMIT } from '$lib/constants';
import { CARD_LIMIT, Dependencies } from '$lib/constants';
import {
View,
getLimit,
@@ -13,7 +13,9 @@ import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ url, route }) => {
export const load: PageLoad = async ({ depends, url, route }) => {
depends(Dependencies.MESSAGING_MESSAGES);
const page = getPage(url);
const search = getSearch(url);
const view = getView(url, route, View.Grid);
@@ -24,38 +26,6 @@ export const load: PageLoad = async ({ url, route }) => {
const parsedQueries = queryParamToMap(query || '[]');
queries.set(parsedQueries);
// TODO: remove when the API is ready with data
// This allows us to mock w/ data and when search returns 0 results
let messages: {
messages: ({ data: Record<string, string> } & Models.Message)[];
total: number;
} = { messages: [], total: 0 };
const params = {
queries: [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]
};
if (search) {
params['search'] = search;
}
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/messages'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
messages = response;
return {
offset,
limit,
@@ -63,6 +33,17 @@ export const load: PageLoad = async ({ url, route }) => {
query,
page,
view,
messages
messages: sdk.forProject.messaging.listMessages(
[
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
],
search || undefined
) as Promise<{
total: number;
messages: (Models.Message & { data: Record<string, string> })[]; // Add typing for message.data
}>
};
};
@@ -3,14 +3,14 @@
import { createEventDispatcher } from 'svelte';
import { targetsById } from './wizard/store';
import UserTargetsModal from './userTargetsModal.svelte';
import type { ProviderTypes } from './providerType.svelte';
import TopicsModal from './topicsModal.svelte';
import { topicsById } from './store';
import type { MessagingProviderType } from '@appwrite.io/console';
export let showDropdown: boolean;
export let showUserTargets: boolean;
export let showTopics: boolean;
export let providerType: ProviderTypes = null;
export let providerType: MessagingProviderType = null;
const dispatch = createEventDispatcher();
@@ -5,8 +5,8 @@
import { providers } from './providers/store';
import Wizard from './wizard.svelte';
import { messageParams, operation, providerType, targetsById } from './wizard/store';
import { ProviderTypes } from './providerType.svelte';
import { topicsById } from './store';
import { MessagingProviderType } from '@appwrite.io/console';
export let showCreateDropdown = false;
</script>
@@ -24,9 +24,9 @@
icon={option.icon}
on:click={() => {
if (
type !== ProviderTypes.Email &&
type !== ProviderTypes.Sms &&
type !== ProviderTypes.Push
type !== MessagingProviderType.Email &&
type !== MessagingProviderType.Sms &&
type !== MessagingProviderType.Push
)
return;
$providerType = type;
@@ -39,20 +39,20 @@
targets: []
};
switch (type) {
case ProviderTypes.Email:
case MessagingProviderType.Email:
$messageParams[$providerType] = {
...common,
subject: '',
content: ''
};
break;
case ProviderTypes.Sms:
case MessagingProviderType.Sms:
$messageParams[$providerType] = {
...common,
content: ''
};
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
$messageParams[$providerType] = {
...common,
title: '',
@@ -10,31 +10,11 @@ export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.MESSAGING_MESSAGE);
try {
const response: Models.Message = await sdk.forProject.client.call(
'GET',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/${params.message}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
const message = await sdk.forProject.messaging.getMessage(params.message);
const topicsById = {};
const topicsById: Record<string, Models.Topic> = {};
const topicsPromise = Promise.allSettled(
response.topics.map((topicId) => {
return sdk.forProject.client.call(
'GET',
new URL(`${sdk.forProject.client.config.endpoint}/messaging/topics/${topicId}`),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
})
message.topics.map((topicId) => sdk.forProject.messaging.getTopic(topicId))
).then((results) => {
results.forEach((result) => {
if (result.status === 'fulfilled') {
@@ -43,19 +23,9 @@ export const load: LayoutLoad = async ({ params, depends }) => {
});
});
const targetsById = {};
const targetsPromise = sdk.forProject.client
.call(
'GET',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/${params.message}/targets`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
)
const targetsById: Record<string, Models.Target> = {};
const targetsPromise = sdk.forProject.messaging
.listTargets(params.message)
.then((response) => {
response.targets.forEach((target) => {
targetsById[target.$id] = target;
@@ -64,12 +34,22 @@ export const load: LayoutLoad = async ({ params, depends }) => {
await Promise.allSettled([topicsPromise, targetsPromise]);
const usersById: Record<string, Models.User<Models.Preferences>> = {};
const usersPromise = Object.values(targetsById).map((target) =>
sdk.forProject.users.get(target.userId).then((user) => {
usersById[user.$id] = user;
})
);
await Promise.allSettled(usersPromise);
return {
message,
topicsById,
targetsById,
usersById,
header: Header,
breadcrumbs: Breadcrumbs,
message: response
breadcrumbs: Breadcrumbs
};
} catch (e) {
throw error(e.code, e.message);
@@ -4,26 +4,22 @@
import EmailPreview from './emailPreview.svelte';
import Overview from './overview.svelte';
import { message } from './store';
import { ProviderTypes } from '../providerType.svelte';
import SMSPreview from './smsPreview.svelte';
import PushPreview from './pushPreview.svelte';
import {
MessageStatuses,
messageParams,
operation,
providerType,
targetsById
} from '../wizard/store';
import { messageParams, operation, providerType, targetsById } from '../wizard/store';
import { topicsById } from '../store';
import { wizard } from '$lib/stores/wizard';
import Wizard from '../wizard.svelte';
import type { PageData } from './$types';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { MessageType, MessagingProviderType } from '@appwrite.io/console';
import Topics from './topics.svelte';
import Targets from './targets.svelte';
export let data: PageData;
async function onEdit() {
if (!isValueOfStringEnum(ProviderTypes, $message.providerType)) {
if (!isValueOfStringEnum(MessagingProviderType, $message.providerType)) {
throw new Error(`Invalid provider type: ${$message.providerType}`);
}
$operation = 'update';
@@ -39,12 +35,12 @@
topics: $message.topics,
users: $message.users,
targets: $message.targets,
status: MessageStatuses.DRAFT,
status: MessageType.Draft,
scheduledAt: $message.scheduledAt
};
switch ($providerType) {
case ProviderTypes.Email:
case MessagingProviderType.Email:
{
const { data } = $message;
const params = ['subject', 'content', 'html'];
@@ -55,7 +51,7 @@
});
}
break;
case ProviderTypes.Sms:
case MessagingProviderType.Sms:
{
const { data } = $message;
const params = ['content'];
@@ -66,7 +62,7 @@
});
}
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
{
const { data } = $message;
const params = [
@@ -99,18 +95,20 @@
<Container>
<Overview />
{#if $message.providerType === ProviderTypes.Email}
{#if $message.providerType === MessagingProviderType.Email}
<EmailPreview
message={$message}
onEdit={$message.status === MessageStatuses.DRAFT ? onEdit : null} />
{:else if $message.providerType === ProviderTypes.Sms}
onEdit={$message.status === MessageType.Draft ? onEdit : null} />
{:else if $message.providerType === MessagingProviderType.Sms}
<SMSPreview
message={$message}
onEdit={$message.status === MessageStatuses.DRAFT ? onEdit : null} />
{:else if $message.providerType === ProviderTypes.Push}
onEdit={$message.status === MessageType.Draft ? onEdit : null} />
{:else if $message.providerType === MessagingProviderType.Push}
<PushPreview
message={$message}
onEdit={$message.status === MessageStatuses.DRAFT ? onEdit : null} />
onEdit={$message.status === MessageType.Draft ? onEdit : null} />
{/if}
<Topics topics={Object.values(data.topicsById)} />
<Targets targets={Object.values(data.targetsById)} usersById={data.usersById} />
<Delete />
</Container>
@@ -2,6 +2,7 @@
import { BoxAvatar, CardGrid, Heading } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { toLocaleDateTime } from '$lib/helpers/date';
import { MessageType } from '@appwrite.io/console';
import DeleteModal from './deleteModal.svelte';
import { message } from './store';
@@ -31,7 +32,11 @@
</svelte:fragment>
<svelte:fragment slot="actions">
<Button secondary on:click={() => (showDelete = true)} event="delete_file">Delete</Button>
<Button
disabled={$message.status === MessageType.Processing}
secondary
on:click={() => (showDelete = true)}
event="delete_file">Delete</Button>
</svelte:fragment>
</CardGrid>
@@ -13,17 +13,7 @@
const deleteMessage = async () => {
try {
await sdk.forProject.client.call(
'DELETE',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/${$message.$id}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
await sdk.forProject.messaging.delete($message.$id);
show = false;
addNotification({
type: 'success',
@@ -2,8 +2,9 @@
import { CardGrid, Heading } from '$lib/components';
import { toLocaleDateTime } from '$lib/helpers/date';
import { message } from './store';
import ProviderType, { ProviderTypes } from '../providerType.svelte';
import ProviderType from '../providerType.svelte';
import MessageStatusPill from '../messageStatusPill.svelte';
import { MessagingProviderType } from '@appwrite.io/console';
let scheduledAt: string = '';
if ($message.status === 'sent') {
@@ -14,13 +15,13 @@
let providerType = 'Invalid provider type';
switch ($message.providerType) {
case ProviderTypes.Email:
case MessagingProviderType.Email:
providerType = 'Email';
break;
case ProviderTypes.Sms:
case MessagingProviderType.Sms:
providerType = 'SMS';
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
providerType = 'Push';
break;
}
@@ -0,0 +1,62 @@
<script lang="ts">
import { MessagingProviderType, type Models } from '@appwrite.io/console';
import {
Table,
TableBody,
TableCell,
TableCellHead,
TableCellText,
TableHeader,
TableRow
} from '$lib/elements/table';
import { CardGrid, Heading, Empty, PaginationInline, Id } from '$lib/components';
export let targets: Models.Target[];
export let usersById: Record<string, Models.User<Models.Preferences>>;
let offset = 0;
const limit = 10;
</script>
<CardGrid>
<Heading tag="h6" size="7" id="variables">Targets</Heading>
<svelte:fragment slot="aside">
{@const sum = targets.length}
{#if sum}
<div class="u-flex u-flex-vertical u-gap-24">
<Table noMargin noStyles>
<TableHeader>
<TableCellHead>ID</TableCellHead>
<TableCellHead>Name</TableCellHead>
<TableCellHead>Identifier</TableCellHead>
</TableHeader>
<TableBody>
{#each targets.slice(offset, offset + limit) as target (target.$id)}
<TableRow>
<TableCell title="id">
<Id value={target.$id}>{target.$id}</Id>
</TableCell>
<TableCellText title="name">
{usersById[target.userId]?.name || 'Unknown'}
</TableCellText>
<TableCellText title="subscribers">
{target.providerType === MessagingProviderType.Push
? target.name
: target.identifier}
</TableCellText>
</TableRow>
{/each}
</TableBody>
</Table>
<div class="u-flex u-main-space-between">
<p class="text">Total targets: {sum}</p>
<PaginationInline {sum} {limit} bind:offset />
</div>
</div>
{:else}
<Empty>Edit the message to add a Target</Empty>
{/if}
</svelte:fragment>
</CardGrid>
@@ -0,0 +1,59 @@
<script lang="ts">
import type { Models } from '@appwrite.io/console';
import {
Table,
TableBody,
TableCell,
TableCellHead,
TableCellText,
TableHeader,
TableRow
} from '$lib/elements/table';
import { CardGrid, Heading, Empty, PaginationInline, Id } from '$lib/components';
export let topics: Models.Topic[];
let offset = 0;
const limit = 10;
</script>
<CardGrid>
<Heading tag="h6" size="7" id="variables">Topics</Heading>
<svelte:fragment slot="aside">
{@const sum = topics.length}
{#if sum}
<div class="u-flex u-flex-vertical u-gap-24">
<Table noMargin noStyles>
<TableHeader>
<TableCellHead>ID</TableCellHead>
<TableCellHead>Name</TableCellHead>
<TableCellHead>Subscribers</TableCellHead>
</TableHeader>
<TableBody>
{#each topics.slice(offset, offset + limit) as topic (topic.$id)}
<TableRow>
<TableCell title="id">
<Id value={topic.$id}>{topic.$id}</Id>
</TableCell>
<TableCellText title="name">
{topic.name}
</TableCellText>
<TableCellText title="subscribers">
{topic.total}
</TableCellText>
</TableRow>
{/each}
</TableBody>
</Table>
<div class="u-flex u-main-space-between">
<p class="text">Total topics: {sum}</p>
<PaginationInline {sum} {limit} bind:offset />
</div>
</div>
{:else}
<Empty>Edit the message to add a Topic</Empty>
{/if}
</svelte:fragment>
</CardGrid>
@@ -7,6 +7,7 @@
Vonage = 'vonage',
Mailgun = 'mailgun',
Sendgrid = 'sendgrid',
SMTP = 'smtp',
FCM = 'fcm',
APNS = 'apns'
}
@@ -49,6 +50,10 @@
case Providers.Mailgun:
icon = 'mailgun';
break;
case Providers.SMTP:
icon = 'smtp';
displayName = name || 'SMTP';
break;
case Providers.Twilio:
icon = 'twilio';
break;
@@ -78,10 +83,14 @@
class="avatar"
class:is-size-large={size === 'l'}
class:is-size-small={size === 's'}>
<img
style:--p-text-size={textSize}
src={`${base}/icons/${$app.themeInUse}/color/${icon}.svg`}
alt={displayName} />
{#if provider === Providers.SMTP}
<span style:--p-text-size={textSize} class="icon-mail" />
{:else}
<img
style:--p-text-size={textSize}
src={`${base}/icons/${$app.themeInUse}/color/${icon}.svg`}
alt={displayName} />
{/if}
</div>
{/if}
<slot>
@@ -1,15 +1,8 @@
<script context="module" lang="ts">
export enum ProviderTypes {
Email = 'email',
Sms = 'sms',
Push = 'push'
}
</script>
<script lang="ts">
import type { Models } from '@appwrite.io/console';
import { MessagingProviderType } from '@appwrite.io/console';
export let type: ProviderTypes | Models.Provider['type'];
export let type: MessagingProviderType | Models.Provider['type'];
export let noIcon = false;
export let size: 's' | 'm' | 'l' = 'm';
@@ -17,15 +10,15 @@
let text = '';
switch (type) {
case ProviderTypes.Email:
case MessagingProviderType.Email:
icon = 'icon-mail';
text = 'Email';
break;
case ProviderTypes.Sms:
case MessagingProviderType.Sms:
icon = 'icon-annotation';
text = 'SMS';
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
icon = 'icon-device-mobile';
text = 'Push';
break;
@@ -1,4 +1,4 @@
import { Query, type Models } from '@appwrite.io/console';
import { Query } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import {
View,
@@ -25,34 +25,6 @@ export const load = async ({ depends, url, route }) => {
const parsedQueries = queryParamToMap(query || '[]');
queries.set(parsedQueries);
// TODO: get rid of demo data
let providers: { providers: Models.Provider[]; total: number } = { providers: [], total: 0 };
const params = {
queries: [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]
};
if (search) {
params['search'] = search;
}
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/providers'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
providers = response;
return {
offset,
limit,
@@ -60,6 +32,14 @@ export const load = async ({ depends, url, route }) => {
query,
page,
view,
providers
providers: sdk.forProject.messaging.listProviders(
[
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
],
search || undefined
)
};
};
@@ -12,204 +12,125 @@
import { project } from '../../store';
import { wizard } from '$lib/stores/wizard';
import { provider, providerParams } from './wizard/store';
import { ID } from '@appwrite.io/console';
import { ID, type Models } from '@appwrite.io/console';
import { Providers } from '../provider.svelte';
async function create() {
try {
let response = { $id: '', name: '' };
let response: Models.Provider;
const providerId = $providerParams[$provider].providerId || ID.unique();
switch ($provider) {
case Providers.Twilio:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/twilio'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
accountSid: $providerParams[$provider].accountSid,
authToken: $providerParams[$provider].authToken,
from: $providerParams[$provider].from
}
response = await sdk.forProject.messaging.createTwilioProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].from,
$providerParams[$provider].accountSid,
$providerParams[$provider].authToken,
$providerParams[$provider].enabled
);
break;
case Providers.Msg91:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/msg91'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
senderId: $providerParams[$provider].senderId,
authKey: $providerParams[$provider].authKey
}
response = await sdk.forProject.messaging.createMsg91Provider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].from,
$providerParams[$provider].senderId,
$providerParams[$provider].authKey,
$providerParams[$provider].enabled
);
break;
case Providers.Telesign:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/telesign'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
username: $providerParams[$provider].username,
password: $providerParams[$provider].password
}
response = await sdk.forProject.messaging.createTelesignProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].from,
$providerParams[$provider].username,
$providerParams[$provider].password,
$providerParams[$provider].enabled
);
break;
case Providers.Textmagic:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/textmagic'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
username: $providerParams[$provider].username,
apiKey: $providerParams[$provider].apiKey
}
response = await sdk.forProject.messaging.createTextmagicProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].from,
$providerParams[$provider].username,
$providerParams[$provider].apiKey,
$providerParams[$provider].enabled
);
break;
case Providers.Vonage:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/vonage'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
apiKey: $providerParams[$provider].apiKey,
apiSecret: $providerParams[$provider].apiSecret
}
response = await sdk.forProject.messaging.createVonageProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].from,
$providerParams[$provider].apiKey,
$providerParams[$provider].apiSecret,
$providerParams[$provider].enabled
);
break;
case Providers.Mailgun:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/mailgun'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
isEuRegion: $providerParams[$provider].isEuRegion,
fromEmail: $providerParams[$provider].fromEmail,
fromName: $providerParams[$provider].fromName,
replyToEmail: $providerParams[$provider].replyToEmail,
replyToName: $providerParams[$provider].replyToName,
apiKey: $providerParams[$provider].apiKey,
domain: $providerParams[$provider].domain
}
response = await sdk.forProject.messaging.createMailgunProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].apiKey,
$providerParams[$provider].domain,
$providerParams[$provider].isEuRegion,
$providerParams[$provider].fromName,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName,
$providerParams[$provider].replyToEmail,
$providerParams[$provider].enabled
);
break;
case Providers.Sendgrid:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/sendgrid'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
fromEmail: $providerParams[$provider].fromEmail,
fromName: $providerParams[$provider].fromName,
replyToEmail: $providerParams[$provider].replyToEmail,
replyToName: $providerParams[$provider].replyToName,
apiKey: $providerParams[$provider].apiKey
}
response = await sdk.forProject.messaging.createSendgridProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].apiKey,
$providerParams[$provider].fromName,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName,
$providerParams[$provider].replyToEmail,
$providerParams[$provider].enabled
);
break;
case Providers.SMTP:
response = await sdk.forProject.messaging.createSMTPProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].host,
$providerParams[$provider].port || undefined,
$providerParams[$provider].username || undefined,
$providerParams[$provider].password || undefined,
$providerParams[$provider].encryption,
$providerParams[$provider].autoTLS,
$providerParams[$provider].mailer || undefined,
$providerParams[$provider].fromName || undefined,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName || undefined,
$providerParams[$provider].replyToEmail || undefined,
$providerParams[$provider].enabled
);
break;
case Providers.FCM:
response = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/providers/fcm'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
serviceAccountJSON: $providerParams[$provider].serviceAccountJSON
}
response = await sdk.forProject.messaging.createFCMProvider(
providerId,
$providerParams[$provider].name,
JSON.parse($providerParams[$provider].serviceAccountJSON),
$providerParams[$provider].enabled
);
break;
case Providers.APNS:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/apns'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
authKey: $providerParams[$provider].authKey,
authKeyId: $providerParams[$provider].authKeyId,
teamId: $providerParams[$provider].teamId,
bundleId: $providerParams[$provider].bundleId
}
response = await sdk.forProject.messaging.createAPNSProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].authKey,
$providerParams[$provider].authKeyId,
$providerParams[$provider].teamId,
$providerParams[$provider].bundleId,
$providerParams[$provider].enabled
);
break;
}
@@ -5,9 +5,9 @@
import { providers } from './store';
import Create from './create.svelte';
import { providerType, provider } from './wizard/store';
import { ProviderTypes } from '../providerType.svelte';
import { Providers } from '../provider.svelte';
import { isValueOfStringEnum } from '$lib/helpers/types';
import { MessagingProviderType } from '@appwrite.io/console';
export let showCreateDropdown = false;
</script>
@@ -25,9 +25,9 @@
icon={option.icon}
on:click={() => {
if (
type !== ProviderTypes.Email &&
type !== ProviderTypes.Sms &&
type !== ProviderTypes.Push
type !== MessagingProviderType.Email &&
type !== MessagingProviderType.Sms &&
type !== MessagingProviderType.Push
)
return;
$providerType = type;
@@ -3,28 +3,13 @@ import Breadcrumbs from './breadcrumbs.svelte';
import Header from './header.svelte';
import { sdk } from '$lib/stores/sdk';
import { Dependencies } from '$lib/constants';
import { error } from '@sveltejs/kit';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.MESSAGING_PROVIDER);
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/providers/' + params.provider),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
try {
return {
header: Header,
breadcrumbs: Breadcrumbs,
provider: response
};
} catch (e) {
throw error(e.code, e.message);
}
return {
header: Header,
breadcrumbs: Breadcrumbs,
provider: sdk.forProject.messaging.getProvider(params.provider)
};
};
@@ -14,17 +14,7 @@
const deleteProvider = async () => {
try {
await sdk.forProject.client.call(
'DELETE',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/providers/' + $provider.$id
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
await sdk.forProject.messaging.deleteProvider($provider.$id);
showDelete = false;
addNotification({
type: 'success',
@@ -10,8 +10,9 @@
import { sdk } from '$lib/stores/sdk';
import { wizard } from '$lib/stores/wizard';
import { onMount } from 'svelte';
import { MessagingProviderType } from '@appwrite.io/console';
import Provider, { Providers } from '../../provider.svelte';
import ProviderType, { ProviderTypes } from '../../providerType.svelte';
import ProviderType from '../../providerType.svelte';
import Update from '../update.svelte';
import { providerParams, providerType, provider as wizardProvider } from '../wizard/store';
import { provider } from './store';
@@ -23,7 +24,7 @@
});
function configure() {
if (!isValueOfStringEnum(ProviderTypes, $provider.type)) {
if (!isValueOfStringEnum(MessagingProviderType, $provider.type)) {
throw new Error(`Invalid provider type: ${$provider.type}`);
}
@@ -104,6 +105,24 @@
fromEmail: $provider.options['from']
};
break;
case Providers.SMTP:
$providerParams[$wizardProvider] = {
providerId: $provider.$id,
name: $provider.name,
enabled: $provider.enabled,
host: $provider.credentials['host'],
port: $provider.credentials['port'],
username: $provider.credentials['username'],
password: $provider.credentials['password'],
fromName: $provider.options['fromName'],
fromEmail: $provider.options['fromEmail'],
replyToName: $provider.options['replyToName'],
replyToEmail: $provider.options['replyToEmail'],
encryption: $provider.options['encryption'],
autoTLS: $provider.options['autoTLS'],
mailer: $provider.options['mailer']
};
break;
case Providers.FCM:
$providerParams[$wizardProvider] = {
providerId: $provider.$id,
@@ -134,165 +153,86 @@
const providerId = $provider.$id;
switch ($provider.provider) {
case Providers.Twilio:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/twilio/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateTwilioProvider(
providerId,
undefined,
enabled
);
break;
case Providers.Msg91:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/msg91/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateMsg91Provider(
providerId,
undefined,
enabled
);
break;
case Providers.Telesign:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/telesign/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateTelesignProvider(
providerId,
undefined,
enabled
);
break;
case Providers.Textmagic:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/textmagic/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateTextmagicProvider(
providerId,
undefined,
enabled
);
break;
case Providers.Vonage:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/vonage/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateVonageProvider(
providerId,
undefined,
enabled
);
break;
case Providers.Mailgun:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/mailgun/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateMailgunProvider(
providerId,
undefined,
undefined,
undefined,
undefined,
enabled
);
break;
case Providers.Sendgrid:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/sendgrid/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateSendgridProvider(
providerId,
undefined,
enabled
);
break;
case Providers.SMTP:
response = await sdk.forProject.messaging.updateSMTPProvider(
providerId,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
enabled
);
break;
case Providers.FCM:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/fcm/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateFCMProvider(
providerId,
undefined,
enabled
);
break;
case Providers.APNS:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
sdk.forProject.client.config.endpoint +
'/messaging/providers/apns/' +
providerId
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
enabled: enabled
}
response = await sdk.forProject.messaging.updateAPNSProvider(
providerId,
undefined,
enabled
);
break;
}
@@ -1,7 +1,7 @@
import type { Column } from '$lib/helpers/types';
import { writable } from 'svelte/store';
import { Providers } from '../provider.svelte';
import { ProviderTypes } from '../providerType.svelte';
import { MessagingProviderType, SMTPEncryption } from '@appwrite.io/console';
export const columns = writable<Column[]>([
{ id: '$id', title: 'Provider ID', type: 'string', show: true },
@@ -12,24 +12,27 @@ export const columns = writable<Column[]>([
]);
type ProvidersMap = {
[key in ProviderTypes]: {
[key in MessagingProviderType]: {
name: string;
text: string;
icon: string;
providers: {
[key in Providers]?: {
imageIcon: string;
imageIcon?: string;
classIcon?: string;
title: string;
link: string;
description: string;
configure: {
label: string;
name: string;
type: 'text' | 'password' | 'phone' | 'email' | 'domain' | 'file' | 'switch';
type: 'text' | 'password' | 'phone' | 'email' | 'domain' | 'file' | 'switch' | 'select';
placeholder?: string;
description?: string;
popover?: string[];
allowedFileExtensions?: string[];
optional?: boolean;
options?: { label: string; value: string | number | boolean }[];
}[];
};
};
@@ -37,7 +40,7 @@ type ProvidersMap = {
};
export const providers: ProvidersMap = {
[ProviderTypes.Push]: {
[MessagingProviderType.Push]: {
name: 'Push notification',
text: 'notifications',
icon: 'device-mobile',
@@ -138,7 +141,7 @@ export const providers: ProvidersMap = {
// }
}
},
[ProviderTypes.Email]: {
[MessagingProviderType.Email]: {
name: 'Email',
text: 'emails',
icon: 'mail',
@@ -188,18 +191,21 @@ export const providers: ProvidersMap = {
label: 'Sender name',
name: 'fromName',
type: 'text',
optional: true,
placeholder: 'Enter name'
},
{
label: 'Reply-to email',
name: 'replyToEmail',
type: 'email',
optional: true,
placeholder: 'Enter email'
},
{
label: 'Reply-to name',
name: 'replyToName',
type: 'text',
optional: true,
placeholder: 'Enter name'
}
]
@@ -231,18 +237,107 @@ export const providers: ProvidersMap = {
label: 'Sender name',
name: 'fromName',
type: 'text',
optional: true,
placeholder: 'Enter name'
},
{
label: 'Reply-to email',
name: 'replyToEmail',
type: 'email',
optional: true,
placeholder: 'Enter email'
},
{
label: 'Reply-to name',
name: 'replyToName',
type: 'text',
optional: true,
placeholder: 'Enter name'
}
]
},
[Providers.SMTP]: {
classIcon: 'mail',
title: 'SMTP',
link: '',
description: '',
configure: [
{
label: 'Host',
name: 'host',
type: 'text',
placeholder: 'Enter host'
},
{
label: 'Port',
name: 'port',
type: 'text',
optional: true,
placeholder: 'Enter port'
},
{
label: 'Username',
name: 'username',
type: 'text',
optional: true,
placeholder: 'Enter username'
},
{
label: 'Password',
name: 'password',
type: 'text',
optional: true,
placeholder: 'Enter password'
},
{
label: 'Encryption',
name: 'encryption',
type: 'select',
options: [
{ label: 'None', value: SMTPEncryption.None },
{ label: 'SSL', value: SMTPEncryption.Ssl },
{ label: 'TLS', value: SMTPEncryption.Tls }
]
},
{
label: 'Auto TLS',
name: 'autoTLS',
description: 'Automatically uses TLS encryption',
type: 'switch',
optional: true
},
{
label: 'Mailer',
name: 'mailer',
type: 'text',
optional: true,
placeholder: 'Enter mailer'
},
{
label: 'Sender email',
name: 'fromEmail',
type: 'email',
placeholder: 'Enter email'
},
{
label: 'Sender name',
name: 'fromName',
type: 'text',
optional: true,
placeholder: 'Enter name'
},
{
label: 'Reply-to email',
name: 'replyToEmail',
type: 'email',
optional: true,
placeholder: 'Enter email'
},
{
label: 'Reply-to name',
name: 'replyToName',
type: 'text',
optional: true,
placeholder: 'Enter name'
}
]
@@ -250,7 +345,7 @@ export const providers: ProvidersMap = {
}
},
[ProviderTypes.Sms]: {
[MessagingProviderType.Sms]: {
name: 'SMS',
text: 'SMS',
icon: 'annotation',
@@ -357,7 +452,7 @@ export const providers: ProvidersMap = {
},
[Providers.Textmagic]: {
imageIcon: 'textmagic',
title: 'TextMagic',
title: 'TextMagic',
link: 'https://app.textmagic.com/login',
description: '',
configure: [
@@ -34,21 +34,7 @@
async function handleDelete() {
showDelete = false;
function deleteProvider(providerId: string) {
return sdk.forProject.client.call(
'DELETE',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
}
const promises = selectedIds.map((id) => deleteProvider(id));
const promises = selectedIds.map((id) => sdk.forProject.messaging.deleteProvider(id));
try {
await Promise.all(promises);
@@ -12,204 +12,123 @@
import { provider, providerParams } from './wizard/store';
import { Providers } from '../provider.svelte';
import { Dependencies } from '$lib/constants';
import type { Models } from '@appwrite.io/console';
async function update() {
try {
let response = { $id: '', name: '' };
let response: Models.Provider;
const providerId = $providerParams[$provider].providerId;
switch ($provider) {
case Providers.Twilio:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/twilio/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
accountSid: $providerParams[$provider].accountSid,
authToken: $providerParams[$provider].authToken,
from: $providerParams[$provider].from
}
response = await sdk.forProject.messaging.updateTwilioProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].accountSid,
$providerParams[$provider].authToken,
$providerParams[$provider].from
);
break;
case Providers.Msg91:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/msg91/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
senderId: $providerParams[$provider].senderId,
authKey: $providerParams[$provider].authKey
}
response = await sdk.forProject.messaging.updateMsg91Provider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].senderId,
$providerParams[$provider].authKey,
$providerParams[$provider].from
);
break;
case Providers.Telesign:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/telesign/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
username: $providerParams[$provider].username,
password: $providerParams[$provider].password
}
response = await sdk.forProject.messaging.updateTelesignProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].username,
$providerParams[$provider].password,
$providerParams[$provider].from
);
break;
case Providers.Textmagic:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/textmagic/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
username: $providerParams[$provider].username,
apiKey: $providerParams[$provider].apiKey
}
response = await sdk.forProject.messaging.updateTextmagicProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].username,
$providerParams[$provider].apiKey,
$providerParams[$provider].from
);
break;
case Providers.Vonage:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/vonage/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
from: $providerParams[$provider].from,
apiKey: $providerParams[$provider].apiKey,
apiSecret: $providerParams[$provider].apiSecret
}
response = await sdk.forProject.messaging.updateVonageProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].apiKey,
$providerParams[$provider].apiSecret,
$providerParams[$provider].from
);
break;
case Providers.Mailgun:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/mailgun/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
isEuRegion: $providerParams[$provider].isEuRegion,
fromEmail: $providerParams[$provider].fromEmail,
fromName: $providerParams[$provider].fromName,
replyToEmail: $providerParams[$provider].replyToEmail,
replyToName: $providerParams[$provider].replyToName,
apiKey: $providerParams[$provider].apiKey,
domain: $providerParams[$provider].domain
}
response = await sdk.forProject.messaging.updateMailgunProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].apiKey,
$providerParams[$provider].domain,
$providerParams[$provider].isEuRegion,
$providerParams[$provider].enabled,
$providerParams[$provider].fromName,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName,
$providerParams[$provider].replyToEmail
);
break;
case Providers.Sendgrid:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/sendgrid/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
fromEmail: $providerParams[$provider].fromEmail,
fromName: $providerParams[$provider].fromName,
replyToEmail: $providerParams[$provider].replyToEmail,
replyToName: $providerParams[$provider].replyToName,
apiKey: $providerParams[$provider].apiKey
}
response = await sdk.forProject.messaging.updateSendgridProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].apiKey,
$providerParams[$provider].fromName,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName,
$providerParams[$provider].replyToEmail
);
break;
case Providers.SMTP:
response = await sdk.forProject.messaging.updateSMTPProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].host,
$providerParams[$provider].port || undefined,
$providerParams[$provider].username || undefined,
$providerParams[$provider].password || undefined,
$providerParams[$provider].encryption,
$providerParams[$provider].autoTLS,
$providerParams[$provider].fromName || undefined,
$providerParams[$provider].fromEmail,
$providerParams[$provider].replyToName || undefined,
$providerParams[$provider].replyToEmail || undefined,
$providerParams[$provider].enabled
);
break;
case Providers.FCM:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/fcm')/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
serviceAccountJSON: $providerParams[$provider].serviceAccountJSON
}
response = await sdk.forProject.messaging.updateFCMProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
JSON.parse($providerParams[$provider].serviceAccountJSON)
);
break;
case Providers.APNS:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/providers/apns/${providerId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
providerId: providerId,
name: $providerParams[$provider].name,
enabled: $providerParams[$provider].enabled,
authKey: $providerParams[$provider].authKey,
authKeyId: $providerParams[$provider].authKeyId,
teamId: $providerParams[$provider].teamId,
bundleId: $providerParams[$provider].bundleId
}
response = await sdk.forProject.messaging.updateAPNSProvider(
providerId,
$providerParams[$provider].name,
$providerParams[$provider].enabled,
$providerParams[$provider].authKey,
$providerParams[$provider].authKeyId,
$providerParams[$provider].teamId,
$providerParams[$provider].bundleId
);
break;
}
@@ -4,6 +4,7 @@
InputDomain,
InputEmail,
InputFile,
InputSelect,
InputSwitch,
InputText,
InputPassword
@@ -58,6 +59,7 @@
id={input.name}
label={input.label}
placeholder={input.placeholder}
required={!input.optional}
isPopoverDefined={input.popover !== undefined}
bind:value={$providerParams[$provider][input.name]}>
<svelte:fragment slot="popover">
@@ -79,6 +81,7 @@
id={input.name}
label={input.label}
placeholder={input.placeholder}
required={!input.optional}
bind:value={$providerParams[$provider][input.name]}>
<svelte:fragment slot="popover">
<p class="body-text-2 u-margin-block-end-16">
@@ -91,6 +94,7 @@
id={input.name}
label={input.label}
placeholder={input.placeholder}
required={!input.optional}
bind:value={$providerParams[$provider][input.name]}>
<svelte:fragment slot="popover">
<p class="body-text-2 u-margin-block-end-16">
@@ -103,6 +107,7 @@
id={input.name}
label={input.label}
placeholder={input.placeholder}
required={!input.optional}
bind:value={$providerParams[$provider][input.name]}>
<svelte:fragment slot="popover">
<p class="body-text-2 u-margin-block-end-16">
@@ -114,6 +119,7 @@
<InputFile
label={input.label}
allowedFileExtensions={input.allowedFileExtensions}
required={!input.optional}
bind:files={files[input.name]}>
<svelte:fragment slot="popover">
<p class="body-text-2 u-margin-block-end-16">
@@ -125,11 +131,19 @@
<InputSwitch
label={input.label}
id={input.name}
required={!input.optional}
bind:value={$providerParams[$provider][input.name]}>
<svelte:fragment slot="description">
{input.description}
</svelte:fragment>
</InputSwitch>
{:else if input.type === 'select'}
<InputSelect
label={input.label}
id={input.name}
options={input.options}
required={!input.optional}
bind:value={$providerParams[$provider][input.name]} />
{/if}
{/each}
</FormList>
@@ -6,6 +6,7 @@
import { FormList, InputText } from '$lib/elements/forms';
import { Pill } from '$lib/elements';
import { Providers } from '../../provider.svelte';
import { SMTPEncryption } from '@appwrite.io/console';
let name = '';
let showCustomId = false;
@@ -91,6 +92,24 @@
replyToName: ''
};
break;
case Providers.SMTP:
$providerParams[$provider] = {
providerId: id,
name: name,
enabled: true,
host: '',
port: 587,
username: '',
password: '',
autoTLS: true,
encryption: SMTPEncryption.Tls,
mailer: '',
fromEmail: '',
fromName: '',
replyToEmail: '',
replyToName: ''
};
break;
case Providers.FCM:
$providerParams[$provider] = {
providerId: id,
@@ -116,7 +135,7 @@
<WizardStep {beforeSubmit}>
<svelte:fragment slot="title">Provider</svelte:fragment>
<FormList>
<FormList gap={16}>
<InputText
id="name"
label="Name"
@@ -144,7 +163,8 @@
name="provider"
{value}
bind:group={$provider}
imageIcon={option.imageIcon}>
imageIcon={option.imageIcon}
icon={option.classIcon}>
<svelte:fragment slot="title">{option.title}</svelte:fragment>
{#if option.description}
{option.description}
@@ -1,6 +1,6 @@
import { writable } from 'svelte/store';
import type { Providers } from '../../provider.svelte';
import type { ProviderTypes } from '../../providerType.svelte';
import type { MessagingProviderType, SMTPEncryption } from '@appwrite.io/console';
type ProviderParams = {
providerId: string;
@@ -64,6 +64,20 @@ export type SendgridProviderParams = ProviderParams & {
apiKey: string;
};
export type SMTPProviderParams = ProviderParams & {
fromEmail: string;
fromName: string;
replyToEmail: string;
replyToName: string;
host: string;
port: number;
username: string;
password: string;
encryption: SMTPEncryption;
autoTLS: boolean;
mailer: string;
};
/**
* Push providers
*/
@@ -83,7 +97,7 @@ export type MQTTProviderParams = ProviderParams & {
serverKey: string;
};
export const providerType = writable<ProviderTypes>(null);
export const providerType = writable<MessagingProviderType>(null);
export const provider = writable<Providers>(null);
export const providerParams = writable<{
twilio: Partial<TwilioProviderParams>;
@@ -93,6 +107,7 @@ export const providerParams = writable<{
vonage: Partial<VonageProviderParams>;
mailgun: Partial<MailgunProviderParams>;
sendgrid: Partial<SendgridProviderParams>;
smtp: Partial<SMTPProviderParams>;
fcm: Partial<FCMProviderParams>;
apns: Partial<APNSProviderParams>;
}>({
@@ -103,6 +118,7 @@ export const providerParams = writable<{
vonage: null,
mailgun: null,
sendgrid: null,
smtp: null,
fcm: null,
apns: null
});
@@ -1,161 +0,0 @@
import { writable } from 'svelte/store';
import type { Column } from '$lib/components/viewSelector.svelte';
export let showCreate = writable(false);
export const columns = writable<Column[]>([
{ id: '$id', title: 'Provider ID', show: true },
{ id: 'name', title: 'Name', show: true },
{ id: 'provider', title: 'Provider', show: true },
{ id: 'channel', title: 'Channel', show: true },
{ id: 'status', title: 'Status', show: true }
]);
export type Instruction = {
text: string;
input: {
label: string;
name: string;
type: 'text' | 'domain' | 'email';
placeholder: string;
};
};
export const providers = {
sms: {
name: 'SMS',
text: 'SMS',
icon: 'annotation',
providers: {
twilio: {
imageIcon: 'twilio',
title: 'Twilio',
description: ''
},
msg91: {
imageIcon: 'msg91',
title: 'MSG91',
description: ''
},
telesign: {
imageIcon: 'telesign',
title: 'Telesign',
description: ''
},
textmagic: {
imageIcon: 'textmagic',
title: 'Textmagic',
description: ''
},
vonage: {
imageIcon: 'vonage',
title: 'Vonage',
description: ''
}
}
},
email: {
name: 'Email',
text: 'emails',
icon: 'mail',
providers: {
mailgun: {
imageIcon: 'mailgun',
title: 'Mailgun',
description: '',
initialize: [
{
text: 'Before you can create a Mailgun provider, you need to first create a <a href="https://www.mailgun.com/" class="link" target="_blank" rel="noopener noreferrer">Mailgun</a> account.'
},
{
text: 'Head to your <b>Profile > API Security</b>.'
},
{
text: '<b>Generate a key</b> and give it a name. Copy and paste it in the field below.',
input: {
label: 'API key',
name: 'apiKey',
type: 'text',
placeholder: 'Enter API key'
}
},
{
// TODO: Update link to domain verification
text: 'Head to <b>Sending > Domains</b> and click on \'Add New Domain\'. Verify your domain by following the <a href="https://www.mailgun.com/" class="link" target="_blank" rel="noopener noreferrer">instructions</a>.',
input: {
label: 'Base URL',
name: 'baseUrl',
type: 'text',
placeholder: 'Enter base URL'
}
}
],
configure: [
{
text: 'Provide a display name your recipient will see when they receive your emails.',
input: {
label: 'From',
name: 'from',
type: 'text',
placeholder: 'Enter name'
}
},
{
text: 'Provide an email address that will be visible to the recipient as the senders email address for this message.',
input: {
label: 'From email address',
name: 'email',
type: 'email',
placeholder: 'Enter email'
}
},
{
text: 'Provide an email address for users to use when replying to your emails.',
input: {
label: 'Reply to',
name: 'replyTo',
type: 'email',
placeholder: 'Enter email'
}
},
{
text: 'Provide the domain as it is registered on Mailgun.',
input: {
label: 'Domain',
name: 'domain',
type: 'domain',
placeholder: 'Enter domain'
}
}
]
},
sendgrid: {
imageIcon: 'sendgrid',
title: 'Sendgrid',
description: ''
}
}
},
push: {
name: 'Push notification',
text: 'notifications',
icon: 'device-mobile',
providers: {
fcm: {
imageIcon: 'firebase',
title: 'FCM',
description: 'Firebase Cloud Messaging'
},
apns: {
imageIcon: 'apple',
title: 'APNS',
description: 'Apple Push Notification Service'
},
mqtt: {
imageIcon: 'mqtt',
title: 'MQTT',
description: 'Message Queuing Telemtry Transport'
}
}
}
};
@@ -1,4 +1,4 @@
import { Query, type Models } from '@appwrite.io/console';
import { Query } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { getLimit, getPage, getQuery, getSearch, pageToOffset } from '$lib/helpers/load';
import { Dependencies, PAGE_LIMIT } from '$lib/constants';
@@ -15,38 +15,20 @@ export const load = async ({ depends, url, route }) => {
const parsedQueries = queryParamToMap(query || '[]');
queries.set(parsedQueries);
const payload = {
queries: [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]
};
if (search) {
payload['search'] = search;
}
// TODO: remove when the API is ready with data
// This allows us to mock w/ data and when search returns 0 results
const topics: { topics: Models.Topic[]; total: number } = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/topics'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
payload
);
return {
offset,
limit,
search,
query,
page,
topics
topics: sdk.forProject.messaging.listTopics(
[
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
],
search || undefined
)
};
};
@@ -17,19 +17,7 @@
const create = async () => {
try {
const topic = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/topics'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
name,
topicId: id ?? ID.unique()
}
);
const topic = await sdk.forProject.messaging.createTopic(id ?? ID.unique(), name);
name = '';
showCreate = false;
showCustomId = false;
@@ -32,19 +32,7 @@
async function handleDelete() {
showDelete = false;
function deleteTopic(topicId: string) {
return sdk.forProject.client.call(
'DELETE',
new URL(`${sdk.forProject.client.config.endpoint}/messaging/topics/${topicId}`),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
}
const promises = selectedIds.map((id) => deleteTopic(id));
const promises = selectedIds.map((id) => sdk.forProject.messaging.deleteTopic(id));
try {
await Promise.all(promises);
@@ -3,28 +3,13 @@ import Breadcrumbs from './breadcrumbs.svelte';
import Header from './header.svelte';
import { sdk } from '$lib/stores/sdk';
import { Dependencies } from '$lib/constants';
import { error } from '@sveltejs/kit';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.MESSAGING_TOPIC);
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/topics/' + params.topic),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
try {
return {
header: Header,
breadcrumbs: Breadcrumbs,
topic: response
};
} catch (e) {
throw error(e.code, e.message);
}
return {
header: Header,
breadcrumbs: Breadcrumbs,
topic: sdk.forProject.messaging.getTopic(params.topic)
};
};
@@ -1,4 +1,4 @@
import { Query, type Models } from '@appwrite.io/console';
import { Query } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { getLimit, getPage, pageToOffset } from '$lib/helpers/load';
import { PAGE_LIMIT } from '$lib/constants';
@@ -9,26 +9,12 @@ export const load: PageLoad = async ({ params, url, route }) => {
const limit = getLimit(url, route, PAGE_LIMIT);
const offset = pageToOffset(page, limit);
const payload = {
queries: [Query.limit(limit), Query.offset(offset)]
};
// TODO: remove when the API is ready with data
// This allows us to mock w/ data and when search returns 0 results
const logs: Models.LogList = await sdk.forProject.client.call(
'GET',
new URL(`${sdk.forProject.client.config.endpoint}/messaging/topics/${params.topic}/logs`),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
payload
);
return {
offset,
limit,
logs
logs: sdk.forProject.messaging.listTopicLogs(params.topic, [
Query.limit(limit),
Query.offset(offset)
])
};
};
@@ -13,15 +13,8 @@
export let showDelete = false;
const deleteTopic = async () => {
try {
await sdk.forProject.client.call(
'DELETE',
new URL(sdk.forProject.client.config.endpoint + '/messaging/topics/' + $topic.$id),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
await sdk.forProject.messaging.deleteTopic($topic.$id);
showDelete = false;
addNotification({
type: 'success',
@@ -22,14 +22,13 @@
import { targetsById } from '../../../store';
import UserTargetsModal from '../../../userTargetsModal.svelte';
import { onMount } from 'svelte';
import type { Subscriber } from './+page';
import { Filters, hasPageQueries } from '$lib/components/filters';
import { columns } from './store';
import { View } from '$lib/helpers/load';
export let data: PageData;
let showAdd = false;
let subscribersByTargetId: Record<string, Subscriber> = {};
let subscribersByTargetId: Record<string, Models.Subscriber> = {};
onMount(() => {
$targetsById = {};
@@ -43,29 +42,13 @@
async function addTargets(event: CustomEvent<Record<string, Models.Target>>) {
showAdd = false;
$targetsById = event.detail;
async function addSubscriber(targetId: string) {
await sdk.forProject.client.call(
'POST',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/topics/${$page.params.topic}/subscribers`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
subscriberId: ID.unique(),
topicId: $page.params.topic,
targetId: targetId
}
);
}
const targetIds = Object.keys($targetsById).filter(
(targetId) => !(targetId in subscribersByTargetId)
);
const promises = targetIds.map(addSubscriber);
const promises = targetIds.map((targetId) =>
sdk.forProject.messaging.createSubscriber($page.params.topic, ID.unique(), targetId)
);
try {
await Promise.all(promises);
@@ -1,22 +1,13 @@
import { Query, type Models } from '@appwrite.io/console';
import { Query } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { getLimit, getPage, getQuery, getSearch, pageToOffset } from '$lib/helpers/load';
import { Dependencies, PAGE_LIMIT } from '$lib/constants';
import type { PageLoad } from './$types';
import { queryParamToMap, queries } from '$lib/components/filters';
export type Subscriber = {
$id: string;
$createdAt: string;
$updatedAt: string;
targetId: string;
target: Models.Target;
userName: string;
topicId: string;
};
export const load: PageLoad = async ({ params, url, route, depends, parent }) => {
export const load: PageLoad = async ({ params, url, route, depends }) => {
depends(Dependencies.MESSAGING_TOPIC_SUBSCRIBERS);
const page = getPage(url);
const limit = getLimit(url, route, PAGE_LIMIT);
const offset = pageToOffset(page, limit);
@@ -26,43 +17,20 @@ export const load: PageLoad = async ({ params, url, route, depends, parent }) =>
const parsedQueries = queryParamToMap(query || '[]');
queries.set(parsedQueries);
const payload = {
queries: [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
]
};
if (search) {
payload['search'] = search;
}
const { topic } = await parent();
// TODO: remove when the API is ready with data
// This allows us to mock w/ data and when search returns 0 results
const subscribers: { subscribers: Subscriber[]; total: number } =
await sdk.forProject.client.call(
'GET',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/topics/${params.topic}/subscribers`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
payload
);
return {
offset,
limit,
search,
query,
topic,
subscribers
subscribers: sdk.forProject.messaging.listSubscribers(
params.topic,
[
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values()
],
search || undefined
)
};
};
@@ -19,19 +19,19 @@
import { addNotification } from '$lib/stores/notifications';
import type { PageData } from './$types';
import { columns } from './store';
import ProviderType, { ProviderTypes } from '../../../providerType.svelte';
import ProviderType from '../../../providerType.svelte';
import { toLocaleDateTime } from '$lib/helpers/date';
import { project } from '$routes/console/project-[project]/store';
import { sdk } from '$lib/stores/sdk';
import { page } from '$app/stores';
import { targetsById } from '../../../store';
import type { Subscriber } from './+page';
import { MessagingProviderType, type Models } from '@appwrite.io/console';
export let data: PageData;
let subscribers: Record<string, Subscriber> = {};
let subscribers: Record<string, Models.Subscriber> = {};
let selectedIds: string[] = [];
let selected: Record<string, Subscriber> = {};
let selected: Record<string, Models.Subscriber> = {};
let showDelete = false;
let deleting = false;
@@ -39,17 +39,7 @@
showDelete = false;
async function deleteSubscriber(subscriberId: string) {
await sdk.forProject.client.call(
'DELETE',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/topics/${$page.params.topic}/subscribers/${subscriberId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
}
);
await sdk.forProject.messaging.deleteSubscriber($page.params.topic, subscriberId);
const { target } = subscribers[subscriberId];
const { [target.$id]: _, ...rest } = $targetsById;
$targetsById = rest;
@@ -125,7 +115,7 @@
</TableCell>
{:else if column.id === 'target'}
<TableCell title={column.title}>
{#if target.providerType === ProviderTypes.Push}
{#if target.providerType === MessagingProviderType.Push}
{target.name}
{:else}
{target.identifier}
@@ -15,19 +15,7 @@
});
async function updateName() {
try {
// await sdk.forProject.users.updateName($provider.$id, providerName);
await sdk.forProject.client.call(
'PATCH',
new URL(`${sdk.forProject.client.config.endpoint}/messaging/topics/${$topic.$id}`),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
name: name
}
);
await sdk.forProject.messaging.updateTopic($topic.$id, name);
await invalidate(Dependencies.MESSAGING_TOPIC);
addNotification({
message: 'Name has been updated',
@@ -4,6 +4,7 @@
import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import { createEventDispatcher } from 'svelte';
import { providerType } from './wizard/store';
export let show: boolean;
export let topicsById: Record<string, Models.Topic>;
@@ -32,25 +33,7 @@
if (!show) return;
const queries = [Query.limit(5), Query.offset(offset)];
const params = {
queries
};
if (search) {
params['search'] = search;
}
// TODO: replace with sdk.forProject.users.list once User type has targets
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/messaging/topics'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
const response = await sdk.forProject.messaging.listTopics(queries, search || undefined);
totalResults = response.total;
topicResultsById = {};
@@ -97,7 +80,10 @@
</script>
<Modal {title} bind:show onSubmit={submit} on:close={reset} size="big">
<p class="text">Select existing topics you want to send this message to its recipients.</p>
<p class="text">
Select existing topics you want to send this message to its subscribers. The message will be
sent only to {$providerType} targets.
</p>
<InputSearch
autofocus
disabled={totalResults === 0 && !search}
@@ -8,14 +8,14 @@
} from '$lib/components';
import { Button, FormList, InputCheckbox, InputSearch } from '$lib/elements/forms';
import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import { Query, type Models, MessagingProviderType } from '@appwrite.io/console';
import { createEventDispatcher } from 'svelte';
import ProviderType, { ProviderTypes } from './providerType.svelte';
import ProviderType from './providerType.svelte';
export let show: boolean;
export let targetsById: Record<string, Models.Target>;
export let providerType: ProviderTypes = null;
export let title = 'Select users';
export let providerType: MessagingProviderType = null;
export let title = 'Select subscribers';
const dispatch = createEventDispatcher();
@@ -40,31 +40,13 @@
if (!show) return;
const queries = [Query.limit(5), Query.offset(offset)];
if (providerType === ProviderTypes.Email) {
if (providerType === MessagingProviderType.Email) {
queries.push(Query.notEqual('email', ''));
} else if (providerType === ProviderTypes.Sms) {
} else if (providerType === MessagingProviderType.Sms) {
queries.push(Query.notEqual('phone', ''));
}
const params = {
queries
};
if (search) {
params['search'] = search;
}
// TODO: replace with sdk.forProject.users.list once User type has targets
const response = await sdk.forProject.client.call(
'GET',
new URL(sdk.forProject.client.config.endpoint + '/users'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
const response = await sdk.forProject.users.list(queries, search || undefined);
totalResults = response.total;
userResultsById = {};
@@ -135,8 +117,15 @@
}
</script>
<Modal {title} bind:show onSubmit={submit} on:close={reset} size="big">
<p class="text">Select recipients for this message from your users.</p>
<Modal {title} bind:show onSubmit={submit} on:close={reset} size="big" headerDivider={false}>
<!-- TODO: Update docs link -->
<p class="text">
Add subscribers to this topic by selecting the targets for directing messages. <a
href="https://appwrite.io/docs"
target="_blank"
rel="noopener noreferrer"
class="link">Learn more about subscribers.</a>
</p>
<InputSearch
autofocus
disabled={totalResults === 0 && !search}
@@ -189,7 +178,7 @@
><ProviderType
type={target.providerType}
noIcon /></span>
{#if target.providerType !== ProviderTypes.Push}
{#if target.providerType !== MessagingProviderType.Push}
{target.identifier}
{:else}
<!-- TODO: Show device info -->
@@ -11,79 +11,46 @@
import { base } from '$app/paths';
import { project } from '../store';
import { wizard } from '$lib/stores/wizard';
import {
providerType,
messageParams,
MessageStatuses,
type PushMessageParams,
type SMSMessageParams,
type EmailMessageParams,
operation
} from './wizard/store';
import { ProviderTypes } from './providerType.svelte';
import { ID } from '@appwrite.io/console';
import { providerType, messageParams, operation } from './wizard/store';
import { ID, MessageType, MessagingProviderType, type Models } from '@appwrite.io/console';
import { Dependencies } from '$lib/constants';
async function create() {
try {
let response = { $id: '' };
let response: Models.Message;
const messageId = $messageParams[$providerType].messageId || ID.unique();
const params = $messageParams[$providerType];
console.log(params);
const payload:
| Partial<SMSMessageParams>
| Partial<EmailMessageParams>
| Partial<PushMessageParams> = {
topics: params.topics || [],
users: params.users || [],
targets: params.targets || []
};
Object.keys(params).forEach((key) => {
if (['messageId', 'topics', 'users', 'targets'].includes(key)) return;
if (typeof params[key] === 'undefined') return;
payload[key] = params[key];
});
switch ($providerType) {
case ProviderTypes.Email:
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/messages/email'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
messageId
}
case MessagingProviderType.Email:
response = await sdk.forProject.messaging.createEmail(
messageId,
$messageParams[$providerType].subject,
$messageParams[$providerType].content,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
undefined,
undefined,
$messageParams[$providerType].status,
$messageParams[$providerType].html,
$messageParams[$providerType].scheduledAt
);
break;
case ProviderTypes.Sms:
response = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/messages/sms'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
messageId
}
case MessagingProviderType.Sms:
response = await sdk.forProject.messaging.createSMS(
messageId,
$messageParams[$providerType].content,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
$messageParams[$providerType].status,
$messageParams[$providerType].scheduledAt
);
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
{
const customData: Record<string, string> = {};
const { data } = $messageParams[ProviderTypes.Push];
const { data } = $messageParams[MessagingProviderType.Push];
if (data && data.length > 0) {
data.forEach((item) => {
if (item[0] === '') return;
@@ -91,35 +58,37 @@
});
}
response = await sdk.forProject.client.call(
'POST',
new URL(
sdk.forProject.client.config.endpoint + '/messaging/messages/push'
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
data: customData,
messageId
}
response = await sdk.forProject.messaging.createPush(
messageId,
$messageParams[$providerType].title,
$messageParams[$providerType].body,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
customData,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
$messageParams[$providerType].status,
$messageParams[$providerType].scheduledAt
);
}
break;
}
wizard.hide();
let message = '';
switch (params.status) {
case MessageStatuses.DRAFT:
switch (response.status) {
case MessageType.Draft:
message = 'The message has been saved as draft.';
break;
case MessageStatuses.PROCESSING:
case MessageType.Processing:
message = 'The message is queued for processing.';
break;
case MessageStatuses.SCHEDULED:
case 'scheduled':
// TODO: fix message status
message = 'The message has been scheduled.';
break;
}
@@ -129,7 +98,7 @@
});
trackEvent(Submit.MessagingMessageCreate, {
providerType: $providerType,
status: params.status
status: response.status
});
await goto(`${base}/console/project-${$project.$id}/messaging/message-${response.$id}`);
} catch (error) {
@@ -143,68 +112,45 @@
async function update() {
try {
let response = { $id: '' };
let response: Models.Message;
const messageId = $messageParams[$providerType].messageId;
const params = $messageParams[$providerType];
console.log(params);
const payload:
| Partial<SMSMessageParams>
| Partial<EmailMessageParams>
| Partial<PushMessageParams> = {
topics: params.topics || [],
users: params.users || [],
targets: params.targets || []
};
Object.keys(params).forEach((key) => {
if (['messageId', 'topics', 'users', 'targets'].includes(key)) return;
if (typeof params[key] === 'undefined') return;
payload[key] = params[key];
});
console.log(payload);
switch ($providerType) {
case ProviderTypes.Email:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/email/${messageId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
messageId
}
case MessagingProviderType.Email:
response = await sdk.forProject.messaging.updateEmail(
messageId,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
$messageParams[$providerType].subject,
$messageParams[$providerType].content,
$messageParams[$providerType].status,
$messageParams[$providerType].html,
undefined,
undefined,
$messageParams[$providerType].scheduledAt
);
break;
case ProviderTypes.Sms:
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/sms/${messageId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
messageId
}
case MessagingProviderType.Sms:
response = await sdk.forProject.messaging.updateSMS(
messageId,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
$messageParams[$providerType].content,
$messageParams[$providerType].status,
$messageParams[$providerType].scheduledAt
);
break;
case ProviderTypes.Push:
case MessagingProviderType.Push:
{
const customData: Record<string, string> = {};
const { data } = $messageParams[ProviderTypes.Push];
const { data } = $messageParams[MessagingProviderType.Push];
if (data && data.length > 0) {
data.forEach((item) => {
if (item[0] === '') return;
@@ -212,35 +158,37 @@
});
}
response = await sdk.forProject.client.call(
'PATCH',
new URL(
`${sdk.forProject.client.config.endpoint}/messaging/messages/push/${messageId}`
),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
{
...payload,
data: customData,
messageId
}
response = await sdk.forProject.messaging.updatePush(
messageId,
$messageParams[$providerType].topics,
$messageParams[$providerType].users,
$messageParams[$providerType].targets,
$messageParams[$providerType].title,
$messageParams[$providerType].body,
customData,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
$messageParams[$providerType].status,
$messageParams[$providerType].scheduledAt
);
}
break;
}
wizard.hide();
let message = '';
switch (params.status) {
case MessageStatuses.DRAFT:
switch (response.status) {
case MessageType.Draft:
message = 'The message has been saved as draft.';
break;
case MessageStatuses.PROCESSING:
case MessageType.Processing:
message = 'The message is queued for processing.';
break;
case MessageStatuses.SCHEDULED:
case 'scheduled':
// TODO: fix message status
message = 'The message has been scheduled.';
break;
}
@@ -264,7 +212,7 @@
}
async function saveDraft() {
$messageParams[$providerType].status = MessageStatuses.DRAFT;
$messageParams[$providerType].status = MessageType.Draft;
if ($operation === 'create') {
create();
} else {
@@ -1,28 +1,5 @@
<script context="module" lang="ts">
export async function createEmailMessage(params: EmailMessageParams) {
const response = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/messages/email'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
return response.json();
}
</script>
<script lang="ts">
import {
messageParams,
providerType,
type EmailMessageParams,
MessageStatuses,
operation
} from './store';
import { messageParams, providerType, operation } from './store';
import {
Button,
FormList,
@@ -36,9 +13,8 @@
import { CustomId, Modal } from '$lib/components';
import { user } from '$lib/stores/user';
import { clickOnEnter } from '$lib/helpers/a11y';
import { ID } from '@appwrite.io/console';
import { ID, MessageType, MessagingProviderType } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { ProviderTypes } from '../providerType.svelte';
let showCustomId = false;
let showTest = false;
@@ -49,17 +25,20 @@
const email = selected === 'self' ? $user.email : otherEmail;
console.log(email);
createEmailMessage({
topics: $messageParams[ProviderTypes.Email]?.topics || [],
targets: $messageParams[ProviderTypes.Email]?.targets || [],
status: MessageStatuses.PROCESSING,
messageId: ID.unique(),
// TODO: properly handle the test email address
users: ['steven'],
subject: $messageParams[ProviderTypes.Email]?.subject || '',
content: $messageParams[ProviderTypes.Email]?.content || '',
html: $messageParams[ProviderTypes.Email]?.html || false
});
// TODO: replace with test method
sdk.forProject.messaging.createEmail(
ID.unique(),
$messageParams[MessagingProviderType.Email]?.subject || undefined,
$messageParams[MessagingProviderType.Email]?.content || undefined,
$messageParams[MessagingProviderType.Email]?.topics || [],
$messageParams[MessagingProviderType.Email]?.users || [],
$messageParams[MessagingProviderType.Email]?.targets || [],
undefined,
undefined,
MessageType.Processing,
$messageParams[MessagingProviderType.Email]?.html || false,
undefined
);
}
$: otherEmail = selected === 'self' ? '' : otherEmail;
@@ -1,19 +1,4 @@
<script context="module" lang="ts">
export async function createPushMessage(params: PushMessageParams) {
const response = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/messages/push'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
return response.json();
}
export function validateData(data: string[][]) {
if (!data || data.length === 0) return;
@@ -39,13 +24,7 @@
</script>
<script lang="ts">
import {
messageParams,
providerType,
MessageStatuses,
type PushMessageParams,
operation
} from './store';
import { messageParams, providerType, operation } from './store';
import {
Button,
FormItem,
@@ -62,9 +41,8 @@
import { CustomId, Modal } from '$lib/components';
import { user } from '$lib/stores/user';
import { clickOnEnter } from '$lib/helpers/a11y';
import { ID } from '@appwrite.io/console';
import { ID, MessageType, MessagingProviderType } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { ProviderTypes } from '../providerType.svelte';
import PushPhone from '../pushPhone.svelte';
import { onMount } from 'svelte';
@@ -76,28 +54,35 @@
let customData: [string, string][] = [];
onMount(() => {
$messageParams[ProviderTypes.Push].data = customData || [['', '']];
$messageParams[MessagingProviderType.Push].data = customData || [['', '']];
});
async function sendTestMessage() {
const email = selected === 'self' ? $user.email : otherEmail;
console.log(email);
createPushMessage({
topics: $messageParams[ProviderTypes.Push]?.topics || [],
targets: $messageParams[ProviderTypes.Push]?.targets || [],
status: MessageStatuses.PROCESSING,
messageId: ID.unique(),
// TODO: properly handle the test email address
users: ['steven'],
body: $messageParams[ProviderTypes.Push]?.body || '',
title: $messageParams[ProviderTypes.Push]?.title || '',
data: $messageParams[ProviderTypes.Push]?.data || []
});
// TODO: replace with test method
sdk.forProject.messaging.createPush(
ID.unique(),
$messageParams[MessagingProviderType.Push]?.title || undefined,
$messageParams[MessagingProviderType.Push]?.body || undefined,
$messageParams[MessagingProviderType.Push]?.topics || [],
$messageParams[MessagingProviderType.Push]?.users || [],
$messageParams[MessagingProviderType.Push]?.targets || [],
$messageParams[MessagingProviderType.Push]?.data || undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
MessageType.Processing,
undefined
);
}
$: otherEmail = selected === 'self' ? '' : otherEmail;
$: customData = $messageParams[ProviderTypes.Push].data;
$: customData = $messageParams[MessagingProviderType.Push].data;
$: dataError = validateData(customData || []);
</script>
@@ -107,14 +92,14 @@
id="title"
label="Title"
placeholder="Enter title"
bind:value={$messageParams[ProviderTypes.Push]['title']}>
bind:value={$messageParams[MessagingProviderType.Push]['title']}>
</InputText>
<div class="u-colum-gap-2">
<InputTextarea
id="message"
label="Message"
placeholder="Type here..."
bind:value={$messageParams[ProviderTypes.Push]['body']}>
bind:value={$messageParams[MessagingProviderType.Push]['body']}>
</InputTextarea>
<!-- TODO: Add support for draft messages -->
<!-- <div class="u-flex u-main-end">
@@ -175,7 +160,9 @@
id={`${rowIndex}-key`}
isMultiple
fullWidth
bind:value={$messageParams[ProviderTypes.Push].data[rowIndex][0]}
bind:value={$messageParams[MessagingProviderType.Push].data[
rowIndex
][0]}
placeholder="Enter key"
label="Key"
showLabel={false} />
@@ -184,7 +171,9 @@
id={`${rowIndex}-value`}
isMultiple
fullWidth
bind:value={$messageParams[ProviderTypes.Push].data[rowIndex][1]}
bind:value={$messageParams[MessagingProviderType.Push].data[
rowIndex
][1]}
placeholder="Enter value"
label="Value"
showLabel={false}
@@ -194,13 +183,14 @@
text
on:click={() => {
if (customData.length === 1) {
$messageParams[ProviderTypes.Push].data = [['', '']];
$messageParams[MessagingProviderType.Push].data = [
['', '']
];
return;
}
$messageParams[ProviderTypes.Push].data = customData.filter(
(_, i) => i !== rowIndex
);
$messageParams[MessagingProviderType.Push].data =
customData.filter((_, i) => i !== rowIndex);
}}>
<span class="icon-x" aria-hidden="true" />
</Button>
@@ -216,7 +206,7 @@
text
disabled={customData && customData[customData.length - 1][0] === ''}
on:click={() => {
$messageParams[ProviderTypes.Push].data = [...customData, ['', '']];
$messageParams[MessagingProviderType.Push].data = [...customData, ['', '']];
}}>
<span class="icon-plus" aria-hidden="true" />
<span class="text">Add data</span>
@@ -1,36 +1,12 @@
<script context="module" lang="ts">
export async function createSMSMessage(params: EmailMessageParams) {
const response = await sdk.forProject.client.call(
'POST',
new URL(sdk.forProject.client.config.endpoint + '/messaging/messages/sms'),
{
'X-Appwrite-Project': sdk.forProject.client.config.project,
'content-type': 'application/json',
'X-Appwrite-Mode': 'admin'
},
params
);
return response.json();
}
</script>
<script lang="ts">
import {
messageParams,
providerType,
type EmailMessageParams,
MessageStatuses,
operation
} from './store';
import { messageParams, providerType, operation } from './store';
import { Button, FormList, InputEmail, InputRadio, InputTextarea } from '$lib/elements/forms';
import { Pill } from '$lib/elements';
import { CustomId, Modal } from '$lib/components';
import { user } from '$lib/stores/user';
import { clickOnEnter } from '$lib/helpers/a11y';
import { ID } from '@appwrite.io/console';
import { ID, MessageType, MessagingProviderType } from '@appwrite.io/console';
import { sdk } from '$lib/stores/sdk';
import { ProviderTypes } from '../providerType.svelte';
import SMSPhone from '../smsPhone.svelte';
let showCustomId = false;
@@ -41,17 +17,16 @@
async function sendTestSMS() {
// const email = selected === 'self' ? $user.email : otherEmail;
createSMSMessage({
topics: $messageParams[ProviderTypes.Email]?.topics || [],
targets: $messageParams[ProviderTypes.Email]?.targets || [],
status: MessageStatuses.PROCESSING,
messageId: ID.unique(),
// TODO: properly handle the test email address
users: ['steven'],
subject: $messageParams[ProviderTypes.Email]?.subject || '',
content: $messageParams[ProviderTypes.Email]?.content || '',
html: $messageParams[ProviderTypes.Email]?.html || false
});
// TODO: replace with test method
sdk.forProject.messaging.createSMS(
ID.unique(),
$messageParams[MessagingProviderType.Sms]?.content || undefined,
$messageParams[MessagingProviderType.Sms]?.topics || [],
$messageParams[MessagingProviderType.Sms]?.users || [],
$messageParams[MessagingProviderType.Sms]?.targets || [],
MessageType.Processing,
undefined
);
}
$: otherEmail = selected === 'self' ? '' : otherEmail;
@@ -2,10 +2,10 @@
import { WizardStep } from '$lib/layout';
import { messageParams, providerType } from './store';
import { providers } from '../providers/store';
import { ProviderTypes } from '../providerType.svelte';
import EmailFormList from './emailFormList.svelte';
import SmsFormList from './smsFormList.svelte';
import PushFormList, { validateData } from './pushFormList.svelte';
import { MessagingProviderType } from '@appwrite.io/console';
async function beforeSubmit() {}
@@ -23,18 +23,18 @@
<WizardStep
{beforeSubmit}
nextDisabled={$providerType === ProviderTypes.Push &&
!!validateData($messageParams[ProviderTypes.Push].data)}>
nextDisabled={$providerType === MessagingProviderType.Push &&
!!validateData($messageParams[MessagingProviderType.Push].data)}>
<svelte:fragment slot="title">Message</svelte:fragment>
<svelte:fragment slot="subtitle">
<!-- TODO: update documentation link -->
{createMessage(providers[$providerType].text)}
</svelte:fragment>
{#if $providerType === ProviderTypes.Email}
{#if $providerType === MessagingProviderType.Email}
<EmailFormList />
{:else if $providerType === ProviderTypes.Sms}
{:else if $providerType === MessagingProviderType.Sms}
<SmsFormList />
{:else if $providerType === ProviderTypes.Push}
{:else if $providerType === MessagingProviderType.Push}
<PushFormList />
{/if}
</WizardStep>
@@ -51,7 +51,7 @@
<svelte:fragment slot="title">Targets</svelte:fragment>
<!-- TODO: add support for topics -->
<svelte:fragment slot="subtitle"
>Select users to whom this message should be directed.</svelte:fragment>
>Select targets to whom this message should be directed.</svelte:fragment>
{#if targetIdsLength === 0 && topicIdsLength === 0}
<Card>
<div class="u-flex u-cross-center u-flex-vertical u-main-center u-flex">
@@ -67,7 +67,7 @@
</Button>
</Actions>
<div class="common-section">
<span class="text"> Select recipients to get started</span>
<span class="text"> Select targets to get started</span>
</div>
</div>
</Card>
@@ -2,7 +2,8 @@
import { FormList, InputDate, InputSelect, InputTime } from '$lib/elements/forms';
import Helper from '$lib/elements/forms/helper.svelte';
import { WizardStep } from '$lib/layout';
import { MessageStatuses, messageParams, providerType } from './store';
import { MessageType } from '@appwrite.io/console';
import { messageParams, providerType } from './store';
let when: 'now' | 'later' = 'now';
let now = new Date();
@@ -27,9 +28,9 @@
};
async function beforeSubmit() {
$messageParams[$providerType].status = MessageStatuses.PROCESSING;
$messageParams[$providerType].status = MessageType.Processing;
if (when === 'later') {
$messageParams[$providerType].status = MessageStatuses.SCHEDULED;
$messageParams[$providerType].status = 'scheduled' as MessageType;
$messageParams[$providerType].scheduledAt = dateTime.toISOString();
}
}
@@ -53,8 +54,7 @@
<svelte:fragment slot="title">Schedule</svelte:fragment>
<!-- TODO: Add link to docs -->
<svelte:fragment slot="subtitle"
>Schedule the time you want your users to receive this message. Learn more in our
documentation.</svelte:fragment>
>Schedule the time you want to deliver this message. Learn more in our documentation.</svelte:fragment>
<FormList>
<div
class="u-grid u-gap-24"
@@ -1,21 +1,12 @@
import type { Models } from '@appwrite.io/console';
import { MessageType, MessagingProviderType, type Models } from '@appwrite.io/console';
import { writable } from 'svelte/store';
import { ProviderTypes } from '../providerType.svelte';
export enum MessageStatuses {
DRAFT = 'draft',
SCHEDULED = 'scheduled',
PROCESSING = 'processing',
SENT = 'sent',
FAILED = 'failed'
}
export type MessageParams = {
messageId: string;
topics: string[];
users: string[];
targets: string[];
status: MessageStatuses;
status: MessageType;
scheduledAt?: string;
};
@@ -42,14 +33,14 @@ export type PushMessageParams = MessageParams & {
};
export const operation = writable<'create' | 'update'>('create');
export const providerType = writable<ProviderTypes>(null);
export const providerType = writable<MessagingProviderType>(null);
export const targetsById = writable<Record<string, Models.Target>>({});
export const messageParams = writable<{
[ProviderTypes.Email]: Partial<EmailMessageParams>;
[ProviderTypes.Sms]: Partial<SMSMessageParams>;
[ProviderTypes.Push]: Partial<PushMessageParams>;
[MessagingProviderType.Email]: Partial<EmailMessageParams>;
[MessagingProviderType.Sms]: Partial<SMSMessageParams>;
[MessagingProviderType.Push]: Partial<PushMessageParams>;
}>({
[ProviderTypes.Email]: null,
[ProviderTypes.Sms]: null,
[ProviderTypes.Push]: null
[MessagingProviderType.Email]: null,
[MessagingProviderType.Sms]: null,
[MessagingProviderType.Push]: null
});
@@ -5,6 +5,7 @@
import { sdk } from '$lib/stores/sdk';
import { createPlatform } from '../store';
import { Submit, trackEvent } from '$lib/actions/analytics';
import { PlatformType } from '@appwrite.io/console';
const projectId = $page.params.project;
@@ -24,7 +25,7 @@
const platform = await sdk.forConsole.projects.createPlatform(
projectId,
'android',
PlatformType.Android,
$createPlatform.name,
$createPlatform.key || undefined,
undefined,
@@ -6,15 +6,9 @@
import { sdk } from '$lib/stores/sdk';
import { createPlatform } from '../store';
import { Submit, trackEvent } from '$lib/actions/analytics';
import { PlatformType } from '@appwrite.io/console';
enum Platform {
iOS = 'apple-ios',
macOS = 'apple-macos',
watchOS = 'apple-watchos',
tvOS = 'apple-tvos'
}
let platform: Platform = Platform.iOS;
let platform: PlatformType = PlatformType.Appleios;
const projectId = $page.params.project;
@@ -50,26 +44,26 @@
<div class="u-flex u-gap-16 u-margin-block-start-8">
<Pill
button
on:click={() => (platform = Platform.iOS)}
selected={platform === Platform.iOS}>
on:click={() => (platform = PlatformType.Appleios)}
selected={platform === PlatformType.Appleios}>
iOS
</Pill>
<Pill
button
on:click={() => (platform = Platform.macOS)}
selected={platform === Platform.macOS}>
on:click={() => (platform = PlatformType.Applemacos)}
selected={platform === PlatformType.Applemacos}>
macOS
</Pill>
<Pill
button
on:click={() => (platform = Platform.watchOS)}
selected={platform === Platform.watchOS}>
on:click={() => (platform = PlatformType.Applewatchos)}
selected={platform === PlatformType.Applewatchos}>
watchOS
</Pill>
<Pill
button
on:click={() => (platform = Platform.tvOS)}
selected={platform === Platform.tvOS}>
on:click={() => (platform = PlatformType.Appletvos)}
selected={platform === PlatformType.Appletvos}>
tvOS
</Pill>
</div>
@@ -6,77 +6,123 @@
import { sdk } from '$lib/stores/sdk';
import { createPlatform } from '../store';
import { Submit, trackEvent } from '$lib/actions/analytics';
import { PlatformType } from '@appwrite.io/console';
import { isValueOfStringEnum } from '$lib/helpers/types';
enum Platform {
Android = 'flutter-android',
Ios = 'flutter-ios',
Linux = 'flutter-linux',
Macos = 'flutter-macos',
Windows = 'flutter-windows',
Web = 'flutter-web'
}
// enum Platform {
// Android = 'flutter-android',
// Ios = 'flutter-ios',
// Linux = 'flutter-linux',
// Macos = 'flutter-macos',
// Windows = 'flutter-windows',
// Web = 'flutter-web'
// }
function isPlatform(value: string): value is Platform {
return Object.values(Platform).includes(value as Platform);
}
// function isPlatform(value: string): value is Platform {
// return Object.values(Platform).includes(value as Platform);
// }
let platform: Platform = isPlatform($createPlatform.type)
let platform: PlatformType = isValueOfStringEnum(PlatformType, $createPlatform.type)
? $createPlatform.type
: Platform.Android;
: PlatformType.Flutterandroid;
const projectId = $page.params.project;
const suggestions = ['*.vercel.app', '*.netlify.app', '*.gitpod.io'];
const placeholder: Record<
Platform,
PlatformType,
{
name: string;
hostname: string;
tooltip: string;
}
> = {
[Platform.Android]: {
[PlatformType.Flutterandroid]: {
name: 'My Android App',
hostname: 'com.company.appname',
tooltip:
'Your package name is generally the applicationId in your app-level build.gradle file.'
},
[Platform.Ios]: {
[PlatformType.Flutterios]: {
name: 'My iOS App',
hostname: 'com.company.appname',
tooltip:
"You can find your Bundle Identifier in the General tab for your app's primary target in Xcode."
},
[Platform.Linux]: {
[PlatformType.Flutterlinux]: {
name: 'My Linux App',
hostname: 'appname',
tooltip: 'Your application name'
},
[Platform.Macos]: {
[PlatformType.Fluttermacos]: {
name: 'My mac OS App',
hostname: 'com.company.appname',
tooltip:
"You can find your Bundle Identifier in the General tab for your app's primary target in Xcode."
},
[Platform.Web]: {
[PlatformType.Flutterweb]: {
name: 'My Web App',
hostname: 'localhost',
tooltip:
'The hostname that your website will use to interact with the Appwrite APIs in production or development environments. No protocol or port number required.'
},
[Platform.Windows]: {
[PlatformType.Flutterwindows]: {
name: 'My Windows App',
hostname: 'appname',
tooltip: 'Your application name'
},
// The following are not used, but added to avoid TS errors
[PlatformType.Web]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Appleios]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Applemacos]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Applewatchos]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Appletvos]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Android]: {
name: '',
hostname: '',
tooltip: ''
},
[PlatformType.Unity]: {
name: '',
hostname: '',
tooltip: ''
}
};
const hostname: Record<Platform, string> = {
[Platform.Android]: 'Package Name',
[Platform.Ios]: 'Bundle ID',
[Platform.Linux]: 'Package Name',
[Platform.Macos]: 'Bundle ID',
[Platform.Web]: 'Hostname',
[Platform.Windows]: 'Package Name'
const hostname: Record<PlatformType, string> = {
[PlatformType.Flutterandroid]: 'Package Name',
[PlatformType.Flutterios]: 'Bundle ID',
[PlatformType.Flutterlinux]: 'Package Name',
[PlatformType.Fluttermacos]: 'Bundle ID',
[PlatformType.Flutterweb]: 'Hostname',
[PlatformType.Flutterwindows]: 'Package Name',
// The following are not used, but added to avoid TS errors
[PlatformType.Web]: '',
[PlatformType.Appleios]: '',
[PlatformType.Applemacos]: '',
[PlatformType.Applewatchos]: '',
[PlatformType.Appletvos]: '',
[PlatformType.Android]: '',
[PlatformType.Unity]: ''
};
async function beforeSubmit() {
@@ -88,9 +134,9 @@
projectId,
platform,
$createPlatform.name,
platform !== Platform.Web ? $createPlatform.key : undefined,
platform !== PlatformType.Flutterweb ? $createPlatform.key : undefined,
undefined,
platform === Platform.Web ? $createPlatform.hostname : undefined
platform === PlatformType.Flutterweb ? $createPlatform.hostname : undefined
);
trackEvent(Submit.PlatformCreate, {
@@ -102,12 +148,12 @@
}
$: registee = {
[Platform.Android]: 'package name',
[Platform.Ios]: 'bundle ID',
[Platform.Linux]: 'package name',
[Platform.Macos]: 'bundle ID',
[Platform.Windows]: 'package name',
[Platform.Web]: 'hostname'
[PlatformType.Flutterandroid]: 'package name',
[PlatformType.Flutterios]: 'bundle ID',
[PlatformType.Flutterlinux]: 'package name',
[PlatformType.Fluttermacos]: 'bundle ID',
[PlatformType.Flutterwindows]: 'package name',
[PlatformType.Flutterweb]: 'hostname'
}[platform];
</script>
@@ -117,38 +163,38 @@
<div class="u-flex u-gap-16 u-margin-block-start-8 u-flex-wrap">
<Pill
button
on:click={() => (platform = Platform.Android)}
selected={platform === Platform.Android}>
on:click={() => (platform = PlatformType.Flutterandroid)}
selected={platform === PlatformType.Flutterandroid}>
Android
</Pill>
<Pill
button
on:click={() => (platform = Platform.Ios)}
selected={platform === Platform.Ios}>
on:click={() => (platform = PlatformType.Flutterios)}
selected={platform === PlatformType.Flutterios}>
iOS
</Pill>
<Pill
button
on:click={() => (platform = Platform.Linux)}
selected={platform === Platform.Linux}>
on:click={() => (platform = PlatformType.Flutterlinux)}
selected={platform === PlatformType.Flutterlinux}>
Linux
</Pill>
<Pill
button
on:click={() => (platform = Platform.Macos)}
selected={platform === Platform.Macos}>
on:click={() => (platform = PlatformType.Fluttermacos)}
selected={platform === PlatformType.Fluttermacos}>
macOS
</Pill>
<Pill
button
on:click={() => (platform = Platform.Windows)}
selected={platform === Platform.Windows}>
on:click={() => (platform = PlatformType.Flutterwindows)}
selected={platform === PlatformType.Flutterwindows}>
Windows
</Pill>
<Pill
button
on:click={() => (platform = Platform.Web)}
selected={platform === Platform.Web}>
on:click={() => (platform = PlatformType.Flutterweb)}
selected={platform === PlatformType.Flutterweb}>
Web
</Pill>
</div>
@@ -161,7 +207,7 @@
placeholder={placeholder[platform].name}
required
bind:value={$createPlatform.name} />
{#if platform === Platform.Web}
{#if platform === PlatformType.Flutterweb}
<div>
<InputText
id="hostname"
@@ -7,6 +7,7 @@
import { sdk } from '$lib/stores/sdk';
import { createPlatform } from '../store';
import { Submit, trackEvent } from '$lib/actions/analytics';
import { PlatformType } from '@appwrite.io/console';
const projectId = $page.params.project;
const suggestions = ['*.vercel.app', '*.netlify.app', '*.gitpod.io'];
@@ -27,7 +28,7 @@
const platform = await sdk.forConsole.projects.createPlatform(
projectId,
'web',
PlatformType.Web,
$createPlatform.name,
undefined,
undefined,
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more