Advertisement
Guest User

Untitled

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