From 63384c50c2c9c3aacf84eb8e4567aa8b70907cea Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Thu, 5 Oct 2023 14:16:15 +0530 Subject: [PATCH] docs: example restructuring (#751) --- .../sdk-backend-node/chat/chat.lowlevel.ts | 667 ++++++++++++++ .../examples/sdk-backend-node/chat/chat.ts | 815 +++++------------- .../examples/sdk-backend-node/chat/index.ts | 30 +- .../chat/{nftChat.ts => nftChat.lowlevel.ts} | 10 +- packages/examples/sdk-backend-node/main.ts | 72 +- .../sdk-backend-node/notification/index.ts | 396 +-------- .../notification/notification.lowlevel.ts | 377 ++++++++ .../notification.ts} | 71 +- .../examples/sdk-backend-node/pushAPI/chat.ts | 227 ----- .../sdk-backend-node/pushAPI/encryption.ts | 38 - .../sdk-backend-node/pushAPI/index.ts | 57 -- .../sdk-backend-node/pushAPI/notification.ts | 58 -- .../sdk-backend-node/pushAPI/profile.ts | 38 - .../sdk-backend-node/pushAPI/stream.ts | 202 ----- .../{spaces => space}/index.ts | 15 +- .../examples/sdk-backend-node/user/index.ts | 75 ++ .../examples/sdk-backend-node/video/index.ts | 12 +- 17 files changed, 1490 insertions(+), 1670 deletions(-) create mode 100644 packages/examples/sdk-backend-node/chat/chat.lowlevel.ts rename packages/examples/sdk-backend-node/chat/{nftChat.ts => nftChat.lowlevel.ts} (96%) create mode 100644 packages/examples/sdk-backend-node/notification/notification.lowlevel.ts rename packages/examples/sdk-backend-node/{pushAPI/channel.ts => notification/notification.ts} (72%) delete mode 100644 packages/examples/sdk-backend-node/pushAPI/chat.ts delete mode 100644 packages/examples/sdk-backend-node/pushAPI/encryption.ts delete mode 100644 packages/examples/sdk-backend-node/pushAPI/index.ts delete mode 100644 packages/examples/sdk-backend-node/pushAPI/notification.ts delete mode 100644 packages/examples/sdk-backend-node/pushAPI/profile.ts delete mode 100644 packages/examples/sdk-backend-node/pushAPI/stream.ts rename packages/examples/sdk-backend-node/{spaces => space}/index.ts (94%) create mode 100644 packages/examples/sdk-backend-node/user/index.ts diff --git a/packages/examples/sdk-backend-node/chat/chat.lowlevel.ts b/packages/examples/sdk-backend-node/chat/chat.lowlevel.ts new file mode 100644 index 000000000..852b62153 --- /dev/null +++ b/packages/examples/sdk-backend-node/chat/chat.lowlevel.ts @@ -0,0 +1,667 @@ +import * as PushAPI from '@pushprotocol/restapi'; +import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; +import { ethers } from 'ethers'; +import { + adjectives, + animals, + colors, + uniqueNamesGenerator, +} from 'unique-names-generator'; +import { ENV } from '../types'; +import { config } from '../config'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { createWalletClient, http } from 'viem'; +import { goerli } from 'viem/chains'; + +// CONFIGS +const { env, showAPIResponse } = config; + +/***************** SAMPLE SIGNER GENERATION *********************/ +/** + * USING VIEM + */ +// Random Wallet Signers +const signer = createWalletClient({ + account: privateKeyToAccount(generatePrivateKey()), + chain: goerli, + transport: http(), +}); +const signerAddress = signer.account.address; +const secondSigner = createWalletClient({ + account: privateKeyToAccount(generatePrivateKey()), + chain: goerli, + transport: http(), +}); +const secondSignerAddress = secondSigner.account.address; +// Dummy Wallet Addresses +const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; +const randomWallet2 = privateKeyToAccount(generatePrivateKey()).address; +const randomWallet3 = privateKeyToAccount(generatePrivateKey()).address; + +/** + * USING ETHERS + */ +// // Random Wallet Signers +// const signer = ethers.Wallet.createRandom(); +// const signerAddress = signer.address; +// const secondSigner = ethers.Wallet.createRandom(); +// const secondSignerAddress = secondSigner.address; +// // Dummy Wallet Addresses +// const randomWallet1 = ethers.Wallet.createRandom().address; +// const randomWallet2 = ethers.Wallet.createRandom().address; +// const randomWallet3 = ethers.Wallet.createRandom().address; + +/************************************************************* */ + +// Group Chat Data +const groupName = uniqueNamesGenerator({ + dictionaries: [adjectives, colors, animals], +}); +const groupDescription = uniqueNamesGenerator({ + dictionaries: [adjectives, colors, animals], +}); +const groupImage = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg=='; + +// Push Chat - Run Chat Use cases +export const runChatLowlevelUseCases = async (): Promise => { + console.log('PushAPI.user.create'); + await PushAPI_user_create(); + + console.log('PushAPI.user.get'); + await PushAPI_user_get(); + + console.log('PushAPI_chat_decryptPGPKey'); + await PushAPI_chat_decryptPGPKey(); + + console.log('PushAPI.chat.chats'); + await PushAPI_chat_chats(); + + console.log('PushAPI.chat.requests'); + await PushAPI_chat_requests(); + + console.log('PushAPI.chat.send'); + const TargetChatId = await PushAPI_chat_send(); + + console.log('PushAPI.chat.approve'); + await PushAPI_chat_approve(); + + console.log('PushAPI chat Video call Notification'); + await PushAPI_chat_video_call_notification(TargetChatId); + + console.log('PushAPI.chat.createGroup'); + const { chatId, name } = await PushAPI_chat_createGroup(); + + console.log('PushAPI.chat.conversationHash'); + await PushAPI_chat_conversationHash(); + + console.log('PushAPI_chat_history'); + await PushAPI_chat_history(); + + console.log('PushAPI.chat.latest'); + await PushAPI_chat_latest(); + + console.log('PushAPI.chat.updateGroup'); + await PushAPI_chat_updateGroup(chatId); + + console.log('PushAPI.chat.getGroupByName'); + await PushAPI_chat_getGroupByName(name); + + console.log('PushAPI.chat.getGroup'); + await PushAPI_chat_getGroup(chatId); + + console.log('PushAPI.chat.decryptConversation'); + await PushAPI_chat_decryptConversation(); + + console.log('Push Chat - PushSDKSocket()'); + await PushChatSDKSocket(); +}; + +// Push Chat - PushAPI.user.create +async function PushAPI_user_create(silent = !showAPIResponse) { + const user = await PushAPI.user.create({ + signer: signer, + env: env as ENV, + }); + + const user_2 = await PushAPI.user.create({ + signer: secondSigner, + env: env as ENV, + }); + + console.log('PushAPI_user_create | Response - 200 OK'); + if (!silent) { + console.log(user); + console.log(user_2); + } + + return user; +} + +// Push Chat - PushAPI.user.get +async function PushAPI_user_get(silent = !showAPIResponse) { + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + console.log('PushAPI_user_get | Response - 200 OK'); + + if (!silent) { + console.log(user); + } +} + +// Push Chat - PushAPI.chat.decryptPGPKey +async function PushAPI_chat_decryptPGPKey(silent = !showAPIResponse) { + // get user and derive encrypted PGP key + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // decrypt the PGP Key + const pgpKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + console.log('PushAPI_chat_decryptPGPKey | Response - 200 OK'); + if (!silent) { + console.log(pgpKey); + } +} + +// Push Chat - PushAPI.chat.chats +async function PushAPI_chat_chats(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Actual api + const response = await PushAPI.chat.chats({ + account: `eip155:${signerAddress}`, + toDecrypt: true, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_chats | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.requests +async function PushAPI_chat_requests(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Actual api + const response = await PushAPI.chat.requests({ + account: `eip155:${signerAddress}`, + toDecrypt: true, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_requests | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.conversationHash +async function PushAPI_chat_conversationHash(silent = !showAPIResponse) { + // conversation hash are also called link inside chat messages + const conversationHash = await PushAPI.chat.conversationHash({ + account: `eip155:${signerAddress}`, + conversationId: `eip155:${secondSignerAddress}`, // 2nd address + env: env as ENV, + }); + + console.log('PushAPI_chat_conversationHash | Response - 200 OK'); + if (!silent) { + console.log(conversationHash); + } +} + +// Push Chat - PushAPI.chat.latest +async function PushAPI_chat_latest(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Fetch conversation hash + // conversation hash are also called link inside chat messages + const conversationHash = await PushAPI.chat.conversationHash({ + account: `eip155:${signerAddress}`, + conversationId: `eip155:${secondSignerAddress}`, // 2nd address + env: env as ENV, + }); + + // Actual API + const response = await PushAPI.chat.latest({ + threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here + account: `eip155:${signerAddress}`, + toDecrypt: true, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_latest | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.history +async function PushAPI_chat_history(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Fetch conversation hash + // conversation hash are also called link inside chat messages + const conversationHash = await PushAPI.chat.conversationHash({ + account: `eip155:${signerAddress}`, + conversationId: `eip155:${secondSignerAddress}`, // 2nd address + env: env as ENV, + }); + + // Actual API + const response = await PushAPI.chat.history({ + threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here + account: `eip155:${signerAddress}`, + limit: 5, + toDecrypt: true, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_history | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.send +// // Will send a message to the user or chat request in case user hasn't approved them +async function PushAPI_chat_send(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Actual api + const response = await PushAPI.chat.send({ + messageObj: { + content: "Gm gm! It's me... Mario", + }, + messageType: 'Text', // can be "Text" | "Image" | "File" | "GIF" + receiverAddress: secondSignerAddress, + + signer: signer, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_send | Response - 200 OK'); + if (!silent) { + console.log(response); + } + return response.chatId; +} + +// Push Chat - Approve +async function PushAPI_chat_approve(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${secondSignerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: secondSigner, + }); + + // Actual api + const approve = await PushAPI.chat.approve({ + status: 'Approved', + senderAddress: signerAddress, // receiver's address or chatId of a group + + signer: secondSigner, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_approve | Response - 200 OK'); + if (!silent) { + console.log(approve); + } +} + +// Push Chat - PushAPI.chat.createGroup +async function PushAPI_chat_createGroup( + silent = !showAPIResponse +): Promise<{ chatId: string; name: string }> { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Actual API + // Convert image to base 64 and pass + const response = await PushAPI.chat.createGroup({ + groupName, + groupDescription, + members: [`eip155:${randomWallet1}`, `eip155:${randomWallet2}`], + groupImage, + admins: [], // takes signer as admin automatically, add more if you want to + isPublic: true, + + signer: signer, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_createGroup | Response - 200 OK'); + if (!silent) { + console.log(response); + } + return { chatId: response.chatId, name: response.groupName }; +} + +// Push Chat - PushAPI.chat.updateGroup +async function PushAPI_chat_updateGroup( + chatId: string, + silent = !showAPIResponse +) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Actual API + // Convert image to base 64 and pass + // This is an idempotent operation, meaning it requires all group info to be passed no matter if only few things change + // Why so? To ensure that verificationProof always is able to replicate the current group info (trustless since signature is stored with the info) + const response = await PushAPI.chat.updateGroup({ + chatId, + groupName, + groupDescription, + members: [ + `eip155:${randomWallet1}`, + `eip155:${randomWallet2}`, + `eip155:${randomWallet3}`, + `eip155:${signerAddress}`, + ], + groupImage, + admins: [`eip155:${signerAddress}`], // takes signer as admin automatically, add more if you want to + + signer: signer, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + console.log('PushAPI_chat_updateGroup | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.getGroupByName +async function PushAPI_chat_getGroupByName( + name: string, + silent = !showAPIResponse +) { + const response = await PushAPI.chat.getGroupByName({ + groupName: name, + env: env as ENV, + }); + + console.log('PushAPI_chat_getGroupByName | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.getGroup +async function PushAPI_chat_getGroup( + chatId: string, + silent = !showAPIResponse +) { + const response = await PushAPI.chat.getGroup({ + chatId: chatId, + env: env as ENV, + }); + + console.log('PushAPI_chat_getGroup | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Chat - PushAPI.chat.decryptConversation +async function PushAPI_chat_decryptConversation(silent = !showAPIResponse) { + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${signerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: signer, + }); + + // Fetch conversation hash + // conversation hash are also called link inside chat messages + const conversationHash = await PushAPI.chat.conversationHash({ + account: `eip155:${signerAddress}`, + conversationId: `eip155:${secondSignerAddress}`, // 2nd address + env: env as ENV, + }); + + // Chat History + const encryptedChats = await PushAPI.chat.history({ + threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here + account: `eip155:${signerAddress}`, + limit: 5, + toDecrypt: false, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + + // Decrypted Chat + const decryptedChat = await PushAPI.chat.decryptConversation({ + messages: encryptedChats, // array of message object fetched from chat.history method + connectedUser: user, // user meta data object fetched from chat.get method + pgpPrivateKey: pgpDecrpyptedPvtKey, //decrypted private key + env: env as ENV, + }); + + console.log('PushAPI_chat_decryptConversation | Response - 200 OK'); + if (!silent) { + console.log(decryptedChat); + } +} + +// Push Chat - Socket Connection +async function PushChatSDKSocket(silent = !showAPIResponse) { + const pushSDKSocket = createSocketConnection({ + user: `eip155:${signerAddress}`, + socketType: 'chat', + socketOptions: { autoConnect: true, reconnectionAttempts: 3 }, + env: env as ENV, + }); + + if (!pushSDKSocket) { + throw new Error('Socket not connected'); + } + + pushSDKSocket.on(EVENTS.CONNECT, async () => { + console.log('Socket Connected - will disconnect after 4 seconds'); + + // send a chat from other wallet to this one to see the result + // Fetch user + const user = await PushAPI.user.get({ + account: `eip155:${secondSignerAddress}`, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + + signer: secondSigner, + }); + + // Actual api + const response = await PushAPI.chat.send({ + messageContent: "Gm gm! It's me... Mario", + messageType: 'Text', + receiverAddress: `eip155:${signerAddress}`, + + signer: secondSigner, + pgpPrivateKey: pgpDecrpyptedPvtKey, + env: env as ENV, + }); + console.log('PushAPI_chat_send | Response - 200 OK'); + }); + + pushSDKSocket.on(EVENTS.DISCONNECT, () => { + console.log('Socket Disconnected'); + }); + + pushSDKSocket.on(EVENTS.CHAT_RECEIVED_MESSAGE, (message) => { + // feedItem is the notification data when that notification was received + console.log('Incoming Push Chat message from Socket'); + if (!silent) { + console.log(message); + } + + // disconnect socket after this, not to be done in real implementations + pushSDKSocket.disconnect(); + }); + + const delay = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)); + await delay(4000); +} + +async function PushAPI_chat_video_call_notification( + chatId: string, + silent = !showAPIResponse +) { + // Fetch user + const user = await PushAPI.user.get({ + account: signerAddress, + env: env as ENV, + }); + + // Decrypt PGP Key + const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ + encryptedPGPPrivateKey: user.encryptedPrivateKey, + signer: signer, + }); + // get PGP KEy + const apiResponse = await PushAPI.payloads.sendNotification({ + senderType: 1, + signer: signer, + pgpPrivateKey: pgpDecrpyptedPvtKey, + chatId: chatId, + type: 3, // target + identityType: 2, // direct payload + notification: { + title: `VC TITLE:`, + body: `VC BODY`, + }, + payload: { + title: `payload title`, + body: `sample msg body`, + cta: '', + img: '', + additionalMeta: { + type: '1+1', + data: 'Random DATA', + domain: 'push.org', + }, + }, + recipients: secondSignerAddress, // recipient address + channel: signerAddress, // your channel address + env: env as ENV, + }); + + console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); + if (!silent) { + console.log(apiResponse); + } +} diff --git a/packages/examples/sdk-backend-node/chat/chat.ts b/packages/examples/sdk-backend-node/chat/chat.ts index 3b594ec1c..fba19a0be 100644 --- a/packages/examples/sdk-backend-node/chat/chat.ts +++ b/packages/examples/sdk-backend-node/chat/chat.ts @@ -1,25 +1,21 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; -import { ethers } from 'ethers'; +import { PushAPI } from '@pushprotocol/restapi'; import { adjectives, animals, colors, uniqueNamesGenerator, } from 'unique-names-generator'; -import { ENV } from '../types'; import { config } from '../config'; import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; import { createWalletClient, http } from 'viem'; import { goerli } from 'viem/chains'; +import { STREAM } from '@pushprotocol/restapi/src/lib/pushstream/pushStreamTypes'; // CONFIGS const { env, showAPIResponse } = config; /***************** SAMPLE SIGNER GENERATION *********************/ -/** - * USING VIEM - */ +// Uing VIEM // Random Wallet Signers const signer = createWalletClient({ account: privateKeyToAccount(generatePrivateKey()), @@ -33,27 +29,20 @@ const secondSigner = createWalletClient({ transport: http(), }); const secondSignerAddress = secondSigner.account.address; +const thirdSigner = createWalletClient({ + account: privateKeyToAccount(generatePrivateKey()), + chain: goerli, + transport: http(), +}); +const thirdSignerAddress = thirdSigner.account.address; + // Dummy Wallet Addresses const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; const randomWallet2 = privateKeyToAccount(generatePrivateKey()).address; const randomWallet3 = privateKeyToAccount(generatePrivateKey()).address; +/****************************************************************/ -/** - * USING ETHERS - */ -// // Random Wallet Signers -// const signer = ethers.Wallet.createRandom(); -// const signerAddress = signer.address; -// const secondSigner = ethers.Wallet.createRandom(); -// const secondSignerAddress = secondSigner.address; -// // Dummy Wallet Addresses -// const randomWallet1 = ethers.Wallet.createRandom().address; -// const randomWallet2 = ethers.Wallet.createRandom().address; -// const randomWallet3 = ethers.Wallet.createRandom().address; - -/************************************************************* */ - -// Group Chat Data +/***************** SAMPLE GROUP DATA ****************************/ const groupName = uniqueNamesGenerator({ dictionaries: [adjectives, colors, animals], }); @@ -62,613 +51,211 @@ const groupDescription = uniqueNamesGenerator({ }); const groupImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg=='; - -// Push Chat - Run Chat Use cases -export const runChatUseCases = async (): Promise => { - console.log(` - ██████ ██ ██ █████ ████████ - ██ ██ ██ ██ ██ ██ - ██ ███████ ███████ ██ - ██ ██ ██ ██ ██ ██ - ██████ ██ ██ ██ ██ ██ - `); - console.log('PushAPI.user.create'); - await PushAPI_user_create(); - - console.log('PushAPI.user.get'); - await PushAPI_user_get(); - - console.log('PushAPI_chat_decryptPGPKey'); - await PushAPI_chat_decryptPGPKey(); - - console.log('PushAPI.chat.chats'); - await PushAPI_chat_chats(); - - console.log('PushAPI.chat.requests'); - await PushAPI_chat_requests(); - - console.log('PushAPI.chat.send'); - const TargetChatId = await PushAPI_chat_send(); - - console.log('PushAPI.chat.approve'); - await PushAPI_chat_approve(); - - console.log('PushAPI chat Video call Notification'); - await PushAPI_chat_video_call_notification(TargetChatId); - - console.log('PushAPI.chat.createGroup'); - const { chatId, name } = await PushAPI_chat_createGroup(); - - console.log('PushAPI.chat.conversationHash'); - await PushAPI_chat_conversationHash(); - - console.log('PushAPI_chat_history'); - await PushAPI_chat_history(); - - console.log('PushAPI.chat.latest'); - await PushAPI_chat_latest(); - - console.log('PushAPI.chat.updateGroup'); - await PushAPI_chat_updateGroup(chatId); - - console.log('PushAPI.chat.getGroupByName'); - await PushAPI_chat_getGroupByName(name); - - console.log('PushAPI.chat.getGroup'); - await PushAPI_chat_getGroup(chatId); - - console.log('PushAPI.chat.decryptConversation'); - await PushAPI_chat_decryptConversation(); - - console.log('Push Chat - PushSDKSocket()'); - await PushChatSDKSocket(); -}; - -// Push Chat - PushAPI.user.create -async function PushAPI_user_create(silent = !showAPIResponse) { - const user = await PushAPI.user.create({ - signer: signer, - env: env as ENV, - }); - - const user_2 = await PushAPI.user.create({ - signer: secondSigner, - env: env as ENV, - }); - - console.log('PushAPI_user_create | Response - 200 OK'); - if (!silent) { - console.log(user); - console.log(user_2); - } - - return user; -} - -// Push Chat - PushAPI.user.get -async function PushAPI_user_get(silent = !showAPIResponse) { - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, +/***************** SAMPLE GROUP DATA ****************************/ + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const eventlistener = async ( + pushAPI: PushAPI, + eventName: string +): Promise => { + pushAPI.stream.on(eventName, (data: any) => { + if (showAPIResponse) { + console.log('Stream Event Received'); + console.log(data); + console.log('\n'); + } }); +}; - console.log('PushAPI_user_get | Response - 200 OK'); - - if (!silent) { - console.log(user); +export const runChatClassUseCases = async (): Promise => { + const userAlice = await PushAPI.initialize(signer, { env }); + const userBob = await PushAPI.initialize(secondSigner, { env }); + const userKate = await PushAPI.initialize(thirdSigner, { env }); + + // Listen stream events to receive websocket events + console.log(`Listening ${STREAM.CHAT} Events`); + eventlistener(userAlice, STREAM.CHAT); + console.log(`Listening ${STREAM.CHAT_OPS} Events`); + eventlistener(userAlice, STREAM.CHAT_OPS); + console.log('\n\n'); + + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.list'); + const aliceChats = await userAlice.chat.list('CHATS'); + const aliceRequests = await userAlice.chat.list('REQUESTS'); + if (showAPIResponse) { + console.log(aliceChats); + console.log(aliceRequests); } -} - -// Push Chat - PushAPI.chat.decryptPGPKey -async function PushAPI_chat_decryptPGPKey(silent = !showAPIResponse) { - // get user and derive encrypted PGP key - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // decrypt the PGP Key - const pgpKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - console.log('PushAPI_chat_decryptPGPKey | Response - 200 OK'); - if (!silent) { - console.log(pgpKey); + console.log('PushAPI.chat.list | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.latest'); + const aliceLatestChatWithBob = await userAlice.chat.latest( + secondSignerAddress + ); + if (showAPIResponse) { + console.log(aliceLatestChatWithBob); } -} - -// Push Chat - PushAPI.chat.chats -async function PushAPI_chat_chats(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Actual api - const response = await PushAPI.chat.chats({ - account: `eip155:${signerAddress}`, - toDecrypt: true, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_chats | Response - 200 OK'); - if (!silent) { - console.log(response); + console.log('PushAPI.chat.latest | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.history'); + const aliceChatHistoryWithBob = await userAlice.chat.history( + secondSignerAddress + ); + if (showAPIResponse) { + console.log(aliceChatHistoryWithBob); } -} - -// Push Chat - PushAPI.chat.requests -async function PushAPI_chat_requests(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Actual api - const response = await PushAPI.chat.requests({ - account: `eip155:${signerAddress}`, - toDecrypt: true, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, + console.log('PushAPI.chat.history | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.send'); + const aliceMessagesBob = await userAlice.chat.send(secondSignerAddress, { + content: 'Hello Bob!', + type: 'Text', }); - - console.log('PushAPI_chat_requests | Response - 200 OK'); - if (!silent) { - console.log(response); + if (showAPIResponse) { + console.log(aliceMessagesBob); } -} - -// Push Chat - PushAPI.chat.conversationHash -async function PushAPI_chat_conversationHash(silent = !showAPIResponse) { - // conversation hash are also called link inside chat messages - const conversationHash = await PushAPI.chat.conversationHash({ - account: `eip155:${signerAddress}`, - conversationId: `eip155:${secondSignerAddress}`, // 2nd address - env: env as ENV, - }); - - console.log('PushAPI_chat_conversationHash | Response - 200 OK'); - if (!silent) { - console.log(conversationHash); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.chat.send | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.accept'); + const bobAcceptsRequest = await userBob.chat.accept(signerAddress); + if (showAPIResponse) { + console.log(bobAcceptsRequest); } -} - -// Push Chat - PushAPI.chat.latest -async function PushAPI_chat_latest(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Fetch conversation hash - // conversation hash are also called link inside chat messages - const conversationHash = await PushAPI.chat.conversationHash({ - account: `eip155:${signerAddress}`, - conversationId: `eip155:${secondSignerAddress}`, // 2nd address - env: env as ENV, - }); - - // Actual API - const response = await PushAPI.chat.latest({ - threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here - account: `eip155:${signerAddress}`, - toDecrypt: true, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_latest | Response - 200 OK'); - if (!silent) { - console.log(response); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.chat.accept | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.reject'); + await userKate.chat.send(signerAddress, { + content: 'Sending malicious message', + type: 'Text', + }); + const AliceRejectsRequest = await userAlice.chat.reject(thirdSignerAddress); + if (showAPIResponse) { + console.log(AliceRejectsRequest); } -} - -// Push Chat - PushAPI.chat.history -async function PushAPI_chat_history(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Fetch conversation hash - // conversation hash are also called link inside chat messages - const conversationHash = await PushAPI.chat.conversationHash({ - account: `eip155:${signerAddress}`, - conversationId: `eip155:${secondSignerAddress}`, // 2nd address - env: env as ENV, - }); - - // Actual API - const response = await PushAPI.chat.history({ - threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here - account: `eip155:${signerAddress}`, - limit: 5, - toDecrypt: true, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_history | Response - 200 OK'); - if (!silent) { - console.log(response); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.chat.reject | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.block'); + const AliceBlocksBob = await userAlice.chat.block([secondSignerAddress]); + if (showAPIResponse) { + console.log(AliceBlocksBob); } -} - -// Push Chat - PushAPI.chat.send -// // Will send a message to the user or chat request in case user hasn't approved them -async function PushAPI_chat_send(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Actual api - const response = await PushAPI.chat.send({ - messageObj: { - content: "Gm gm! It's me... Mario", - }, - messageType: 'Text', // can be "Text" | "Image" | "File" | "GIF" - receiverAddress: secondSignerAddress, - - signer: signer, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_send | Response - 200 OK'); - if (!silent) { - console.log(response); + console.log('PushAPI.chat.block | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.chat.unblock'); + const AliceUnblocksBob = await userAlice.chat.unblock([secondSignerAddress]); + if (showAPIResponse) { + console.log(AliceUnblocksBob); } - return response.chatId; -} - -// Push Chat - Approve -async function PushAPI_chat_approve(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${secondSignerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: secondSigner, - }); - - // Actual api - const approve = await PushAPI.chat.approve({ - status: 'Approved', - senderAddress: signerAddress, // receiver's address or chatId of a group - - signer: secondSigner, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_approve | Response - 200 OK'); - if (!silent) { - console.log(approve); + console.log('PushAPI.chat.unblock | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.create'); + const createdGroup = await userAlice.chat.group.create(groupName, { + description: groupDescription, + image: groupImage, + members: [randomWallet1, randomWallet2], + admins: [], + private: false, + }); + const groupChatId = createdGroup.chatId; // to be used in other examples + if (showAPIResponse) { + console.log(createdGroup); } -} - -// Push Chat - PushAPI.chat.createGroup -async function PushAPI_chat_createGroup( - silent = !showAPIResponse -): Promise<{ chatId: string; name: string }> { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Actual API - // Convert image to base 64 and pass - const response = await PushAPI.chat.createGroup({ - groupName, - groupDescription, - members: [`eip155:${randomWallet1}`, `eip155:${randomWallet2}`], - groupImage, - admins: [], // takes signer as admin automatically, add more if you want to - isPublic: true, - - signer: signer, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_createGroup | Response - 200 OK'); - if (!silent) { - console.log(response); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.create | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.permissions'); + const grouppermissions = await userAlice.chat.group.permissions(groupChatId); + if (showAPIResponse) { + console.log(grouppermissions); } - return { chatId: response.chatId, name: response.groupName }; -} - -// Push Chat - PushAPI.chat.updateGroup -async function PushAPI_chat_updateGroup( - chatId: string, - silent = !showAPIResponse -) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Actual API - // Convert image to base 64 and pass - // This is an idempotent operation, meaning it requires all group info to be passed no matter if only few things change - // Why so? To ensure that verificationProof always is able to replicate the current group info (trustless since signature is stored with the info) - const response = await PushAPI.chat.updateGroup({ - chatId, - groupName, - groupDescription, - members: [ - `eip155:${randomWallet1}`, - `eip155:${randomWallet2}`, - `eip155:${randomWallet3}`, - `eip155:${signerAddress}`, - ], - groupImage, - admins: [`eip155:${signerAddress}`], // takes signer as admin automatically, add more if you want to - - signer: signer, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - console.log('PushAPI_chat_updateGroup | Response - 200 OK'); - if (!silent) { - console.log(response); + console.log('PushAPI.group.permissions | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.info'); + const groupInfo = await userAlice.chat.group.info(groupChatId); + if (showAPIResponse) { + console.log(groupInfo); } -} - -// Push Chat - PushAPI.chat.getGroupByName -async function PushAPI_chat_getGroupByName( - name: string, - silent = !showAPIResponse -) { - const response = await PushAPI.chat.getGroupByName({ - groupName: name, - env: env as ENV, - }); - - console.log('PushAPI_chat_getGroupByName | Response - 200 OK'); - if (!silent) { - console.log(response); + console.log('PushAPI.group.info | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.update'); + const updatedGroup = await userAlice.chat.group.update(groupChatId, { + description: 'Updated Description', + }); + if (showAPIResponse) { + console.log(updatedGroup); } -} - -// Push Chat - PushAPI.chat.getGroup -async function PushAPI_chat_getGroup( - chatId: string, - silent = !showAPIResponse -) { - const response = await PushAPI.chat.getGroup({ - chatId: chatId, - env: env as ENV, - }); - - console.log('PushAPI_chat_getGroup | Response - 200 OK'); - if (!silent) { - console.log(response); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.update | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.add'); + const addMember = await userAlice.chat.group.add(groupChatId, { + role: 'MEMBER', + accounts: [randomWallet3], + }); + if (showAPIResponse) { + console.log(addMember); } -} - -// Push Chat - PushAPI.chat.decryptConversation -async function PushAPI_chat_decryptConversation(silent = !showAPIResponse) { - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${signerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: signer, - }); - - // Fetch conversation hash - // conversation hash are also called link inside chat messages - const conversationHash = await PushAPI.chat.conversationHash({ - account: `eip155:${signerAddress}`, - conversationId: `eip155:${secondSignerAddress}`, // 2nd address - env: env as ENV, - }); - - // Chat History - const encryptedChats = await PushAPI.chat.history({ - threadhash: conversationHash.threadHash, // get conversation hash from conversationHash function and send the response threadhash here - account: `eip155:${signerAddress}`, - limit: 5, - toDecrypt: false, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - - // Decrypted Chat - const decryptedChat = await PushAPI.chat.decryptConversation({ - messages: encryptedChats, // array of message object fetched from chat.history method - connectedUser: user, // user meta data object fetched from chat.get method - pgpPrivateKey: pgpDecrpyptedPvtKey, //decrypted private key - env: env as ENV, - }); - - console.log('PushAPI_chat_decryptConversation | Response - 200 OK'); - if (!silent) { - console.log(decryptedChat); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.add | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.remove'); + const removeMember = await userAlice.chat.group.remove(groupChatId, { + role: 'MEMBER', + accounts: [randomWallet3], + }); + if (showAPIResponse) { + console.log(removeMember); } -} - -// Push Chat - Socket Connection -async function PushChatSDKSocket(silent = !showAPIResponse) { - const pushSDKSocket = createSocketConnection({ - user: `eip155:${signerAddress}`, - socketType: 'chat', - socketOptions: { autoConnect: true, reconnectionAttempts: 3 }, - env: env as ENV, - }); - - if (!pushSDKSocket) { - throw new Error('Socket not connected'); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.remove | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.join'); + const joinGrp = await userBob.chat.group.join(groupChatId); + if (showAPIResponse) { + console.log(joinGrp); } - - pushSDKSocket.on(EVENTS.CONNECT, async () => { - console.log('Socket Connected - will disconnect after 4 seconds'); - - // send a chat from other wallet to this one to see the result - // Fetch user - const user = await PushAPI.user.get({ - account: `eip155:${secondSignerAddress}`, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - - signer: secondSigner, - }); - - // Actual api - const response = await PushAPI.chat.send({ - messageContent: "Gm gm! It's me... Mario", - messageType: 'Text', - receiverAddress: `eip155:${signerAddress}`, - - signer: secondSigner, - pgpPrivateKey: pgpDecrpyptedPvtKey, - env: env as ENV, - }); - console.log('PushAPI_chat_send | Response - 200 OK'); - }); - - pushSDKSocket.on(EVENTS.DISCONNECT, () => { - console.log('Socket Disconnected'); - }); - - pushSDKSocket.on(EVENTS.CHAT_RECEIVED_MESSAGE, (message) => { - // feedItem is the notification data when that notification was received - console.log('Incoming Push Chat message from Socket'); - if (!silent) { - console.log(message); - } - - // disconnect socket after this, not to be done in real implementations - pushSDKSocket.disconnect(); - }); - - const delay = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)); - await delay(4000); -} - -async function PushAPI_chat_video_call_notification( - chatId: string, - silent = !showAPIResponse -) { - // Fetch user - const user = await PushAPI.user.get({ - account: signerAddress, - env: env as ENV, - }); - - // Decrypt PGP Key - const pgpDecrpyptedPvtKey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - signer: signer, - }); - // get PGP KEy - const apiResponse = await PushAPI.payloads.sendNotification({ - senderType: 1, - signer: signer, - pgpPrivateKey: pgpDecrpyptedPvtKey, - chatId: chatId, - type: 3, // target - identityType: 2, // direct payload - notification: { - title: `VC TITLE:`, - body: `VC BODY`, - }, - payload: { - title: `payload title`, - body: `sample msg body`, - cta: '', - img: '', - additionalMeta: { - type: '1+1', - data: 'Random DATA', - domain: 'push.org', - }, - }, - recipients: secondSignerAddress, // recipient address - channel: signerAddress, // your channel address - env: env as ENV, - }); - - console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); - if (!silent) { - console.log(apiResponse); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.join | Response - 200 OK\n\n'); + //------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.leave'); + const leaveGrp = await userBob.chat.group.leave(groupChatId); + if (showAPIResponse) { + console.log(leaveGrp); } -} + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.leave | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.group.reject'); + const sampleGrp = await userAlice.chat.group.create('Sample Grp', { + description: groupDescription, + image: groupImage, + members: [secondSignerAddress], // invite bob + admins: [], + private: true, + }); + await userBob.chat.group.reject(sampleGrp.chatId); + await delay(2000); // Delay added to log the events in order + console.log('PushAPI.group.reject | Response - 200 OK\n\n'); +}; diff --git a/packages/examples/sdk-backend-node/chat/index.ts b/packages/examples/sdk-backend-node/chat/index.ts index 40bccd361..85621540f 100644 --- a/packages/examples/sdk-backend-node/chat/index.ts +++ b/packages/examples/sdk-backend-node/chat/index.ts @@ -1,2 +1,28 @@ -export { runChatUseCases } from './chat'; -export { runNFTChatUseCases } from './nftChat'; +import { runChatLowlevelUseCases } from './chat.lowlevel'; +import { runNFTChatLowLevelUseCases } from './nftChat.lowlevel'; +import { runChatClassUseCases } from './chat'; + +export const runChatUseCases = async (): Promise => { + console.log(` +░█████╗░██╗░░██╗░█████╗░████████╗ +██╔══██╗██║░░██║██╔══██╗╚══██╔══╝ +██║░░╚═╝███████║███████║░░░██║░░░ +██║░░██╗██╔══██║██╔══██║░░░██║░░░ +╚█████╔╝██║░░██║██║░░██║░░░██║░░░ +░╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░ + `); + + await runChatClassUseCases(); + console.log(` +▒█▀▀█ ▒█░▒█ ░█▀▀█ ▀▀█▀▀ ░ ▒█░░░ ▒█▀▀▀█ ▒█░░▒█ ▒█░░░ ▒█▀▀▀ ▒█░░▒█ ▒█▀▀▀ ▒█░░░ +▒█░░░ ▒█▀▀█ ▒█▄▄█ ░▒█░░ ▄ ▒█░░░ ▒█░░▒█ ▒█▒█▒█ ▒█░░░ ▒█▀▀▀ ░▒█▒█░ ▒█▀▀▀ ▒█░░░ +▒█▄▄█ ▒█░▒█ ▒█░▒█ ░▒█░░ █ ▒█▄▄█ ▒█▄▄▄█ ▒█▄▀▄█ ▒█▄▄█ ▒█▄▄▄ ░░▀▄▀░ ▒█▄▄▄ ▒█▄▄█ + `); + await runChatLowlevelUseCases(); + console.log(` +▒█▄░▒█ ▒█▀▀▀ ▀▀█▀▀ ▒█▀▀█ ▒█░▒█ ░█▀▀█ ▀▀█▀▀ ░ ▒█░░░ ▒█▀▀▀█ ▒█░░▒█ ▒█░░░ ▒█▀▀▀ ▒█░░▒█ ▒█▀▀▀ ▒█░░░ +▒█▒█▒█ ▒█▀▀▀ ░▒█░░ ▒█░░░ ▒█▀▀█ ▒█▄▄█ ░▒█░░ ▄ ▒█░░░ ▒█░░▒█ ▒█▒█▒█ ▒█░░░ ▒█▀▀▀ ░▒█▒█░ ▒█▀▀▀ ▒█░░░ +▒█░░▀█ ▒█░░░ ░▒█░░ ▒█▄▄█ ▒█░▒█ ▒█░▒█ ░▒█░░ █ ▒█▄▄█ ▒█▄▄▄█ ▒█▄▀▄█ ▒█▄▄█ ▒█▄▄▄ ░░▀▄▀░ ▒█▄▄▄ ▒█▄▄█ + `); + await runNFTChatLowLevelUseCases(); +}; diff --git a/packages/examples/sdk-backend-node/chat/nftChat.ts b/packages/examples/sdk-backend-node/chat/nftChat.lowlevel.ts similarity index 96% rename from packages/examples/sdk-backend-node/chat/nftChat.ts rename to packages/examples/sdk-backend-node/chat/nftChat.lowlevel.ts index a3d6a0cfd..2f5142d5c 100644 --- a/packages/examples/sdk-backend-node/chat/nftChat.ts +++ b/packages/examples/sdk-backend-node/chat/nftChat.lowlevel.ts @@ -74,15 +74,7 @@ const skipExample = () => { }; // Push Chat - Run Chat Use cases -export const runNFTChatUseCases = async (): Promise => { - console.log(` - ███ ██ ███████ ████████ ██████ ██ ██ █████ ████████ - ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ █████ ██ ██ ███████ ███████ ██ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ████ ██ ██ ██████ ██ ██ ██ ██ ██ - `); - +export const runNFTChatLowLevelUseCases = async (): Promise => { if (skipExample()) { console.log('Skipping examples as required env vars are missing'); return; diff --git a/packages/examples/sdk-backend-node/main.ts b/packages/examples/sdk-backend-node/main.ts index dbb09f210..e8a538268 100644 --- a/packages/examples/sdk-backend-node/main.ts +++ b/packages/examples/sdk-backend-node/main.ts @@ -1,11 +1,12 @@ -import { runNotificaitonsUseCases } from './notification'; -import { runChatUseCases, runNFTChatUseCases } from './chat'; +import { runUserCases } from './user'; +import { runNotificationUseCases } from './notification'; +import { runChatUseCases } from './chat'; import { runVideoUseCases } from './video'; -import { runSpacesUseCases } from './spaces'; -import { runPushAPICases } from './pushAPI'; +import { runSpaceUseCases } from './space'; import { config } from './config'; import { ENV } from './types'; +import { exit } from 'process'; // CONFIGS const { env } = config; @@ -15,12 +16,12 @@ const start = async (): Promise => { console.log(`${returnHeadingLog()}`); console.log(`${returnENVLog()}`); - await runPushAPICases(); - await runNotificaitonsUseCases(); + await runUserCases(); + await runNotificationUseCases(); await runChatUseCases(); - await runNFTChatUseCases(); await runVideoUseCases(); - await runSpacesUseCases(); + await runSpaceUseCases(); + exit(0); }; start(); @@ -32,39 +33,54 @@ start(); // ----------- function returnHeadingLog() { const headingLog = ` - ███████ ██████ ██ ██ ███████ ██ ██ ███ ██ ██████ ████████ ██ ██████ ███ ██ █████ ██ ██ ████████ ██ ██ - ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ - ███████ ██ ██ █████ █████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██ ██ ██ ████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ███████ ██████ ██ ██ ██ ██████ ██ ████ ██████ ██ ██ ██████ ██ ████ ██ ██ ███████ ██ ██ ██ + +░██████╗██████╗░██╗░░██╗ ███████╗██╗░░░██╗███╗░░██╗░█████╗░████████╗██╗░█████╗░███╗░░██╗░█████╗░██╗░░░░░██╗████████╗██╗░░░██╗ +██╔════╝██╔══██╗██║░██╔╝ ██╔════╝██║░░░██║████╗░██║██╔══██╗╚══██╔══╝██║██╔══██╗████╗░██║██╔══██╗██║░░░░░██║╚══██╔══╝╚██╗░██╔╝ +╚█████╗░██║░░██║█████═╝░ █████╗░░██║░░░██║██╔██╗██║██║░░╚═╝░░░██║░░░██║██║░░██║██╔██╗██║███████║██║░░░░░██║░░░██║░░░░╚████╔╝░ +░╚═══██╗██║░░██║██╔═██╗░ ██╔══╝░░██║░░░██║██║╚████║██║░░██╗░░░██║░░░██║██║░░██║██║╚████║██╔══██║██║░░░░░██║░░░██║░░░░░╚██╔╝░░ +██████╔╝██████╔╝██║░╚██╗ ██║░░░░░╚██████╔╝██║░╚███║╚█████╔╝░░░██║░░░██║╚█████╔╝██║░╚███║██║░░██║███████╗██║░░░██║░░░░░░██║░░░ +╚═════╝░╚═════╝░╚═╝░░╚═╝ ╚═╝░░░░░░╚═════╝░╚═╝░░╚══╝░╚════╝░░░░╚═╝░░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝╚══════╝╚═╝░░░╚═╝░░░░░░╚═╝░░░ `; return headingLog; } function returnENVLog() { let environmentLog = ` - ███████ ████████ █████ ██████ ██ ███ ██ ██████ - ██ ██ ██ ██ ██ ██ ████ ██ ██ - ███████ ██ ███████ ██ ███ ██ ██ ██ ██ ██ ███ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ███████ ██ ██ ██ ██████ ██ ██ ████ ██████ + +███████╗███╗░░██╗██╗░░░██╗ ░░░░░░ ░██████╗████████╗░█████╗░░██████╗░██╗███╗░░██╗░██████╗░ +██╔════╝████╗░██║██║░░░██║ ░░░░░░ ██╔════╝╚══██╔══╝██╔══██╗██╔════╝░██║████╗░██║██╔════╝░ +█████╗░░██╔██╗██║╚██╗░██╔╝ █████╗ ╚█████╗░░░░██║░░░███████║██║░░██╗░██║██╔██╗██║██║░░██╗░ +██╔══╝░░██║╚████║░╚████╔╝░ ╚════╝ ░╚═══██╗░░░██║░░░██╔══██║██║░░╚██╗██║██║╚████║██║░░╚██╗ +███████╗██║░╚███║░░╚██╔╝░░ ░░░░░░ ██████╔╝░░░██║░░░██║░░██║╚██████╔╝██║██║░╚███║╚██████╔╝ +╚══════╝╚═╝░░╚══╝░░░╚═╝░░░ ░░░░░░ ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝░╚═════╝░╚═╝╚═╝░░╚══╝░╚═════╝░ `; if (env === ENV.PROD) { environmentLog = ` - ██████ ██████ ██████ ██████ ██ ██ ██████ ████████ ██ ██████ ███ ██ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ - ██████ ██████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██████ ██████ ██████ ██████ ██ ██ ██████ ██ ████ +███████╗███╗░░██╗██╗░░░██╗ ░░░░░░ ██████╗░██████╗░░█████╗░██████╗░ +██╔════╝████╗░██║██║░░░██║ ░░░░░░ ██╔══██╗██╔══██╗██╔══██╗██╔══██╗ +█████╗░░██╔██╗██║╚██╗░██╔╝ █████╗ ██████╔╝██████╔╝██║░░██║██║░░██║ +██╔══╝░░██║╚████║░╚████╔╝░ ╚════╝ ██╔═══╝░██╔══██╗██║░░██║██║░░██║ +███████╗██║░╚███║░░╚██╔╝░░ ░░░░░░ ██║░░░░░██║░░██║╚█████╔╝██████╔╝ +╚══════╝╚═╝░░╚══╝░░░╚═╝░░░ ░░░░░░ ╚═╝░░░░░╚═╝░░╚═╝░╚════╝░╚═════╝░ `; } else if (env === ENV.DEV) { environmentLog = ` - ██████ ███████ ██ ██ - ██ ██ ██ ██ ██ - ██ ██ █████ ██ ██ - ██ ██ ██ ██ ██ - ██████ ███████ ████ +███████╗███╗░░██╗██╗░░░██╗ ░░░░░░ ██████╗░███████╗██╗░░░██╗ +██╔════╝████╗░██║██║░░░██║ ░░░░░░ ██╔══██╗██╔════╝██║░░░██║ +█████╗░░██╔██╗██║╚██╗░██╔╝ █████╗ ██║░░██║█████╗░░╚██╗░██╔╝ +██╔══╝░░██║╚████║░╚████╔╝░ ╚════╝ ██║░░██║██╔══╝░░░╚████╔╝░ +███████╗██║░╚███║░░╚██╔╝░░ ░░░░░░ ██████╔╝███████╗░░╚██╔╝░░ +╚══════╝╚═╝░░╚══╝░░░╚═╝░░░ ░░░░░░ ╚═════╝░╚══════╝░░░╚═╝░░░ + `; + } else if (env === ENV.LOCAL) { + environmentLog = ` +███████╗███╗░░██╗██╗░░░██╗ ░░░░░░ ██╗░░░░░░█████╗░░█████╗░░█████╗░██╗░░░░░ +██╔════╝████╗░██║██║░░░██║ ░░░░░░ ██║░░░░░██╔══██╗██╔══██╗██╔══██╗██║░░░░░ +█████╗░░██╔██╗██║╚██╗░██╔╝ █████╗ ██║░░░░░██║░░██║██║░░╚═╝███████║██║░░░░░ +██╔══╝░░██║╚████║░╚████╔╝░ ╚════╝ ██║░░░░░██║░░██║██║░░██╗██╔══██║██║░░░░░ +███████╗██║░╚███║░░╚██╔╝░░ ░░░░░░ ███████╗╚█████╔╝╚█████╔╝██║░░██║███████╗ +╚══════╝╚═╝░░╚══╝░░░╚═╝░░░ ░░░░░░ ╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝╚══════╝ `; } diff --git a/packages/examples/sdk-backend-node/notification/index.ts b/packages/examples/sdk-backend-node/notification/index.ts index 605a60a23..f2251c1c7 100644 --- a/packages/examples/sdk-backend-node/notification/index.ts +++ b/packages/examples/sdk-backend-node/notification/index.ts @@ -1,384 +1,20 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; -import { ethers } from 'ethers'; -import { config } from '../config'; +import { runNotificaitonsLowLevelUseCases } from './notification.lowlevel'; +import { runNotificationClassUseCases } from './notification'; -import { createWalletClient, http } from 'viem'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { goerli } from 'viem/chains'; - -enum ENV { - PROD = 'prod', - STAGING = 'staging', - DEV = 'dev', - /** - * **This is for local development only** - */ - LOCAL = 'local', -} - -// CONFIGS -const { env, showAPIResponse } = config; - -// If you own a channel, you can use your channel address as well -const channelPrivateKey = process.env.WALLET_PRIVATE_KEY; - -/***************** SAMPLE SIGNER GENERATION *********************/ -/** - * USING VIEM - */ -const signerChannel = channelPrivateKey - ? createWalletClient({ - account: privateKeyToAccount(`0x${channelPrivateKey}`), - chain: goerli, - transport: http(), - }) - : undefined; -const channelAddress = signerChannel - ? signerChannel.account.address - : undefined; -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const signerAddress = signer.account.address; -// Dummy Wallet Addresses -const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; - -/** - * USING ETHERS - */ -// const signerChannel = new ethers.Wallet(`0x${channelPrivateKey}`); -// const channelAddress = signerChannel.address; -// // Random Wallet Signers -// const signer = ethers.Wallet.createRandom(); -// const signerAddress = signer.address; -// // Dummy Wallet Addresses -// const randomWallet1 = ethers.Wallet.createRandom().address; -/************************************************************* */ - -const skipExample = () => { - const requiredEnvVars = ['WALLET_PRIVATE_KEY']; - - for (const envVar of requiredEnvVars) { - if (!process.env[envVar]) { - return true; // Skip the example if any of the required env vars is missing - } - } - - return false; // All required env vars are present, don't skip the example -}; - -// Push Notification - Run Notifications Use cases -export const runNotificaitonsUseCases = async (): Promise => { +export const runNotificationUseCases = async (): Promise => { + console.log(` +███╗░░██╗░█████╗░████████╗██╗███████╗██╗░█████╗░░█████╗░████████╗██╗░█████╗░███╗░░██╗ +████╗░██║██╔══██╗╚══██╔══╝██║██╔════╝██║██╔══██╗██╔══██╗╚══██╔══╝██║██╔══██╗████╗░██║ +██╔██╗██║██║░░██║░░░██║░░░██║█████╗░░██║██║░░╚═╝███████║░░░██║░░░██║██║░░██║██╔██╗██║ +██║╚████║██║░░██║░░░██║░░░██║██╔══╝░░██║██║░░██╗██╔══██║░░░██║░░░██║██║░░██║██║╚████║ +██║░╚███║╚█████╔╝░░░██║░░░██║██║░░░░░██║╚█████╔╝██║░░██║░░░██║░░░██║╚█████╔╝██║░╚███║ +╚═╝░░╚══╝░╚════╝░░░░╚═╝░░░╚═╝╚═╝░░░░░╚═╝░╚════╝░╚═╝░░╚═╝░░░╚═╝░░░╚═╝░╚════╝░╚═╝░░╚══╝ + `); + await runNotificationClassUseCases(); console.log(` - ███ ██ ██████ ████████ ██ ███████ ██ ██████ █████ ████████ ██ ██████ ███ ██ ███████ - ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ - ██ ██ ██ ██ ██ ██ ██ █████ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ███████ - ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ - ██ ████ ██████ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██████ ██ ████ ███████ +▒█▄░▒█ ▒█▀▀▀█ ▀▀█▀▀ ▀█▀ ▒█▀▀▀ ▀█▀ ▒█▀▀█ ░█▀▀█ ▀▀█▀▀ ▀█▀ ▒█▀▀▀█ ▒█▄░▒█ ░ ▒█░░░ ▒█▀▀▀█ ▒█░░▒█ ▒█░░░ ▒█▀▀▀ ▒█░░▒█ ▒█▀▀▀ ▒█░░░ +▒█▒█▒█ ▒█░░▒█ ░▒█░░ ▒█░ ▒█▀▀▀ ▒█░ ▒█░░░ ▒█▄▄█ ░▒█░░ ▒█░ ▒█░░▒█ ▒█▒█▒█ ▄ ▒█░░░ ▒█░░▒█ ▒█▒█▒█ ▒█░░░ ▒█▀▀▀ ░▒█▒█░ ▒█▀▀▀ ▒█░░░ +▒█░░▀█ ▒█▄▄▄█ ░▒█░░ ▄█▄ ▒█░░░ ▄█▄ ▒█▄▄█ ▒█░▒█ ░▒█░░ ▄█▄ ▒█▄▄▄█ ▒█░░▀█ █ ▒█▄▄█ ▒█▄▄▄█ ▒█▄▀▄█ ▒█▄▄█ ▒█▄▄▄ ░░▀▄▀░ ▒█▄▄▄ ▒█▄▄█ `); - console.log('PushAPI.user.getFeeds'); - await PushAPI_user_getFeeds(); - - console.log('PushAPI.user.getFeeds [Spam]'); - await PushAPI_user_getFeeds__spam(); - - console.log('PushAPI.user.getSubscriptions'); - await PushAPI_user_getSubscriptions(); - - if (!skipExample()) { - console.log('PushAPI.channels.getChannel()'); - await PushAPI_channels_getChannel(); - - console.log('PushAPI.channels.search()'); - await PushAPI_channels_search(); - - console.log('PushAPI.channels.subscribe()'); - await PushAPI_channels_subscribe(); - - console.log('PushAPI.channels.unsubscribe()'); - await PushAPI_channels_unsubscribe(); - - // IMPORTANT: VARIOUS OTHER NOTIFICATIONS FORMAT SUPPORTED - // EXAMPLES HERE: https://github.com/ethereum-push-notification-service/push-sdk/blob/main/packages/restapi/README.md - console.log( - 'PushAPI.payloads.sendNotification() [Direct Payload, Single Recipient]' - ); - await PushAPI_payloads_sendNotification__direct_payload_single_recipient(); - - console.log( - 'PushAPI.payloads.sendNotification() [Direct Payload, Batch of Recipients (Subset)]' - ); - await PushAPI_payloads_sendNotification__direct_payload_group_of_recipient_subset(); - - console.log( - 'PushAPI.payloads.sendNotification() [Direct Payload, All Recipients (Broadcast)]' - ); - await PushAPI_payloads_sendNotification__direct_payload_all_recipients_brodcast(); - - console.log('PushAPI.channels._getSubscribers()'); - await PushAPI_channels_getSubscribers(); - - console.log('Push Notification - PushSDKSocket()'); - await PushSDKSocket(); - } + await runNotificaitonsLowLevelUseCases(); }; - -// Push Notification - PushAPI.user.getFeeds -async function PushAPI_user_getFeeds(silent = !showAPIResponse) { - const notifications = await PushAPI.user.getFeeds({ - user: `eip155:5:${signerAddress}`, // user address in CAIP - env: env as ENV, - }); - - console.log('PushAPI.user.getFeeds | Response - 200 OK'); - if (!silent) { - console.log(notifications); - } -} - -// Push Notification - PushAPI.user.getFeeds - Spam -async function PushAPI_user_getFeeds__spam(silent = !showAPIResponse) { - const notifications = await PushAPI.user.getFeeds({ - user: `eip155:5:${signerAddress}`, // user address in CAIP - spam: true, - env: env as ENV, - }); - - console.log('PushAPI.user.getFeeds [Spam] | Response - 200 OK'); - if (!silent) { - console.log(notifications); - } -} - -// Push Notification - PushAPI.user.getSubscriptions -async function PushAPI_user_getSubscriptions(silent = !showAPIResponse) { - const subscriptions = await PushAPI.user.getSubscriptions({ - user: `eip155:5:${signerAddress}`, // user address in CAIP - env: env as ENV, - }); - - console.log('PushAPI.user.getSubscriptions | Response - 200 OK'); - if (!silent) { - console.log(subscriptions); - } -} - -// Push Notification - PushAPI.channels.getChannel -async function PushAPI_channels_getChannel(silent = !showAPIResponse) { - const channelData = await PushAPI.channels.getChannel({ - channel: channelAddress as string, - env: env as ENV, - }); - - console.log('PushAPI.channels.getChannel | Response - 200 OK'); - if (!silent) { - console.log(channelData); - } -} - -// Push Notification - PushAPI.channels.search -async function PushAPI_channels_search(silent = !showAPIResponse) { - const channelsData = await PushAPI.channels.search({ - query: 'push', // a search query - page: 1, // page index - limit: 20, // no of items per page - env: env as ENV, - }); - - console.log('PushAPI.channels.search | Response - 200 OK'); - if (!silent) { - console.log(channelsData); - } -} - -// Push Notification - PushAPI.channels.subscribe -async function PushAPI_channels_subscribe(silent = !showAPIResponse) { - const response = await PushAPI.channels.subscribe({ - signer: signer, - channelAddress: `eip155:5:${channelAddress}`, // channel address in CAIP - userAddress: `eip155:5:${signerAddress}`, // user address in CAIP - onSuccess: () => { - console.log('opt in success'); - }, - onError: () => { - console.error('opt in error'); - }, - env: env as ENV, - }); - - console.log('PushAPI.channels.subscribe | Response - 200 OK'); - if (!silent) { - console.log(response); - } -} - -// Push Notification - PushAPI.channels.unsubscribe -async function PushAPI_channels_unsubscribe(silent = !showAPIResponse) { - const response = await PushAPI.channels.unsubscribe({ - signer: signer, - channelAddress: `eip155:5:${channelAddress}`, // channel address in CAIP - userAddress: `eip155:5:${signerAddress}`, // user address in CAIP - onSuccess: () => { - console.log('opt out success'); - }, - onError: () => { - console.error('opt out error'); - }, - env: env as ENV, - }); - - console.log('PushAPI.channels.unsubscribe | Response - 200 OK'); - if (!silent) { - console.log(response); - } -} - -// Push Notification - Send Notifications -// Direct payload for single recipient(target) -// PushAPI.payloads.sendNotification -async function PushAPI_payloads_sendNotification__direct_payload_single_recipient( - silent = !showAPIResponse -) { - const apiResponse = await PushAPI.payloads.sendNotification({ - signer: signerChannel, // Need to resolve to channel address - type: 3, // target - identityType: 2, // direct payload - notification: { - title: `notification TITLE:`, - body: `notification BODY`, - }, - payload: { - title: `payload title`, - body: `sample msg body`, - cta: '', - img: '', - }, - recipients: `eip155:5:${signerAddress}`, // recipient address - channel: `eip155:5:${channelAddress}`, // your channel address - env: env as ENV, - }); - - console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); - if (!silent) { - console.log(apiResponse); - } -} - -// Push Notification - Direct payload for group of recipients(subset) -// PushAPI.payloads.sendNotification -async function PushAPI_payloads_sendNotification__direct_payload_group_of_recipient_subset( - silent = !showAPIResponse -) { - const apiResponse = await PushAPI.payloads.sendNotification({ - signer: signerChannel, // Need to resolve to channel address - type: 4, // subset - identityType: 2, // direct payload - notification: { - title: `notification TITLE:`, - body: `notification BODY`, - }, - payload: { - title: `payload title`, - body: `sample msg body`, - cta: '', - img: '', - }, - recipients: [`eip155:5:${signerAddress}`, `eip155:5:${randomWallet1}`], // recipient addresses - channel: `eip155:5:${channelAddress}`, // your channel address - env: env as ENV, - }); - - console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); - if (!silent) { - console.log(apiResponse); - } -} - -// Push Notification - Direct payload for all recipients(broadcast) -// PushAPI.payloads.sendNotification -async function PushAPI_payloads_sendNotification__direct_payload_all_recipients_brodcast( - silent = !showAPIResponse -) { - const apiResponse = await PushAPI.payloads.sendNotification({ - signer: signerChannel, // Needs to resolve to channel address - type: 1, // broadcast - identityType: 2, // direct payload - notification: { - title: `notification TITLE:`, - body: `notification BODY`, - }, - payload: { - title: `payload title`, - body: `sample msg body`, - cta: '', - img: '', - }, - channel: `eip155:5:${channelAddress}`, // your channel address - env: env as ENV, - }); - - console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); - if (!silent) { - console.log(apiResponse); - } -} - -// Push Notification - Get Subscribers list from channels (DEPRECATED) -async function PushAPI_channels_getSubscribers(silent = !showAPIResponse) { - const subscribers = await PushAPI.channels._getSubscribers({ - channel: `eip155:5:${channelAddress}`, // channel address in CAIP - env: env as ENV, - }); - - console.log('PushAPI.channels._getSubscribers | Response - 200 OK'); - if (!silent) { - console.log(subscribers); - } -} - -// Push Notification - Socket Connection -async function PushSDKSocket(silent = !showAPIResponse) { - const pushSDKSocket = createSocketConnection({ - user: `eip155:5:${signerAddress}`, // CAIP, see below - socketOptions: { autoConnect: false }, - env: env as ENV, - }); - - if (!pushSDKSocket) { - throw new Error('PushSDKSocket | Socket Connection Failed'); - } - - pushSDKSocket.connect(); - - pushSDKSocket.on(EVENTS.CONNECT, async () => { - console.log('Socket Connected - will disconnect after 4 seconds'); - - // send a notification to see the result - await PushAPI_payloads_sendNotification__direct_payload_single_recipient( - true - ); - }); - - pushSDKSocket.on(EVENTS.DISCONNECT, () => { - console.log('Socket Disconnected'); - }); - - pushSDKSocket.on(EVENTS.USER_FEEDS, (feedItem) => { - // feedItem is the notification data when that notification was received - console.log('Incoming Feed from Socket'); - if (!silent) { - console.log(feedItem); - } - - // disconnect socket after this, not to be done in real implementations - pushSDKSocket.disconnect(); - }); - - const delay = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)); - await delay(4000); -} diff --git a/packages/examples/sdk-backend-node/notification/notification.lowlevel.ts b/packages/examples/sdk-backend-node/notification/notification.lowlevel.ts new file mode 100644 index 000000000..e2f04f99a --- /dev/null +++ b/packages/examples/sdk-backend-node/notification/notification.lowlevel.ts @@ -0,0 +1,377 @@ +import * as PushAPI from '@pushprotocol/restapi'; +import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; +import { ethers } from 'ethers'; +import { config } from '../config'; + +import { createWalletClient, http } from 'viem'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { goerli } from 'viem/chains'; + +enum ENV { + PROD = 'prod', + STAGING = 'staging', + DEV = 'dev', + /** + * **This is for local development only** + */ + LOCAL = 'local', +} + +// CONFIGS +const { env, showAPIResponse } = config; + +// If you own a channel, you can use your channel address as well +const channelPrivateKey = process.env.WALLET_PRIVATE_KEY; + +/***************** SAMPLE SIGNER GENERATION *********************/ +/** + * USING VIEM + */ +const signerChannel = channelPrivateKey + ? createWalletClient({ + account: privateKeyToAccount(`0x${channelPrivateKey}`), + chain: goerli, + transport: http(), + }) + : undefined; +const channelAddress = signerChannel + ? signerChannel.account.address + : undefined; +// Random Wallet Signers +const signer = createWalletClient({ + account: privateKeyToAccount(generatePrivateKey()), + chain: goerli, + transport: http(), +}); +const signerAddress = signer.account.address; +// Dummy Wallet Addresses +const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; + +/** + * USING ETHERS + */ +// const signerChannel = new ethers.Wallet(`0x${channelPrivateKey}`); +// const channelAddress = signerChannel.address; +// // Random Wallet Signers +// const signer = ethers.Wallet.createRandom(); +// const signerAddress = signer.address; +// // Dummy Wallet Addresses +// const randomWallet1 = ethers.Wallet.createRandom().address; +/************************************************************* */ + +const skipExample = () => { + const requiredEnvVars = ['WALLET_PRIVATE_KEY']; + + for (const envVar of requiredEnvVars) { + if (!process.env[envVar]) { + return true; // Skip the example if any of the required env vars is missing + } + } + + return false; // All required env vars are present, don't skip the example +}; + +// Push Notification - Run Notifications Use cases +export const runNotificaitonsLowLevelUseCases = async (): Promise => { + console.log('PushAPI.user.getFeeds'); + await PushAPI_user_getFeeds(); + + console.log('PushAPI.user.getFeeds [Spam]'); + await PushAPI_user_getFeeds__spam(); + + console.log('PushAPI.user.getSubscriptions'); + await PushAPI_user_getSubscriptions(); + + if (!skipExample()) { + console.log('PushAPI.channels.getChannel()'); + await PushAPI_channels_getChannel(); + + console.log('PushAPI.channels.search()'); + await PushAPI_channels_search(); + + console.log('PushAPI.channels.subscribe()'); + await PushAPI_channels_subscribe(); + + console.log('PushAPI.channels.unsubscribe()'); + await PushAPI_channels_unsubscribe(); + + // IMPORTANT: VARIOUS OTHER NOTIFICATIONS FORMAT SUPPORTED + // EXAMPLES HERE: https://github.com/ethereum-push-notification-service/push-sdk/blob/main/packages/restapi/README.md + console.log( + 'PushAPI.payloads.sendNotification() [Direct Payload, Single Recipient]' + ); + await PushAPI_payloads_sendNotification__direct_payload_single_recipient(); + + console.log( + 'PushAPI.payloads.sendNotification() [Direct Payload, Batch of Recipients (Subset)]' + ); + await PushAPI_payloads_sendNotification__direct_payload_group_of_recipient_subset(); + + console.log( + 'PushAPI.payloads.sendNotification() [Direct Payload, All Recipients (Broadcast)]' + ); + await PushAPI_payloads_sendNotification__direct_payload_all_recipients_brodcast(); + + console.log('PushAPI.channels._getSubscribers()'); + await PushAPI_channels_getSubscribers(); + + console.log('Push Notification - PushSDKSocket()'); + await PushSDKSocket(); + } +}; + +// Push Notification - PushAPI.user.getFeeds +async function PushAPI_user_getFeeds(silent = !showAPIResponse) { + const notifications = await PushAPI.user.getFeeds({ + user: `eip155:5:${signerAddress}`, // user address in CAIP + env: env as ENV, + }); + + console.log('PushAPI.user.getFeeds | Response - 200 OK'); + if (!silent) { + console.log(notifications); + } +} + +// Push Notification - PushAPI.user.getFeeds - Spam +async function PushAPI_user_getFeeds__spam(silent = !showAPIResponse) { + const notifications = await PushAPI.user.getFeeds({ + user: `eip155:5:${signerAddress}`, // user address in CAIP + spam: true, + env: env as ENV, + }); + + console.log('PushAPI.user.getFeeds [Spam] | Response - 200 OK'); + if (!silent) { + console.log(notifications); + } +} + +// Push Notification - PushAPI.user.getSubscriptions +async function PushAPI_user_getSubscriptions(silent = !showAPIResponse) { + const subscriptions = await PushAPI.user.getSubscriptions({ + user: `eip155:5:${signerAddress}`, // user address in CAIP + env: env as ENV, + }); + + console.log('PushAPI.user.getSubscriptions | Response - 200 OK'); + if (!silent) { + console.log(subscriptions); + } +} + +// Push Notification - PushAPI.channels.getChannel +async function PushAPI_channels_getChannel(silent = !showAPIResponse) { + const channelData = await PushAPI.channels.getChannel({ + channel: channelAddress as string, + env: env as ENV, + }); + + console.log('PushAPI.channels.getChannel | Response - 200 OK'); + if (!silent) { + console.log(channelData); + } +} + +// Push Notification - PushAPI.channels.search +async function PushAPI_channels_search(silent = !showAPIResponse) { + const channelsData = await PushAPI.channels.search({ + query: 'push', // a search query + page: 1, // page index + limit: 20, // no of items per page + env: env as ENV, + }); + + console.log('PushAPI.channels.search | Response - 200 OK'); + if (!silent) { + console.log(channelsData); + } +} + +// Push Notification - PushAPI.channels.subscribe +async function PushAPI_channels_subscribe(silent = !showAPIResponse) { + const response = await PushAPI.channels.subscribe({ + signer: signer, + channelAddress: `eip155:5:${channelAddress}`, // channel address in CAIP + userAddress: `eip155:5:${signerAddress}`, // user address in CAIP + onSuccess: () => { + console.log('opt in success'); + }, + onError: () => { + console.error('opt in error'); + }, + env: env as ENV, + }); + + console.log('PushAPI.channels.subscribe | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Notification - PushAPI.channels.unsubscribe +async function PushAPI_channels_unsubscribe(silent = !showAPIResponse) { + const response = await PushAPI.channels.unsubscribe({ + signer: signer, + channelAddress: `eip155:5:${channelAddress}`, // channel address in CAIP + userAddress: `eip155:5:${signerAddress}`, // user address in CAIP + onSuccess: () => { + console.log('opt out success'); + }, + onError: () => { + console.error('opt out error'); + }, + env: env as ENV, + }); + + console.log('PushAPI.channels.unsubscribe | Response - 200 OK'); + if (!silent) { + console.log(response); + } +} + +// Push Notification - Send Notifications +// Direct payload for single recipient(target) +// PushAPI.payloads.sendNotification +async function PushAPI_payloads_sendNotification__direct_payload_single_recipient( + silent = !showAPIResponse +) { + const apiResponse = await PushAPI.payloads.sendNotification({ + signer: signerChannel, // Need to resolve to channel address + type: 3, // target + identityType: 2, // direct payload + notification: { + title: `notification TITLE:`, + body: `notification BODY`, + }, + payload: { + title: `payload title`, + body: `sample msg body`, + cta: '', + img: '', + }, + recipients: `eip155:5:${signerAddress}`, // recipient address + channel: `eip155:5:${channelAddress}`, // your channel address + env: env as ENV, + }); + + console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); + if (!silent) { + console.log(apiResponse); + } +} + +// Push Notification - Direct payload for group of recipients(subset) +// PushAPI.payloads.sendNotification +async function PushAPI_payloads_sendNotification__direct_payload_group_of_recipient_subset( + silent = !showAPIResponse +) { + const apiResponse = await PushAPI.payloads.sendNotification({ + signer: signerChannel, // Need to resolve to channel address + type: 4, // subset + identityType: 2, // direct payload + notification: { + title: `notification TITLE:`, + body: `notification BODY`, + }, + payload: { + title: `payload title`, + body: `sample msg body`, + cta: '', + img: '', + }, + recipients: [`eip155:5:${signerAddress}`, `eip155:5:${randomWallet1}`], // recipient addresses + channel: `eip155:5:${channelAddress}`, // your channel address + env: env as ENV, + }); + + console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); + if (!silent) { + console.log(apiResponse); + } +} + +// Push Notification - Direct payload for all recipients(broadcast) +// PushAPI.payloads.sendNotification +async function PushAPI_payloads_sendNotification__direct_payload_all_recipients_brodcast( + silent = !showAPIResponse +) { + const apiResponse = await PushAPI.payloads.sendNotification({ + signer: signerChannel, // Needs to resolve to channel address + type: 1, // broadcast + identityType: 2, // direct payload + notification: { + title: `notification TITLE:`, + body: `notification BODY`, + }, + payload: { + title: `payload title`, + body: `sample msg body`, + cta: '', + img: '', + }, + channel: `eip155:5:${channelAddress}`, // your channel address + env: env as ENV, + }); + + console.log('PushAPI.payloads.sendNotification | Response - 204 OK'); + if (!silent) { + console.log(apiResponse); + } +} + +// Push Notification - Get Subscribers list from channels (DEPRECATED) +async function PushAPI_channels_getSubscribers(silent = !showAPIResponse) { + const subscribers = await PushAPI.channels._getSubscribers({ + channel: `eip155:5:${channelAddress}`, // channel address in CAIP + env: env as ENV, + }); + + console.log('PushAPI.channels._getSubscribers | Response - 200 OK'); + if (!silent) { + console.log(subscribers); + } +} + +// Push Notification - Socket Connection +async function PushSDKSocket(silent = !showAPIResponse) { + const pushSDKSocket = createSocketConnection({ + user: `eip155:5:${signerAddress}`, // CAIP, see below + socketOptions: { autoConnect: false }, + env: env as ENV, + }); + + if (!pushSDKSocket) { + throw new Error('PushSDKSocket | Socket Connection Failed'); + } + + pushSDKSocket.connect(); + + pushSDKSocket.on(EVENTS.CONNECT, async () => { + console.log('Socket Connected - will disconnect after 4 seconds'); + + // send a notification to see the result + await PushAPI_payloads_sendNotification__direct_payload_single_recipient( + true + ); + }); + + pushSDKSocket.on(EVENTS.DISCONNECT, () => { + console.log('Socket Disconnected'); + }); + + pushSDKSocket.on(EVENTS.USER_FEEDS, (feedItem) => { + // feedItem is the notification data when that notification was received + console.log('Incoming Feed from Socket'); + if (!silent) { + console.log(feedItem); + } + + // disconnect socket after this, not to be done in real implementations + pushSDKSocket.disconnect(); + }); + + const delay = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)); + await delay(4000); +} diff --git a/packages/examples/sdk-backend-node/pushAPI/channel.ts b/packages/examples/sdk-backend-node/notification/notification.ts similarity index 72% rename from packages/examples/sdk-backend-node/pushAPI/channel.ts rename to packages/examples/sdk-backend-node/notification/notification.ts index 7e6b236a0..2865fee94 100644 --- a/packages/examples/sdk-backend-node/pushAPI/channel.ts +++ b/packages/examples/sdk-backend-node/notification/notification.ts @@ -1,11 +1,27 @@ import { PushAPI } from '@pushprotocol/restapi'; import { config } from '../config'; import { ethers } from 'ethers'; +import { STREAM } from '@pushprotocol/restapi/src/lib/pushstream/pushStreamTypes'; // CONFIGS const { env, showAPIResponse } = config; -export const runPushAPIChannelCases = async (): Promise => { +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const eventlistener = async ( + pushAPI: PushAPI, + eventName: string +): Promise => { + pushAPI.stream.on(eventName, (data: any) => { + if (showAPIResponse) { + console.log('Stream Event Received'); + console.log(data); + console.log('\n'); + } + }); +}; + +export const runNotificationClassUseCases = async (): Promise => { if (!process.env.WALLET_PRIVATE_KEY) { console.log( 'skipping PushAPI.channel examples, no private key passed in .env' @@ -27,6 +43,13 @@ export const runPushAPIChannelCases = async (): Promise => { // ------------------------------------------------------------------- // ------------------------------------------------------------------- const userAlice = await PushAPI.initialize(signer, { env }); + + // Listen Stream Events for getting websocket events + console.log(`Listening ${STREAM.NOTIF} Events`); + eventlistener(userAlice, STREAM.NOTIF); + console.log(`Listening ${STREAM.NOTIF_OPS} Events`); + eventlistener(userAlice, STREAM.NOTIF_OPS); + console.log('\n\n'); // ------------------------------------------------------------------- // ------------------------------------------------------------------- console.log('PushAPI.channel.info'); @@ -63,14 +86,16 @@ export const runPushAPIChannelCases = async (): Promise => { body: 'test', }, }); - const targetedNotif = await userAlice.channel.send([randomWallet1], { + await delay(3000); // Delay added to log the events in order + const targetedNotif = await userAlice.channel.send([signer.address], { notification: { title: 'test', body: 'test', }, }); + await delay(3000); // Delay added to log the events in order const subsetNotif = await userAlice.channel.send( - [randomWallet1, randomWallet2], + [randomWallet1, randomWallet2, signer.address], { notification: { title: 'test', @@ -78,6 +103,7 @@ export const runPushAPIChannelCases = async (): Promise => { }, } ); + await delay(3000); // Delay added to log the events in order if (showAPIResponse) { console.log(broadcastNotif, targetedNotif, subsetNotif); } @@ -189,4 +215,43 @@ export const runPushAPIChannelCases = async (): Promise => { console.log(aliasInfo); } console.log('PushAPI.channel.alias.info | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.notification.list'); + const inboxNotifications = await userAlice.notification.list('INBOX'); + const spamNotifications = await userAlice.notification.list('SPAM'); + if (showAPIResponse) { + console.log(inboxNotifications, spamNotifications); + } + console.log('PushAPI.notification.list | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.notification.subscribe'); + const subscribeResponse = await userAlice.notification.subscribe( + 'eip155:5:0xD8634C39BBFd4033c0d3289C4515275102423681' // channel to subscribe + ); + if (showAPIResponse) { + console.log(subscribeResponse); + } + console.log('PushAPI.notification.subscribe | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.notification.subscriptions'); + const aliceSubscriptions = await userAlice.notification.subscriptions(); + if (showAPIResponse) { + console.log(aliceSubscriptions); + } + console.log('PushAPI.notification.subscriptions | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.notification.unsubscribe'); + const unsubscribeResponse = await userAlice.notification.unsubscribe( + 'eip155:5:0xD8634C39BBFd4033c0d3289C4515275102423681' // channel to unsubscribe + ); + if (showAPIResponse) { + console.log(unsubscribeResponse); + } + console.log('PushAPI.notification.unsubscribe | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- }; diff --git a/packages/examples/sdk-backend-node/pushAPI/chat.ts b/packages/examples/sdk-backend-node/pushAPI/chat.ts deleted file mode 100644 index f34973ec1..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/chat.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { - adjectives, - animals, - colors, - uniqueNamesGenerator, -} from 'unique-names-generator'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const signerAddress = signer.account.address; -const secondSigner = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const secondSignerAddress = secondSigner.account.address; -const thirdSigner = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const thirdSignerAddress = thirdSigner.account.address; - -// Dummy Wallet Addresses -const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; -const randomWallet2 = privateKeyToAccount(generatePrivateKey()).address; -const randomWallet3 = privateKeyToAccount(generatePrivateKey()).address; -/****************************************************************/ - -/***************** SAMPLE GROUP DATA ****************************/ -const groupName = uniqueNamesGenerator({ - dictionaries: [adjectives, colors, animals], -}); -const groupDescription = uniqueNamesGenerator({ - dictionaries: [adjectives, colors, animals], -}); -const groupImage = - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg=='; -/***************** SAMPLE GROUP DATA ****************************/ - -export const runPushAPIChatCases = async (): Promise => { - const userAlice = await PushAPI.initialize(signer, { env }); - const userBob = await PushAPI.initialize(secondSigner, { env }); - const tempUser = await PushAPI.initialize(thirdSigner, { env }); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.list'); - const aliceChats = await userAlice.chat.list('CHATS'); - const aliceRequests = await userAlice.chat.list('REQUESTS'); - if (showAPIResponse) { - console.log(aliceChats); - console.log(aliceRequests); - } - console.log('PushAPI.chat.list | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.latest'); - const aliceLatestChatWithBob = await userAlice.chat.latest( - secondSignerAddress - ); - if (showAPIResponse) { - console.log(aliceLatestChatWithBob); - } - console.log('PushAPI.chat.latest | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.history'); - const aliceChatHistoryWithBob = await userAlice.chat.history( - secondSignerAddress - ); - if (showAPIResponse) { - console.log(aliceChatHistoryWithBob); - } - console.log('PushAPI.chat.history | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.send'); - const aliceMessagesBob = await userAlice.chat.send(secondSignerAddress, { - content: 'Hello Bob!', - type: 'Text', - }); - if (showAPIResponse) { - console.log(aliceMessagesBob); - } - console.log('PushAPI.chat.send | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.accept'); - const bobAcceptsRequest = await userBob.chat.accept(signerAddress); - if (showAPIResponse) { - console.log(bobAcceptsRequest); - } - console.log('PushAPI.chat.accept | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.reject'); - await tempUser.chat.send(secondSignerAddress, { - content: 'Sending malicious message', - type: 'Text', - }); - const bobRejectsRequest = await userBob.chat.reject(thirdSignerAddress); - if (showAPIResponse) { - console.log(bobRejectsRequest); - } - console.log('PushAPI.chat.reject | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.block'); - const AliceBlocksBob = await userAlice.chat.block([secondSignerAddress]); - if (showAPIResponse) { - console.log(AliceBlocksBob); - } - console.log('PushAPI.chat.block | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.chat.unblock'); - const AliceUnblocksBob = await userAlice.chat.unblock([secondSignerAddress]); - if (showAPIResponse) { - console.log(AliceUnblocksBob); - } - console.log('PushAPI.chat.unblock | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.create'); - const createdGroup = await userAlice.chat.group.create(groupName, { - description: groupDescription, - image: groupImage, - members: [randomWallet1, randomWallet2], - admins: [], - private: false, - }); - const groupChatId = createdGroup.chatId; // to be used in other examples - if (showAPIResponse) { - console.log(createdGroup); - } - console.log('PushAPI.group.create | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.permissions'); - const grouppermissions = await userAlice.chat.group.permissions(groupChatId); - if (showAPIResponse) { - console.log(grouppermissions); - } - console.log('PushAPI.group.permissions | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.info'); - const groupInfo = await userAlice.chat.group.info(groupChatId); - if (showAPIResponse) { - console.log(groupInfo); - } - console.log('PushAPI.group.info | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.update'); - const updatedGroup = await userAlice.chat.group.update(groupChatId, { - description: 'Updated Description', - }); - if (showAPIResponse) { - console.log(updatedGroup); - } - console.log('PushAPI.group.update | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.add'); - const addMember = await userAlice.chat.group.add(groupChatId, { - role: 'MEMBER', - accounts: [randomWallet3], - }); - if (showAPIResponse) { - console.log(addMember); - } - console.log('PushAPI.group.add | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.remove'); - const removeMember = await userAlice.chat.group.remove(groupChatId, { - role: 'MEMBER', - accounts: [randomWallet3], - }); - if (showAPIResponse) { - console.log(removeMember); - } - console.log('PushAPI.group.remove | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.join'); - const joinGrp = await userBob.chat.group.join(groupChatId); - if (showAPIResponse) { - console.log(joinGrp); - } - console.log('PushAPI.group.join | Response - 200 OK\n\n'); - //------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.leave'); - const leaveGrp = await userBob.chat.group.leave(groupChatId); - if (showAPIResponse) { - console.log(leaveGrp); - } - console.log('PushAPI.group.leave | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.group.reject'); - const sampleGrp = await userAlice.chat.group.create('Sample Grp', { - description: groupDescription, - image: groupImage, - members: [secondSignerAddress], // invite bob - admins: [], - private: true, - }); - await userBob.chat.group.reject(sampleGrp.chatId); - console.log('PushAPI.group.reject | Response - 200 OK\n\n'); -}; diff --git a/packages/examples/sdk-backend-node/pushAPI/encryption.ts b/packages/examples/sdk-backend-node/pushAPI/encryption.ts deleted file mode 100644 index 67300c65f..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/encryption.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); - -export const runPushAPIEncryptionCases = async (): Promise => { - const userAlice = await PushAPI.initialize(signer, { env }); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.encryption.info'); - const encryptionInfo = await userAlice.encryption.info(); - if (showAPIResponse) { - console.log(encryptionInfo); - } - console.log('PushAPI.encryption.info | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.encryption.update'); - const PGP_V3 = 'eip191-aes256-gcm-hkdf-sha256'; - const encryptionUpdate = await userAlice.encryption.update(PGP_V3 as any); - if (showAPIResponse) { - console.log(encryptionUpdate); - } - console.log('PushAPI.encryption.update | Response - 200 OK\n\n'); -}; diff --git a/packages/examples/sdk-backend-node/pushAPI/index.ts b/packages/examples/sdk-backend-node/pushAPI/index.ts deleted file mode 100644 index e7931842c..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/index.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; -import { runPushAPIChatCases } from './chat'; -import { runPushAPIEncryptionCases } from './encryption'; -import { runPushAPINotificationCases } from './notification'; -import { runPushAPIProfileCases } from './profile'; -import { runPushAPIStreamCases } from './stream'; -import { runPushAPIChannelCases } from './channel'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); - -export const runPushAPICases = async (): Promise => { - console.log(` - -██████╗░██╗░░░██╗░██████╗██╗░░██╗░█████╗░██████╗░██╗ ░█████╗░██╗░░░░░░█████╗░░██████╗░██████╗ -██╔══██╗██║░░░██║██╔════╝██║░░██║██╔══██╗██╔══██╗██║ ██╔══██╗██║░░░░░██╔══██╗██╔════╝██╔════╝ -██████╔╝██║░░░██║╚█████╗░███████║███████║██████╔╝██║ ██║░░╚═╝██║░░░░░███████║╚█████╗░╚█████╗░ -██╔═══╝░██║░░░██║░╚═══██╗██╔══██║██╔══██║██╔═══╝░██║ ██║░░██╗██║░░░░░██╔══██║░╚═══██╗░╚═══██╗ -██║░░░░░╚██████╔╝██████╔╝██║░░██║██║░░██║██║░░░░░██║ ╚█████╔╝███████╗██║░░██║██████╔╝██████╔╝ -╚═╝░░░░░░╚═════╝░╚═════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝ ░╚════╝░╚══════╝╚═╝░░╚═╝╚═════╝░╚═════╝░ - `); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.initialize'); - const userAlice = await PushAPI.initialize(signer, { env }); - console.log('PushAPI.initialize | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - // todo : This is yet to be discussed - console.log('PushAPI.info'); - const userAliceInfo = await userAlice.info(); - if (showAPIResponse) { - console.log(userAliceInfo); - } - console.log('PushAPI.info | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - await runPushAPIProfileCases(); // PushAPI.profile - await runPushAPIChatCases(); // PushAPI.chat - await runPushAPIEncryptionCases(); // PushAPI.encryption - await runPushAPINotificationCases(); // PushAPI.notification - await runPushAPIChannelCases(); // PushAPI.channel - await runPushAPIStreamCases(); // PushAPI.stream -}; diff --git a/packages/examples/sdk-backend-node/pushAPI/notification.ts b/packages/examples/sdk-backend-node/pushAPI/notification.ts deleted file mode 100644 index 579ea1e2b..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/notification.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); - -export const runPushAPINotificationCases = async (): Promise => { - const userAlice = await PushAPI.initialize(signer, { env }); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.notification.list'); - const inboxNotifications = await userAlice.notification.list('INBOX'); - const spamNotifications = await userAlice.notification.list('SPAM'); - if (showAPIResponse) { - console.log(inboxNotifications, spamNotifications); - } - console.log('PushAPI.notification.list | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.notification.subscribe'); - const subscribeResponse = await userAlice.notification.subscribe( - 'eip155:5:0xD8634C39BBFd4033c0d3289C4515275102423681' // channel to subscribe - ); - if (showAPIResponse) { - console.log(subscribeResponse); - } - console.log('PushAPI.notification.subscribe | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.notification.subscriptions'); - const aliceSubscriptions = await userAlice.notification.subscriptions(); - if (showAPIResponse) { - console.log(aliceSubscriptions); - } - console.log('PushAPI.notification.subscriptions | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.notification.unsubscribe'); - const unsubscribeResponse = await userAlice.notification.unsubscribe( - 'eip155:5:0xD8634C39BBFd4033c0d3289C4515275102423681' // channel to unsubscribe - ); - if (showAPIResponse) { - console.log(unsubscribeResponse); - } - console.log('PushAPI.notification.unsubscribe | Response - 200 OK\n\n'); -}; diff --git a/packages/examples/sdk-backend-node/pushAPI/profile.ts b/packages/examples/sdk-backend-node/pushAPI/profile.ts deleted file mode 100644 index f72d93f1b..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/profile.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); - -export const runPushAPIProfileCases = async (): Promise => { - const userAlice = await PushAPI.initialize(signer, { env }); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.profile.info'); - const userAliceProfileInfo = await userAlice.profile.info(); - if (showAPIResponse) { - console.log(userAliceProfileInfo); - } - console.log('PushAPI.profile.info | Response - 200 OK\n\n'); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('PushAPI.profile.update'); - const updatedName = 'Bob The Builder'; - const response = await userAlice.profile.update({ name: updatedName }); - if (showAPIResponse) { - console.log(response); - } - console.log('PushAPI.profile.update | Response - 200 OK\n\n'); -}; diff --git a/packages/examples/sdk-backend-node/pushAPI/stream.ts b/packages/examples/sdk-backend-node/pushAPI/stream.ts deleted file mode 100644 index e10c599c8..000000000 --- a/packages/examples/sdk-backend-node/pushAPI/stream.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { PushAPI } from '@pushprotocol/restapi'; -import { config } from '../config'; -import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; -import { createWalletClient, http } from 'viem'; -import { goerli } from 'viem/chains'; -import { STREAM } from '@pushprotocol/restapi/src/lib/pushstream/pushStreamTypes'; - -// CONFIGS -const { env, showAPIResponse } = config; - -/***************** SAMPLE SIGNER GENERATION *********************/ -// Uing VIEM -// Random Wallet Signers -const signer = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const signerAddress = signer.account.address; -const secondSigner = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const secondSignerAddress = secondSigner.account.address; -const thirdSigner = createWalletClient({ - account: privateKeyToAccount(generatePrivateKey()), - chain: goerli, - transport: http(), -}); -const thirdSignerAddress = thirdSigner.account.address; -// Dummy Wallet Addresses -const randomWallet1 = privateKeyToAccount(generatePrivateKey()).address; - -const eventlistener = async ( - pushAPI: PushAPI, - eventName: string -): Promise => { - pushAPI.stream.on(eventName, (data: any) => { - if (showAPIResponse) { - console.log(data); - } - }); -}; - -const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - -export const runPushAPIStreamCases = async (): Promise => { - const userAlice = await PushAPI.initialize(signer, { env }); - const userBob = await PushAPI.initialize(secondSigner, { env }); - const userKate = await PushAPI.initialize(thirdSigner, { env }); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log(`Listening ${STREAM.PROFILE} Events`); - eventlistener(userAlice, STREAM.PROFILE); - console.log(`Listening ${STREAM.ENCRYPTION} Events`); - eventlistener(userAlice, STREAM.ENCRYPTION); - console.log(`Listening ${STREAM.NOTIF} Events`); - eventlistener(userAlice, STREAM.NOTIF); - console.log(`Listening ${STREAM.NOTIF_OPS} Events`); - eventlistener(userAlice, STREAM.NOTIF_OPS); - console.log(`Listening ${STREAM.CHAT} Events`); - eventlistener(userAlice, STREAM.CHAT); - console.log(`Listening ${STREAM.CHAT_OPS} Events`); - eventlistener(userAlice, STREAM.CHAT_OPS); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nNew Chat Request, Expected Events:\n1. chat.request'); - await userAlice.chat.send(secondSignerAddress, { - content: 'Hello Bob! from Alice', - }); - await delay(3000); // Delay added to log the events in order - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nNew Chat Request, Expected Events:\n1. chat.request'); - await userAlice.chat.send(thirdSignerAddress, { - content: 'Hello Kate! from Alice', - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nChat Request Accept, Expected Events:\n1. chat.accept'); - await userBob.chat.accept(signerAddress); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nChat Request Reject, Expected Events:\n1. chat.reject'); - await userKate.chat.reject(signerAddress); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nCreate Chat Group, Expected Events:\n1. chat.group.create'); - const groupChatId = ( - await userAlice.chat.group.create('Test Grp', { - description: 'Test Desc', - image: - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg==', - members: [secondSignerAddress, thirdSignerAddress], - admins: [], - private: false, - }) - ).chatId; - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nUpdate Chat Group, Expected Events:\n1. chat.group.update'); - await userAlice.chat.group.update(groupChatId, { - description: 'Updated Test Desc', - image: - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg==', - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nAdd member to Group, Expected Events:\n1. chat.request'); - await userAlice.chat.group.add(groupChatId, { - role: 'MEMBER', - accounts: [randomWallet1], - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log( - '\n\nRemove member from Group, Expected Events:\n1. chat.group.participant.remove' - ); - await userAlice.chat.group.remove(groupChatId, { - role: 'MEMBER', - accounts: [randomWallet1], - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nAdd Admin to Group, Expected Events:\n1. chat.request'); - await userAlice.chat.group.add(groupChatId, { - role: 'ADMIN', - accounts: [randomWallet1], - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log( - '\n\nRemove Admin from Group, Expected Events:\n1. chat.group.participant.remove' - ); - await userAlice.chat.group.remove(groupChatId, { - role: 'ADMIN', - accounts: [randomWallet1], - }); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log('\n\nJoin Group, Expected Events:\n1. chat.accept'); - await userBob.chat.group.join(groupChatId); - await delay(3000); - //------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log( - '\n\nLeave Group, Expected Events:\n1. chat.group.participant.leave' - ); - await userBob.chat.group.leave(groupChatId); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - console.log( - '\n\nReject Group Joining Request, Expected Events:\n1. chat.reject' - ); - await userKate.chat.group.reject(groupChatId); - await delay(3000); - // ------------------------------------------------------------------- - // ------------------------------------------------------------------- - if (process.env.WALLET_PRIVATE_KEY) { - // create signer - const channelSigner = createWalletClient({ - account: privateKeyToAccount(`0x${process.env.WALLET_PRIVATE_KEY}`), - chain: goerli, - transport: http(), - }); - - await userAlice.notification.subscribe( - `eip155:5:${channelSigner.account.address}` // channel to subscribe - ); - - const channelUser = await PushAPI.initialize(channelSigner, { env }); - console.log( - '\n\nSend channel notification, Expected Events:\n1. notif.send' - ); - await channelUser.channel.send(['*'], { - notification: { - title: 'test', - body: 'test', - }, - }); - await delay(3000); - - await userAlice.notification.unsubscribe( - `eip155:5:${channelSigner.account.address}` // channel to subscribe - ); - } else { - console.log( - 'Skipping channel notification streams, as WALLET_PRIVATE_KEY is not present in .env' - ); - } -}; diff --git a/packages/examples/sdk-backend-node/spaces/index.ts b/packages/examples/sdk-backend-node/space/index.ts similarity index 94% rename from packages/examples/sdk-backend-node/spaces/index.ts rename to packages/examples/sdk-backend-node/space/index.ts index 64e04891d..43c7afb32 100644 --- a/packages/examples/sdk-backend-node/spaces/index.ts +++ b/packages/examples/sdk-backend-node/space/index.ts @@ -43,15 +43,14 @@ const spaceDescription = uniqueNamesGenerator({ const spaceImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAvklEQVR4AcXBsW2FMBiF0Y8r3GQb6jeBxRauYRpo4yGQkMd4A7kg7Z/GUfSKe8703fKDkTATZsJsrr0RlZSJ9r4RLayMvLmJjnQS1d6IhJkwE2bT13U/DBzp5BN73xgRZsJMmM1HOolqb/yWiWpvjJSUiRZWopIykTATZsJs5g+1N6KSMiO1N/5DmAkzYTa9Lh6MhJkwE2ZzSZlo7xvRwson3txERzqJhJkwE2bT6+JhoKTMJ2pvjAgzYSbMfgDlXixqjH6gRgAAAABJRU5ErkJggg=='; -export const runSpacesUseCases = async (): Promise => { +export const runSpaceUseCases = async (): Promise => { console.log(` - ███████╗██████╗ █████╗ ██████╗███████╗███████╗ - ██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝ - ███████╗██████╔╝███████║██║ █████╗ ███████╗ - ╚════██║██╔═══╝ ██╔══██║██║ ██╔══╝ ╚════██║ - ███████║██║ ██║ ██║╚██████╗███████╗███████║ - ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ - +░██████╗██████╗░░█████╗░░█████╗░███████╗ +██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝ +╚█████╗░██████╔╝███████║██║░░╚═╝█████╗░░ +░╚═══██╗██╔═══╝░██╔══██║██║░░██╗██╔══╝░░ +██████╔╝██║░░░░░██║░░██║╚█████╔╝███████╗ +╚═════╝░╚═╝░░░░░╚═╝░░╚═╝░╚════╝░╚══════╝ `); console.log('PushAPI.user.create'); diff --git a/packages/examples/sdk-backend-node/user/index.ts b/packages/examples/sdk-backend-node/user/index.ts new file mode 100644 index 000000000..6a9dd6d30 --- /dev/null +++ b/packages/examples/sdk-backend-node/user/index.ts @@ -0,0 +1,75 @@ +import { PushAPI } from '@pushprotocol/restapi'; +import { config } from '../config'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { createWalletClient, http } from 'viem'; +import { goerli } from 'viem/chains'; + +// CONFIGS +const { env, showAPIResponse } = config; + +/***************** SAMPLE SIGNER GENERATION *********************/ +// Uing VIEM +// Random Wallet Signers +const signer = createWalletClient({ + account: privateKeyToAccount(generatePrivateKey()), + chain: goerli, + transport: http(), +}); + +export const runUserCases = async (): Promise => { + console.log(` +██╗░░░██╗░██████╗███████╗██████╗░ +██║░░░██║██╔════╝██╔════╝██╔══██╗ +██║░░░██║╚█████╗░█████╗░░██████╔╝ +██║░░░██║░╚═══██╗██╔══╝░░██╔══██╗ +╚██████╔╝██████╔╝███████╗██║░░██║ +░╚═════╝░╚═════╝░╚══════╝╚═╝░░╚═╝ +`); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.initialize'); + const userAlice = await PushAPI.initialize(signer, { env }); + console.log('PushAPI.initialize | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.info'); + const userAliceInfo = await userAlice.info(); + if (showAPIResponse) { + console.log(userAliceInfo); + } + console.log('PushAPI.info | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.profile.info'); + const userAliceProfileInfo = await userAlice.profile.info(); + if (showAPIResponse) { + console.log(userAliceProfileInfo); + } + console.log('PushAPI.profile.info | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.profile.update'); + const updatedName = 'Bob The Builder'; + const response = await userAlice.profile.update({ name: updatedName }); + if (showAPIResponse) { + console.log(response); + } + console.log('PushAPI.profile.update | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.encryption.info'); + const encryptionInfo = await userAlice.encryption.info(); + if (showAPIResponse) { + console.log(encryptionInfo); + } + console.log('PushAPI.encryption.info | Response - 200 OK\n\n'); + // ------------------------------------------------------------------- + // ------------------------------------------------------------------- + console.log('PushAPI.encryption.update'); + const PGP_V3 = 'eip191-aes256-gcm-hkdf-sha256'; + const encryptionUpdate = await userAlice.encryption.update(PGP_V3 as any); + if (showAPIResponse) { + console.log(encryptionUpdate); + } + console.log('PushAPI.encryption.update | Response - 200 OK\n\n'); +}; diff --git a/packages/examples/sdk-backend-node/video/index.ts b/packages/examples/sdk-backend-node/video/index.ts index e9202c387..afc8e636e 100644 --- a/packages/examples/sdk-backend-node/video/index.ts +++ b/packages/examples/sdk-backend-node/video/index.ts @@ -45,12 +45,12 @@ const skipExample = () => { // Push Video - Run Video Use cases export const runVideoUseCases = async (): Promise => { console.log(` - ██╗ ██╗██╗██████╗ ███████╗ ██████╗ - ██║ ██║██║██╔══██╗██╔════╝██╔═══██╗ - ██║ ██║██║██║ ██║█████╗ ██║ ██║ - ╚██╗ ██╔╝██║██║ ██║██╔══╝ ██║ ██║ - ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝ - ╚═══╝ ╚═╝╚═════╝ ╚══════╝ ╚═════╝ +██╗░░░██╗██╗██████╗░███████╗░█████╗░ +██║░░░██║██║██╔══██╗██╔════╝██╔══██╗ +╚██╗░██╔╝██║██║░░██║█████╗░░██║░░██║ +░╚████╔╝░██║██║░░██║██╔══╝░░██║░░██║ +░░╚██╔╝░░██║██████╔╝███████╗╚█████╔╝ +░░░╚═╝░░░╚═╝╚═════╝░╚══════╝░╚════╝░ `); if (videoLocalStream === null) {