add route and action to leave DM channel

This commit is contained in:
HF 2020-11-26 00:17:23 +01:00
parent f42078853a
commit ab910619f8
14 changed files with 254 additions and 76 deletions

View File

@ -118,3 +118,32 @@ export async function requestBlockDm(block: boolean) {
return 'Connection Error'; return 'Connection Error';
} }
} }
/*
* leaving Chat Channel (i.e. DM channel)
* channelId 8nteger id of channel
* return error string or null if successful
*/
export async function requestLeaveChan(channelId: boolean) {
const response = await fetchWithTimeout('api/leavechan', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ channelId }),
});
try {
const res = await response.json();
if (res.errors) {
return res.errors[0];
}
if (response.ok && res.status === 'ok') {
return null;
}
return 'Unknown Error';
} catch {
return 'Connection Error';
}
}

View File

@ -11,6 +11,7 @@ import {
requestStartDm, requestStartDm,
requestBlock, requestBlock,
requestBlockDm, requestBlockDm,
requestLeaveChan,
} from './fetch'; } from './fetch';
export function sweetAlert( export function sweetAlert(
@ -760,10 +761,10 @@ export function showChatModal(forceModal: boolean = false): Action {
return showModal('CHAT'); return showModal('CHAT');
} }
export function setChatChannel(channelId: number): Action { export function setChatChannel(cid: number): Action {
return { return {
type: 'SET_CHAT_CHANNEL', type: 'SET_CHAT_CHANNEL',
channelId, cid,
}; };
} }
@ -797,6 +798,13 @@ export function blockingDm(blockDm: boolean): Action {
}; };
} }
export function removeChatChannel(cid: number): Action {
return {
type: 'REMOVE_CHAT_CHANNEL',
cid,
};
}
/* /*
* query: Object with either userId: number or userName: string * query: Object with either userId: number or userName: string
*/ */
@ -812,10 +820,10 @@ export function startDm(query): PromiseAction {
'OK', 'OK',
)); ));
} else { } else {
const channelId = res[0]; const cid = res[0];
if (channelId) { if (cid) {
dispatch(addChatChannel(res)); dispatch(addChatChannel(res));
dispatch(setChatChannel(channelId)); dispatch(setChatChannel(cid));
} }
} }
dispatch(setApiFetching(false)); dispatch(setApiFetching(false));
@ -866,6 +874,26 @@ export function setBlockingDm(
}; };
} }
export function setLeaveChannel(
cid: number,
) {
return async (dispatch) => {
dispatch(setApiFetching(true));
const res = await requestLeaveChan(cid);
if (res) {
dispatch(sweetAlert(
'Leaving Channel Error',
res,
'error',
'OK',
));
} else {
dispatch(removeChatChannel(cid));
}
dispatch(setApiFetching(false));
};
}
export function hideModal(): Action { export function hideModal(): Action {
return { return {
type: 'HIDE_MODAL', type: 'HIDE_MODAL',

View File

@ -69,8 +69,9 @@ export type Action =
isPing: boolean, isPing: boolean,
} }
| { type: 'RECEIVE_CHAT_HISTORY', cid: number, history: Array } | { type: 'RECEIVE_CHAT_HISTORY', cid: number, history: Array }
| { type: 'SET_CHAT_CHANNEL', channelId: number } | { type: 'SET_CHAT_CHANNEL', cid: number }
| { type: 'ADD_CHAT_CHANNEL', channel: Array } | { type: 'ADD_CHAT_CHANNEL', channel: Array }
| { type: 'REMOVE_CHAT_CHANNEL', cid: number }
| { type: 'SET_CHAT_FETCHING', fetching: boolean } | { type: 'SET_CHAT_FETCHING', fetching: boolean }
| { type: 'SET_CHAT_INPUT_MSG', message: string } | { type: 'SET_CHAT_INPUT_MSG', message: string }
| { type: 'ADD_CHAT_INPUT_MSG', message: string } | { type: 'ADD_CHAT_INPUT_MSG', message: string }

View File

@ -10,6 +10,7 @@ import { connect } from 'react-redux';
import { import {
hideContextMenu, hideContextMenu,
setLeaveChannel,
} from '../actions'; } from '../actions';
import type { State } from '../reducers'; import type { State } from '../reducers';
@ -18,6 +19,7 @@ const UserContextMenu = ({
yPos, yPos,
cid, cid,
channels, channels,
leave,
close, close,
}) => { }) => {
const wrapperRef = useRef(null); const wrapperRef = useRef(null);
@ -29,13 +31,14 @@ const UserContextMenu = ({
close(); close();
} }
}; };
const handleWindowResize = () => close();
document.addEventListener('mousedown', handleClickOutside); document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('touchstart', handleClickOutside); document.addEventListener('touchstart', handleClickOutside);
window.addEventListener('resize', handleClickOutside); window.addEventListener('resize', handleWindowResize);
return () => { return () => {
document.removeEventListener('mousedown', handleClickOutside); document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('touchstart', handleClickOutside); document.removeEventListener('touchstart', handleClickOutside);
window.removeEventListener('resize', handleClickOutside); window.removeEventListener('resize', handleWindowResize);
}; };
}, [wrapperRef]); }, [wrapperRef]);
@ -62,16 +65,19 @@ const UserContextMenu = ({
top: yPos, top: yPos,
}} }}
> >
<div <div>
style={{ borderBottom: 'thin solid' }}
>
Mute Mute
</div> </div>
{(channelArray[2] !== 0) {(channelArray[2] !== 0)
&& ( && (
<div <div
role="button" role="button"
onClick={() => {
leave(cid);
close();
}}
tabIndex={0} tabIndex={0}
style={{ borderTop: 'thin solid' }}
> >
Close Close
</div> </div>
@ -105,6 +111,9 @@ function mapDispatchToProps(dispatch) {
close() { close() {
dispatch(hideContextMenu()); dispatch(hideContextMenu());
}, },
leave(cid) {
dispatch(setLeaveChannel(cid));
},
}; };
} }

View File

@ -19,6 +19,7 @@ import {
const ChannelDropDown = ({ const ChannelDropDown = ({
channels, channels,
chatChannel, chatChannel,
chatRead,
setChannel, setChannel,
}) => { }) => {
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
@ -75,66 +76,79 @@ const ChannelDropDown = ({
> >
{chatChannelName} {chatChannelName}
</div> </div>
<div {(show)
ref={wrapperRef} && (
style={{
position: 'absolute',
bottom: offset + 5,
right: 9,
display: (show) ? 'initial' : 'none',
}}
className="channeldd"
>
<div>
<span
onClick={() => setType(0)}
>
<MdChat />
</span>
|
<span
onClick={() => setType(1)}
>
<FaUserFriends />
</span>
</div>
<div <div
className="channeldds" ref={wrapperRef}
style={{
position: 'absolute',
bottom: offset + 5,
right: 9,
}}
className="channeldd"
> >
{ <div>
channels.filter((ch) => { <span
const chType = ch[2]; onClick={() => setType(0)}
if (type === 1 && chType === 1) { >
return true; <MdChat />
} </span>
if (type === 0 && chType !== 1) { |
return true; <span
} onClick={() => setType(1)}
return false; >
}).map((ch) => ( <FaUserFriends />
<div </span>
onClick={() => setChannel(ch[0])} </div>
style={(ch[0] === chatChannel) ? { <div
fontWeight: 'bold', className="channeldds"
fontSize: 17, >
} : null} {
> channels.filter((ch) => {
{ch[1]} const chType = ch[2];
</div> if (type === 1 && chType === 1) {
)) return true;
} }
if (type === 0 && chType !== 1) {
return true;
}
return false;
}).map((ch) => (
<div
onClick={() => setChannel(ch[0])}
style={(ch[0] === chatChannel) ? {
fontWeight: 'bold',
fontSize: 17,
} : null}
className={
`chn${
(ch[0] === chatChannel) ? ' selected' : ''
}${
(chatRead[ch[0]] < ch[3]) ? ' unread' : ''
}`
}
>
{ch[1]}
</div>
))
}
</div>
</div> </div>
</div> )}
</div> </div>
); );
}; };
function mapStateToProps(state: State) { function mapStateToProps(state: State) {
const { chatChannel } = state.gui; const {
chatChannel,
chatRead,
} = state.gui;
const { channels } = state.chat; const { channels } = state.chat;
return { return {
channels, channels,
chatChannel, chatChannel,
chatRead,
}; };
} }

View File

@ -35,13 +35,14 @@ const UserContextMenu = ({
close(); close();
} }
}; };
const handleWindowResize = () => close();
document.addEventListener('mousedown', handleClickOutside); document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('touchstart', handleClickOutside); document.addEventListener('touchstart', handleClickOutside);
window.addEventListener('resize', handleClickOutside); window.addEventListener('resize', handleWindowResize);
return () => { return () => {
document.removeEventListener('mousedown', handleClickOutside); document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('touchstart', handleClickOutside); document.removeEventListener('touchstart', handleClickOutside);
window.removeEventListener('resize', handleClickOutside); window.removeEventListener('resize', handleWindowResize);
}; };
}, [wrapperRef]); }, [wrapperRef]);

