1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-08 18:30:53 +00:00

Add popup notices (#3130)

* popup notice

* update notice detail

* update notice implement logic

* optimized code

* optimzied code

* repair bug

* mark click item as read

* delete to_user

* update api

* refactor code

* update api

* update message

* fix repo share bug

* delete unnecessary code
This commit is contained in:
杨顺强
2019-03-25 10:24:49 +08:00
committed by Daniel Pan
parent bcf1279905
commit 8321d3a530
4 changed files with 508 additions and 15 deletions

View File

@@ -0,0 +1,219 @@
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { gettext, siteRoot } from '../../utils/constants';
import { Utils } from '../../utils/utils';
const propTypes = {
noticeItem: PropTypes.object.isRequired,
onNoticeItemClick: PropTypes.func.isRequired,
};
const MSG_TYPE_ADD_USER_TO_GROUP = 'add_user_to_group'
const MSG_TYPE_REPO_SHARE = 'repo_share'
const MSG_TYPE_REPO_SHARE_TO_GROUP = 'repo_share_to_group'
const MSG_TYPE_REPO_TRANSFER = 'repo_transfer'
const MSG_TYPE_FILE_UPLOADED = 'file_uploaded'
const MSG_TYPE_FILE_COMMENT = 'file_comment'
const MSG_TYPE_DRAFT_COMMENT = 'draft_comment'
const MSG_TYPE_DRAFT_REVIEWER = 'draft_reviewer'
const MSG_TYPE_GUEST_INVITATION_ACCEPTED = 'guest_invitation_accepted'
class NoticeItem extends React.Component {
generatorNoticeInfo () {
let noticeItem = this.props.noticeItem;
let noticeType = noticeItem.type;
let detail = noticeItem.detail;
if (noticeType === MSG_TYPE_ADD_USER_TO_GROUP) {
let avatar_url = detail.group_staff_avatar_url;
let groupStaff = detail.group_staff_name;
let userHref = siteRoot + 'profile/' + detail.group_staff_email + '/';
let groupHref = siteRoot + 'group/' + detail.group_id + '/';
let groupName = detail.group_name;
let notice = gettext('User {user_link} has added you to {group_link}');
let userLink = '<a href=' + userHref + '>' + groupStaff + '</a>';
let groupLink = '<a href=' + groupHref + '>' + groupName + '</a>';
notice = notice.replace('{user_link}', userLink);
notice = notice.replace('{group_link}', groupLink);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_REPO_SHARE) {
let avatar_url = detail.share_from_user_avatar_url;
let shareFrom = detail.share_from_user_name;
let repoName = detail.repo_name;
let repoUrl = siteRoot + 'library/' + detail.repo_id + '/' + repoName + '/';
let path = detail.path;
let notice = '';
let repoLink = '<a href=' + repoUrl + '>' + repoName + '</a>';
if (path === '/') { // share repo
notice = gettext('{share_from} has shared a library named {repo_link} to you.');
} else { // share folder
notice = gettext('{share_from} has shared a folder named {repo_link} to you.');
}
notice = notice.replace('{share_from}', shareFrom);
notice = notice.replace('{repo_link}', repoLink);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_REPO_SHARE_TO_GROUP) {
let avatar_url = detail.share_from_user_avatar_url;
let shareFrom = detail.share_from_user_name;
let repoName = detail.repo_name;
let repoUrl = siteRoot + 'library/' + detail.repo_id + '/' + repoName + '/';
let groupUrl = siteRoot + 'group/' + detail.group_id + '/';
let groupName = detail.group_name;
let path = detail.path;
let notice = '';
let repoLink = '<a href=' + repoUrl + '>' + repoName + '</a>';
let groupLink = '<a href=' + groupUrl + '>' + groupName + '</a>';
if (path === '/') {
notice = gettext('{share_from} has shared a library named {repo_link} to group {group_link}.');
} else {
notice = gettext('{share_from} has shared a folder named {repo_link} to group {group_link}.');
}
notice = notice.replace('{share_from}', shareFrom);
notice = notice.replace('{repo_link}', repoLink);
notice = notice.replace('{group_link}', groupLink);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_REPO_TRANSFER) {
let avatar_url = detail.transfer_from_user_avatar_url;
let repoOwner = detail.transfer_from_user_name;
let repoName = detail.repo_name;
let repoUrl = siteRoot + 'library/' + detail.repo_id + '/' + repoName + '/';
let notice = gettext('{user} has transfered a library named {repo_link} to you.');
let repoLink = '<a href=' + repoUrl + '>' + repoName + '</a>';
notice = notice.replace('{user}', repoOwner);
notice = notice.replace('{repo_link}', repoLink);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_FILE_UPLOADED) {
let avatar_url = detail.uploaded_user_avatar_url;
let fileName = detail.file_name;
let fileLink = siteRoot + 'lib/' + detail.repo_id + '/' + 'file' + Utils.encodePath(detail.file_path);
let folderName = detail.folder_name;
let folderLink = siteRoot + 'library/' + detail.repo_id + '/' + detail.repo_name + Utils.encodePath(detail.folder_path);
let notice = '';
if (detail.repo_id) { // todo is repo exist ?
let uploadFileLink = '<a href=' + fileLink + '>' + fileName + '</a>';
let uploadedLink = '<a href=' + folderLink + '>' + folderName + '</a>';
notice = gettext('A file named {upload_file_link} is uploaded to {uploaded_link}.');
notice = notice.replace('{upload_file_link}', uploadFileLink);
notice = notice.replace('{uploaded_link}', uploadedLink);
} else {
notice = gettext('A file name {file_name} is uploaded to {dest}.');
notice = notice.replace('{file_name}', fileName);
notice = notice.replace('{dest}', '<strong>Deleted Library</strong>')
}
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_FILE_COMMENT) {
let avatar_url = detail.author_avatar_url;
let author = detail.author_name;
let fileName = detail.file_name;
let fileUrl = siteRoot + 'lib/' + detail.repo_id + '/' + 'file' + detail.file_path;
let notice = gettext('File {file_link} has a new comment form user {author}.');
let fileLink = '<a href=' + fileUrl + '>' + fileName + '</a>';
notice = notice.replace('{file_link}', fileLink);
notice = notice.replace('{author}', author);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_DRAFT_COMMENT) {
let avatar_url = detail.author_avatar_url;
let author = detail.author_name;
let draftId = detail.draft_id;
let draftUrl = siteRoot + 'drafts/' + draftId + '/';
let notice = gettext('{draft_link} has a new comment from user {author}.');
let draftLink = '<a href=' + draftUrl + '>' + gettext('Draft') + '#' + draftId + '</a>';
notice = notice.replace('{draft_link}', draftLink);
notice = notice.replace('{author}', author);
return {avatar_url, notice};
}
if (noticeType === MSG_TYPE_DRAFT_REVIEWER) {
let avatar_url = detail.request_user_avatat_url;
let fromUser = detail.request_user_name;
let draftId = detail.draft_id;
let draftUrl = siteRoot + 'drafts/' + draftId + '/';
let notice = gettext('{from_user} has sent you a request for {draft_link}.');
let draftLink = '<a href=' + draftUrl + '>' + gettext('Draft') + '#' + draftId + '</a>';
notice = notice.replace('{from_user}', fromUser);
notice = notice.replace('{draft_link}', draftLink);
return {avatar_url, notice};
}
// if (noticeType === MSG_TYPE_GUEST_INVITATION_ACCEPTED) {
// }
}
onNoticeItemClick = () => {
let item = this.props.noticeItem;
if (item.seen === true) {
return;
}
this.props.onNoticeItemClick(item);
}
render() {
let noticeItem = this.props.noticeItem;
let { avatar_url, notice } = this.generatorNoticeInfo();
return (
<li onClick={this.onNoticeItemClick} className={noticeItem.seen ? 'read' : 'unread'}>
<div className="notice-item">
<div className="main-info">
<img src={avatar_url} width="32" height="32" className="avatar" />
<p className="brief" dangerouslySetInnerHTML={{__html: notice}}></p>
</div>
<p className="time">{moment(noticeItem.timestamp).fromNow()}</p>
</div>
</li>
)
}
}
NoticeItem.propTypes = propTypes;
export default NoticeItem;

View File

@@ -1,14 +1,15 @@
import React from 'react';
import { seafileAPI } from '../../utils/seafile-api';
import { gettext, siteRoot } from '../../utils/constants';
import NoticeItem from './notice-item';
class Notification extends React.Component {
constructor(props) {
super(props);
this.state = {
showNotice: false,
notice_html: '',
unseenCount: 0,
noticeList: [],
};
}
@@ -32,15 +33,31 @@ class Notification extends React.Component {
}
loadNotices = () => {
seafileAPI.listPopupNotices().then(res => {
this.setState({
notice_html: res.data.notice_html
});
let page = 1;
let perPage = 5;
seafileAPI.listPopupNotices(page, perPage).then(res => {
let noticeList = res.data.notification_list;
this.setState({noticeList: noticeList});
});
}
onNoticeItemClick = (noticeItem) => {
let noticeList = this.state.noticeList.map(item => {
if (item.id === noticeItem.id) {
item.seen = true;
}
return item;
});
seafileAPI.markNoticeAsRead(noticeItem.id);
let unseenCount = this.state.unseenCount === 0 ? 0 : this.state.unseenCount - 1;
this.setState({
noticeList: noticeList,
unseenCount: unseenCount,
});
}
render() {
const { notice_html } = this.state;
return (
<div id="notifications">
@@ -55,7 +72,11 @@ class Notification extends React.Component {
<a href="#" onClick={this.onClick} title={gettext('Close')} aria-label={gettext('Close')} className="sf-popover-close js-close sf2-icon-x1 action-icon float-right"></a>
</div>
<div className="sf-popover-con">
<ul className="notice-list" dangerouslySetInnerHTML={{__html: notice_html}}></ul>
<ul className="notice-list">
{this.state.noticeList.map(item => {
return (<NoticeItem key={item.id} noticeItem={item} onNoticeItemClick={this.onNoticeItemClick}/>);
})}
</ul>
<a href={siteRoot + 'notification/list/'} className="view-all">{gettext('See All Notifications')}</a>
</div>
</div>

View File

@@ -13,10 +13,15 @@ from seahub.api2.throttling import UserRateThrottle
from seahub.notifications.models import UserNotification
from seahub.notifications.models import get_cache_key_of_unseen_notifications
from seahub.notifications.views import add_notice_from_info
from seahub.notifications.utils import update_notice_detail
from seahub.api2.utils import api_error, to_python_boolean
from seahub.utils.timeutils import datetime_to_isoformat_timestr
logger = logging.getLogger(__name__)
json_content_type = 'application/json; charset=utf-8'
class NotificationsView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
@@ -24,28 +29,62 @@ class NotificationsView(APIView):
throttle_classes = (UserRateThrottle,)
def get(self, request):
""" currently only used for get unseen notifications count
""" used for get notifications
Permission checking:
1. login user.
"""
result = {}
username = request.user.username
cache_key = get_cache_key_of_unseen_notifications(username)
try:
per_page = int(request.GET.get('per_page', ''))
page = int(request.GET.get('page', ''))
except ValueError:
per_page = 25
page = 1
start = (page - 1) * per_page
end = page * per_page
notice_list = UserNotification.objects.get_user_notifications(username)[start:end]
result_notices = update_notice_detail(request, notice_list)
notification_list = []
unseen_count = 0
for i in result_notices:
if i.detail is not None:
notice = {}
notice['id'] = i.id
notice['type'] = i.msg_type
notice['detail'] = i.detail
notice['time'] = datetime_to_isoformat_timestr(i.timestamp)
notice['seen'] = i.seen
if not i.seen:
unseen_count += 1
notification_list.append(notice)
cache_key = get_cache_key_of_unseen_notifications(username)
count_from_cache = cache.get(cache_key, None)
# for case of count value is `0`
if count_from_cache is not None:
result['unseen_count'] = count_from_cache
unseen_num = count_from_cache
else:
count_from_db = UserNotification.objects.count_unseen_user_notifications(username)
result['unseen_count'] = count_from_db
result['unseen_count'] = unseen_count
# set cache
cache.set(cache_key, count_from_db)
cache.set(cache_key, unseen_count)
unseen_num = unseen_count
total_count = UserNotification.objects.filter(to_user=username).count()
result['notification_list'] = notification_list
result['count'] = total_count
result['unseen_count'] = unseen_num
return Response(result)
@@ -68,6 +107,7 @@ class NotificationsView(APIView):
return Response({'success': True})
class NotificationView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)

View File

@@ -1,8 +1,19 @@
# Copyright (c) 2012-2016 Seafile Ltd.
import os
import json
import logging
from django.core.cache import cache
from django.core.urlresolvers import reverse
from seaserv import ccnet_api, seafile_api
from seahub.notifications.models import Notification
from seahub.notifications.settings import NOTIFICATION_CACHE_TIMEOUT
from seahub.avatar.templatetags.avatar_tags import api_avatar_url
from seahub.base.templatetags.seahub_tags import email2nickname
logger = logging.getLogger(__name__)
def refresh_cache():
"""
Function to be called when change primary notification.
@@ -10,3 +21,205 @@ def refresh_cache():
cache.set('CUR_TOPINFO', Notification.objects.all().filter(primary=1),
NOTIFICATION_CACHE_TIMEOUT)
def update_notice_detail(request, notices):
repo_dict = {}
for notice in notices:
if notice.is_repo_share_msg():
try:
d = json.loads(notice.detail)
repo_id = d['repo_id']
path = d.get('path', '/')
org_id = d.get('org_id', None)
if path == '/':
repo = seafile_api.get_repo(repo_id)
else:
if org_id:
owner = seafile_api.get_org_repo_owner(repo_id)
repo = seafile_api.get_org_virtual_repo(
org_id, repo_id, path, owner)
else:
owner = seafile_api.get_repo_owner(repo_id)
repo = seafile_api.get_virtual_repo(repo_id, path, owner)
if repo is None:
notice.detail = None
else:
d.pop('org_id')
share_from_user_name = email2nickname(d['share_from'])
url, is_default, date_uploaded = api_avatar_url(d['share_from'], 32)
d['repo_name'] = repo.name
d['repo_id'] = repo.id
d['share_from_user_email'] = d.pop('share_from')
d['share_from_user_name'] = share_from_user_name
d['share_from_user_avatar_url'] = request.build_absolute_uri(url)
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_repo_share_to_group_msg():
try:
d = json.loads(notice.detail)
group_id = d['group_id']
path = d.get('path', '/')
org_id = d.get('org_id', None)
repo_id = d['repo_id']
group = ccnet_api.get_group(group_id)
if path == '/':
repo = seafile_api.get_repo(repo_id)
else:
if org_id:
owner = seafile_api.get_org_repo_owner(repo_id)
repo = seafile_api.get_org_virtual_repo(
org_id, repo_id, path, owner)
else:
owner = seafile_api.get_repo_owner(repo_id)
repo = seafile_api.get_virtual_repo(repo_id, path, owner)
if not repo or not group:
notice.detail = None
else:
d.pop('org_id')
share_from_user_name = email2nickname(d['share_from'])
url, is_default, date_uploaded = api_avatar_url(d['share_from'], 32)
d['share_from_user_email'] = d.pop('share_from')
d['share_from_user_name'] = share_from_user_name
d['share_from_user_avatar_url'] = request.build_absolute_uri(url)
d['repo_name'] = repo.name
d['repo_id'] = repo.id
d['group_name'] = group.group_name
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_add_user_to_group():
try:
d = json.loads(notice.detail)
group_id = d['group_id']
group = ccnet_api.get_group(group_id)
if group is None:
notice.detail = None
else:
group_staff_name = email2nickname(d['group_staff'])
url, is_default, date_uploaded = api_avatar_url(d['group_staff'], 32)
d['group_staff_email'] = d.pop('group_staff')
d['group_staff_name'] = group_staff_name
d['group_staff_avatar_url'] = request.build_absolute_uri(url)
d['group_name'] = group.group_name
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_draft_comment_msg():
try:
d = json.loads(notice.detail)
author_name = email2nickname(d['author'])
url, is_default, date_uploaded = api_avatar_url(d['author'], 32)
d['author_name'] = author_name
d['author_email'] = d.pop('author')
d['author_avatar_url'] = request.build_absolute_uri(url)
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_repo_transfer_msg():
try:
d = json.loads(notice.detail)
repo_id = d['repo_id']
repo = seafile_api.get_repo(repo_id)
if not repo:
notice.detail = None
else:
d.pop('org_id')
repo_owner_email = d['repo_owner']
repo_owner_name = email2nickname(repo_owner_email)
d['transfer_from_user_email'] = d.pop('repo_owner')
d['transfer_from_user_name'] = repo_owner_name
url, is_default, date_uploaded = api_avatar_url(repo_owner_email, 32)
d['transfer_from_user_avatar_url'] = request.build_absolute_uri(url)
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_draft_reviewer_msg():
try:
d = json.loads(notice.detail)
d.pop('to_user')
request_user_name = email2nickname(d['from_user'])
url, is_default, date_uploaded = api_avatar_url(d['from_user'], 32)
d['request_user_name'] = request_user_name
d['request_user_email'] = d.pop('from_user')
d['request_user_avatat_url'] = request.build_absolute_uri(url)
notice.detail = d
except Exception as e:
logger.error(e)
elif notice.is_file_uploaded_msg():
try:
d = json.loads(notice.detail)
filename = d['file_name']
repo_id = d['repo_id']
if repo_id in repo_dict:
repo = repo_dict[repo_id]
else:
repo = seafile_api.get_repo(repo_id)
repo_dict[repo_id] = repo
if repo:
if d['uploaded_to'] == '/':
# current upload path is '/'
file_path = '/' + filename
name = repo.name
else:
uploaded_to = d['uploaded_to'].rstrip('/')
file_path = uploaded_to + '/' + filename
name = os.path.basename(uploaded_to)
d['repo_name'] = repo.name
d['folder_path'] = d.pop('uploaded_to')
d['folder_name'] = name
d['file_path'] = file_path
url, is_default, date_uploaded = api_avatar_url('', 32)
d['uploaded_user_avatar_url'] = request.build_absolute_uri(url)
notice.detail = d
else:
notice.detail = None
except Exception as e:
logger.error(e)
elif notice.is_file_comment_msg():
try:
d = json.loads(notice.detail)
repo_id = d['repo_id']
file_path = d['file_path']
if repo_id in repo_dict:
repo = repo_dict[repo_id]
else:
repo = seafile_api.get_repo(repo_id)
repo_dict[repo_id] = repo
if repo is None or not seafile_api.get_file_id_by_path(repo.id, file_path):
notice.detail = None
else:
author_name = email2nickname(d['author'])
file_name = os.path.basename(file_path)
url, is_default, date_uploaded = api_avatar_url(d['author'], 32)
d['author_avatar_url'] = request.build_absolute_uri(url)
d['author_email'] = d.pop('author')
d['author_name'] = author_name
d['file_name'] = file_name
notice.detail = d
except Exception as e:
logger.error(e)
return notices