1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-16 23:29:49 +00:00

multi share links (#5412)

* support more than one share link for each user for a file/folder

* improve frontend page

* optimize frontend page

* [share dialog] 'share link' panel: redesign(list links & offer 'Details' for each link)

---------

Co-authored-by: llj <lingjun.li1@gmail.com>
This commit is contained in:
WJH
2023-03-28 16:29:34 +08:00
committed by GitHub
parent 641dc04f86
commit b89b446037
3 changed files with 392 additions and 103 deletions

View File

@@ -1,4 +1,4 @@
import React from 'react';
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import copy from 'copy-to-clipboard';
@@ -19,6 +19,7 @@ const propTypes = {
repoID: PropTypes.string.isRequired,
closeShareDialog: PropTypes.func.isRequired,
userPerm: PropTypes.string,
itemType: PropTypes.string
};
const inputWidth = Utils.isDesktop() ? 250 : 210;
@@ -33,7 +34,6 @@ class GenerateShareLink extends React.Component {
this.state = {
isOpIconShown: false,
isValidate: false,
isShowPasswordInput: shareLinkForceUsePassword ? true : false,
isPasswordVisible: false,
isExpireChecked: !this.isExpireDaysNoLimit,
@@ -47,6 +47,7 @@ class GenerateShareLink extends React.Component {
storedPasswordVisible: false,
errorInfo: '',
sharedLinkInfo: null,
shareLinks: [],
isNoticeMessageShow: false,
isLoading: true,
permissionOptions: [],
@@ -59,15 +60,10 @@ class GenerateShareLink extends React.Component {
let path = this.props.itemPath;
let repoID = this.props.repoID;
seafileAPI.getShareLink(repoID, path).then((res) => {
if (res.data.length !== 0) {
let sharedLinkInfo = new ShareLink(res.data[0]);
this.setState({
isLoading: false,
sharedLinkInfo: sharedLinkInfo
shareLinks: res.data.map(item => new ShareLink(item))
});
} else {
this.setState({isLoading: false});
}
}).catch(error => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
@@ -178,9 +174,19 @@ class GenerateShareLink extends React.Component {
expirationTime = expDate.format();
}
}
seafileAPI.createShareLink(repoID, itemPath, password, expirationTime, permissions).then((res) => {
let sharedLinkInfo = new ShareLink(res.data);
this.setState({sharedLinkInfo: sharedLinkInfo});
seafileAPI.createMultiShareLink(repoID, itemPath, password, expirationTime, permissions).then((res) => {
const links = this.state.shareLinks;
links.unshift(new ShareLink(res.data));
this.setState({
password: '',
passwdnew: '',
isShowPasswordInput: shareLinkForceUsePassword ? true : false,
expireDays: this.defaultExpireDays,
expDate: null,
isExpireChecked: !this.isExpireDaysNoLimit,
errorInfo: '',
shareLinks: links
});
}).catch((error) => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
@@ -203,19 +209,14 @@ class GenerateShareLink extends React.Component {
}
deleteShareLink = () => {
let sharedLinkInfo = this.state.sharedLinkInfo;
const { sharedLinkInfo, shareLinks } = this.state;
seafileAPI.deleteShareLink(sharedLinkInfo.token).then(() => {
this.setState({
password: '',
passwdnew: '',
isShowPasswordInput: shareLinkForceUsePassword ? true : false,
expireDays: this.defaultExpireDays,
expDate: null,
isExpireChecked: !this.isExpireDaysNoLimit,
errorInfo: '',
sharedLinkInfo: null,
isNoticeMessageShow: false,
sharedLinkInfo: null,
shareLinks: shareLinks.filter(item => item.token !== sharedLinkInfo.token)
});
toaster.success(gettext('The link is deleted.'));
}).catch((error) => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
@@ -318,11 +319,10 @@ class GenerateShareLink extends React.Component {
}
updateExpiration = (e) => {
e.preventDefault();
e.nativeEvent.stopImmediatePropagation();
let { expType, expireDays, expDate } = this.state;
const { expType, expireDays, expDate, sharedLinkInfo, shareLinks } = this.state;
let expirationTime = '';
if (expType == 'by-days') {
@@ -331,11 +331,12 @@ class GenerateShareLink extends React.Component {
expirationTime = expDate.format();
}
seafileAPI.updateShareLink(this.state.sharedLinkInfo.token, '', expirationTime).then((res) => {
let sharedLinkInfo = new ShareLink(res.data);
seafileAPI.updateShareLink(sharedLinkInfo.token, '', expirationTime).then((res) => {
const updatedShareLink = new ShareLink(res.data);
this.setState({
sharedLinkInfo: sharedLinkInfo,
isEditingExpiration: false,
sharedLinkInfo: updatedShareLink,
shareLinks: shareLinks.map(item => item.token == sharedLinkInfo.token ? updatedShareLink : item)
});
}).catch((error) => {
let errMessage = Utils.getErrorMsg(error);
@@ -360,36 +361,40 @@ class GenerateShareLink extends React.Component {
}
changePerm = (permission) => {
const permissionDetails = Utils.getShareLinkPermissionObject(permission).permissionDetails;
seafileAPI.updateShareLink(this.state.sharedLinkInfo.token, JSON.stringify(permissionDetails)).then((res) => {
let sharedLinkInfo = new ShareLink(res.data);
this.setState({sharedLinkInfo: sharedLinkInfo});
let message = gettext('Successfully modified permission.');
toaster.success(message);
const { sharedLinkInfo, shareLinks } = this.state;
const { permissionDetails } = Utils.getShareLinkPermissionObject(permission);
seafileAPI.updateShareLink(sharedLinkInfo.token, JSON.stringify(permissionDetails)).then((res) => {
const updatedShareLink = new ShareLink(res.data);
this.setState({
sharedLinkInfo: updatedShareLink,
shareLinks: shareLinks.map(item => item.token == sharedLinkInfo.token ? updatedShareLink : item)
});
}).catch((error) => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
});
}
showLinkDetails = (link) => {
this.setState({
sharedLinkInfo: link
});
}
render() {
if (this.state.isLoading) {
return <Loading />;
}
let passwordLengthTip = gettext('(at least {passwordMinLength} characters and includes {passwordStrengthLevel} of the following: number, upper letter, lower letter and other symbols)');
passwordLengthTip = passwordLengthTip.replace('{passwordMinLength}', shareLinkPasswordMinLength)
.replace('{passwordStrengthLevel}', shareLinkPasswordStrengthLevel);
const { userPerm } = this.props;
const { isCustomPermission } = Utils.getUserPermission(userPerm);
const { shareLinks, permissionOptions, sharedLinkInfo, isOpIconShown } = this.state;
if (this.state.sharedLinkInfo) {
let sharedLinkInfo = this.state.sharedLinkInfo;
if (sharedLinkInfo) {
let currentPermission = Utils.getShareLinkPermissionStr(sharedLinkInfo.permissions);
const { permissionOptions , isOpIconShown } = this.state;
return (
<div>
<button className="fa fa-arrow-left back-icon border-0 bg-transparent text-secondary p-0" onClick={this.showLinkDetails.bind(this, null)} title={gettext('Back')} aria-label={gettext('Back')}></button>
<Form className="mb-4">
<FormGroup className="mb-0">
<dt className="text-secondary font-weight-normal">{gettext('Link:')}</dt>
@@ -505,6 +510,7 @@ class GenerateShareLink extends React.Component {
);
} else {
return (
<Fragment>
<Form className="generate-share-link">
<FormGroup check>
{shareLinkForceUsePassword ? (
@@ -514,7 +520,7 @@ class GenerateShareLink extends React.Component {
</Label>
) : (
<Label check>
<Input type="checkbox" onChange={this.onPasswordInputChecked} />
<Input type="checkbox" checked={this.state.isShowPasswordInput} onChange={this.onPasswordInputChecked} />
<span>{gettext('Add password protection')}</span>
</Label>
)}
@@ -522,7 +528,7 @@ class GenerateShareLink extends React.Component {
<div className="ml-4">
<FormGroup>
<Label for="passwd">{gettext('Password')}</Label>
<span className="tip">{passwordLengthTip}</span>
<span className="tip">{gettext('(at least {passwordMinLength} characters and includes {passwordStrengthLevel} of the following: number, upper letter, lower letter and other symbols)').replace('{passwordMinLength}', shareLinkPasswordMinLength).replace('{passwordStrengthLevel}', shareLinkPasswordStrengthLevel)}</span>
<InputGroup style={{width: inputWidth}}>
<Input id="passwd" type={this.state.isPasswordVisible ? 'text' : 'password'} value={this.state.password || ''} onChange={this.inputPassword} />
<InputGroupAddon addonType="append">
@@ -583,11 +589,88 @@ class GenerateShareLink extends React.Component {
{this.state.errorInfo && <Alert color="danger" className="mt-2">{gettext(this.state.errorInfo)}</Alert>}
<Button onClick={this.generateShareLink} className="mt-2">{gettext('Generate')}</Button>
</Form>
{shareLinks.length > 0 && (
<table>
<thead>
<tr>
<th width="28%">{gettext('Link')}</th>
<th width="30%">{gettext('Permission')}</th>
<th width="30%">{gettext('Expiration')}</th>
<th width="12%"></th>
</tr>
</thead>
<tbody>
{
shareLinks.map((item, index) => {
return (
<LinkItem
key={index}
item={item}
permissionOptions={permissionOptions}
showLinkDetails={this.showLinkDetails}
/>
);
})
}
</tbody>
</table>
)}
</Fragment>
);
}
}
}
class LinkItem extends React.Component {
constructor(props) {
super(props);
}
cutLink = (link) => {
let length = link.length;
return link.slice(0, 9) + '...' + link.slice(length-5);
}
viewDetails = () => {
this.props.showLinkDetails(this.props.item);
}
render() {
const { item, permissionOptions } = this.props;
const { permissions, link, expire_date } = item;
const currentPermission = Utils.getShareLinkPermissionStr(permissions);
return (
<tr>
<td>{this.cutLink(link)}</td>
<td>
{(isPro && permissions) && (
<ShareLinkPermissionEditor
isTextMode={true}
isEditIconShow={false}
currentPermission={currentPermission}
permissionOptions={permissionOptions}
onPermissionChanged={() => {}}
/>
)}
</td>
<td>
{expire_date ? moment(expire_date).format('YYYY-MM-DD HH:mm') : '--'}
</td>
<td>
<button onClick={this.viewDetails} className="border-0 btn-sm text-gray">{gettext('Details')}</button>
</td>
</tr>
);
}
}
LinkItem.propTypes = {
item: PropTypes.object.isRequired,
permissionOptions: PropTypes.array,
showLinkDetails : PropTypes.func.isRequired
};
GenerateShareLink.propTypes = propTypes;
export default GenerateShareLink;

View File

@@ -0,0 +1,204 @@
# Copyright (c) 2012-2016 Seafile Ltd.
import os
import stat
import logging
import dateutil.parser
from dateutil.relativedelta import relativedelta
from constance import config
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.utils import timezone
from django.utils.timezone import get_current_timezone
from django.utils.translation import ugettext as _
from seaserv import seafile_api
from seahub.api2.utils import api_error
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.permissions import CanGenerateShareLink
from seahub.constants import PERMISSION_READ_WRITE, PERMISSION_READ, PERMISSION_PREVIEW_EDIT, PERMISSION_PREVIEW
from seahub.share.models import FileShare
from seahub.utils import is_org_context, get_password_strength_level, is_valid_password
from seahub.utils.repo import parse_repo_perm
from seahub.settings import SHARE_LINK_EXPIRE_DAYS_MAX, SHARE_LINK_EXPIRE_DAYS_MIN, SHARE_LINK_EXPIRE_DAYS_DEFAULT
from seahub.views.file import can_edit_file
from seahub.api2.endpoints.share_links import get_share_link_info, check_permissions_arg
logger = logging.getLogger(__name__)
class MultiShareLinks(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated, CanGenerateShareLink)
throttle_classes = (UserRateThrottle,)
def post(self, request):
# argument check
repo_id = request.data.get('repo_id', None)
if not repo_id:
error_msg = 'repo_id invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
path = request.data.get('path', None)
if not path:
error_msg = 'path invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
password = request.data.get('password', None)
if config.SHARE_LINK_FORCE_USE_PASSWORD and not password:
error_msg = _('Password is required.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if password:
if len(password) < config.SHARE_LINK_PASSWORD_MIN_LENGTH:
error_msg = _('Password is too short.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if get_password_strength_level(password) < config.SHARE_LINK_PASSWORD_STRENGTH_LEVEL:
error_msg = _('Password is too weak.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if not is_valid_password(password):
error_msg = _('Password can only contain number, upper letter, lower letter and other symbols.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
expire_days = request.data.get('expire_days', '')
expiration_time = request.data.get('expiration_time', '')
if expire_days and expiration_time:
error_msg = 'Can not pass expire_days and expiration_time at the same time.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
expire_date = None
if expire_days:
try:
expire_days = int(expire_days)
except ValueError:
error_msg = 'expire_days invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if expire_days <= 0:
error_msg = 'expire_days invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if SHARE_LINK_EXPIRE_DAYS_MIN > 0:
if expire_days < SHARE_LINK_EXPIRE_DAYS_MIN:
error_msg = _('Expire days should be greater or equal to %s') % SHARE_LINK_EXPIRE_DAYS_MIN
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if SHARE_LINK_EXPIRE_DAYS_MAX > 0:
if expire_days > SHARE_LINK_EXPIRE_DAYS_MAX:
error_msg = _('Expire days should be less than or equal to %s') % SHARE_LINK_EXPIRE_DAYS_MAX
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
expire_date = timezone.now() + relativedelta(days=expire_days)
elif expiration_time:
try:
expire_date = dateutil.parser.isoparse(expiration_time)
except Exception as e:
logger.error(e)
error_msg = 'expiration_time invalid, should be iso format, for example: 2020-05-17T10:26:22+08:00'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
expire_date = expire_date.astimezone(get_current_timezone()).replace(tzinfo=None)
if SHARE_LINK_EXPIRE_DAYS_MIN > 0:
expire_date_min_limit = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_MIN)
expire_date_min_limit = expire_date_min_limit.replace(hour=0).replace(minute=0).replace(second=0)
if expire_date < expire_date_min_limit:
error_msg = _('Expiration time should be later than %s.') % \
expire_date_min_limit.strftime("%Y-%m-%d %H:%M:%S")
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if SHARE_LINK_EXPIRE_DAYS_MAX > 0:
expire_date_max_limit = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_MAX)
expire_date_max_limit = expire_date_max_limit.replace(hour=23).replace(minute=59).replace(second=59)
if expire_date > expire_date_max_limit:
error_msg = _('Expiration time should be earlier than %s.') % \
expire_date_max_limit.strftime("%Y-%m-%d %H:%M:%S")
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
else:
if SHARE_LINK_EXPIRE_DAYS_DEFAULT > 0:
expire_date = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_DEFAULT)
try:
perm = check_permissions_arg(request)
except Exception as e:
logger.error(e)
error_msg = 'permissions invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
# resource check
repo = seafile_api.get_repo(repo_id)
if not repo:
error_msg = 'Library %s not found.' % repo_id
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
dirent = None
if path != '/':
dirent = seafile_api.get_dirent_by_path(repo_id, path)
if not dirent:
error_msg = 'Dirent %s not found.' % path
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# permission check
if repo.encrypted:
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
username = request.user.username
repo_folder_permission = seafile_api.check_permission_by_path(repo_id, path, username)
if parse_repo_perm(repo_folder_permission).can_generate_share_link is False:
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
if repo_folder_permission in (PERMISSION_PREVIEW_EDIT, PERMISSION_PREVIEW) \
and perm != FileShare.PERM_VIEW_ONLY:
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
if repo_folder_permission in (PERMISSION_READ, ) \
and perm not in (FileShare.PERM_VIEW_DL, FileShare.PERM_VIEW_ONLY):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
# can_upload requires rw repo permission
if perm == FileShare.PERM_VIEW_DL_UPLOAD and \
repo_folder_permission != PERMISSION_READ_WRITE:
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
if path != '/':
s_type = 'd' if stat.S_ISDIR(dirent.mode) else 'f'
if s_type == 'f':
file_name = os.path.basename(path.rstrip('/'))
can_edit, error_msg = can_edit_file(file_name, dirent.size, repo)
if not can_edit and perm in (FileShare.PERM_EDIT_DL, FileShare.PERM_EDIT_ONLY):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
else:
s_type = 'd'
# create share link
org_id = request.user.org.org_id if is_org_context(request) else None
if s_type == 'f':
fs = FileShare.objects.create_file_link(username, repo_id, path,
password, expire_date,
permission=perm, org_id=org_id)
else:
fs = FileShare.objects.create_dir_link(username, repo_id, path,
password, expire_date,
permission=perm, org_id=org_id)
link_info = get_share_link_info(fs)
return Response(link_info)

View File

@@ -42,6 +42,7 @@ from seahub.api2.endpoints.share_links import ShareLinks, ShareLink, \
ShareLinkOnlineOfficeLock, ShareLinkDirents, ShareLinkSaveFileToRepo, \
ShareLinkUpload, ShareLinkUploadDone, ShareLinkSaveItemsToRepo, \
ShareLinkRepoTags, ShareLinkRepoTagsTaggedFiles, ShareLinksCleanInvalid
from seahub.api2.endpoints.multi_share_links import MultiShareLinks
from seahub.api2.endpoints.shared_folders import SharedFolders
from seahub.api2.endpoints.shared_repos import SharedRepos, SharedRepo
from seahub.api2.endpoints.upload_links import UploadLinks, UploadLink, \
@@ -344,6 +345,7 @@ urlpatterns = [
## user::shared-download-links
url(r'^api/v2.1/share-links/$', ShareLinks.as_view(), name='api-v2.1-share-links'),
url(r'^api/v2.1/multi-share-links/$', MultiShareLinks.as_view(), name='api-v2.1-multi-share-links'),
url(r'^api/v2.1/share-links/clean-invalid/$', ShareLinksCleanInvalid.as_view(), name='api-v2.1-share-links-clean-invalid'),
url(r'^api/v2.1/share-links/(?P<token>[a-f0-9]+)/$', ShareLink.as_view(), name='api-v2.1-share-link'),
url(r'^api/v2.1/share-links/(?P<token>[a-f0-9]+)/save-file-to-repo/$', ShareLinkSaveFileToRepo.as_view(), name='api-v2.1-share-link-save-file-to-repo'),