View File

@ -54,18 +54,12 @@ export class ChatProvider {
const { name } = CHAT_CHANNELS[i]; const { name } = CHAT_CHANNELS[i];
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const channel = await Channel.findOrCreate({ const channel = await Channel.findOrCreate({
attributes: [
'id',
'type',
'lastMessage',
],
where: { name }, where: { name },
defaults: { defaults: {
name, name,
}, },
raw: true,
}); });
const { id, type, lastMessage } = channel[0]; const { id, type, lastTs } = channel[0];
if (name === 'int') { if (name === 'int') {
this.intChannelId = id; this.intChannelId = id;
} }
@ -76,7 +70,7 @@ export class ChatProvider {
id, id,
name, name,
type, type,
lastMessage, lastTs,
]); ]);
this.defaultChannelIds.push(id); this.defaultChannelIds.push(id);
} }

View File

@ -43,6 +43,17 @@ const Channel = Model.define('Channel', {
}, },
}, { }, {
updatedAt: false, updatedAt: false,
getterMethods: {
lastTs(): number {
return new Date(this.lastMessage).valueOf();
},
},
setterMethods: {
lastTs(ts: number) {
this.setDataValue('lastMessage', new Date(ts).toISOString());
},
},
}); });
/* /*

View File

@ -60,7 +60,7 @@ class User {
const { const {
id, id,
type, type,
lastMessage, lastTs,
dmu1, dmu1,
dmu2, dmu2,
} = reguser.channel[i]; } = reguser.channel[i];
@ -74,7 +74,7 @@ class User {
id, id,
name, name,
type, type,
lastMessage, lastTs,
]); ]);
} }
} }

View File

@ -8,7 +8,7 @@ export type ChatState = {
inputMessage: string, inputMessage: string,
// [[cid, name, type, lastMessage], [cid2, name2, type2, lastMessage2],...] // [[cid, name, type, lastMessage], [cid2, name2, type2, lastMessage2],...]
channels: Array, channels: Array,
// [[userId, userName], [userId2, userName2],...] // [[uId, userName], [userId2, userName2],...]
blocked: Array, blocked: Array,
// { cid: [message1,message2,message3,...]} // { cid: [message1,message2,message3,...]}
messages: Object, messages: Object,
@ -56,9 +56,9 @@ export default function chat(
case 'ADD_CHAT_CHANNEL': { case 'ADD_CHAT_CHANNEL': {
const { channel } = action; const { channel } = action;
const channelId = channel[0]; const cid = channel[0];
const channels = state.channels const channels = state.channels
.filter((ch) => (ch[0] !== channelId)); .filter((ch) => (ch[0] !== cid));
channels.push(channel); channels.push(channel);
return { return {
...state, ...state,
@ -66,6 +66,18 @@ export default function chat(
}; };
} }
case 'REMOVE_CHAT_CHANNEL': {
const { cid } = action;
const channels = state.channels.filter(
// eslint-disable-next-line eqeqeq
(chan) => (chan[0] != cid),
);
return {
...state,
channels,
};
}
case 'SET_CHAT_INPUT_MSG': { case 'SET_CHAT_INPUT_MSG': {
const { message } = action; const { message } = action;
return { return {

View File

@ -16,6 +16,9 @@ export type GUIState = {
paletteOpen: boolean, paletteOpen: boolean,
menuOpen: boolean, menuOpen: boolean,
chatChannel: number, chatChannel: number,
// timestamps of last read post per channel
// { 1: Date.now() }
chatRead: {},
style: string, style: string,
}; };
@ -31,6 +34,7 @@ const initialState: GUIState = {
paletteOpen: true, paletteOpen: true,
menuOpen: false, menuOpen: false,
chatChannel: 1, chatChannel: 1,
chatRead: {},
style: 'default', style: 'default',
}; };
@ -107,7 +111,7 @@ export default function gui(
case 'SET_CHAT_CHANNEL': { case 'SET_CHAT_CHANNEL': {
return { return {
...state, ...state,
chatChannel: action.channelId, chatChannel: action.cid,
}; };
} }

View File

@ -19,6 +19,7 @@ import ranking from './ranking';
import history from './history'; import history from './history';
import chatHistory from './chathistory'; import chatHistory from './chathistory';
import startDm from './startdm'; import startDm from './startdm';
import leaveChan from './leavechan';
import block from './block'; import block from './block';
import blockdm from './blockdm'; import blockdm from './blockdm';
@ -85,6 +86,8 @@ router.get('/chathistory', chatHistory);
router.post('/startdm', startDm); router.post('/startdm', startDm);
router.post('/leavechan', leaveChan);
router.post('/block', block); router.post('/block', block);
router.post('/blockdm', blockdm); router.post('/blockdm', blockdm);

View File

@ -0,0 +1,72 @@
/*
*
* starts a DM session
*
* @flow
*/
import type { Request, Response } from 'express';
import logger from '../../core/logger';
async function leaveChan(req: Request, res: Response) {
const channelId = parseInt(req.body.channelId, 10);
const { user } = req;
const errors = [];
if (channelId && Number.isNaN(channelId)) {
errors.push('Invalid channelId');
}
if (!user || !user.regUser) {
errors.push('You are not logged in');
}
if (errors.length) {
res.status(400);
res.json({
errors,
});
return;
}
const userChannels = user.regUser.channel;
let channel = null;
for (let i = 0; i < userChannels.length; i += 1) {
if (userChannels[i].id === channelId) {
channel = userChannels[i];
break;
}
}
if (!channel) {
res.status(401);
res.json({
errors: ['You are not in this channel'],
});
return;
}
/*
* Just supporting DMs by now, because
* Channels do not get deleted when all Users left.
* Group Channels need this.
* Faction and Default channels should be impossible to leave
*/
if (channel.type !== 1) {
res.status(401);
res.json({
errors: ['Can not leave this channel'],
});
return;
}
logger.info(
`Removing user ${user.getName()} from channel ${channel.name || channelId}`,
);
user.regUser.removeChannel(channel);
// TODO: inform websocket to remove channelId from user
res.json({
status: 'ok',
});
}
export default leaveChan;

View File

@ -194,7 +194,7 @@ app.get('/', async (req, res) => {
// ip config // ip config
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// use this if models changed: // use this if models changed:
const promise = models.sync({ alter: { drop: false } }) const promise = models.sync({ alter: { drop: true } })
// const promise = models.sync() // const promise = models.sync()
.catch((err) => logger.error(err.stack)); .catch((err) => logger.error(err.stack));
promise.then(() => { promise.then(() => {