Skip to content

Commit

Permalink
Chats req changes (#375)
Browse files Browse the repository at this point in the history
* fix: added pagination and deprecation tag

* fix: grp bug and tracking prev nft dids
  • Loading branch information
Aman035 authored May 10, 2023
1 parent a88cace commit 6b72ff4
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 23 deletions.
31 changes: 31 additions & 0 deletions packages/demoreact/src/app/ChatTest/GetChats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,21 @@ const GetChatsTest = () => {
const [getChatsResponse, setGetChatsResponse] = useState<any>('');
const [toDecrypt, setToDecrypt] = useState<boolean>(false);
const [account, setAccount] = useState<string>(acc);
const [page, setPage] = useState<number>(1);
const [limit, setLimit] = useState<number>(10);

const updateAccount = (e: React.SyntheticEvent<HTMLElement>) => {
setAccount((e.target as HTMLInputElement).value);
};

const updatePage = (e: React.SyntheticEvent<HTMLElement>) => {
setPage(parseInt((e.target as HTMLInputElement).value));
};

const updateLimit = (e: React.SyntheticEvent<HTMLElement>) => {
setLimit(parseInt((e.target as HTMLInputElement).value));
};

const updateToDecrypt = (e: React.SyntheticEvent<HTMLElement>) => {
setToDecrypt((e.target as HTMLInputElement).checked);
};
Expand All @@ -43,6 +54,8 @@ const GetChatsTest = () => {
pgpPrivateKey: pvtkey,
toDecrypt,
env,
page,
limit,
});

setGetChatsResponse(response);
Expand Down Expand Up @@ -71,6 +84,24 @@ const GetChatsTest = () => {
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem style={{ marginTop: 20 }}>
<label>page</label>
<input
type="text"
onChange={updatePage}
value={page}
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem style={{ marginTop: 20 }}>
<label>limit</label>
<input
type="text"
onChange={updateLimit}
value={limit}
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem>
<input
type="checkbox"
Expand Down
37 changes: 34 additions & 3 deletions packages/demoreact/src/app/ChatTest/GetRequests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,24 @@ const GetRequestsTest = () => {
const [getRequestsResponse, setGetRequestsResponse] = useState<any>('');
const [toDecrypt, setToDecrypt] = useState<boolean>(false);
const [account, setAccount] = useState<string>(acc);
const [page, setPage] = useState<number>(1);
const [limit, setLimit] = useState<number>(10);

const updateToDecrypt = (e: React.SyntheticEvent<HTMLElement>) => {
setToDecrypt((e.target as HTMLInputElement).checked);
};
const updateAccount = (e: React.SyntheticEvent<HTMLElement>) => {
setAccount((e.target as HTMLInputElement).value);
};

const updatePage = (e: React.SyntheticEvent<HTMLElement>) => {
setPage(parseInt((e.target as HTMLInputElement).value));
};

const updateLimit = (e: React.SyntheticEvent<HTMLElement>) => {
setLimit(parseInt((e.target as HTMLInputElement).value));
};

const updateToDecrypt = (e: React.SyntheticEvent<HTMLElement>) => {
setToDecrypt((e.target as HTMLInputElement).checked);
};
const testGetRequests = async () => {
try {
setLoading(true);
Expand All @@ -44,6 +55,8 @@ const GetRequestsTest = () => {
pgpPrivateKey: pvtkey,
toDecrypt,
env,
page,
limit,
});

setGetRequestsResponse(response);
Expand Down Expand Up @@ -81,6 +94,24 @@ const GetRequestsTest = () => {
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem style={{ marginTop: 20 }}>
<label>page</label>
<input
type="text"
onChange={updatePage}
value={page}
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem style={{ marginTop: 20 }}>
<label>limit</label>
<input
type="text"
onChange={updateLimit}
value={limit}
style={{ width: 400, height: 30 }}
/>
</SectionItem>
<SectionItem style={{ marginTop: 20 }}>
<SectionButton onClick={testGetRequests}>
get requests
Expand Down
19 changes: 15 additions & 4 deletions packages/restapi/src/lib/chat/chats.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import axios from 'axios';
import { getAPIBaseUrls, isValidETHAddress, walletToPCAIP10 } from '../helpers';
import { getAPIBaseUrls, isValidETHAddress } from '../helpers';
import Constants, { ENV } from '../constants';
import { IFeeds } from '../types';
import { getInboxLists, getUserDID } from './helpers';
import { getInboxLists, getUserDID, addDeprecatedInfo } from './helpers';

export type ChatsOptionsType = {
account: string;
Expand All @@ -11,6 +11,14 @@ export type ChatsOptionsType = {
* If true, the method will return decrypted message content in response
*/
toDecrypt?: boolean;
/**
* page index - default 1
*/
page?: number;
/**
* no of items per page - default 10 - max 30
*/
limit?: number;
/**
* Environment variable
*/
Expand All @@ -26,19 +34,22 @@ export const chats = async (options: ChatsOptionsType): Promise<IFeeds[]> => {
pgpPrivateKey,
env = Constants.ENV.PROD,
toDecrypt = false,
page = 1,
limit = 10,
} = options || {};
if (!isValidETHAddress(account)) {
throw new Error(`Invalid address!`);
}
const user = await getUserDID(account, env);
const API_BASE_URL = getAPIBaseUrls(env);
const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/chats`;
const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/chats?page=${page}&limit=${limit}`;
const requestUrl = `${apiEndpoint}`;
try {
const response = await axios.get(requestUrl);
const chats: IFeeds[] = response.data.chats;
const updatedChats = addDeprecatedInfo(chats);
const feeds: IFeeds[] = await getInboxLists({
lists: chats,
lists: updatedChats,
user: user,
toDecrypt,
pgpPrivateKey,
Expand Down
54 changes: 46 additions & 8 deletions packages/restapi/src/lib/chat/helpers/inbox.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import Constants, {ENV} from '../../constants';
import { decryptMessage, pCAIP10ToWallet } from '../../helpers';
import Constants, { ENV } from '../../constants';
import {
decryptMessage,
isValidCAIP10NFTAddress,
pCAIP10ToWallet,
} from '../../helpers';
import { IFeeds, IMessageIPFS, IUser } from '../../types';
import { get as getUser } from '../../user';
import { getCID } from '../ipfs';
Expand All @@ -10,13 +14,13 @@ type InboxListsType = {
user: string; //caip10
toDecrypt: boolean;
pgpPrivateKey?: string;
env?: ENV;
env?: ENV;
};
type DecryptConverationType = {
messages: IMessageIPFS[];
connectedUser: IUser; //caip10
pgpPrivateKey?: string;
env?: ENV;
env?: ENV;
};

export const getInboxLists = async (
Expand Down Expand Up @@ -49,10 +53,14 @@ export const getInboxLists = async (
sigType: '',
signature: '',
toCAIP10: '',
toDID: ''
}
toDID: '',
};
}
feeds.push({ ...list, msg: message, groupInformation: list.groupInformation });
feeds.push({
...list,
msg: message,
groupInformation: list.groupInformation,
});
}

if (toDecrypt)
Expand Down Expand Up @@ -92,8 +100,38 @@ export const decryptConversation = async (options: DecryptConverationType) => {
signatureValidationPubliKey: signatureValidationPubliKey,
pgpPrivateKey,
message: message,
});
});
}
}
return messages;
};

//immediately invoked function expression to maintain latestDIDs
export const addDeprecatedInfo = (() => {
// mapping for LAtest NFT DIDs
const latestDIDs: { [key: string]: string } = {};
return (chats: IFeeds[]): IFeeds[] => {
chats.forEach((chat) => {
if (isValidCAIP10NFTAddress(chat.did)) {
const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':');
const timestamp = chat.did.split(':')[5];
if (
!latestDIDs[didWithoutTimestamp] ||
timestamp > latestDIDs[didWithoutTimestamp].split(':')[5]
) {
latestDIDs[didWithoutTimestamp] = chat.did;
}
}
});
chats.forEach((chat) => {
if (isValidCAIP10NFTAddress(chat.did)) {
const didWithoutTimestamp = chat.did.split(':').slice(0, 5).join(':');
if (latestDIDs[didWithoutTimestamp] !== chat.did) {
chat['deprecated'] = true;
chat['deprecatedCode'] = 'NFT Owner Changed';
}
}
});
return chats;
};
})();
32 changes: 24 additions & 8 deletions packages/restapi/src/lib/chat/requests.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import axios from 'axios';
import { getAPIBaseUrls, isValidETHAddress, walletToPCAIP10 } from '../helpers';
import Constants, {ENV} from '../constants';
import { getAPIBaseUrls, isValidETHAddress } from '../helpers';
import Constants, { ENV } from '../constants';
import { IFeeds } from '../types';
import { getInboxLists, getUserDID } from './helpers';
import { addDeprecatedInfo, getInboxLists, getUserDID } from './helpers';

export type RequestOptionsType = {
account: string;
Expand All @@ -11,31 +11,47 @@ export type RequestOptionsType = {
* If true, the method will return decrypted message content in response
*/
toDecrypt?: boolean;
/**
* page index - default 1
*/
page?: number;
/**
* no of items per page - default 10 - max 30
*/
limit?: number;
/**
* Environment variable
*/
env?: ENV;
};

/**
* The first time an address wants to send a message to another peer, the address sends an intent request. This first message shall not land in this peer Inbox but in its Request box.
* The first time an address wants to send a message to another peer, the address sends an intent request. This first message shall not land in this peer Inbox but in its Request box.
* This function will return all the chats that landed on the address' Request box. The user can then approve the request or ignore it for now.
*/
export const requests = async (
options: RequestOptionsType
): Promise<IFeeds[]> => {
const { account, pgpPrivateKey, env = Constants.ENV.PROD, toDecrypt = false } = options || {};
const {
account,
pgpPrivateKey,
env = Constants.ENV.PROD,
toDecrypt = false,
page = 1,
limit = 10,
} = options || {};
const user = await getUserDID(account, env);
const API_BASE_URL = getAPIBaseUrls(env);
const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/requests`;
const apiEndpoint = `${API_BASE_URL}/v1/chat/users/${user}/requests?page=${page}&limit=${limit}`;
try {
if (!isValidETHAddress(user)) {
throw new Error(`Invalid address!`);
}
const response = await axios.get(apiEndpoint);
const requests: IFeeds[] = response.data.requests;
const updatedRequests = addDeprecatedInfo(requests);
const Feeds: IFeeds[] = await getInboxLists({
lists: requests,
lists: updatedRequests,
user,
toDecrypt,
pgpPrivateKey,
Expand All @@ -47,4 +63,4 @@ export const requests = async (
console.error(`[Push SDK] - API ${requests.name}: `, err);
throw Error(`[Push SDK] - API ${requests.name}: ${err}`);
}
};
};
2 changes: 2 additions & 0 deletions packages/restapi/src/lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ export interface IFeeds {
cid?: string;
chatId?: string;
groupInformation?: GroupDTO;
deprecated?: boolean; // scope only at sdk level
deprecatedCode?: string; // scope only at sdk level
}
export interface IUser {
did: string;
Expand Down

0 comments on commit 6b72ff4

Please sign in to comment.