Advertisement
Guest User

Untitled

a guest
Sep 7th, 2023
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.08 KB | None | 0 0
  1. import React, { useState, useEffect } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { ChannelMembership, ChannelType, ChannelRepository } from '@amityco/js-sdk';
  4. import { useIntl } from 'react-intl';
  5.  
  6. import { notification } from '~/core/components/Notification';
  7. import RecentChat from '~/chat/components/RecentChat';
  8. import Chat from '~/chat/components/Chat';
  9. import ChatDetails from '~/chat/components/ChatDetails';
  10.  
  11. import { ApplicationContainer } from './styles';
  12. import CreateChatModal from '~/chat/components/Chat/CreateChatModal';
  13.  
  14. import { useSDK } from '~/core/hooks/useSDK';
  15. import useUser from '~/core/hooks/useUser';
  16. import { UserRepository } from '@amityco/js-sdk';
  17.  
  18. const channelRepo = new ChannelRepository();
  19.  
  20. const ChatApplication = ({
  21. membershipFilter,
  22. defaultChannelId,
  23. onMemberSelect,
  24. onChannelSelect,
  25. onAddNewChannel,
  26. onEditChatMember,
  27. }) => {
  28. console.log(`Hit the application page. channelId: ${defaultChannelId}`);
  29.  
  30. const { formatMessage } = useIntl();
  31. const [currentChannelData, setCurrentChannelData] = useState(null);
  32. const [shouldShowChatDetails, setShouldShowChatDetails] = useState(false);
  33.  
  34. const showChatDetails = () => setShouldShowChatDetails(true);
  35. const hideChatDetails = () => setShouldShowChatDetails(false);
  36.  
  37. const [isChatModalOpened, setChatModalOpened] = useState(false);
  38. const openChatModal = () => setChatModalOpened(true);
  39.  
  40. const handleChannelSelect = (newChannelData) => {
  41. if (currentChannelData?.channelId === newChannelData?.channelId) return;
  42. if (currentChannelData?.channelId == newChannelData?.channelId) return;
  43.  
  44. hideChatDetails();
  45. onChannelSelect(newChannelData);
  46. setCurrentChannelData(newChannelData);
  47. };
  48.  
  49. const leaveChat = () => {
  50. ChannelRepository.leaveChannel(currentChannelData?.channelId)
  51. .then(() => {
  52. notification.success({
  53. content: formatMessage({ id: 'chat.leaveChat.success' }),
  54. });
  55. })
  56. .catch(() => {
  57. notification.error({
  58. content: formatMessage({ id: 'chat.leaveChat.error' }),
  59. });
  60. });
  61.  
  62. setCurrentChannelData(null);
  63. };
  64.  
  65. const { currentUserId, client } = useSDK();
  66. const [userModel, setUserModel] = useState(null);
  67. const [selectedChannel, setSelectedChannel] = useState("");
  68. const [systemMessage, setSystemMessage] = useState("");
  69.  
  70. let liveUser = UserRepository.getUser(currentUserId)
  71. liveUser.once('dataUpdated', model =>
  72. {
  73. setUserModel(model);
  74.  
  75. // Check if user model was properly set and has the metadata we need
  76. if (null !== userModel && userModel.metadata.teamId)
  77. {
  78. console.log("Retrieved User '"+userModel.displayName+"' ("+userModel.userId+") teamId: " + userModel.metadata.teamId); // + ", " + JSON.stringify(userModel));
  79. }
  80. else
  81. {
  82. console.log("Retrieved user, but without proper team metadata. Returning.");
  83. setSystemMessage("You do not have the required team meta data.");
  84. return;
  85. }
  86.  
  87. // Get the user's teamId
  88. let customChannel = userModel.metadata.teamId;
  89.  
  90. // Check if a team chat channel exists by that teamId
  91. let searchingChannel = ChannelRepository.getChannel(customChannel)
  92.  
  93. // A channel with that channelId was successfully found
  94. searchingChannel.once('dataUpdated', data =>
  95. {
  96. if (data && data.channelId)
  97. {
  98. console.log("Channel '" + data.displayName + "' exists! Entering...");
  99.  
  100. // Team chat channel was found, so enter it if you're a member
  101. setSelectedChannel(customChannel);
  102. setSystemMessage("");
  103. // If you're not a member, join the channel, and then enter it
  104. }
  105. else
  106. {
  107. console.log("Channel found, but doesn't have name or id?");
  108. }
  109. });
  110.  
  111. // A channel with that channelId does not exist
  112. searchingChannel.once('dataError', error =>
  113. {
  114. console.log("Error receiving channel: " + error);
  115.  
  116. // Check if you're the leader of the team,
  117. if (userModel.userId === userModel.metadata.teamLeaderId)
  118. {
  119. // if you're the leader, create the channel
  120. const liveChannel = ChannelRepository.createChannel({
  121. channelId: customChannel,
  122. type: ChannelType.Live,
  123. displayName : userModel.metadata.teamName,
  124. userIds: [ userModel.userId ],
  125. })
  126.  
  127. liveChannel.once('dataUpdated', model =>
  128. {
  129. console.log(`Channel created successfully! ${model.channelId}`);
  130. setSelectedChannel(customChannel);
  131. setSystemMessage("");
  132. });
  133.  
  134. liveChannel.once('dataError', error =>
  135. {
  136. console.log("Channel didn't get created: " + error);
  137. });
  138. }
  139.  
  140. // if you're not the team leader, display message "Please wait for leader to log-in and establish a team chat channel."
  141. else
  142. {
  143. console.log("The user '"+userModel.displayName+"' ("+userModel.userId+") is not the team leader. Channel creation delayed. Returning.");
  144.  
  145. // Display message that leader needs to log-in first to create chat channel
  146. setSystemMessage("The Team Leader is required to log-in to generate this team's chat channel!");
  147. return;
  148. }
  149.  
  150. });
  151.  
  152. })
  153.  
  154.  
  155. useEffect(() =>
  156. {
  157. console.log("Hit application's useEffect for channel: " + selectedChannel);
  158.  
  159. if (!selectedChannel || selectedChannel === "")
  160. {
  161. console.log("selectedChannel is not currently set.");
  162. return;
  163. }
  164.  
  165. console.log(`(Handling channel selection '${selectedChannel})'`);
  166.  
  167. handleChannelSelect({ channelId: selectedChannel, channelType: ChannelType.Standard });
  168. // eslint-disable-next-line react-hooks/exhaustive-deps
  169. }, [selectedChannel]);
  170.  
  171. return (
  172. <ApplicationContainer>
  173. {currentChannelData && (
  174. <Chat
  175. channelId={currentChannelData.channelId}
  176. shouldShowChatDetails={shouldShowChatDetails}
  177. onChatDetailsClick={showChatDetails}
  178. chatSystemMessage = {systemMessage}
  179. />
  180. )}
  181. {shouldShowChatDetails && currentChannelData && (
  182. <ChatDetails
  183. channelId={currentChannelData.channelId}
  184. leaveChat={leaveChat}
  185. onEditChatMemberClick={onEditChatMember}
  186. onMemberSelect={onMemberSelect}
  187. onClose={hideChatDetails}
  188. />
  189. )}
  190. {isChatModalOpened && <CreateChatModal onClose={() => setChatModalOpened(false)} />}
  191. </ApplicationContainer>
  192. );
  193. };
  194.  
  195. ChatApplication.propTypes = {
  196. membershipFilter: PropTypes.oneOf(Object.values(ChannelMembership)),
  197. defaultChannelId: PropTypes.string,
  198. onMemberSelect: PropTypes.func,
  199. onChannelSelect: PropTypes.func,
  200. onAddNewChannel: PropTypes.func,
  201. onEditChatMember: PropTypes.func,
  202. };
  203.  
  204. ChatApplication.defaultProps = {
  205. membershipFilter: ChannelMembership.None,
  206. defaultChannelId: 0,
  207. onMemberSelect: () => {},
  208. onChannelSelect: () => {},
  209. onAddNewChannel: () => {},
  210. onEditChatMember: () => {},
  211. };
  212.  
  213. export default ChatApplication;
  214.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement