1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-04-28 03:10:45 +00:00

Merge branch '7.0'

This commit is contained in:
plt 2019-06-06 08:07:18 +08:00
commit 62f5d6502b
14 changed files with 828 additions and 15 deletions

View File

@ -204,6 +204,11 @@ module.exports = {
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + "/repo-history.js",
],
repoFolderTrash: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + "/repo-folder-trash.js",
],
orgAdmin: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),

View File

@ -89,6 +89,7 @@ module.exports = {
viewFileUnknown: [require.resolve('./polyfills'), paths.appSrc + "/view-file-unknown.js"],
settings: [require.resolve('./polyfills'), paths.appSrc + "/settings.js"],
repoHistory: [require.resolve('./polyfills'), paths.appSrc + "/repo-history.js"],
repoFolderTrash: [require.resolve('./polyfills'), paths.appSrc + "/repo-folder-trash.js"],
orgAdmin: [require.resolve('./polyfills'), paths.appSrc + "/pages/org-admin"],
sysAdmin: [require.resolve('./polyfills'), paths.appSrc + "/pages/sys-admin"],
viewDataGrid: [require.resolve('./polyfills'), paths.appSrc + "/view-file-ctable.js"],

View File

@ -84,7 +84,7 @@ class DirTool extends React.Component {
let { repoID, repoName, permission, currentPath } = this.props;
let isFile = this.isMarkdownFile(currentPath);
let name = Utils.getFileName(currentPath);
let trashUrl = siteRoot + 'repo/recycle/' + repoID + '/?referer=' + encodeURIComponent(location.href);
let trashUrl = siteRoot + 'repo/' + repoID + '/trash/';
let historyUrl = siteRoot + 'repo/history/' + repoID + '/';
if (permission) {
if (isFile) { // isFile
@ -96,7 +96,7 @@ class DirTool extends React.Component {
);
} else {
if (name) { // name not '' is not root path
trashUrl = siteRoot + 'dir/recycle/' + repoID + '/?dir_path=' + encodeURIComponent(currentPath) + '&referer=' + encodeURIComponent(location.href);
trashUrl = siteRoot + 'repo/' + repoID + '/trash/?path=' + encodeURIComponent(currentPath);
return (
<ul className="path-toolbar">
<li className="toolbar-item"><a className="op-link sf2-icon-recycle" href={trashUrl} title={gettext('Trash')} aria-label={gettext('Trash')}></a></li>

View File

@ -0,0 +1,90 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import Select from 'react-select/lib/Creatable';
import { gettext } from '../../utils/constants';
import { seafileAPI } from '../../utils/seafile-api';
import toaster from '../toast';
const propTypes = {
repoID: PropTypes.string.isRequired,
refreshTrash: PropTypes.func.isRequired,
toggleDialog: PropTypes.func.isRequired
};
class CleanTrash extends React.Component {
constructor(props) {
super(props);
this.options = [
{label: gettext('3 days ago'), value: 3},
{label: gettext('1 week ago'), value: 7},
{label: gettext('1 month ago'), value: 30},
{label: gettext('all'), value: 0}
];
this.state = {
inputValue: this.options[0],
submitBtnDisabled: false
};
}
handleInputChange = (value) => {
this.setState({
inputValue: value
});
}
formSubmit = () => {
const inputValue = this.state.inputValue;
const { repoID } = this.props;
this.setState({
submitBtnDisabled: true
});
seafileAPI.deleteRepoTrash(repoID, inputValue.value).then((res) => {
toaster.success(gettext('Clean succeeded.'));
this.props.refreshTrash();
this.props.toggleDialog();
}).catch((error) => {
let errorMsg = '';
if (error.response) {
errorMsg = error.response.data.error_msg || gettext('Error');
} else {
errorMsg = gettext('Please check the network.');
}
this.setState({
formErrorMsg: errorMsg,
submitBtnDisabled: false
});
});
}
render() {
const { formErrorMsg } = this.state;
return (
<Modal isOpen={true} centered={true} toggle={this.props.toggleDialog}>
<ModalHeader toggle={this.props.toggleDialog}>{gettext('Clean')}</ModalHeader>
<ModalBody>
<React.Fragment>
<p>{gettext('Clear files in trash and history')}</p>
<Select
defaultValue={this.options[0]}
options={this.options}
autoFocus={false}
onChange={this.handleInputChange}
placeholder=''
/>
{formErrorMsg && <p className="error m-0 mt-2">{formErrorMsg}</p>}
</React.Fragment>
</ModalBody>
<ModalFooter>
<button className="btn btn-primary" disabled={this.state.submitBtnDisabled} onClick={this.formSubmit}>{gettext('Submit')}</button>
</ModalFooter>
</Modal>
);
}
}
CleanTrash.propTypes = propTypes;
export default CleanTrash;

View File

@ -0,0 +1,33 @@
body {
overflow: hidden;
}
#wrapper {
height: 100%;
}
.top-header {
background: #f4f4f7;
border-bottom: 1px solid #e8e8e8;
padding: .5rem 1rem;
flex-shrink: 0;
}
.go-back {
color: #c0c0c0;
font-size: 1.75rem;
position: absolute;
left: -40px;
top: -5px;
}
.op-bar {
padding: 9px 10px;
background: #f2f2f2;
border-radius: 2px;
}
.more {
background: #efefef;
border: 0;
color: #777;
}
.more:hover {
color: #000;
background: #dfdfdf;
}

View File

@ -56,7 +56,7 @@ class Draft extends React.Component {
reviewers: [],
inResizing: false,
rightPartWidth: 30,
freezePublish: false
draftStatus: window.draft.config.draftStatus,
};
this.quote = '';
this.newIndex = null;
@ -410,7 +410,7 @@ class Draft extends React.Component {
onPublishDraft = () => {
seafileAPI.publishDraft(draftID).then(res => {
this.setState({
freezePublish: !this.state.freezePublish
draftStatus: res.data.draft_status,
});
});
}
@ -734,8 +734,9 @@ class Draft extends React.Component {
const { draftInfo, reviewers, originRepoName } = this.state;
const onResizeMove = this.state.inResizing ? this.onResizeMouseMove : null;
const draftLink = siteRoot + 'lib/' + draftRepoID + '/file' + draftFilePath + '?mode=edit';
const freezePublish = (this.state.freezePublish || draftStatus === 'published') ? true : false;
const canPublish = !this.state.freezePublish && draftFileExists && filePermission == 'rw';
const showPublishedButton = this.state.draftStatus == 'published';
const showPublishButton = this.state.draftStatus == 'open' && filePermission == 'rw';
const showEditButton = this.state.draftStatus == 'open' && filePermission == 'rw';
const time = moment(draftInfo.mtime * 1000).format('YYYY-MM-DD HH:mm');
const url = `${siteRoot}profile/${encodeURIComponent(draftInfo.last_modifier_email)}/`;
return(
@ -750,7 +751,7 @@ class Draft extends React.Component {
<span className="file-name">{draftFileName}</span>
<span className="mx-2 file-review">{gettext('Review')}</span>
</div>
{(!freezePublish && draftInfo.mtime) &&
{(!showPublishedButton && draftInfo.mtime) &&
<div className="last-modification">
<a href={url}>{draftInfo.last_modifier_name}</a><span className="mx-1">{time}</span>
</div>
@ -759,17 +760,17 @@ class Draft extends React.Component {
</div>
<div className="button-group">
{this.renderDiffButton()}
{(draftFileExists && !freezePublish) &&
{showEditButton &&
<a href={draftLink} className="mx-1">
<Button className="file-operation-btn" color="secondary">{gettext('Edit Draft')}</Button>
</a>
}
{canPublish &&
{showPublishButton &&
<button className='btn btn-success file-operation-btn' title={gettext('Publish draft')} onClick={this.onPublishDraft}>
{gettext('Publish')}
</button>
}
{freezePublish &&
{showPublishedButton &&
<button className='btn btn-success file-operation-btn' title={gettext('Published')} disabled>
{gettext('Published')}
</button>

View File

@ -600,9 +600,15 @@ class LibContentView extends React.Component {
}
this.deleteDirent(direntPath);
});
var msg = gettext('Successfully deleted {name} and other {n} items.');
msg = msg.replace('{name}', dirNames[0]);
msg = msg.replace('{n}', dirNames.length - 1);
let msg = '';
if (direntPaths.length > 1) {
msg = gettext('Successfully deleted {name} and other {n} items.');
msg = msg.replace('{name}', dirNames[0]);
msg = msg.replace('{n}', dirNames.length - 1);
} else {
msg = gettext('Successfully deleted {name}.');
msg = msg.replace('{name}', dirNames[0]);
}
toaster.success(msg);
}).catch(() => {
var msg = gettext('Failed to delete {name} and other {n} items.');

View File

@ -0,0 +1,439 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { navigate } from '@reach/router';
import moment from 'moment';
import { Utils } from './utils/utils';
import { gettext, loginUrl, siteRoot, mediaUrl, logoPath, logoWidth, logoHeight, siteTitle } from './utils/constants';
import { seafileAPI } from './utils/seafile-api';
import Loading from './components/loading';
import ModalPortal from './components/modal-portal';
import toaster from './components/toast';
import CommonToolbar from './components/toolbar/common-toolbar';
import CleanTrash from './components/dialog/clean-trash';
import './css/toolbar.css';
import './css/search.css';
import './css/repo-folder-trash.css';
const {
repoID,
repoFolderName,
path,
enableClean
} = window.app.pageOptions;
class RepoFolderTrash extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
errorMsg: '',
items: [],
scanStat: null,
more: false,
isCleanTrashDialogOpen: false
};
}
componentDidMount() {
this.getItems();
}
getItems = (scanStat) => {
seafileAPI.getRepoFolderTrash(repoID, path, scanStat).then((res) => {
const { data, more, scan_stat } = res.data;
if (!data.length && more) {
this.getItems(scan_stat);
} else {
this.setState({
isLoading: false,
items: this.state.items.concat(data),
more: more,
scanStat: scan_stat
});
}
}).catch((error) => {
if (error.response) {
if (error.response.status == 403) {
this.setState({
isLoading: false,
errorMsg: gettext('Permission denied')
});
location.href = `${loginUrl}?next=${encodeURIComponent(location.href)}`;
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Error')
});
}
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Please check the network.')
});
}
});
}
getMore = () => {
this.getItems(this.state.scanStat);
}
onSearchedClick = (selectedItem) => {
if (selectedItem.is_dir === true) {
let url = siteRoot + 'library/' + selectedItem.repo_id + '/' + selectedItem.repo_name + selectedItem.path;
navigate(url, {repalce: true});
} else {
let url = siteRoot + 'lib/' + selectedItem.repo_id + '/file' + Utils.encodePath(selectedItem.path);
let newWindow = window.open('about:blank');
newWindow.location.href = url;
}
}
goBack = (e) => {
e.preventDefault();
window.history.back();
}
cleanTrash = () => {
this.toggleCleanTrashDialog();
}
toggleCleanTrashDialog = () => {
this.setState({
isCleanTrashDialogOpen: !this.state.isCleanTrashDialogOpen
});
}
refreshTrash = () => {
this.setState({
isLoading: true,
errorMsg: '',
items: [],
scanStat: null,
more: false,
showFolder: false
});
this.getItems();
}
renderFolder = (commitID, baseDir, folderPath) => {
this.setState({
showFolder: true,
commitID: commitID,
baseDir: baseDir,
folderPath: folderPath,
folderItems: [],
isLoading: true
});
seafileAPI.listCommitDir(repoID, commitID, `${baseDir.substr(0, baseDir.length - 1)}${folderPath}`).then((res) => {
this.setState({
isLoading: false,
folderItems: res.data.dirent_list
});
}).catch((error) => {
if (error.response) {
if (error.response.status == 403) {
this.setState({
isLoading: false,
errorMsg: gettext('Permission denied')
});
location.href = `${loginUrl}?next=${encodeURIComponent(location.href)}`;
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Error')
});
}
} else {
this.setState({
isLoading: false,
errorMsg: gettext('Please check the network.')
});
}
});
}
clickRoot = (e) => {
e.preventDefault();
this.refreshTrash();
}
clickFolderPath = (folderPath, e) => {
e.preventDefault();
const { commitID, baseDir } = this.state;
this.renderFolder(commitID, baseDir, folderPath);
}
renderFolderPath = () => {
const pathList = this.state.folderPath.split('/');
return (
<React.Fragment>
<a href="#" onClick={this.clickRoot}>{repoFolderName}</a>
<span> / </span>
{pathList.map((item, index) => {
if (index > 0 && index != pathList.length - 1) {
return (
<React.Fragment key={index}>
<a href="#" onClick={this.clickFolderPath.bind(this, pathList.slice(0, index+1).join('/'))}>{pathList[index]}</a>
<span> / </span>
</React.Fragment>
);
}
}
)}
{pathList[pathList.length - 1]}
</React.Fragment>
);
}
render() {
const { isCleanTrashDialogOpen, showFolder } = this.state;
return (
<React.Fragment>
<div className="h-100 d-flex flex-column">
<div className="top-header d-flex justify-content-between">
<a href={siteRoot}>
<img src={mediaUrl + logoPath} height={logoHeight} width={logoWidth} title={siteTitle} alt="logo" />
</a>
<CommonToolbar onSearchedClick={this.onSearchedClick} />
</div>
<div className="flex-auto container-fluid pt-4 pb-6 o-auto">
<div className="row">
<div className="col-md-10 offset-md-1">
<h2 dangerouslySetInnerHTML={{__html: Utils.generateDialogTitle(gettext('{placeholder} Trash'), repoFolderName)}}></h2>
<a href="#" className="go-back" title={gettext('Back')} onClick={this.goBack}>
<span className="fas fa-chevron-left"></span>
</a>
<div className="d-flex justify-content-between align-items-center op-bar">
<p className="m-0">{gettext('Current path: ')}{showFolder ? this.renderFolderPath() : repoFolderName}</p>
{(path == '/' && enableClean && !showFolder) &&
<button className="btn btn-secondary" onClick={this.cleanTrash}>{gettext('Clean')}</button>
}
</div>
<Content
data={this.state}
getMore={this.getMore}
renderFolder={this.renderFolder}
/>
</div>
</div>
</div>
</div>
{isCleanTrashDialogOpen &&
<ModalPortal>
<CleanTrash
repoID={repoID}
refreshTrash={this.refreshTrash}
toggleDialog={this.toggleCleanTrashDialog}
/>
</ModalPortal>
}
</React.Fragment>
);
}
}
class Content extends React.Component {
constructor(props) {
super(props);
this.theadData = [
{width: '5%', text: ''},
{width: '45%', text: gettext('Name')},
{width: '20%', text: gettext('Delete Time')},
{width: '15%', text: gettext('Size')},
{width: '15%', text: ''}
];
}
render() {
const { isLoading, errorMsg, items, more, showFolder, commitID, baseDir, folderPath, folderItems } = this.props.data;
return (
<React.Fragment>
<table className="table-hover">
<thead>
<tr>
{this.theadData.map((item, index) => {
return <th key={index} width={item.width}>{item.text}</th>;
})}
</tr>
</thead>
<tbody>
{showFolder ?
folderItems.map((item, index) => {
return <FolderItem
key={index}
item={item}
commitID={commitID}
baseDir={baseDir}
folderPath={folderPath}
renderFolder={this.props.renderFolder}
/>;
}) :
items.map((item, index) => {
return <Item
key={index}
item={item}
renderFolder={this.props.renderFolder}
/>;
})}
</tbody>
</table>
{isLoading && <Loading />}
{errorMsg && <p className="error mt-6 text-center">{errorMsg}</p>}
{(more && !isLoading && !showFolder) && (
<button className="btn btn-block more mt-6" onClick={this.props.getMore}>{gettext('More')}</button>
)}
</React.Fragment>
);
}
}
class Item extends React.Component {
constructor(props) {
super(props);
this.state = {
restored: false,
isIconShown: false
};
}
handleMouseOver = () => {
this.setState({isIconShown: true});
}
handleMouseOut = () => {
this.setState({isIconShown: false});
}
restoreItem = (e) => {
e.preventDefault();
const item = this.props.item;
const { commit_id, parent_dir, obj_name } = item;
const path = parent_dir + obj_name;
const request = item.is_dir ?
seafileAPI.restoreFolder(repoID, commit_id, path) :
seafileAPI.restoreFile(repoID, commit_id, path);
request.then((res) => {
this.setState({
restored: true
}); toaster.success(gettext('Successfully restored 1 item.'));
}).catch((error) => {
let errorMsg = '';
if (error.response) {
errorMsg = error.response.data.error_msg || gettext('Error');
} else {
errorMsg = gettext('Please check the network.');
}
toaster.danger(errorMsg);
});
}
renderFolder = (e) => {
e.preventDefault();
const item = this.props.item;
this.props.renderFolder(item.commit_id, item.parent_dir, Utils.joinPath('/', item.obj_name));
}
render() {
const item = this.props.item;
const { restored, isIconShown } = this.state;
if (restored) {
return null;
}
return item.is_dir ? (
<React.Fragment>
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFolderIconUrl()} alt={gettext('Directory')} width="24" /></td>
<td><a href="#" onClick={this.renderFolder}>{item.obj_name}</a></td>
<td title={moment(item.deleted_time).format('LLLL')}>{moment(item.deleted_time).format('YYYY-MM-DD')}</td>
<td></td>
<td>
<a href="#" className={isIconShown ? '': 'invisible'} onClick={this.restoreItem}>{gettext('Restore')}</a>
</td>
</tr>
</React.Fragment>
) : (
<React.Fragment>
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFileIconUrl(item.obj_name)} alt={gettext('File')} width="24" /></td>
<td><a href={`${siteRoot}repo/${repoID}/trash/files/?obj_id=${item.obj_id}&commit_id=${item.commit_id}&base=${encodeURIComponent(item.parent_dir)}&p=${encodeURIComponent('/' + item.obj_name)}`} target="_blank">{item.obj_name}</a></td>
<td title={moment(item.deleted_time).format('LLLL')}>{moment(item.deleted_time).format('YYYY-MM-DD')}</td>
<td>{Utils.bytesToSize(item.size)}</td>
<td>
<a href="#" className={isIconShown ? '': 'invisible'} onClick={this.restoreItem}>{gettext('Restore')}</a>
</td>
</tr>
</React.Fragment>
);
}
}
class FolderItem extends React.Component {
constructor(props) {
super(props);
this.state = {
isIconShown: false
};
}
handleMouseOver = () => {
this.setState({isIconShown: true});
}
handleMouseOut = () => {
this.setState({isIconShown: false});
}
renderFolder = (e) => {
e.preventDefault();
const item = this.props.item;
const { commitID, baseDir, folderPath } = this.props;
this.props.renderFolder(commitID, baseDir, Utils.joinPath(folderPath, item.name));
}
render() {
const item = this.props.item;
const { isIconShown } = this.state;
const { commitID, baseDir, folderPath } = this.props;
return item.type == 'dir' ? (
<React.Fragment>
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFolderIconUrl()} alt={gettext('Directory')} width="24" /></td>
<td><a href="#" onClick={this.renderFolder}>{item.name}</a></td>
<td></td>
<td></td>
<td></td>
</tr>
</React.Fragment>
) : (
<React.Fragment>
<tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
<td className="text-center"><img src={Utils.getFileIconUrl(item.name)} alt={gettext('File')} width="24" /></td>
<td><a href={`${siteRoot}repo/${repoID}/trash/files/?obj_id=${item.obj_id}&commit_id=${commitID}&base=${encodeURIComponent(baseDir)}&p=${encodeURIComponent(Utils.joinPath(folderPath, item.name))}`} target="_blank">{item.name}</a></td>
<td></td>
<td>{Utils.bytesToSize(item.size)}</td>
<td></td>
</tr>
</React.Fragment>
);
}
}
ReactDOM.render(
<RepoFolderTrash />,
document.getElementById('wrapper')
);

View File

@ -173,7 +173,10 @@ class DraftView(APIView):
# 3. Send draft file publish msg.
send_draft_publish_msg(draft, username, dst_file_path)
return Response({'published_file_path': dst_file_path})
result = {}
result['published_file_path'] = dst_file_path
result['draft_status'] = draft.status
return Response(result)
except Exception as e:
logger.error(e)
error_msg = 'Internal Server Error'

View File

@ -0,0 +1,90 @@
# Copyright (c) 2012-2019 Seafile Ltd.
# encoding: utf-8
import stat
import logging
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 seahub.api2.throttling import UserRateThrottle
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.utils import api_error
from seahub.views import check_folder_permission
from seaserv import seafile_api
from seahub.utils import normalize_dir_path
logger = logging.getLogger(__name__)
class RepoCommitDirView(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def _get_item_info(self, dirent, path):
# # seahub/seahub/api2/views get_dir_file_recursively
entry = {}
if stat.S_ISDIR(dirent.mode):
entry['type'] = 'dir'
else:
entry['type'] = 'file'
entry['size'] = dirent.size
entry['parent_dir'] = path
entry['obj_id'] = dirent.obj_id
entry['name'] = dirent.obj_name
return entry
def get(self, request, repo_id, commit_id, format=None):
""" List dir by commit
used when get files/dirs in a trash or history dir
Permission checking:
1. all authenticated user can perform this action.
"""
# argument check
path = request.GET.get('path', '/')
path = normalize_dir_path(path)
# 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)
commit = seafile_api.get_commit(repo.id, repo.version, commit_id)
if not commit:
error_msg = 'Commit %s not found.' % commit
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
dir_id = seafile_api.get_dir_id_by_commit_and_path(repo_id, commit_id, path)
if not dir_id:
error_msg = 'Folder %s not found.' % path
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# permission check
if not check_folder_permission(request, repo_id, '/'):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
# # seafile_api.list_dir_by_commit_and_path
# def list_dir_by_commit_and_path(self, repo_id, commit_id, path, offset=-1, limit=-1):
# dir_id = seafserv_threaded_rpc.get_dir_id_by_commit_and_path(repo_id, commit_id, path)
# if dir_id is None:
# return None
# return seafserv_threaded_rpc.list_dir(repo_id, dir_id, offset, limit)
dir_entries = seafile_api.list_dir_by_dir_id(repo_id, dir_id)
items = []
for dirent in dir_entries:
items.append(self._get_item_info(dirent, path))
return Response({'dirent_list': items})

View File

@ -0,0 +1,22 @@
{% extends 'base_for_react.html' %}
{% load seahub_tags i18n %}
{% load render_bundle from webpack_loader %}
{% block sub_title %}{% trans "Trash" %} - {% endblock %}
{% block extra_style %}
{% render_bundle 'repoFolderTrash' 'css' %}
{% endblock %}
{% block extra_script %}
<script type="text/javascript">
// overwrite the one in base_for_react.html
window.app.pageOptions = {
repoID: '{{repo.id}}',
repoFolderName: '{{repo_folder_name|escapejs}}',
path: '{{path|escapejs}}',
enableClean: {% if enable_clean %} true {% else %} false {% endif %}
};
</script>
{% render_bundle 'repoFolderTrash' 'js' %}
{% endblock %}

View File

@ -52,6 +52,7 @@ from seahub.api2.endpoints.dir import DirView, DirDetailView
from seahub.api2.endpoints.file_tag import FileTagView
from seahub.api2.endpoints.file_tag import FileTagsView
from seahub.api2.endpoints.repo_trash import RepoTrash
from seahub.api2.endpoints.repo_commit_dir import RepoCommitDirView
from seahub.api2.endpoints.deleted_repos import DeletedRepos
from seahub.api2.endpoints.repo_history import RepoHistory
from seahub.api2.endpoints.repo_set_password import RepoSetPassword
@ -171,6 +172,7 @@ urlpatterns = [
url(r'^repo/history/view/(?P<repo_id>[-0-9a-f]{36})/$', repo_history_view, name='repo_history_view'),
url(r'^repo/recycle/(?P<repo_id>[-0-9a-f]{36})/$', repo_recycle_view, name='repo_recycle_view'),
url(r'^dir/recycle/(?P<repo_id>[-0-9a-f]{36})/$', dir_recycle_view, name='dir_recycle_view'),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/trash/$', repo_folder_trash, name="repo_folder_trash"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/raw/(?P<file_path>.*)$', view_raw_file, name="view_raw_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/history/files/$', view_history_file, name="view_history_file"),
url(r'^repo/(?P<repo_id>[-0-9a-f]{36})/trash/files/$', view_trash_file, name="view_trash_file"),
@ -327,6 +329,7 @@ urlpatterns = [
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/file/history/$', FileHistoryView.as_view(), name='api-v2.1-file-history-view'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/file/new_history/$', NewFileHistoryView.as_view(), name='api-v2.1-new-file-history-view'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/dir/$', DirView.as_view(), name='api-v2.1-dir-view'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/commits/(?P<commit_id>[0-9a-f]{40})/dir/$', RepoCommitDirView.as_view(), name='api-v2.1-repo-commit-dir'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/dir/detail/$', DirDetailView.as_view(), name='api-v2.1-dir-detail-view'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/trash/$', RepoTrash.as_view(), name='api-v2.1-repo-trash'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/history/$', RepoHistory.as_view(), name='api-v2.1-repo-history'),

View File

@ -409,7 +409,6 @@ def dir_recycle_view(request, repo_id):
if not seafile_api.get_dir_id_by_path(repo_id, dir_path) or \
check_folder_permission(request, repo_id, dir_path) != 'rw':
return render_permission_error(request, _(u'Unable to view recycle page'))
commit_id = request.GET.get('commit_id', '')
@ -419,6 +418,30 @@ def dir_recycle_view(request, repo_id):
else:
return render_dir_recycle_dir(request, repo_id, commit_id, dir_path, referer)
@login_required
def repo_folder_trash(request, repo_id):
path = request.GET.get('path', '/')
if not seafile_api.get_dir_id_by_path(repo_id, path) or \
check_folder_permission(request, repo_id, path) != 'rw':
return render_permission_error(request, _(u'Unable to view recycle page'))
repo = get_repo(repo_id)
if not repo:
raise Http404
if path == '/':
name = repo.name
else:
name = os.path.basename(path.rstrip('/'))
return render(request, 'repo_folder_trash_react.html', {
'repo': repo,
'repo_folder_name': name,
'path': path,
'enable_clean': config.ENABLE_USER_CLEAN_TRASH,
})
def can_access_repo_setting(request, repo_id, username):
repo = seafile_api.get_repo(repo_id)
if not repo:

View File

@ -0,0 +1,97 @@
import os
import json
from django.core.urlresolvers import reverse
from seaserv import seafile_api
from seahub.test_utils import BaseTestCase
from seahub.utils import normalize_dir_path
from tests.common.utils import randstring
class RepoCommitDirTest(BaseTestCase):
def setUp(self):
self.user_name = self.user.username
self.admin_name = self.admin.username
self.repo_id = self.repo.id
self.repo_name = self.repo.repo_name
self.file_path = self.file
self.file_name = os.path.basename(self.file_path)
self.folder_path = self.folder
self.folder_name = os.path.basename(self.folder.rstrip('/'))
self.inner_file_name = 'inner.txt'
self.inner_file = self.create_file(
repo_id=self.repo.id, parent_dir=self.folder_path,
filename=self.inner_file_name, username=self.user_name)
self.trash_url = reverse('api-v2.1-repo-trash', args=[self.repo_id])
def tearDown(self):
self.remove_repo()
self.remove_group()
def test_get(self):
# delete a folder first
seafile_api.del_file(self.repo_id, '/', self.folder_name, self.user_name)
self.login_as(self.user)
# get commit id
trash_resp = self.client.get(self.trash_url)
self.assertEqual(200, trash_resp.status_code)
trash_json_resp = json.loads(trash_resp.content)
assert trash_json_resp['data'][0]['obj_name'] == self.folder_name
assert trash_json_resp['data'][0]['is_dir']
assert trash_json_resp['data'][0]['commit_id']
commit_id = trash_json_resp['data'][0]['commit_id']
url = reverse('api-v2.1-repo-commit-dir', args=[self.repo_id, commit_id])
# test can get
resp = self.client.get(url + '?path=' + self.folder_path)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['dirent_list']
assert json_resp['dirent_list'][0]
assert json_resp['dirent_list'][0]['type'] == 'file'
assert json_resp['dirent_list'][0]['name'] == self.inner_file_name
assert json_resp['dirent_list'][0]['parent_dir'] == normalize_dir_path(self.folder_path)
assert json_resp['dirent_list'][0]['size'] == 0
# test can get without path
resp = self.client.get(url)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['dirent_list']
assert json_resp['dirent_list'][0]
assert json_resp['dirent_list'][0]['type'] == 'dir'
assert json_resp['dirent_list'][0]['name'] == self.folder_name
assert json_resp['dirent_list'][0]['parent_dir'] == '/'
assert json_resp['dirent_list'][0]['obj_id']
assert json_resp['dirent_list'][1]
assert json_resp['dirent_list'][1]['type'] == 'file'
assert json_resp['dirent_list'][1]['name'] == self.file_name
assert json_resp['dirent_list'][1]['parent_dir'] == '/'
assert json_resp['dirent_list'][0]['obj_id']
assert json_resp['dirent_list'][1]['size'] == 0
# test_can_not_get_with_invalid_path_parameter
invalid_path = randstring(6)
resp = self.client.get(url + '?path=' + invalid_path)
self.assertEqual(404, resp.status_code)
# test_can_not_get_with_invalid_repo_permission
self.logout()
self.login_as(self.admin)
resp = self.client.get(url + '?path=' + self.folder_path)
self.assertEqual(403, resp.status_code)