added attachment embed and q-manager to groups

This commit is contained in:
2024-11-30 13:14:33 +02:00
parent b661bd3869
commit 1f900dd72b
23 changed files with 1828 additions and 828 deletions

View File

@@ -3,7 +3,7 @@ import { AppViewer } from './AppViewer';
import Frame from 'react-frame-component';
import { MyContext, isMobile } from '../../App';
const AppViewerContainer = React.forwardRef(({ app, isSelected, hide, isDevMode }, ref) => {
const AppViewerContainer = React.forwardRef(({ app, isSelected, hide, isDevMode, customHeight }, ref) => {
const { rootHeight } = useContext(MyContext);
@@ -36,7 +36,7 @@ const AppViewerContainer = React.forwardRef(({ app, isSelected, hide, isDevMode
}
style={{
display: (!isSelected || hide) && 'none',
height: !isMobile ? '100vh' : `calc(${rootHeight} - 60px - 45px)`,
height: customHeight ? customHeight : !isMobile ? '100vh' : `calc(${rootHeight} - 60px - 45px)`,
border: 'none',
width: '100%',
overflow: 'hidden',

View File

@@ -182,7 +182,7 @@ const UIQortalRequests = [
'GET_WALLET_BALANCE', 'GET_USER_WALLET_INFO', 'GET_CROSSCHAIN_SERVER_INFO',
'GET_TX_ACTIVITY_SUMMARY', 'GET_FOREIGN_FEE', 'UPDATE_FOREIGN_FEE',
'GET_SERVER_CONNECTION_HISTORY', 'SET_CURRENT_FOREIGN_SERVER',
'ADD_FOREIGN_SERVER', 'REMOVE_FOREIGN_SERVER', 'GET_DAY_SUMMARY', 'CREATE_TRADE_BUY_ORDER', 'CREATE_TRADE_SELL_ORDER', 'CANCEL_TRADE_SELL_ORDER', 'IS_USING_GATEWAY', 'ADMIN_ACTION', 'SIGN_TRANSACTION', 'OPEN_NEW_TAB', 'CREATE_AND_COPY_EMBED_LINK'
'ADD_FOREIGN_SERVER', 'REMOVE_FOREIGN_SERVER', 'GET_DAY_SUMMARY', 'CREATE_TRADE_BUY_ORDER', 'CREATE_TRADE_SELL_ORDER', 'CANCEL_TRADE_SELL_ORDER', 'IS_USING_GATEWAY', 'ADMIN_ACTION', 'SIGN_TRANSACTION', 'OPEN_NEW_TAB', 'CREATE_AND_COPY_EMBED_LINK', 'DECRYPT_QORTAL_GROUP_DATA'
];
@@ -481,7 +481,7 @@ isDOMContentLoaded: false
} else if (
event?.data?.action === 'PUBLISH_MULTIPLE_QDN_RESOURCES' ||
event?.data?.action === 'PUBLISH_QDN_RESOURCE' ||
event?.data?.action === 'ENCRYPT_DATA'
event?.data?.action === 'ENCRYPT_DATA' || event?.data?.action === 'ENCRYPT_DATA_WITH_SHARING_KEY' || 'ENCRYPT_QORTAL_GROUP_DATA'
) {
let data;

View File

@@ -15,16 +15,18 @@ import { CustomizedSnackbars } from '../Snackbar/Snackbar'
import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from '../../constants/codes'
import { useMessageQueue } from '../../MessageQueueContext'
import { executeEvent } from '../../utils/events'
import { Box, ButtonBase, Typography } from '@mui/material'
import { Box, ButtonBase, Divider, Typography } from '@mui/material'
import ShortUniqueId from "short-unique-id";
import { ReplyPreview } from './MessageItem'
import { ExitIcon } from '../../assets/Icons/ExitIcon'
import { RESOURCE_TYPE_NUMBER_GROUP_CHAT_REACTIONS } from '../../constants/resourceTypes'
import { isExtMsg } from '../../background'
import AppViewerContainer from '../Apps/AppViewerContainer'
import CloseIcon from "@mui/icons-material/Close";
const uid = new ShortUniqueId({ length: 5 });
export const ChatGroup = ({selectedGroup, secretKey, setSecretKey, getSecretKey, myAddress, handleNewEncryptionNotification, hide, handleSecretKeyCreationInProgress, triedToFetchSecretKey, myName, balance, getTimestampEnterChatParent}) => {
export const ChatGroup = ({selectedGroup, secretKey, setSecretKey, getSecretKey, myAddress, handleNewEncryptionNotification, hide, handleSecretKeyCreationInProgress, triedToFetchSecretKey, myName, balance, getTimestampEnterChatParent, hideView}) => {
const [messages, setMessages] = useState([])
const [chatReferences, setChatReferences] = useState({})
const [isSending, setIsSending] = useState(false)
@@ -36,7 +38,7 @@ export const ChatGroup = ({selectedGroup, secretKey, setSecretKey, getSecretKey,
const [isFocusedParent, setIsFocusedParent] = useState(false);
const [replyMessage, setReplyMessage] = useState(null)
const [onEditMessage, setOnEditMessage] = useState(null)
const [isOpenQManager, setIsOpenQManager] = useState(null)
const [messageSize, setMessageSize] = useState(0)
const hasInitializedWebsocket = useRef(false)
@@ -143,7 +145,6 @@ const [messageSize, setMessageSize] = useState(0)
messages?.forEach((message)=> {
try {
const decodeMsg = atob(message.data);
if(decodeMsg === PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY){
handleSecretKeyCreationInProgress()
return
@@ -174,7 +175,6 @@ const [messageSize, setMessageSize] = useState(0)
console.error(error);
}
}
const decryptMessages = (encryptedMessages: any[], isInitiated: boolean )=> {
try {
@@ -729,6 +729,10 @@ const clearEditorContent = () => {
resumeAllQueues()
}
}, [])
const openQManager = useCallback(()=> {
setIsOpenQManager(true)
}, [])
return (
<div style={{
@@ -741,7 +745,7 @@ const clearEditorContent = () => {
left: hide && '-100000px',
}}>
<ChatList enableMentions onReply={onReply} onEdit={onEdit} chatId={selectedGroup} initialMessages={messages} myAddress={myAddress} tempMessages={tempMessages} handleReaction={handleReaction} chatReferences={chatReferences} tempChatReferences={tempChatReferences} members={members} myName={myName} selectedGroup={selectedGroup} />
<ChatList openQManager={openQManager} enableMentions onReply={onReply} onEdit={onEdit} chatId={selectedGroup} initialMessages={messages} myAddress={myAddress} tempMessages={tempMessages} handleReaction={handleReaction} chatReferences={chatReferences} tempChatReferences={tempChatReferences} members={members} myName={myName} selectedGroup={selectedGroup} />
<div style={{
@@ -894,6 +898,55 @@ const clearEditorContent = () => {
</Box>
{/* <button onClick={sendMessage}>send</button> */}
</div>
{isOpenQManager !== null && (
<Box sx={{
position: 'fixed',
height: '600px',
maxHeight: '100vh',
width: '400px',
maxWidth: '100vw',
backgroundColor: '#27282c',
zIndex: 100,
bottom: 0,
right: 0,
overflow: 'hidden',
borderTopLeftRadius: '10px',
borderTopRightRadius: '10px',
display: hideView ? 'none' : isOpenQManager === true ? 'block' : 'none',
boxShadow: 4,
}}>
<Box sx={{
height: '100%',
width: '100%',
}}>
<Box sx={{
height: '40px',
display: 'flex',
alignItems: 'center',
padding: '5px',
justifyContent: 'space-between'
}}>
<Typography>Q-Manager</Typography>
<ButtonBase onClick={()=> {
setIsOpenQManager(false)
}}><CloseIcon sx={{
color: 'white'
}} /></ButtonBase>
</Box>
<Divider />
<AppViewerContainer customHeight="560px" app={{
tabId: '5558588',
name: 'Q-Manager',
service: 'APP'
}} isSelected />
</Box>
</Box>
)}
{/* <ChatContainerComp messages={formatMessages} /> */}
<LoadingSnackbar open={isLoading} info={{
message: "Loading chat... please wait."

View File

@@ -27,6 +27,7 @@ export const ChatList = ({
myName,
selectedGroup,
enableMentions,
openQManager
}) => {
const parentRef = useRef();
const [messages, setMessages] = useState(initialMessages);
@@ -407,6 +408,7 @@ export const ChatList = ({
</div>
{enableMentions && (
<ChatOptions
openQManager={openQManager}
messages={messages}
goToMessage={goToMessage}
members={members}

View File

@@ -12,6 +12,7 @@ import SearchIcon from "@mui/icons-material/Search";
import { Spacer } from "../../common/Spacer";
import AlternateEmailIcon from "@mui/icons-material/AlternateEmail";
import CloseIcon from "@mui/icons-material/Close";
import InsertLinkIcon from '@mui/icons-material/InsertLink';
import {
AppsSearchContainer,
AppsSearchLeft,
@@ -42,7 +43,7 @@ const cache = new CellMeasurerCache({
defaultHeight: 50,
});
export const ChatOptions = ({ messages, goToMessage, members, myName, selectedGroup }) => {
export const ChatOptions = ({ messages, goToMessage, members, myName, selectedGroup, openQManager }) => {
const [mode, setMode] = useState("default");
const [searchValue, setSearchValue] = useState("");
const [selectedMember, setSelectedMember] = useState(0);
@@ -676,6 +677,16 @@ export const ChatOptions = ({ messages, goToMessage, members, myName, selectedGr
}}>
<SearchIcon />
</ButtonBase>
<ButtonBase onClick={() => {
setMode("default")
setSearchValue('')
setSelectedMember(0)
openQManager()
}}>
<InsertLinkIcon sx={{
color: 'white'
}} />
</ButtonBase>
<ContextMenuMentions getTimestampMention={getTimestampMention} groupId={selectedGroup}>
<ButtonBase onClick={() => {
setMode("mentions")
@@ -686,7 +697,10 @@ export const ChatOptions = ({ messages, goToMessage, members, myName, selectedGr
color: mentionList?.length > 0 && (!lastMentionTimestamp || lastMentionTimestamp < mentionList[0]?.timestamp) ? 'var(--unread)' : 'white'
}} />
</ButtonBase>
</ContextMenuMentions>
</Box>
</Box>
);

View File

@@ -0,0 +1,297 @@
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { MyContext, getBaseApiReact } from "../../App";
import {
Card,
CardContent,
CardHeader,
Typography,
RadioGroup,
Radio,
FormControlLabel,
Button,
Box,
ButtonBase,
Divider,
Dialog,
IconButton,
CircularProgress,
} from "@mui/material";
import { base64ToBlobUrl } from "../../utils/fileReading";
import { saveFileToDiskGeneric } from "../../utils/generateWallet/generateWallet";
import AttachmentIcon from '@mui/icons-material/Attachment';
import RefreshIcon from "@mui/icons-material/Refresh";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import { CustomLoader } from "../../common/CustomLoader";
import { Spacer } from "../../common/Spacer";
import { FileAttachmentContainer, FileAttachmentFont } from "./Embed-styles";
import DownloadIcon from "@mui/icons-material/Download";
import SaveIcon from '@mui/icons-material/Save';
import { useSetRecoilState } from "recoil";
import { blobControllerAtom } from "../../atoms/global";
export const AttachmentCard = ({
resourceData,
resourceDetails,
owner,
refresh,
openExternal,
external,
isLoadingParent,
errorMsg,
encryptionType,
}) => {
const [isOpen, setIsOpen] = useState(true);
const { downloadResource } = useContext(MyContext);
const saveToDisk = async ()=> {
const { name, service, identifier } = resourceData;
const url = `${getBaseApiReact()}/arbitrary/${service}/${name}/${identifier}`;
fetch(url)
.then(response => response.blob())
.then(async blob => {
await saveFileToDiskGeneric(blob, resourceData?.fileName)
})
.catch(error => {
console.error("Error fetching the video:", error);
});
}
const saveToDiskEncrypted = async ()=> {
let blobUrl
try {
const { name, service, identifier,key } = resourceData;
const url = `${getBaseApiReact()}/arbitrary/${service}/${name}/${identifier}?encoding=base64`;
const res = await fetch(url)
const data = await res.text();
let decryptedData
try {
if(key && encryptionType === 'private'){
decryptedData = await window.sendMessage(
"DECRYPT_DATA_WITH_SHARING_KEY",
{
encryptedData: data,
key: decodeURIComponent(key),
}
);
}
if(encryptionType === 'group'){
decryptedData = await window.sendMessage(
"DECRYPT_QORTAL_GROUP_DATA",
{
data64: data,
groupId: 683,
}
);
}
} catch (error) {
throw new Error('Unable to decrypt')
}
if (!decryptedData || decryptedData?.error) throw new Error("Could not decrypt data");
blobUrl = base64ToBlobUrl(decryptedData, resourceData?.mimeType)
const response = await fetch(blobUrl);
const blob = await response.blob();
await saveFileToDiskGeneric(blob, resourceData?.fileName)
} catch (error) {
console.error(error)
} finally {
if(blobUrl){
URL.revokeObjectURL(blobUrl);
}
}
}
return (
<Card
sx={{
backgroundColor: "#1F2023",
height: "250px",
// height: isOpen ? "auto" : "150px",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "16px 16px 0px 16px",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<AttachmentIcon
sx={{
color: "white",
}}
/>
<Typography>ATTACHMENT embed</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<ButtonBase>
<RefreshIcon
onClick={refresh}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
{external && (
<ButtonBase>
<OpenInNewIcon
onClick={openExternal}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
)}
</Box>
</Box>
<Box
sx={{
padding: "8px 16px 8px 16px",
}}
>
<Typography
sx={{
fontSize: "12px",
color: "white",
}}
>
Created by {owner}
</Typography>
<Typography
sx={{
fontSize: "12px",
color: "cadetblue",
}}
>
{encryptionType === 'private' ? "ENCRYPTED" : encryptionType === 'group' ? 'GROUP ENCRYPTED' : "Not encrypted"}
</Typography>
</Box>
<Divider sx={{ borderColor: "rgb(255 255 255 / 10%)" }} />
<Box
sx={{
display: "flex",
flexDirection: "column",
width: "100%",
alignItems: "center",
}}
>
{isLoadingParent && isOpen && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<CustomLoader />{" "}
</Box>
)}
{errorMsg && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<Typography
sx={{
fontSize: "14px",
color: "var(--unread)",
}}
>
{errorMsg}
</Typography>{" "}
</Box>
)}
</Box>
<Box>
<CardContent>
{resourceData?.fileName && (
<>
<Typography sx={{
fontSize: '14px'
}}>{resourceData?.fileName}</Typography>
<Spacer height="10px" />
</>
)}
<ButtonBase sx={{
width: '90%',
maxWidth: '400px'
}} onClick={()=> {
if(resourceDetails?.status?.status === 'READY'){
if(encryptionType){
saveToDiskEncrypted()
return
}
saveToDisk()
return
}
downloadResource(resourceData)
}}>
<FileAttachmentContainer >
<Typography>{resourceDetails?.status?.status}</Typography>
{!resourceDetails && (
<>
<DownloadIcon />
<FileAttachmentFont>Download File</FileAttachmentFont>
</>
)}
{resourceDetails && resourceDetails?.status?.status !== 'READY' && (
<>
<CircularProgress sx={{
color: 'white'
}} size={20} />
<FileAttachmentFont>Downloading: {resourceDetails?.status?.percentLoaded || '0'}%</FileAttachmentFont>
</>
)}
{resourceDetails && resourceDetails?.status?.status === 'READY' && (
<>
<SaveIcon />
<FileAttachmentFont>Save to Disk</FileAttachmentFont>
</>
)}
</FileAttachmentContainer>
</ButtonBase>
</CardContent>
</Box>
</Card>
);
};

View File

@@ -0,0 +1,18 @@
import { Box, Typography, styled } from "@mui/material";
export const FileAttachmentContainer = styled(Box)(({ theme }) => ({
display: "flex",
alignItems: "center",
padding: "5px 10px",
border: `1px solid ${theme.palette.text.primary}`,
width: "100%",
gap: '20px'
}));
export const FileAttachmentFont = styled(Typography)(({ theme }) => ({
fontSize: "20px",
letterSpacing: 0,
fontWeight: 400,
userSelect: "none",
whiteSpace: "nowrap",
}));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,264 @@
import React, { useEffect, useState } from "react";
import {
Card,
CardContent,
Typography,
Box,
ButtonBase,
Divider,
Dialog,
IconButton,
} from "@mui/material";
import RefreshIcon from "@mui/icons-material/Refresh";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import { CustomLoader } from "../../common/CustomLoader";
import ImageIcon from "@mui/icons-material/Image";
import CloseIcon from "@mui/icons-material/Close";
export const ImageCard = ({
image,
fetchImage,
owner,
refresh,
openExternal,
external,
isLoadingParent,
errorMsg,
encryptionType,
}) => {
const [isOpen, setIsOpen] = useState(true);
const [height, setHeight] = useState('400px')
useEffect(() => {
if (isOpen) {
fetchImage();
}
}, [isOpen]);
useEffect(()=> {
if(errorMsg){
setHeight('300px')
}
}, [errorMsg])
return (
<Card
sx={{
backgroundColor: "#1F2023",
height: height,
transition: "height 0.6s ease-in-out",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "16px 16px 0px 16px",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<ImageIcon
sx={{
color: "white",
}}
/>
<Typography>IMAGE embed</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<ButtonBase>
<RefreshIcon
onClick={refresh}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
{external && (
<ButtonBase>
<OpenInNewIcon
onClick={openExternal}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
)}
</Box>
</Box>
<Box
sx={{
padding: "8px 16px 8px 16px",
}}
>
<Typography
sx={{
fontSize: "12px",
color: "white",
}}
>
Created by {owner}
</Typography>
<Typography
sx={{
fontSize: "12px",
color: "cadetblue",
}}
>
{encryptionType === 'private' ? "ENCRYPTED" : encryptionType === 'group' ? 'GROUP ENCRYPTED' : "Not encrypted"}
</Typography>
</Box>
<Divider sx={{ borderColor: "rgb(255 255 255 / 10%)" }} />
<Box
sx={{
display: "flex",
flexDirection: "column",
width: "100%",
alignItems: "center",
}}
>
{isLoadingParent && isOpen && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<CustomLoader />{" "}
</Box>
)}
{errorMsg && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<Typography
sx={{
fontSize: "14px",
color: "var(--unread)",
}}
>
{errorMsg}
</Typography>{" "}
</Box>
)}
</Box>
<Box>
<CardContent>
<ImageViewer src={image} />
</CardContent>
</Box>
</Card>
);
};
export function ImageViewer({ src, alt = "" }) {
const [isFullscreen, setIsFullscreen] = useState(false);
const handleOpenFullscreen = () => setIsFullscreen(true);
const handleCloseFullscreen = () => setIsFullscreen(false);
return (
<>
{/* Image in container */}
<Box
sx={{
maxWidth: "100%", // Prevent horizontal overflow
display: "flex",
justifyContent: "center",
cursor: "pointer",
}}
onClick={handleOpenFullscreen}
>
<img
src={src}
alt={alt}
style={{
maxWidth: "100%",
maxHeight: "450px", // Adjust max height for small containers
objectFit: "contain", // Preserve aspect ratio
}}
/>
</Box>
{/* Fullscreen Viewer */}
<Dialog
open={isFullscreen}
onClose={handleCloseFullscreen}
maxWidth="lg"
fullWidth
fullScreen
sx={{
"& .MuiDialog-paper": {
margin: 0,
maxWidth: "100%",
width: "100%",
height: "100vh",
overflow: "hidden", // Prevent scrollbars
},
}}
>
<Box
sx={{
position: "relative",
width: "100%",
height: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center",
backgroundColor: "#000", // Optional: dark background for fullscreen mode
}}
>
{/* Close Button */}
<IconButton
onClick={handleCloseFullscreen}
sx={{
position: "absolute",
top: 8,
right: 8,
zIndex: 10,
color: "white",
}}
>
<CloseIcon />
</IconButton>
{/* Fullscreen Image */}
<img
src={src}
alt={alt}
style={{
maxWidth: "100%",
maxHeight: "100%",
objectFit: "contain", // Preserve aspect ratio
}}
/>
</Box>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,388 @@
import React, { useContext, useEffect, useState } from "react";
import { MyContext } from "../../App";
import {
Card,
CardContent,
CardHeader,
Typography,
RadioGroup,
Radio,
FormControlLabel,
Button,
Box,
ButtonBase,
Divider,
} from "@mui/material";
import { getNameInfo } from "../Group/Group";
import PollIcon from "@mui/icons-material/Poll";
import { getFee } from "../../background";
import RefreshIcon from "@mui/icons-material/Refresh";
import { Spacer } from "../../common/Spacer";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
export const PollCard = ({
poll,
setInfoSnack,
setOpenSnack,
refresh,
openExternal,
external,
isLoadingParent,
errorMsg,
}) => {
const [selectedOption, setSelectedOption] = useState("");
const [ownerName, setOwnerName] = useState("");
const [showResults, setShowResults] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const { show, userInfo } = useContext(MyContext);
const [isLoadingSubmit, setIsLoadingSubmit] = useState(false);
const handleVote = async () => {
const fee = await getFee("VOTE_ON_POLL");
await show({
message: `Do you accept this VOTE_ON_POLL transaction? POLLS are public!`,
publishFee: fee.fee + " QORT",
});
setIsLoadingSubmit(true);
window
.sendMessage(
"voteOnPoll",
{
pollName: poll?.info?.pollName,
optionIndex: +selectedOption,
},
60000
)
.then((response) => {
setIsLoadingSubmit(false);
if (response.error) {
setInfoSnack({
type: "error",
message: response?.error || "Unable to vote.",
});
setOpenSnack(true);
return;
} else {
setInfoSnack({
type: "success",
message:
"Successfully voted. Please wait a couple minutes for the network to propogate the changes.",
});
setOpenSnack(true);
}
})
.catch((error) => {
setIsLoadingSubmit(false);
setInfoSnack({
type: "error",
message: error?.message || "Unable to vote.",
});
setOpenSnack(true);
});
};
const getName = async (owner) => {
try {
const res = await getNameInfo(owner);
if (res) {
setOwnerName(res);
}
} catch (error) {}
};
useEffect(() => {
if (poll?.info?.owner) {
getName(poll.info.owner);
}
}, [poll?.info?.owner]);
return (
<Card
sx={{
backgroundColor: "#1F2023",
height: isOpen ? "auto" : "150px",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "16px 16px 0px 16px",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<PollIcon
sx={{
color: "white",
}}
/>
<Typography>POLL embed</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<ButtonBase>
<RefreshIcon
onClick={refresh}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
{external && (
<ButtonBase>
<OpenInNewIcon
onClick={openExternal}
sx={{
fontSize: "24px",
color: "white",
}}
/>
</ButtonBase>
)}
</Box>
</Box>
<Box
sx={{
padding: "8px 16px 8px 16px",
}}
>
<Typography
sx={{
fontSize: "12px",
}}
>
Created by {ownerName || poll?.info?.owner}
</Typography>
</Box>
<Divider sx={{ borderColor: "rgb(255 255 255 / 10%)" }} />
<Box
sx={{
display: "flex",
flexDirection: "column",
width: "100%",
alignItems: "center",
}}
>
{!isOpen && !errorMsg && (
<>
<Spacer height="5px" />
<Button
size="small"
variant="contained"
sx={{
backgroundColor: "var(--green)",
}}
onClick={() => {
setIsOpen(true);
}}
>
Show poll
</Button>
</>
)}
{isLoadingParent && isOpen && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<CustomLoader />{" "}
</Box>
)}
{errorMsg && (
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
}}
>
{" "}
<Typography
sx={{
fontSize: "14px",
color: "var(--unread)",
}}
>
{errorMsg}
</Typography>{" "}
</Box>
)}
</Box>
<Box
sx={{
display: isOpen ? "block" : "none",
}}
>
<CardHeader
title={poll?.info?.pollName}
subheader={poll?.info?.description}
sx={{
"& .MuiCardHeader-title": {
fontSize: "18px", // Custom font size for title
},
}}
/>
<CardContent>
<Typography
sx={{
fontSize: "18px",
}}
>
Options
</Typography>
<RadioGroup
value={selectedOption}
onChange={(e) => setSelectedOption(e.target.value)}
>
{poll?.info?.pollOptions?.map((option, index) => (
<FormControlLabel
key={index}
value={index}
control={
<Radio
sx={{
color: "white", // Unchecked color
"&.Mui-checked": {
color: "var(--green)", // Checked color
},
}}
/>
}
label={option?.optionName}
/>
))}
</RadioGroup>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "20px",
}}
>
<Button
variant="contained"
color="primary"
disabled={!selectedOption || isLoadingSubmit}
onClick={handleVote}
>
Vote
</Button>
<Typography
sx={{
fontSize: "14px",
fontStyle: "italic",
}}
>
{" "}
{`${poll?.votes?.totalVotes} ${
poll?.votes?.totalVotes === 1 ? " vote" : " votes"
}`}
</Typography>
</Box>
<Spacer height="10px" />
<Typography
sx={{
fontSize: "14px",
visibility: poll?.votes?.votes?.find(
(item) => item?.voterPublicKey === userInfo?.publicKey
)
? "visible"
: "hidden",
}}
>
You've already voted.
</Typography>
<Spacer height="10px" />
{isLoadingSubmit && (
<Typography
sx={{
fontSize: "12px",
}}
>
Is processing transaction, please wait...
</Typography>
)}
<ButtonBase
onClick={() => {
setShowResults((prev) => !prev);
}}
>
{showResults ? "hide " : "show "} results
</ButtonBase>
</CardContent>
{showResults && <PollResults votes={poll?.votes} />}
</Box>
</Card>
);
};
const PollResults = ({ votes }) => {
const maxVotes = Math.max(
...votes?.voteCounts?.map((option) => option.voteCount)
);
const options = votes?.voteCounts;
return (
<Box sx={{ width: "100%", p: 2 }}>
{options
.sort((a, b) => b.voteCount - a.voteCount) // Sort options by votes (highest first)
.map((option, index) => (
<Box key={index} sx={{ mb: 2 }}>
<Box sx={{ display: "flex", justifyContent: "space-between" }}>
<Typography
variant="body1"
sx={{ fontWeight: index === 0 ? "bold" : "normal" }}
>
{`${index + 1}. ${option.optionName}`}
</Typography>
<Typography
variant="body1"
sx={{ fontWeight: index === 0 ? "bold" : "normal" }}
>
{option.voteCount} votes
</Typography>
</Box>
<Box
sx={{
mt: 1,
height: 10,
backgroundColor: "#e0e0e0",
borderRadius: 5,
overflow: "hidden",
}}
>
<Box
sx={{
width: `${(option.voteCount / maxVotes) * 100}%`,
height: "100%",
backgroundColor: index === 0 ? "#3f51b5" : "#f50057",
transition: "width 0.3s ease-in-out",
}}
/>
</Box>
</Box>
))}
</Box>
);
};

View File

@@ -0,0 +1,40 @@
function decodeHTMLEntities(str) {
const txt = document.createElement("textarea");
txt.innerHTML = str;
return txt.value;
}
export const parseQortalLink = (link) => {
const prefix = "qortal://use-embed/";
if (!link.startsWith(prefix)) {
throw new Error("Invalid link format");
}
// Decode any HTML entities in the link
link = decodeHTMLEntities(link);
// Separate the type and query string
const [typePart, queryPart] = link.slice(prefix.length).split("?");
// Ensure only the type is parsed
const type = typePart.split("/")[0].toUpperCase();
const params = {};
if (queryPart) {
const queryPairs = queryPart.split("&");
queryPairs.forEach((pair) => {
const [key, value] = pair.split("=");
if (key && value) {
const decodedKey = decodeURIComponent(key.trim());
const decodedValue = value.trim().replace(
/<\/?[^>]+(>|$)/g,
"" // Remove any HTML tags
);
params[decodedKey] = decodedValue;
}
});
}
return { type, ...params };
};

View File

@@ -118,6 +118,36 @@ import { formatEmailDate } from "./QMailMessages";
// }
// });
export const getPublishesFromAdmins = async (admins: string[], groupId) => {
// const validApi = await findUsableApi();
const queryString = admins.map((name) => `name=${name}`).join("&");
const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT_PRIVATE&identifier=symmetric-qchat-group-${
groupId
}&exactmatchnames=true&limit=0&reverse=true&${queryString}&prefix=true`;
const response = await fetch(url);
if (!response.ok) {
throw new Error("network error");
}
const adminData = await response.json();
const filterId = adminData.filter(
(data: any) =>
data.identifier === `symmetric-qchat-group-${groupId}`
);
if (filterId?.length === 0) {
return false;
}
const sortedData = filterId.sort((a: any, b: any) => {
// Get the most recent date for both a and b
const dateA = a.updated ? new Date(a.updated) : new Date(a.created);
const dateB = b.updated ? new Date(b.updated) : new Date(b.created);
// Sort by most recent
return dateB.getTime() - dateA.getTime();
});
return sortedData[0];
};
interface GroupProps {
myAddress: string;
isFocused: boolean;
@@ -685,36 +715,7 @@ export const Group = ({
// };
// }, [checkGroupListFunc, myAddress]);
const getPublishesFromAdmins = async (admins: string[]) => {
// const validApi = await findUsableApi();
const queryString = admins.map((name) => `name=${name}`).join("&");
const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT_PRIVATE&identifier=symmetric-qchat-group-${
selectedGroup?.groupId
}&exactmatchnames=true&limit=0&reverse=true&${queryString}&prefix=true`;
const response = await fetch(url);
if (!response.ok) {
throw new Error("network error");
}
const adminData = await response.json();
const filterId = adminData.filter(
(data: any) =>
data.identifier === `symmetric-qchat-group-${selectedGroup?.groupId}`
);
if (filterId?.length === 0) {
return false;
}
const sortedData = filterId.sort((a: any, b: any) => {
// Get the most recent date for both a and b
const dateA = a.updated ? new Date(a.updated) : new Date(a.created);
const dateB = b.updated ? new Date(b.updated) : new Date(b.created);
// Sort by most recent
return dateB.getTime() - dateA.getTime();
});
return sortedData[0];
};
const getSecretKey = async (
loadingGroupParam?: boolean,
secretKeyToPublish?: boolean
@@ -763,7 +764,7 @@ export const Group = ({
throw new Error("Network error");
}
const publish =
publishFromStorage || (await getPublishesFromAdmins(names));
publishFromStorage || (await getPublishesFromAdmins(names, selectedGroup?.groupId));
if (prevGroupId !== selectedGroupRef.current.groupId) {
if (settimeoutForRefetchSecretKey.current) {
@@ -791,12 +792,9 @@ export const Group = ({
);
data = await res.text();
}
const decryptedKey: any = await decryptResource(data);
const dataint8Array = base64ToUint8Array(decryptedKey.data);
const decryptedKeyToObject = uint8ArrayToObject(dataint8Array);
if (!validateSecretKey(decryptedKeyToObject))
throw new Error("SecretKey is not valid");
setSecretKeyDetails(publish);
@@ -2478,6 +2476,7 @@ export const Group = ({
setNewEncryptionNotification
}
hide={groupSection !== "chat" || !secretKey}
hideView={!(desktopViewMode === 'chat' && selectedGroup)}
handleSecretKeyCreationInProgress={
handleSecretKeyCreationInProgress
}