chore: fixs,updates,refactors etc

This commit is contained in:
zerosoul
2022-05-05 16:49:24 +08:00
parent 4d1c463792
commit 11e5581774
10 changed files with 1425 additions and 1298 deletions
+137 -150
View File
@@ -1,161 +1,148 @@
import { useEffect, useState } from "react";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { useSelector } from "react-redux";
import Styled from "./styled";
import Image from "./Image";
import useRemoveLocalMessage from "../../hook/useRemoveLocalMessage";
import useUploadFile from "../../hook/useUploadFile";
import useSendMessage from "../../hook/useSendMessage";
import Progress from "./Progress";
import { getFileIcon, formatBytes, isImage, getImageSize } from "../../utils";
import IconDownload from "../../../assets/icons/download.svg";
import IconClose from "../../../assets/icons/close.circle.svg";
import { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useSelector } from 'react-redux';
import Styled from './styled';
import Image from './Image';
import useRemoveLocalMessage from '../../hook/useRemoveLocalMessage';
import useUploadFile from '../../hook/useUploadFile';
import useSendMessage from '../../hook/useSendMessage';
import Progress from './Progress';
import { getFileIcon, formatBytes, isImage, getImageSize } from '../../utils';
import IconDownload from '../../../assets/icons/download.svg';
import IconClose from '../../../assets/icons/close.circle.svg';
dayjs.extend(relativeTime);
const isLocalFile = (content) => {
return content && typeof content == 'string' && content.startsWith('blob:');
};
export default function FileMessage({
context = "",
to = null,
created_at,
from_uid = null,
content = "",
download = "",
thumbnail = "",
properties = { local_id: 0, name: "", size: 0, content_type: "" },
context = '',
to = null,
created_at,
from_uid = null,
content = '',
download = '',
thumbnail = '',
properties = { local_id: 0, name: '', size: 0, content_type: '' }
}) {
const [imageSize, setImageSize] = useState(null);
const [uploadingFile, setUploadingFile] = useState(false);
const removeLocalMessage = useRemoveLocalMessage({ context, id: to });
const {
sendMessage,
isSuccess: sendMessageSuccess,
isSending,
} = useSendMessage({
context,
from: from_uid,
to,
});
const {
stopUploading,
data,
uploadFile,
progress,
isSuccess: uploadSuccess,
} = useUploadFile();
const fromUser = useSelector((store) => store.contacts.byId[from_uid]);
const { size, name, content_type } = properties ?? {};
useEffect(() => {
const handleUpSend = async ({ url, name, type }) => {
try {
setUploadingFile(true);
if (type.startsWith("image")) {
const size = await getImageSize(url);
setImageSize(size);
}
let file = await fetch(url)
.then((r) => r.blob())
.then((blobFile) => new File([blobFile], name, { type }));
const [imageSize, setImageSize] = useState(null);
const [uploadingFile, setUploadingFile] = useState(false);
const removeLocalMessage = useRemoveLocalMessage({ context, id: to });
const {
sendMessage,
isSuccess: sendMessageSuccess,
isSending
} = useSendMessage({
context,
from: from_uid,
to
});
const { stopUploading, data, uploadFile, progress, isSuccess: uploadSuccess } = useUploadFile();
const fromUser = useSelector((store) => store.contacts.byId[from_uid]);
const { size, name, content_type } = properties ?? {};
useEffect(() => {
const handleUpSend = async ({ url, name, type }) => {
try {
setUploadingFile(true);
if (type.startsWith('image')) {
const size = await getImageSize(url);
setImageSize(size);
}
let file = await fetch(url)
.then((r) => r.blob())
.then((blobFile) => new File([blobFile], name, { type }));
await uploadFile(file);
setUploadingFile(false);
} catch (error) {
setUploadingFile(false);
console.log("fetch local file error", error);
}
};
// local file
if (content && typeof content == "string" && content.startsWith("blob:")) {
handleUpSend({ url: content, name, type: content_type });
}
}, [content, name, content_type]);
useEffect(() => {
const props = properties ?? {};
const propsV2 = imageSize ? { ...props, ...imageSize } : props;
// 本地文件 并且上传成功
if (uploadSuccess && content.startsWith("blob:")) {
console.log(
"send local file message",
uploadSuccess,
propsV2,
data,
content
);
// 把已经上传的东西当做消息发出去
const { path } = data;
sendMessage({
ignoreLocal: true,
type: "file",
content: { path },
properties: propsV2,
});
}
}, [uploadSuccess, data, properties, content]);
useEffect(() => {
if (sendMessageSuccess) {
// 回收本地资源
URL.revokeObjectURL(content);
}
}, [sendMessageSuccess, content]);
const handleCancel = () => {
stopUploading();
URL.revokeObjectURL(content);
removeLocalMessage(properties.local_id);
await uploadFile(file);
setUploadingFile(false);
} catch (error) {
setUploadingFile(false);
console.log('fetch local file error', error);
}
};
if (!properties) return null;
const icon = getFileIcon(content_type, name);
// local file
if (isLocalFile(content)) {
handleUpSend({ url: content, name, type: content_type });
}
}, [content, name, content_type]);
useEffect(() => {
const props = properties ?? {};
const propsV2 = imageSize ? { ...props, ...imageSize } : props;
// 本地文件 并且上传成功
if (uploadSuccess && isLocalFile(content)) {
console.log('send local file message', uploadSuccess, propsV2, data, content);
// 把已经上传的东西当做消息发出去
const { path } = data;
sendMessage({
ignoreLocal: true,
type: 'file',
content: { path },
properties: propsV2
});
}
}, [uploadSuccess, data, properties, content]);
useEffect(() => {
if (sendMessageSuccess) {
// 回收本地资源
URL.revokeObjectURL(content);
}
}, [sendMessageSuccess, content]);
const handleCancel = () => {
stopUploading();
URL.revokeObjectURL(content);
removeLocalMessage(properties.local_id);
};
if (!properties) return null;
const icon = getFileIcon(content_type, name);
if (!content || !name) return null;
if (!content || !name) return null;
console.log("file content", content, name, content_type, size);
const sending = uploadingFile || isSending;
console.log('file content', content, name, content_type, size);
const sending = uploadingFile || isSending;
if (isImage(content_type, size))
return (
<Image
uploading={sending}
progress={progress}
properties={{ ...imageSize, ...properties }}
size={size}
content={content}
download={download}
thumbnail={thumbnail}
/>
);
if (isImage(content_type, size))
return (
<Styled className={`file_message ${sending ? "sending" : ""}`}>
<div className="basic">
{icon}
<div className="info">
<span className="name">{name}</span>
<span className="details">
{/* <Progress value={30} width={"80%"} /> */}
{sending ? (
<Progress value={progress} width={"80%"} />
) : (
<>
<i className="size">{formatBytes(size)}</i>
<i className="time">{dayjs(created_at).fromNow()}</i>
{fromUser && (
<i className="from">
by <strong>{fromUser.name}</strong>
</i>
)}
</>
)}
</span>
</div>
{/* <IconClose className="cancel" /> */}
{sending ? (
<IconClose className="cancel" onClick={handleCancel} />
) : (
<a
className="download"
download={name}
href={`${content}&download=true`}
>
<IconDownload />
</a>
)}
</div>
</Styled>
<Image
uploading={sending}
progress={progress}
properties={{ ...imageSize, ...properties }}
size={size}
content={content}
download={download}
thumbnail={thumbnail}
/>
);
return (
<Styled className={`file_message ${sending ? 'sending' : ''}`}>
<div className="basic">
{icon}
<div className="info">
<span className="name">{name}</span>
<span className="details">
{/* <Progress value={30} width={"80%"} /> */}
{sending ? (
<Progress value={progress} width={'80%'} />
) : (
<>
<i className="size">{formatBytes(size)}</i>
<i className="time">{dayjs(created_at).fromNow()}</i>
{fromUser && (
<i className="from">
by <strong>{fromUser.name}</strong>
</i>
)}
</>
)}
</span>
</div>
{/* <IconClose className="cancel" /> */}
{sending ? (
<IconClose className="cancel" onClick={handleCancel} />
) : (
<a className="download" download={name} href={`${content}&download=true`}>
<IconDownload />
</a>
)}
</div>
</Styled>
);
}
+124 -125
View File
@@ -1,135 +1,134 @@
// import React from "react";
import { useSelector } from "react-redux";
import { NavLink } from "react-router-dom";
import styled from "styled-components";
import IconMessage from "../../assets/icons/message.svg";
import IconCall from "../../assets/icons/call.svg";
import IconMore from "../../assets/icons/more.svg";
import Avatar from "../../common/component/Avatar";
import toast from "react-hot-toast";
import { useSelector } from 'react-redux';
import { NavLink } from 'react-router-dom';
import styled from 'styled-components';
import IconMessage from '../../assets/icons/message.svg';
import IconCall from '../../assets/icons/call.svg';
import IconMore from '../../assets/icons/more.svg';
import Avatar from '../../common/component/Avatar';
import toast from 'react-hot-toast';
const StyledWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 80px;
width: 432px;
gap: 4px;
.avatar {
width: 80px;
height: 80px;
border-radius: 50%;
}
.name {
user-select: text;
font-weight: bold;
font-size: 18px;
line-height: 100%;
color: #1c1c1e;
}
.email {
user-select: text;
font-weight: normal;
font-size: 14px;
line-height: 20px;
color: #98a2b3;
}
.intro {
color: #344054;
font-style: normal;
font-weight: 400;
font-size: 14px;
line-height: 20px;
}
.icons {
margin-top: 24px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 80px;
width: 432px;
gap: 4px;
.avatar {
width: 80px;
height: 80px;
border-radius: 50%;
}
.name {
user-select: text;
font-weight: bold;
font-size: 18px;
line-height: 100%;
color: #1c1c1e;
}
.email {
user-select: text;
font-weight: normal;
font-size: 14px;
line-height: 20px;
color: #98a2b3;
}
.intro {
color: #344054;
font-style: normal;
font-weight: 400;
font-size: 14px;
line-height: 20px;
gap: 8px;
.icon {
cursor: pointer;
font-weight: 500;
font-size: 14px;
line-height: 20px;
color: #22ccee;
display: flex;
align-items: center;
flex-direction: column;
gap: 4px;
background: #f9fafb;
border-radius: 8px;
width: 128px;
padding: 14px 0 12px 0;
&:hover {
background: #f2f4f7;
}
&.call,
&.more {
svg path {
fill: #22ccee;
}
}
}
}
.line {
width: 100%;
height: 1px;
border: none;
background-color: rgba(0, 0, 0, 0.1);
}
&.card {
padding: 16px;
width: 280px;
background: #ffffff;
box-shadow: 0px 20px 25px 20px rgba(31, 41, 55, 0.1), 0px 10px 10px rgba(31, 41, 55, 0.04);
border-radius: 6px;
.icons {
margin-top: 24px;
display: flex;
align-items: center;
gap: 8px;
.icon {
cursor: pointer;
font-weight: 500;
font-size: 14px;
line-height: 20px;
color: #22ccee;
display: flex;
align-items: center;
flex-direction: column;
gap: 4px;
background: #f9fafb;
border-radius: 8px;
width: 128px;
padding: 14px 0 12px 0;
&:hover {
background: #f2f4f7;
}
&.call,
&.more {
svg path {
fill: #22ccee;
}
}
}
}
.line {
width: 100%;
height: 1px;
border: none;
background-color: rgba(0, 0, 0, 0.1);
}
&.card {
padding: 16px;
width: 280px;
background: #ffffff;
box-shadow: 0px 20px 25px 20px rgba(31, 41, 55, 0.1),
0px 10px 10px rgba(31, 41, 55, 0.04);
border-radius: 6px;
.icons {
padding-bottom: 2px;
}
padding-bottom: 2px;
}
}
`;
export default function Profile({ uid = null, type = "embed" }) {
const data = useSelector((store) => store.contacts.byId[uid]);
if (!data) return null;
// console.log("profile", data);
const {
name,
email,
avatar,
introduction = "This guy has nothing to introduce",
} = data;
const handleClick = () => {
toast.success("cooming soon...");
};
return (
<StyledWrapper className={type}>
<Avatar className="avatar" url={avatar} name={name} />
<h2 className="name">{name}</h2>
<span className="email">{email}</span>
<p className="intro">{introduction}</p>
<ul className="icons">
<NavLink to={`/chat/dm/${uid}`}>
<li className="icon chat">
<IconMessage />
<span className="txt">Message</span>
</li>
</NavLink>
{/* <NavLink to={`#`}> */}
{type !== "card" && (
<li className="icon call" onClick={handleClick}>
<IconCall />
<span className="txt">Call</span>
</li>
)}
{/* </NavLink> */}
<li className="icon more" onClick={handleClick}>
<IconMore />
<span className="txt">More</span>
</li>
</ul>
{/* {type == "embed" && <hr className="line" />} */}
</StyledWrapper>
);
export default function Profile({ uid = null, type = 'embed' }) {
const data = useSelector((store) => store.contacts.byId[uid]);
if (!data) return null;
// console.log("profile", data);
const {
name,
email,
avatar
// introduction = "This guy has nothing to introduce",
} = data;
const handleClick = () => {
toast.success('cooming soon...');
};
return (
<StyledWrapper className={type}>
<Avatar className="avatar" url={avatar} name={name} />
<h2 className="name">{name}</h2>
<span className="email">{email}</span>
{/* <p className="intro">{introduction}</p> */}
<ul className="icons">
<NavLink to={`/chat/dm/${uid}`}>
<li className="icon chat">
<IconMessage />
<span className="txt">Message</span>
</li>
</NavLink>
{/* <NavLink to={`#`}> */}
{type !== 'card' && (
<li className="icon call" onClick={handleClick}>
<IconCall />
<span className="txt">Call</span>
</li>
)}
{/* </NavLink> */}
<li className="icon more" onClick={handleClick}>
<IconMore />
<span className="txt">More</span>
</li>
</ul>
{/* {type == "embed" && <hr className="line" />} */}
</StyledWrapper>
);
}
+195 -197
View File
@@ -1,131 +1,131 @@
import BASE_URL, { FILE_IMAGE_SIZE, ContentTypes } from "../app/config";
import IconPdf from "../assets/icons/file.pdf.svg";
import IconAudio from "../assets/icons/file.audio.svg";
import IconVideo from "../assets/icons/file.video.svg";
import IconUnkown from "../assets/icons/file.unkown.svg";
import IconDoc from "../assets/icons/file.doc.svg";
import IconCode from "../assets/icons/file.code.svg";
import IconImage from "../assets/icons/file.image.svg";
export const isImage = (file_type = "", size = 0) => {
return file_type.startsWith("image") && size <= FILE_IMAGE_SIZE;
import BASE_URL, { FILE_IMAGE_SIZE, ContentTypes } from '../app/config';
import IconPdf from '../assets/icons/file.pdf.svg';
import IconAudio from '../assets/icons/file.audio.svg';
import IconVideo from '../assets/icons/file.video.svg';
import IconUnkown from '../assets/icons/file.unkown.svg';
import IconDoc from '../assets/icons/file.doc.svg';
import IconCode from '../assets/icons/file.code.svg';
import IconImage from '../assets/icons/file.image.svg';
export const isImage = (file_type = '', size = 0) => {
return file_type.startsWith('image') && size <= FILE_IMAGE_SIZE;
};
export const isObjectEqual = (obj1, obj2) => {
let o1 = Object.entries(obj1 ?? {})
.sort()
.toString();
let o2 = Object.entries(obj2 ?? {})
.sort()
.toString();
return o1 === o2;
let o1 = Object.entries(obj1 ?? {})
.sort()
.toString();
let o2 = Object.entries(obj2 ?? {})
.sort()
.toString();
return o1 === o2;
};
export const isTreatAsImage = (file) => {
let isImage = false;
if (!file) return isImage;
const { type, size } = file;
if (type.startsWith("image")) {
// 10MB
return size < 1000 * 1000;
}
return isImage;
let isImage = false;
if (!file) return isImage;
const { type, size } = file;
if (type.startsWith('image')) {
// 10MB
return size < 1000 * 1000;
}
return isImage;
};
export const getNonNullValues = (obj, whiteList = ["log_id"]) => {
const tmp = {};
Object.keys(obj).forEach((k) => {
if (!whiteList.includes(k) && obj[k] !== null) {
tmp[k] = obj[k];
}
});
return tmp;
export const getNonNullValues = (obj, whiteList = ['log_id']) => {
const tmp = {};
Object.keys(obj).forEach((k) => {
if (!whiteList.includes(k) && obj[k] !== null) {
tmp[k] = obj[k];
}
});
return tmp;
};
export function getDefaultSize(size = null, min = 480) {
if (!size) return { width: 0, height: 0 };
const { width: oWidth, height: oHeight } = size;
if (oWidth == oHeight) {
const tmp = min > oWidth ? oWidth : min;
return { width: tmp, height: tmp };
}
const isVertical = oWidth > oHeight ? false : true;
let dWidth = 0;
let dHeight = 0;
if (isVertical) {
dHeight = oHeight >= min ? min : oHeight;
dWidth = (oWidth / oHeight) * dHeight;
} else {
dWidth = oWidth >= min ? min : oWidth;
dHeight = (oHeight / oWidth) * dWidth;
}
return { width: dWidth, height: dHeight };
if (!size) return { width: 0, height: 0 };
const { width: oWidth, height: oHeight } = size;
if (oWidth == oHeight) {
const tmp = min > oWidth ? oWidth : min;
return { width: tmp, height: tmp };
}
const isVertical = oWidth > oHeight ? false : true;
let dWidth = 0;
let dHeight = 0;
if (isVertical) {
dHeight = oHeight >= min ? min : oHeight;
dWidth = (oWidth / oHeight) * dHeight;
} else {
dWidth = oWidth >= min ? min : oWidth;
dHeight = (oHeight / oWidth) * dWidth;
}
return { width: dWidth, height: dHeight };
}
export function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return "0 Bytes";
if (bytes === 0) return '0 Bytes';
const k = 1000;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const k = 1000;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export const getImageSize = (url) => {
const size = { width: 0, height: 0 };
if (!url) return size;
return new Promise((resolve) => {
const img = new Image();
img.src = url;
img.onload = () => {
size.width = img.width;
size.height = img.height;
resolve(size);
};
img.onerror = () => {
resolve(size);
};
});
const size = { width: 0, height: 0 };
if (!url) return size;
return new Promise((resolve) => {
const img = new Image();
img.src = url;
img.onload = () => {
size.width = img.width;
size.height = img.height;
resolve(size);
};
img.onerror = () => {
resolve(size);
};
});
};
export const getInitials = (name) => {
const arr = name.split(" ").filter((n) => !!n);
return arr
.map((t) => t[0])
.join("")
.toUpperCase();
const arr = name.split(' ').filter((n) => !!n);
return arr
.map((t) => t[0])
.join('')
.toUpperCase();
};
export const getInitialsAvatar = ({
initials = "UK",
initial_size = 0,
size = 200,
foreground = "#fff",
background = "#4c99e9",
weight = 400,
fontFamily = "'Lato', 'Lato-Regular', 'Helvetica Neue'",
initials = 'UK',
initial_size = 0,
size = 200,
foreground = '#fff',
background = '#4c99e9',
weight = 400,
fontFamily = "'Lato', 'Lato-Regular', 'Helvetica Neue'"
}) => {
const canvas = document.createElement("canvas");
const width = size;
const height = size;
const devicePixelRatio = Math.max(window.devicePixelRatio, 1);
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
const canvas = document.createElement('canvas');
const width = size;
const height = size;
const devicePixelRatio = Math.max(window.devicePixelRatio, 1);
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
const context = canvas.getContext("2d");
context.scale(devicePixelRatio, devicePixelRatio);
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fill();
// 两个字符,自动缩放40
context.font = `${weight} ${
((initial_size || height) - (initials.length == 2 ? 40 : 0)) / 2
}px ${fontFamily}`;
context.textAlign = "center";
const context = canvas.getContext('2d');
context.scale(devicePixelRatio, devicePixelRatio);
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fill();
// 两个字符,自动缩放40
context.font = `${weight} ${
((initial_size || height) - (initials.length == 2 ? 40 : 0)) / 2
}px ${fontFamily}`;
context.textAlign = 'center';
context.textBaseline = "middle";
context.fillStyle = foreground;
context.fillText(initials, width / 2, height / 2);
context.textBaseline = 'middle';
context.fillStyle = foreground;
context.fillText(initials, width / 2, height / 2);
/* istanbul ignore next */
return canvas.toDataURL("image/png");
/* istanbul ignore next */
return canvas.toDataURL('image/png');
};
/**
* @param {File|Blob} - file to slice
@@ -133,103 +133,101 @@ export const getInitialsAvatar = ({
* @return {Array} - an array of Blobs
**/
export function sliceFile(file, chunksAmount) {
if (!file) return null;
let byteIndex = 0;
let chunks = [];
if (!file) return null;
let byteIndex = 0;
let chunks = [];
for (let i = 0; i < chunksAmount; i += 1) {
let byteEnd = Math.ceil((file.size / chunksAmount) * (i + 1));
chunks.push(file.slice(byteIndex, byteEnd));
byteIndex += byteEnd - byteIndex;
}
for (let i = 0; i < chunksAmount; i += 1) {
let byteEnd = Math.ceil((file.size / chunksAmount) * (i + 1));
chunks.push(file.slice(byteIndex, byteEnd));
byteIndex += byteEnd - byteIndex;
}
return chunks;
return chunks;
}
export const getFileIcon = (type, name = "") => {
let icon = null;
export const getFileIcon = (type, name = '') => {
let icon = null;
const checks = {
image: /^image/gi,
audio: /^audio/gi,
video: /^video/gi,
code: /(json|javascript|java|rb|c|php|xml|css|html)$/gi,
doc: /^text/gi,
pdf: /\/pdf$/gi,
const checks = {
image: /^image/gi,
audio: /^audio/gi,
video: /^video/gi,
code: /(json|javascript|java|rb|c|php|xml|css|html)$/gi,
doc: /^text/gi,
pdf: /\/pdf$/gi
};
const _arr = name.split('.');
const _type = type || _arr[_arr.length - 1];
switch (true) {
case checks.image.test(_type):
{
console.log('image');
icon = <IconImage className="icon" />;
}
break;
case checks.pdf.test(_type):
icon = <IconPdf className="icon" />;
break;
case checks.code.test(_type):
icon = <IconCode className="icon" />;
break;
case checks.doc.test(_type):
icon = <IconDoc className="icon" />;
break;
case checks.audio.test(_type):
icon = <IconAudio className="icon" />;
break;
case checks.video.test(_type):
icon = <IconVideo className="icon" />;
break;
default:
icon = <IconUnkown className="icon" />;
break;
}
return icon;
};
export const normalizeArchiveData = (data = null, filePath = null, uid = null) => {
if (!data || !filePath) return [];
const { messages, users } = data;
const getUrls = (uid, { content, content_type, file_id, thumbnail_id, filePath, avatar }) => {
// uid存在,则favorite,否则archive
const prefix = uid
? `${BASE_URL}/favorite/${uid}/${file_id}`
: `${BASE_URL}/resource/archive/attachment?file_path=${filePath}&attachment_id=`;
return {
transformedContent: content_type == ContentTypes.file ? `${prefix}${file_id}` : content,
thumbnail: content_type == ContentTypes.file ? `${prefix}${thumbnail_id}` : '',
download:
content_type == ContentTypes.file ? `${prefix}${file_id}${uid ? '?' : '&'}download=true` : '',
avatarUrl: avatar !== null ? `${prefix}${avatar}` : ''
};
const _arr = name.split(".");
const _type = type || _arr[_arr.length - 1];
switch (true) {
case checks.image.test(_type):
{
console.log("image");
icon = <IconImage className="icon" />;
}
break;
case checks.pdf.test(_type):
icon = <IconPdf className="icon" />;
break;
case checks.code.test(_type):
icon = <IconCode className="icon" />;
break;
case checks.doc.test(_type):
icon = <IconDoc className="icon" />;
break;
case checks.audio.test(_type):
icon = <IconAudio className="icon" />;
break;
case checks.video.test(_type):
icon = <IconVideo className="icon" />;
break;
};
return messages.map(
({ source, mid, content, file_id, thumbnail_id, content_type, properties, from_user }) => {
let user = { ...(users[from_user] || {}) };
const { transformedContent, thumbnail, download, avatar } = getUrls(uid, {
content,
content_type,
filePath,
file_id,
thumbnail_id,
avatar: user.avatar
});
default:
icon = <IconUnkown className="icon" />;
break;
user.avatar = avatar;
console.log('user data', transformedContent, user);
return {
source,
from_mid: mid,
user,
content: transformedContent,
content_type,
properties,
download,
thumbnail
};
}
return icon;
};
export const normalizeArchiveData = (data = null, filePath = null) => {
if (!data || !filePath) return [];
const { messages, users } = data;
return messages.map(
({
source,
mid,
content,
file_id,
thumbnail_id,
content_type,
properties,
from_user,
}) => {
const transformedContent =
content_type == ContentTypes.file
? `${BASE_URL}/resource/archive/attachment?file_path=${filePath}&attachment_id=${file_id}`
: content;
const thumbnail =
content_type == ContentTypes.file
? `${BASE_URL}/resource/archive/attachment?file_path=${filePath}&attachment_id=${thumbnail_id}`
: "";
const download =
content_type == ContentTypes.file
? `${BASE_URL}/resource/archive/attachment?file_path=${filePath}&attachment_id=${file_id}&download=true`
: "";
let user = { ...(users[from_user] || {}) };
user.avatar =
user.avatar !== null
? `${BASE_URL}/resource/archive/attachment?file_path=${filePath}&attachment_id=${user.avatar}`
: "";
console.log("user data", transformedContent, user);
return {
source,
from_mid: mid,
user,
content: transformedContent,
content_type,
properties,
download,
thumbnail,
};
}
);
);
};