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
+170 -171
View File
@@ -1,178 +1,177 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import { createApi } from '@reduxjs/toolkit/query/react';
// import toast from "react-hot-toast";
import baseQuery from "./base.query";
import BASE_URL, { ContentTypes } from "../config";
import { updateChannel } from "../slices/channels";
import { removeMessage } from "../slices/message";
import { removeChannelSession } from "../slices/message.channel";
import { removeReactionMessage } from "../slices/message.reaction";
import { onMessageSendStarted } from "./handlers";
import baseQuery from './base.query';
import BASE_URL, { ContentTypes } from '../config';
import { updateChannel } from '../slices/channels';
import { removeMessage } from '../slices/message';
import { removeChannelSession } from '../slices/message.channel';
import { removeReactionMessage } from '../slices/message.reaction';
import { onMessageSendStarted } from './handlers';
export const channelApi = createApi({
reducerPath: "channelApi",
baseQuery,
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
query: () => ({ url: `group` }),
}),
getChannel: builder.query({
query: (id) => ({ url: `group/${id}` }),
}),
createChannel: builder.mutation({
query: (data) => ({
url: "group",
method: "POST",
body: data,
}),
}),
updateChannel: builder.mutation({
query: ({ id, ...data }) => ({
url: `group/${id}`,
method: "PUT",
body: data,
}),
async onQueryStarted(
{ id, name, description },
{ dispatch, queryFulfilled }
) {
// id: who send to ,from_uid: who sent
const patchResult = dispatch(updateChannel({ id, name, description }));
try {
await queryFulfilled;
} catch {
console.log("channel update failed");
patchResult.undo();
}
},
}),
getHistoryMessages: builder.query({
query: ({ gid, mid = 0, limit = 50 }) => ({
url: `/group/${gid}/history?before=${mid}&limit=${limit}`,
}),
// async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
// const {
// ui: { channelSetting },
// channelMessage,
// } = getState();
// try {
// await queryFulfilled;
// dispatch(removeChannel(id));
// if (id == channelSetting) {
// dispatch(toggleChannelSetting());
// }
// // 删掉该channel下的所有消息&reaction
// const mids = channelMessage[id];
// if (mids) {
// dispatch(removeChannelSession(id));
// dispatch(removeMessage(mids));
// dispatch(removeReactionMessage(mids));
// }
// } catch {
// console.log("remove channel error");
// }
// },
}),
createInviteLink: builder.query({
query: (gid) => ({
headers: {
"content-type": "text/plain",
accept: "text/plain",
},
url: `/group/${gid}/create_invite_link`,
responseHandler: (response) => response.text(),
}),
transformResponse: (link) => {
// 替换掉域名
const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
},
}),
removeChannel: builder.query({
query: (id) => ({
url: `group/${id}`,
method: "DELETE",
}),
async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
const { channelMessage } = getState();
try {
await queryFulfilled;
// 删掉该channel下的所有消息&reaction
const mids = channelMessage[id];
if (mids) {
dispatch(removeChannelSession(id));
dispatch(removeMessage(mids));
dispatch(removeReactionMessage(mids));
}
} catch {
console.log("remove channel error");
}
},
}),
sendChannelMsg: builder.mutation({
query: ({ id, content, type = "text", properties = "" }) => ({
headers: {
"content-type": ContentTypes[type],
"X-Properties": properties ? btoa(JSON.stringify(properties)) : "",
},
url: `group/${id}/send`,
method: "POST",
body: type == "file" ? JSON.stringify(content) : content,
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, "channel");
},
}),
addMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/add`,
method: "POST",
body: members,
}),
}),
removeMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/remove`,
method: "POST",
body: members,
}),
}),
updateIcon: builder.mutation({
query: ({ gid, image }) => ({
headers: {
"content-type": "image/png",
},
url: `/group/${gid}/avatar`,
method: "POST",
body: image,
}),
async onQueryStarted({ gid }, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(
updateChannel({
id: gid,
icon: `${BASE_URL}/resource/group_avatar?gid=${gid}&t=${new Date().getTime()}`,
})
);
} catch (error) {
console.log("err", error);
}
},
}),
reducerPath: 'channelApi',
baseQuery,
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
query: () => ({ url: `group` })
}),
getChannel: builder.query({
query: (id) => ({ url: `group/${id}` })
}),
createChannel: builder.mutation({
query: (data) => ({
url: 'group',
method: 'POST',
body: data
})
}),
updateChannel: builder.mutation({
query: ({ id, ...data }) => ({
url: `group/${id}`,
method: 'PUT',
body: data
}),
async onQueryStarted({ id, name, description }, { dispatch, queryFulfilled }) {
// id: who send to ,from_uid: who sent
const patchResult = dispatch(updateChannel({ id, name, description }));
try {
await queryFulfilled;
} catch {
console.log('channel update failed');
patchResult.undo();
}
}
}),
getHistoryMessages: builder.query({
query: ({ gid, mid = 0, limit = 50 }) => ({
url: `/group/${gid}/history?before=${mid}&limit=${limit}`
})
// async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
// const {
// ui: { channelSetting },
// channelMessage,
// } = getState();
// try {
// await queryFulfilled;
// dispatch(removeChannel(id));
// if (id == channelSetting) {
// dispatch(toggleChannelSetting());
// }
// // 删掉该channel下的所有消息&reaction
// const mids = channelMessage[id];
// if (mids) {
// dispatch(removeChannelSession(id));
// dispatch(removeMessage(mids));
// dispatch(removeReactionMessage(mids));
// }
// } catch {
// console.log("remove channel error");
// }
// },
}),
createInviteLink: builder.query({
query: (gid) => ({
headers: {
'content-type': 'text/plain',
accept: 'text/plain'
},
url: `/group/${gid}/create_invite_link`,
responseHandler: (response) => response.text()
}),
transformResponse: (link) => {
// 替换掉域名
const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
}
}),
removeChannel: builder.query({
query: (id) => ({
url: `group/${id}`,
method: 'DELETE'
}),
async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
const { channelMessage } = getState();
try {
await queryFulfilled;
// 删掉该channel下的所有消息&reaction
const mids = channelMessage[id];
if (mids) {
dispatch(removeChannelSession(id));
dispatch(removeMessage(mids));
dispatch(removeReactionMessage(mids));
}
} catch {
console.log('remove channel error');
}
}
}),
sendChannelMsg: builder.mutation({
query: ({ id, content, type = 'text', properties = '' }) => ({
headers: {
'content-type': ContentTypes[type],
'X-Properties': properties
? btoa(unescape(encodeURIComponent(JSON.stringify(properties))))
: ''
},
url: `group/${id}/send`,
method: 'POST',
body: type == 'file' ? JSON.stringify(content) : content
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, 'channel');
}
}),
addMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/add`,
method: 'POST',
body: members
})
}),
removeMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/remove`,
method: 'POST',
body: members
})
}),
updateIcon: builder.mutation({
query: ({ gid, image }) => ({
headers: {
'content-type': 'image/png'
},
url: `/group/${gid}/avatar`,
method: 'POST',
body: image
}),
async onQueryStarted({ gid }, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(
updateChannel({
id: gid,
icon: `${BASE_URL}/resource/group_avatar?gid=${gid}&t=${new Date().getTime()}`
})
);
} catch (error) {
console.log('err', error);
}
}
})
})
});
export const {
useLazyCreateInviteLinkQuery,
useCreateInviteLinkQuery,
useLazyGetHistoryMessagesQuery,
useGetChannelQuery,
useUpdateChannelMutation,
useLazyRemoveChannelQuery,
useGetChannelsQuery,
useCreateChannelMutation,
useSendChannelMsgMutation,
useAddMembersMutation,
useRemoveMembersMutation,
useUpdateIconMutation,
useLazyCreateInviteLinkQuery,
useCreateInviteLinkQuery,
useLazyGetHistoryMessagesQuery,
useGetChannelQuery,
useUpdateChannelMutation,
useLazyRemoveChannelQuery,
useGetChannelsQuery,
useCreateChannelMutation,
useSendChannelMsgMutation,
useAddMembersMutation,
useRemoveMembersMutation,
useUpdateIconMutation
} = channelApi;
+111 -109
View File
@@ -1,116 +1,118 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import { createApi } from '@reduxjs/toolkit/query/react';
// import toast from "react-hot-toast";
import { KEY_UID } from "../config";
import baseQuery from "./base.query";
import { resetAuthData, setUid } from "../slices/auth.data";
import { updateMute } from "../slices/footprint";
import { fullfillContacts } from "../slices/contacts";
import BASE_URL, { ContentTypes } from "../config";
import { onMessageSendStarted } from "./handlers";
import { KEY_UID } from '../config';
import baseQuery from './base.query';
import { resetAuthData, setUid } from '../slices/auth.data';
import { updateMute } from '../slices/footprint';
import { fullfillContacts } from '../slices/contacts';
import BASE_URL, { ContentTypes } from '../config';
import { onMessageSendStarted } from './handlers';
export const contactApi = createApi({
reducerPath: "contactApi",
baseQuery,
endpoints: (builder) => ({
getContacts: builder.query({
query: () => ({ url: `user` }),
transformResponse: (data) => {
return data.map((user) => {
const avatar =
user.avatar_updated_at == 0
? ""
: `${BASE_URL}/resource/avatar?uid=${user.uid}&t=${user.avatar_updated_at}`;
user.avatar = avatar;
return user;
});
},
async onQueryStarted(data, { dispatch, queryFulfilled }) {
const local_uid = localStorage.getItem(KEY_UID);
try {
const { data: contacts } = await queryFulfilled;
const matchedUser = contacts.find((c) => c.uid == local_uid);
console.log("wtf", contacts, matchedUser);
if (!matchedUser) {
// 用户已注销或被禁用
console.log("no matched user, redirect to login");
dispatch(resetAuthData());
} else {
const markedContacts = contacts.map((u) => {
return u.uid == matchedUser.uid ? { ...u, online: true } : u;
});
dispatch(setUid(matchedUser.uid));
dispatch(fullfillContacts(markedContacts));
}
} catch {
console.log("get contact list error");
}
},
}),
deleteContact: builder.query({
query: (uid) => ({ url: `/admin/user/${uid}`, method: "DELETE" }),
}),
updateMuteSetting: builder.mutation({
query: (data) => ({
url: `/user/mute`,
method: "POST",
body: data,
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(updateMute(data));
} catch (error) {
console.log("update mute failed", error);
}
},
}),
updateAvatar: builder.mutation({
query: (data) => ({
headers: {
"content-type": "image/png",
},
url: `user/avatar`,
method: "POST",
body: data,
}),
}),
updateInfo: builder.mutation({
query: (data) => ({
url: `user`,
method: "PUT",
body: data,
}),
}),
register: builder.mutation({
query: (data) => ({
url: `user/register`,
method: "POST",
body: data,
}),
}),
sendMsg: builder.mutation({
query: ({ id, content, type = "text", properties = "" }) => ({
headers: {
"content-type": ContentTypes[type],
"X-Properties": properties ? btoa(JSON.stringify(properties)) : "",
},
url: `user/${id}/send`,
method: "POST",
body: type == "file" ? JSON.stringify(content) : content,
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, "user");
},
}),
reducerPath: 'contactApi',
baseQuery,
endpoints: (builder) => ({
getContacts: builder.query({
query: () => ({ url: `user` }),
transformResponse: (data) => {
return data.map((user) => {
const avatar =
user.avatar_updated_at == 0
? ''
: `${BASE_URL}/resource/avatar?uid=${user.uid}&t=${user.avatar_updated_at}`;
user.avatar = avatar;
return user;
});
},
async onQueryStarted(data, { dispatch, queryFulfilled }) {
const local_uid = localStorage.getItem(KEY_UID);
try {
const { data: contacts } = await queryFulfilled;
const matchedUser = contacts.find((c) => c.uid == local_uid);
console.log('wtf', contacts, matchedUser);
if (!matchedUser) {
// 用户已注销或被禁用
console.log('no matched user, redirect to login');
dispatch(resetAuthData());
} else {
const markedContacts = contacts.map((u) => {
return u.uid == matchedUser.uid ? { ...u, online: true } : u;
});
dispatch(setUid(matchedUser.uid));
dispatch(fullfillContacts(markedContacts));
}
} catch {
console.log('get contact list error');
}
}
}),
deleteContact: builder.query({
query: (uid) => ({ url: `/admin/user/${uid}`, method: 'DELETE' })
}),
updateMuteSetting: builder.mutation({
query: (data) => ({
url: `/user/mute`,
method: 'POST',
body: data
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(updateMute(data));
} catch (error) {
console.log('update mute failed', error);
}
}
}),
updateAvatar: builder.mutation({
query: (data) => ({
headers: {
'content-type': 'image/png'
},
url: `user/avatar`,
method: 'POST',
body: data
})
}),
updateInfo: builder.mutation({
query: (data) => ({
url: `user`,
method: 'PUT',
body: data
})
}),
register: builder.mutation({
query: (data) => ({
url: `user/register`,
method: 'POST',
body: data
})
}),
sendMsg: builder.mutation({
query: ({ id, content, type = 'text', properties = '' }) => ({
headers: {
'content-type': ContentTypes[type],
'X-Properties': properties
? btoa(unescape(encodeURIComponent(JSON.stringify(properties))))
: ''
},
url: `user/${id}/send`,
method: 'POST',
body: type == 'file' ? JSON.stringify(content) : content
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, 'user');
}
})
})
});
export const {
useUpdateMuteSettingMutation,
useLazyDeleteContactQuery,
useUpdateInfoMutation,
useUpdateAvatarMutation,
useGetContactsQuery,
useLazyGetContactsQuery,
useSendMsgMutation,
useRegisterMutation,
useUpdateMuteSettingMutation,
useLazyDeleteContactQuery,
useUpdateInfoMutation,
useUpdateAvatarMutation,
useGetContactsQuery,
useLazyGetContactsQuery,
useSendMsgMutation,
useRegisterMutation
} = contactApi;
+205 -204
View File
@@ -1,213 +1,214 @@
import { createApi } from "@reduxjs/toolkit/query/react";
import { ContentTypes } from "../config";
import { updateReadChannels, updateReadUsers } from "../slices/footprint";
import { createApi } from '@reduxjs/toolkit/query/react';
import { ContentTypes } from '../config';
import { updateReadChannels, updateReadUsers } from '../slices/footprint';
import {
fullfillFavorites,
populateFavorite,
addFavorite,
deleteFavorite,
} from "../slices/favorites";
import { onMessageSendStarted } from "./handlers";
import { normalizeArchiveData } from "../../common/utils";
fullfillFavorites,
populateFavorite,
addFavorite,
deleteFavorite
} from '../slices/favorites';
import { onMessageSendStarted } from './handlers';
import { normalizeArchiveData } from '../../common/utils';
// import { updateMessage } from "../slices/message";
import baseQuery from "./base.query";
import baseQuery from './base.query';
export const messageApi = createApi({
reducerPath: "messageApi",
baseQuery,
endpoints: (builder) => ({
editMessage: builder.mutation({
query: ({ mid, content, type = "text" }) => ({
headers: {
"content-type": ContentTypes[type],
},
url: `/message/${mid}/edit`,
method: "PUT",
body: content,
}),
// async onQueryStarted({mid,content},{dispatch}){
// dispatch()
// }
}),
reactMessage: builder.mutation({
query: ({ mid, action }) => ({
url: `/message/${mid}/like`,
method: "PUT",
body: { action },
}),
}),
deleteMessage: builder.query({
query: (mid) => ({
url: `/message/${mid}`,
method: "DELETE",
}),
}),
prepareUploadFile: builder.mutation({
query: (meta = {}) => ({
url: `/resource/file/prepare`,
method: "POST",
body: meta,
}),
}),
createArchive: builder.mutation({
query: (mids = []) => ({
url: `/resource/archive`,
method: "POST",
body: { mid_list: mids },
}),
}),
uploadFile: builder.mutation({
query: (formData) => ({
// headers: {
// "content-type": ContentTypes.formData,
// },
url: `/resource/file/upload`,
method: "POST",
body: formData,
}),
transformResponse: (data) => {
console.log("upload file response", data);
return data ? data : {};
},
}),
getOGInfo: builder.query({
query: (url) => ({
url: `/resource/open_graphic_parse?url=${encodeURIComponent(url)}`,
}),
}),
getArchiveMessage: builder.query({
query: (file_path) => ({
url: `/resource/archive?file_path=${encodeURIComponent(file_path)}`,
}),
}),
pinMessage: builder.mutation({
query: ({ gid, mid }) => ({
url: `/group/${gid}/pin`,
method: "POST",
body: { mid },
}),
}),
unpinMessage: builder.mutation({
query: ({ gid, mid }) => ({
url: `/group/${gid}/unpin`,
method: "POST",
body: { mid },
}),
}),
favoriteMessage: builder.mutation({
query: (mids) => ({
url: `/favorite`,
method: "POST",
body: { mid_list: mids },
}),
async onQueryStarted(mids, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled;
const { created_at, id } = data;
dispatch(addFavorite({ id, created_at }));
dispatch(messageApi.endpoints.getFavoriteDetails.initiate(id));
} catch (err) {
console.log("get favorite list error", err);
}
},
}),
removeFavorite: builder.query({
query: (id) => ({
url: `/favorite/${id}`,
method: "DELETE",
}),
async onQueryStarted(id, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(deleteFavorite(id));
} catch (err) {
console.log("get favorite list error", err);
}
},
}),
getFavoriteDetails: builder.query({
query: (id) => ({
url: `/favorite/${id}`,
}),
async onQueryStarted(id, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled;
const messages = normalizeArchiveData(data, id);
dispatch(populateFavorite({ id, messages }));
} catch (err) {
console.log("get favorite list error", err);
}
},
}),
getFavorites: builder.query({
query: () => ({
url: `/favorite`,
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
try {
const { data: favorites } = await queryFulfilled;
dispatch(fullfillFavorites(favorites));
for (const fav of favorites) {
const { id } = fav;
dispatch(messageApi.endpoints.getFavoriteDetails.initiate(id));
}
} catch (err) {
console.log("get favorite list error", err);
}
},
}),
replyMessage: builder.mutation({
query: ({ reply_mid, content, type = "text" }) => ({
headers: {
"content-type": ContentTypes[type],
},
url: `/message/${reply_mid}/reply`,
method: "POST",
body: content,
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, param1.context);
},
}),
readMessage: builder.mutation({
query: (data) => ({
url: `/user/read-index`,
method: "POST",
body: data,
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
const { users = null, groups = null } = data;
if (users) {
dispatch(updateReadUsers(users));
}
if (groups) {
dispatch(updateReadChannels(groups));
}
try {
await queryFulfilled;
} catch {
// todo
}
},
}),
reducerPath: 'messageApi',
baseQuery,
endpoints: (builder) => ({
editMessage: builder.mutation({
query: ({ mid, content, type = 'text' }) => ({
headers: {
'content-type': ContentTypes[type]
},
url: `/message/${mid}/edit`,
method: 'PUT',
body: content
})
// async onQueryStarted({mid,content},{dispatch}){
// dispatch()
// }
}),
reactMessage: builder.mutation({
query: ({ mid, action }) => ({
url: `/message/${mid}/like`,
method: 'PUT',
body: { action }
})
}),
deleteMessage: builder.query({
query: (mid) => ({
url: `/message/${mid}`,
method: 'DELETE'
})
}),
prepareUploadFile: builder.mutation({
query: (meta = {}) => ({
url: `/resource/file/prepare`,
method: 'POST',
body: meta
})
}),
createArchive: builder.mutation({
query: (mids = []) => ({
url: `/resource/archive`,
method: 'POST',
body: { mid_list: mids }
})
}),
uploadFile: builder.mutation({
query: (formData) => ({
// headers: {
// "content-type": ContentTypes.formData,
// },
url: `/resource/file/upload`,
method: 'POST',
body: formData
}),
transformResponse: (data) => {
console.log('upload file response', data);
return data ? data : {};
}
}),
getOGInfo: builder.query({
query: (url) => ({
url: `/resource/open_graphic_parse?url=${encodeURIComponent(url)}`
})
}),
getArchiveMessage: builder.query({
query: (file_path) => ({
url: `/resource/archive?file_path=${encodeURIComponent(file_path)}`
})
}),
pinMessage: builder.mutation({
query: ({ gid, mid }) => ({
url: `/group/${gid}/pin`,
method: 'POST',
body: { mid }
})
}),
unpinMessage: builder.mutation({
query: ({ gid, mid }) => ({
url: `/group/${gid}/unpin`,
method: 'POST',
body: { mid }
})
}),
favoriteMessage: builder.mutation({
query: (mids) => ({
url: `/favorite`,
method: 'POST',
body: { mid_list: mids }
}),
async onQueryStarted(mids, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled;
const { created_at, id } = data;
dispatch(addFavorite({ id, created_at }));
dispatch(messageApi.endpoints.getFavoriteDetails.initiate(id));
} catch (err) {
console.log('get favorite list error', err);
}
}
}),
removeFavorite: builder.query({
query: (id) => ({
url: `/favorite/${id}`,
method: 'DELETE'
}),
async onQueryStarted(id, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(deleteFavorite(id));
} catch (err) {
console.log('get favorite list error', err);
}
}
}),
getFavoriteDetails: builder.query({
query: (id) => ({
url: `/favorite/${id}`
}),
async onQueryStarted(id, { dispatch, queryFulfilled, getState }) {
try {
const { data } = await queryFulfilled;
const loginUid = getState().authData.uid;
const messages = normalizeArchiveData(data, id, loginUid);
dispatch(populateFavorite({ id, messages }));
} catch (err) {
console.log('get favorite list error', err);
}
}
}),
getFavorites: builder.query({
query: () => ({
url: `/favorite`
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
try {
const { data: favorites } = await queryFulfilled;
dispatch(fullfillFavorites(favorites));
for (const fav of favorites) {
const { id } = fav;
dispatch(messageApi.endpoints.getFavoriteDetails.initiate(id));
}
} catch (err) {
console.log('get favorite list error', err);
}
}
}),
replyMessage: builder.mutation({
query: ({ reply_mid, content, type = 'text' }) => ({
headers: {
'content-type': ContentTypes[type]
},
url: `/message/${reply_mid}/reply`,
method: 'POST',
body: content
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, param1.context);
}
}),
readMessage: builder.mutation({
query: (data) => ({
url: `/user/read-index`,
method: 'POST',
body: data
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
const { users = null, groups = null } = data;
if (users) {
dispatch(updateReadUsers(users));
}
if (groups) {
dispatch(updateReadChannels(groups));
}
try {
await queryFulfilled;
} catch {
// todo
}
}
})
})
});
export const {
useLazyRemoveFavoriteQuery,
useUnpinMessageMutation,
useLazyGetFavoritesQuery,
useFavoriteMessageMutation,
usePinMessageMutation,
useLazyGetArchiveMessageQuery,
useGetArchiveMessageQuery,
useLazyGetOGInfoQuery,
usePrepareUploadFileMutation,
useUploadFileMutation,
useEditMessageMutation,
useReactMessageMutation,
useReplyMessageMutation,
useLazyDeleteMessageQuery,
useReadMessageMutation,
useCreateArchiveMutation,
useLazyRemoveFavoriteQuery,
useUnpinMessageMutation,
useLazyGetFavoritesQuery,
useFavoriteMessageMutation,
usePinMessageMutation,
useLazyGetArchiveMessageQuery,
useGetArchiveMessageQuery,
useLazyGetOGInfoQuery,
usePrepareUploadFileMutation,
useUploadFileMutation,
useEditMessageMutation,
useReactMessageMutation,
useReplyMessageMutation,
useLazyDeleteMessageQuery,
useReadMessageMutation,
useCreateArchiveMutation
} = messageApi;
+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,
};
}
);
);
};
+91 -101
View File
@@ -1,110 +1,100 @@
import { useEffect } from "react";
import { Route, Routes, HashRouter } from "react-router-dom";
import { Provider, useSelector } from "react-redux";
import { useEffect } from 'react';
import { Route, Routes, HashRouter } from 'react-router-dom';
import { Provider, useSelector } from 'react-redux';
// import Welcome from './Welcome'
import NotFoundPage from "./404";
import OAuthPage from "./oauth";
import LoginPage from "./login";
import HomePage from "./home";
import ChatPage from "./chat";
import FavoritesPage from "./favs";
import ContactsPage from "./contacts";
import RequireAuth from "../common/component/RequireAuth";
import RequireNoAuth from "../common/component/RequireNoAuth";
import Meta from "../common/component/Meta";
import NotFoundPage from './404';
import OAuthPage from './oauth';
import LoginPage from './login';
import HomePage from './home';
import ChatPage from './chat';
import FavoritesPage from './favs';
import ContactsPage from './contacts';
import RequireAuth from '../common/component/RequireAuth';
import RequireNoAuth from '../common/component/RequireNoAuth';
import Meta from '../common/component/Meta';
import store from "../app/store";
import InvitePage from "./invite";
import SettingPage from "./setting";
import SettingChannelPage from "./settingChannel";
import toast from "react-hot-toast";
import ResourceManagement from "./resources";
import store from '../app/store';
import InvitePage from './invite';
import SettingPage from './setting';
import SettingChannelPage from './settingChannel';
import toast from 'react-hot-toast';
import ResourceManagement from './resources';
const PageRoutes = () => {
const {
ui: { online },
fileMessages,
} = useSelector((store) => {
return { ui: store.ui, fileMessages: store.fileMessage };
});
// 掉线检测
useEffect(() => {
let toastId = 0;
if (!online) {
toast.error("Network Offline!", { duration: Infinity });
} else {
toast.dismiss(toastId);
}
}, [online]);
const {
ui: { online },
fileMessages
} = useSelector((store) => {
return { ui: store.ui, fileMessages: store.fileMessage };
});
// 掉线检测
useEffect(() => {
let toastId = 0;
if (!online) {
toast.error('Network Offline!', { duration: Infinity });
} else {
toast.dismiss(toastId);
}
}, [online]);
return (
<HashRouter>
<Routes>
<Route
path="/oauth/:token"
element={
<RequireNoAuth>
<OAuthPage />
</RequireNoAuth>
}
/>
<Route
path="/login"
element={
<RequireNoAuth>
<LoginPage />
</RequireNoAuth>
}
/>
<Route path="/invite" element={<InvitePage />} />
<Route
path="/"
element={
<RequireAuth>
<HomePage />
</RequireAuth>
}
>
<Route path="setting">
<Route index element={<SettingPage />} />
<Route path="channel/:cid" element={<SettingChannelPage />} />
</Route>
<Route index element={<ChatPage />} />
<Route path="chat">
<Route index element={<ChatPage />} />
<Route path="channel/:channel_id" element={<ChatPage />} />
<Route path="dm/:user_id" element={<ChatPage />} />
</Route>
<Route path="contacts">
<Route index element={<ContactsPage />} />
<Route path=":user_id" element={<ContactsPage />} />
</Route>
<Route path="favs" element={<FavoritesPage />}></Route>
<Route
path="files"
element={<ResourceManagement fileMessages={fileMessages} />}
></Route>
</Route>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</HashRouter>
);
return (
<HashRouter>
<Routes>
<Route path="/oauth/:token" element={<OAuthPage />} />
<Route
path="/login"
element={
<RequireNoAuth>
<LoginPage />
</RequireNoAuth>
}
/>
<Route path="/invite" element={<InvitePage />} />
<Route
path="/"
element={
<RequireAuth>
<HomePage />
</RequireAuth>
}
>
<Route path="setting">
<Route index element={<SettingPage />} />
<Route path="channel/:cid" element={<SettingChannelPage />} />
</Route>
<Route index element={<ChatPage />} />
<Route path="chat">
<Route index element={<ChatPage />} />
<Route path="channel/:channel_id" element={<ChatPage />} />
<Route path="dm/:user_id" element={<ChatPage />} />
</Route>
<Route path="contacts">
<Route index element={<ContactsPage />} />
<Route path=":user_id" element={<ContactsPage />} />
</Route>
<Route path="favs" element={<FavoritesPage />}></Route>
<Route path="files" element={<ResourceManagement fileMessages={fileMessages} />}></Route>
</Route>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</HashRouter>
);
};
// const local_key = "AUTH_DATA";
export default function ReduxRoutes() {
// const [authData, setAuthData] = useState(
// JSON.parse(localStorage.getItem(local_key))
// );
// const updateAuthData = (data) => {
// localStorage.setItem(local_key, JSON.stringify(data));
// setAuthData(data);
// };
return (
<Provider store={store}>
{/* <PersistGate loading={null} persistor={persistStore(store)}> */}
<Meta />
<PageRoutes />
{/* </PersistGate> */}
</Provider>
);
// const [authData, setAuthData] = useState(
// JSON.parse(localStorage.getItem(local_key))
// );
// const updateAuthData = (data) => {
// localStorage.setItem(local_key, JSON.stringify(data));
// setAuthData(data);
// };
return (
<Provider store={store}>
{/* <PersistGate loading={null} persistor={persistStore(store)}> */}
<Meta />
<PageRoutes />
{/* </PersistGate> */}
</Provider>
);
}
+96 -43
View File
@@ -1,54 +1,107 @@
// import React from "react";
import styled from "styled-components";
import { useEffect } from 'react';
import styled from 'styled-components';
import { hideAll } from 'tippy.js';
const StyledConfirm = styled.div`
padding: 12px;
border-radius: 10px;
border: 1px solid orange;
background-color: #fff;
display: flex;
flex-direction: column;
gap: 10px;
width: 250px;
.tip {
/* word-break: break-all; */
color: orange;
font-size: 12px;
line-height: 1.5;
}
.btns {
display: flex;
width: 100%;
justify-content: flex-end;
gap: 14px;
}
`;
const Styled = styled.div`
max-width: 500px;
max-width: 500px;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 15px;
> .input {
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 15px;
.input {
width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
label {
white-space: nowrap;
font-size: 14px;
color: #555;
}
}
.tip {
font-size: 12px;
color: #999;
line-height: 1.5;
gap: 8px;
label {
white-space: nowrap;
font-size: 14px;
color: #555;
}
}
> .tip {
font-size: 12px;
color: #999;
line-height: 1.5;
}
`;
import Input from "../../common/component/styled/Input";
import Button from "../../common/component/styled/Button";
import Input from '../../common/component/styled/Input';
import Button from '../../common/component/styled/Button';
import {
useGetThirdPartySecretQuery,
useUpdateThirdPartySecretMutation,
} from "../../app/services/server";
useGetThirdPartySecretQuery,
useUpdateThirdPartySecretMutation
} from '../../app/services/server';
import Tippy from '@tippyjs/react';
import toast from 'react-hot-toast';
export default function APIConfig() {
const { data } = useGetThirdPartySecretQuery();
const [
updateSecret,
{ data: updatedSecret },
] = useUpdateThirdPartySecretMutation();
console.log("secret", data);
return (
<Styled>
<div className="input">
<label htmlFor="secret">API Secure Key:</label>
<Input type="password" id="secret" value={updatedSecret || data} />
</div>
<Button onClick={updateSecret}>Update Secret</Button>
const { data } = useGetThirdPartySecretQuery();
const [updateSecret, { data: updatedSecret, isSuccess, isLoading }] =
useUpdateThirdPartySecretMutation();
console.log('secret', data);
useEffect(() => {
if (isSuccess) {
hideAll();
toast.success('Update API Secret Successfully!');
}
}, [isSuccess]);
return (
<Styled>
<div className="input">
<label htmlFor="secret">API Secure Key:</label>
<Input type="password" id="secret" value={updatedSecret || data} />
</div>
<Tippy
delay={[0, 0]}
duration={0}
interactive
placement="right-start"
trigger="click"
content={
<StyledConfirm>
<div className="tip">
Tip: The security key agreed between the rustchat server and the
third-party app is used to encrypt the communication data.{" "}
Are you sure to update API secret? Previous secret will be invalided
</div>
</Styled>
);
<div className="btns">
<Button onClick={hideAll} className="cancel small">
Cancel
</Button>
<Button disabled={isLoading} className="small danger" onClick={updateSecret}>
Yes
</Button>
</div>
</StyledConfirm>
}
>
<Button>Update Secret</Button>
</Tippy>
<div className="tip">
Tip: The security key agreed between the rustchat server and the third-party app is used to
encrypt the communication data.{' '}
</div>
</Styled>
);
}