Mention users in comments (#429)

Mention users in comments (#429)
This commit is contained in:
MrPercheul 2022-06-01 13:23:21 +02:00 committed by GitHub
parent cbc9633fe2
commit f6a78dd0b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 194 additions and 24 deletions

View File

@ -86,6 +86,7 @@ MAX_MEDIA_PER_PLAYLIST = 70
UPLOAD_MAX_SIZE = 800 * 1024 * 1000 * 5
MAX_CHARS_FOR_COMMENT = 10000 # so that it doesn't end up huge
ALLOW_MENTION_IN_COMMENTS = False # allowing to mention other users with @ in the comments
# valid options: content, author
RELATED_MEDIA_STRATEGY = "content"

BIN
docs/images/Mention1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
docs/images/Mention2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

BIN
docs/images/Mention3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
docs/images/Mention4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -5,7 +5,8 @@
- [Downloading media](#downloading-media)
- [Adding captions/subtitles](#adding-captionssubtitles)
- [Search media](#search-media)
- [Using Timestamps for sharing](#using-timestamps-for-sharing)
- [Using Timestamps for sharing](#-using-timestamps-for-sharing)
- [Mentionning users in comments](#Mentionning-users-in-comments)
- [Share media](#share-media)
- [Embed media](#embed-media)
- [Customize my profile options](#customize-my-profile-options)
@ -220,6 +221,19 @@ Comments can also include timestamps. They are automatically detected upon posti
<img src="./images/Demo3.png"/>
</p>
## Mentionning users in comments
Comments can also mention other users by tagging with '@'. This will open suggestion box showing usernames, and the selection will refine as the user continues typing.
Comments send with mentions will contain a link to the user page, and can be setup to send a mail to the mentionned user.
<p align="left">
<img src="./images/Mention1.png"/>
<img src="./images/Mention2.png"/>
<img src="./images/Mention3.png"/>
<img src="./images/Mention4.png"/>
</p>
## Search media
How search can be used

View File

@ -13,6 +13,7 @@ def stuff(request):
ret["CAN_LOGIN"] = settings.LOGIN_ALLOWED
ret["CAN_REGISTER"] = settings.REGISTER_ALLOWED
ret["CAN_UPLOAD_MEDIA"] = settings.UPLOAD_MEDIA_ALLOWED
ret["CAN_MENTION_IN_COMMENTS"] = settings.ALLOW_MENTION_IN_COMMENTS
ret["CAN_LIKE_MEDIA"] = settings.CAN_LIKE_MEDIA
ret["CAN_DISLIKE_MEDIA"] = settings.CAN_DISLIKE_MEDIA
ret["CAN_REPORT_MEDIA"] = settings.CAN_REPORT_MEDIA

View File

@ -4,6 +4,7 @@
import itertools
import logging
import random
import re
from datetime import datetime
from django.conf import settings
@ -324,8 +325,6 @@ def update_user_ratings(user, media, user_ratings):
def notify_user_on_comment(friendly_token):
"""Notify users through email, for a set of actions"""
media = None
media = models.Media.objects.filter(friendly_token=friendly_token).first()
if not media:
return False
@ -347,6 +346,55 @@ View it on %s
return True
def notify_user_on_mention(friendly_token, user_mentioned, cleaned_comment):
from users.models import User
media = models.Media.objects.filter(friendly_token=friendly_token).first()
if not media:
return False
user = User.objects.filter(username=user_mentioned).first()
media_url = settings.SSL_FRONTEND_HOST + media.get_absolute_url()
if user.notification_on_comments:
title = "[{}] - You were mentioned in a comment".format(settings.PORTAL_NAME)
msg = """
You were mentioned in a comment on %s .
View it on %s
Comment : %s
""" % (
media.title,
media_url,
cleaned_comment,
)
email = EmailMessage(title, msg, settings.DEFAULT_FROM_EMAIL, [user.email])
email.send(fail_silently=True)
return True
def check_comment_for_mention(friendly_token, comment_text):
"""Check the comment for any mentions, and notify each mentioned users"""
cleaned_comment = ''
matches = re.findall('@\\(_(.+?)_\\)', comment_text)
if matches:
cleaned_comment = clean_comment(comment_text)
for match in list(dict.fromkeys(matches)):
notify_user_on_mention(friendly_token, match, cleaned_comment)
def clean_comment(raw_comment):
"""Clean the comment fromn ID and username Mentions for preview purposes"""
cleaned_comment = re.sub('@\\(_(.+?)_\\)', '', raw_comment)
cleaned_comment = cleaned_comment.replace("[_", '')
cleaned_comment = cleaned_comment.replace("_]", '')
return cleaned_comment
def list_tasks():
"""Lists celery tasks
To be used in an admin dashboard

View File

@ -32,6 +32,7 @@ from users.models import User
from .forms import ContactForm, MediaForm, SubtitleForm
from .helpers import clean_query, produce_ffmpeg_commands
from .methods import (
check_comment_for_mention,
get_user_or_session,
is_mediacms_editor,
is_mediacms_manager,
@ -1277,6 +1278,9 @@ class CommentDetail(APIView):
serializer.save(user=request.user, media=media)
if request.user != media.user:
notify_user_on_comment(friendly_token=media.friendly_token)
# here forward the comment to check if a user was mentioned
if settings.ALLOW_MENTION_IN_COMMENTS:
check_comment_for_mention(friendly_token=media.friendly_token, comment_text=serializer.data['text'])
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

View File

@ -46,6 +46,7 @@
"normalize.css": "^8.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-mentions": "^4.3.1",
"sortablejs": "^1.13.0",
"timeago.js": "^4.0.2",
"url-parse": "^1.5.1"

View File

@ -94,6 +94,7 @@ body.dark_theme {
--comment-date-hover-text-color: #fff;
--comment-text-color: rgba(255, 255, 255, 0.88);
--comment-text-mentions-background-color-highlight:#006622;
--comment-actions-material-icon-text-color: rgba(255, 255, 255, 0.74);

View File

@ -94,6 +94,7 @@ body {
--comment-date-hover-text-color: #0a0a0a;
--comment-text-color: #111;
--comment-text-mentions-background-color-highlight:#00cc44;
--comment-actions-material-icon-text-color: rgba(17, 17, 17, 0.8);

View File

@ -1,4 +1,5 @@
import React, { useState, useRef, useEffect } from 'react';
import { MentionsInput, Mention } from 'react-mentions';
import PropTypes from 'prop-types';
import { format } from 'timeago.js';
import { usePopup } from '../../utils/hooks/';
@ -25,6 +26,7 @@ function CommentForm(props) {
const [madeChanges, setMadeChanges] = useState(false);
const [textareaFocused, setTextareaFocused] = useState(false);
const [textareaLineHeight, setTextareaLineHeight] = useState(-1);
const [userList, setUsersList] = useState('');
const [loginUrl] = useState(
!MemberContext._currentValue.is.anonymous
@ -42,6 +44,17 @@ function CommentForm(props) {
setTextareaFocused(false);
}
function onUsersLoad()
{
const userList =[...MediaPageStore.get('users')];
const cleanList = []
userList.forEach(user => {
cleanList.push({id : user.username, display : user.name});
});
setUsersList(cleanList);
}
function onCommentSubmit() {
textareaRef.current.style.height = '';
@ -61,6 +74,21 @@ function CommentForm(props) {
setMadeChanges(false);
}
function onChangeWithMention(event, newValue, newPlainTextValue, mentions) {
textareaRef.current.style.height = '';
setValue(newValue);
setMadeChanges(true);
const contentHeight = textareaRef.current.scrollHeight;
const contentLineHeight =
0 < textareaLineHeight ? textareaLineHeight : parseFloat(window.getComputedStyle(textareaRef.current).lineHeight);
setTextareaLineHeight(contentLineHeight);
textareaRef.current.style.height =
Math.max(20, textareaLineHeight * Math.ceil(contentHeight / contentLineHeight)) + 'px';
}
function onChange(event) {
textareaRef.current.style.height = '';
@ -81,7 +109,7 @@ function CommentForm(props) {
return;
}
const val = textareaRef.current.value.trim();
const val = value.trim();
if ('' !== val) {
MediaPageActions.submitComment(val);
@ -91,10 +119,18 @@ function CommentForm(props) {
useEffect(() => {
MediaPageStore.on('comment_submit', onCommentSubmit);
MediaPageStore.on('comment_submit_fail', onCommentSubmitFail);
if (MediaCMS.features.media.actions.comment_mention === true)
{
MediaPageStore.on('users_load', onUsersLoad);
}
return () => {
MediaPageStore.removeListener('comment_submit', onCommentSubmit);
MediaPageStore.removeListener('comment_submit_fail', onCommentSubmitFail);
if (MediaCMS.features.media.actions.comment_mention === true)
{
MediaPageStore.removeListener('users_load', onUsersLoad);
}
};
});
@ -104,6 +140,22 @@ function CommentForm(props) {
<UserThumbnail />
<div className="form">
<div className={'form-textarea-wrap' + (textareaFocused ? ' focused' : '')}>
{ MediaCMS.features.media.actions.comment_mention ?
<MentionsInput
inputRef={textareaRef}
className="form-textarea"
rows="1"
placeholder={'Add a ' + commentsText.single + '...'}
value={value}
onChange={onChangeWithMention}
onFocus={onFocus}
onBlur={onBlur}>
<Mention
data={userList}
markup="@(___id___)[___display___]"
/>
</MentionsInput>
:
<textarea
ref={textareaRef}
className="form-textarea"
@ -114,6 +166,7 @@ function CommentForm(props) {
onFocus={onFocus}
onBlur={onBlur}
></textarea>
}
</div>
<div className="form-buttons">
<button className={'' === value.trim() ? 'disabled' : ''} onClick={submitComment}>
@ -236,6 +289,10 @@ function Comment(props) {
};
}, []);
function parseComment(text) {
return { __html: text.replace(/\n/g, `<br />`) };
}
return (
<div className="comment">
<div className="comment-inner">
@ -255,7 +312,7 @@ function Comment(props) {
<div
ref={commentTextInnerRef}
className="comment-text-inner"
dangerouslySetInnerHTML={{ __html: props.text }}
dangerouslySetInnerHTML={parseComment(props.text)}
></div>
</div>
{enabledViewMoreContent ? (
@ -370,6 +427,12 @@ export default function CommentsList(props) {
function onCommentsLoad() {
const retrievedComments = [...MediaPageStore.get('media-comments')];
if (MediaCMS.features.media.actions.comment_mention === true)
{
retrievedComments.forEach(comment => {
comment.text = setMentions(comment.text);
});
}
retrievedComments.forEach(comment => {
comment.text = setTimestampAnchors(comment.text);
});
@ -378,6 +441,13 @@ export default function CommentsList(props) {
setComments(retrievedComments);
}
function setMentions(text)
{
let sanitizedComment = text.split('@(_').join("<a href=\"/user/");
sanitizedComment = sanitizedComment.split('_)[_').join("\">");
return sanitizedComment.split('_]').join("</a>");
}
function setTimestampAnchors(text)
{
function wrapTimestampWithAnchor(match, string)

View File

@ -2,7 +2,7 @@
.comments-form-inner {
.form {
.form-textarea-wrap {
.form-textarea-wrap{
border-color: var(--comments-textarea-wrapper-border-color);
&:after {
@ -10,13 +10,20 @@
}
}
.form-textarea {
.form-textarea, .form-textarea__input, .form-textarea__suggestions__list {
color: var(--comments-textarea-text-color);
&:placeholder {
color: var(--comments-textarea-text-placeholder-color);
}
}
.form-textarea__suggestions__list {
background-color: var(--body-bg-color);
}
strong {
background-color: var(--comment-text-mentions-background-color-highlight)
}
}
}
@ -160,7 +167,7 @@
}
}
.form-textarea {
.form-textarea, .form-textarea__input {
position: relative;
resize: none;
display: block;
@ -204,7 +211,7 @@
text-decoration: none;
.form-textarea {
.form-textarea, .form-textarea__input {
opacity: 0.5;
}
}

View File

@ -18,6 +18,7 @@ export function init(user, features) {
deleteProfile: false,
readComment: true,
addComment: false,
mentionComment: false,
deleteComment: false,
editMedia: false,
deleteMedia: false,
@ -60,6 +61,7 @@ export function init(user, features) {
MEMBER.can.deleteProfile = true === user.can.deleteProfile;
MEMBER.can.addComment = true === user.can.addComment;
MEMBER.can.mentionComment = true === user.can.mentionComment;
MEMBER.can.deleteComment = true === user.can.deleteComment;
MEMBER.can.editMedia = true === user.can.editMedia;
MEMBER.can.deleteMedia = true === user.can.deleteMedia;
@ -100,6 +102,7 @@ export function init(user, features) {
const mediaActions = features.media.actions;
MEMBER.can.addComment = MEMBER.can.addComment && true === mediaActions.comment;
MEMBER.can.mentionComment = MEMBER.can.mentionComment && true === mediaActions.comment_mention;
MEMBER.can.likeMedia = false === mediaActions.like ? false : true;
MEMBER.can.dislikeMedia = false === mediaActions.dislike ? false : true;

View File

@ -51,6 +51,7 @@ class MediaPageStore extends EventEmitter {
this.pagePlaylistId = null;
this.pagePlaylistData = null;
this.userList = null;
MediaPageStoreData[
Object.defineProperty(this, 'id', { value: 'MediaPageStoreData_' + Object.keys(MediaPageStoreData).length }).id
@ -158,6 +159,12 @@ class MediaPageStore extends EventEmitter {
getRequest(this.commentsAPIUrl, !1, this.commentsResponse);
}
loadUsers() {
this.usersAPIUrl = this.mediacms_config.api.users;
this.usersResponse = this.usersResponse.bind(this);
getRequest(this.usersAPIUrl, !1, this.usersResponse);
}
loadPlaylists() {
if (!this.mediacms_config.member.can.saveMedia) {
return;
@ -187,6 +194,7 @@ class MediaPageStore extends EventEmitter {
}
this.loadPlaylists();
this.loadUsers();
if (this.mediacms_config.member.can.readComment) {
this.loadComments();
@ -215,6 +223,13 @@ class MediaPageStore extends EventEmitter {
}
}
usersResponse(response) {
if (response && response.data) {
MediaPageStoreData.userList = response.data.count ? response.data.results : [];
this.emit('users_load');
}
}
playlistsResponse(response) {
if (response && response.data) {
let tmp_playlists = response.data.count ? response.data.results : [];
@ -403,6 +418,9 @@ class MediaPageStore extends EventEmitter {
i,
r = null;
switch (type) {
case 'users':
r = MediaPageStoreData.userList || [];
break;
case 'playlists':
r = MediaPageStoreData[this.id].playlists || [];
break;

View File

@ -22,6 +22,7 @@ MediaCMS.features = {
dislike: {% if CAN_DISLIKE_MEDIA %}true{% else %}false{% endif %},
download: true,
comment: true,
comment_mention: {% if CAN_MENTION_IN_COMMENTS %}true{% else %}false{% endif %},
save: true,
},
shareOptions: [ 'embed', 'fb', 'tw', 'whatsapp', 'telegram', 'reddit', 'tumblr', 'vk', 'pinterest', 'mix', 'linkedin', 'email' ],