OpenDroneMap-WebODM/app/static/app/js/components/ProjectListItem.jsx

513 wiersze
16 KiB
React
Czysty Zwykły widok Historia

import '../css/ProjectListItem.scss';
import React from 'react';
import update from 'immutability-helper';
2016-10-25 14:47:49 +00:00
import TaskList from './TaskList';
import NewTaskPanel from './NewTaskPanel';
2019-02-20 21:42:20 +00:00
import ImportTaskPanel from './ImportTaskPanel';
import UploadProgressBar from './UploadProgressBar';
import ErrorMessage from './ErrorMessage';
import EditProjectDialog from './EditProjectDialog';
import Dropzone from '../vendor/dropzone';
import csrf from '../django/csrf';
import HistoryNav from '../classes/HistoryNav';
2017-09-06 15:47:04 +00:00
import PropTypes from 'prop-types';
2019-06-27 15:29:46 +00:00
import ResizeModes from '../classes/ResizeModes';
import $ from 'jquery';
class ProjectListItem extends React.Component {
2017-09-06 15:47:04 +00:00
static propTypes = {
history: PropTypes.object.isRequired,
data: PropTypes.object.isRequired, // project json
onDelete: PropTypes.func
}
2016-10-11 20:37:00 +00:00
constructor(props){
super(props);
this.historyNav = new HistoryNav(props.history);
this.state = {
showTaskList: this.historyNav.isValueInQSList("project_task_open", props.data.id),
upload: this.getDefaultUploadState(),
error: "",
2016-11-15 16:51:19 +00:00
data: props.data,
2019-02-20 21:42:20 +00:00
refreshing: false,
2019-08-29 02:16:39 +00:00
importing: false,
buttons: []
};
2016-10-25 14:47:49 +00:00
this.toggleTaskList = this.toggleTaskList.bind(this);
2016-10-18 15:25:14 +00:00
this.closeUploadError = this.closeUploadError.bind(this);
this.cancelUpload = this.cancelUpload.bind(this);
2016-10-21 14:42:46 +00:00
this.handleTaskSaved = this.handleTaskSaved.bind(this);
this.viewMap = this.viewMap.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handleEditProject = this.handleEditProject.bind(this);
this.updateProject = this.updateProject.bind(this);
this.taskDeleted = this.taskDeleted.bind(this);
this.hasPermission = this.hasPermission.bind(this);
}
2016-11-15 16:51:19 +00:00
refresh(){
// Update project information based on server
this.setState({refreshing: true});
this.refreshRequest =
$.getJSON(`/api/projects/${this.state.data.id}/`)
.done((json) => {
this.setState({data: json});
})
.fail((_, __, e) => {
this.setState({error: e.message});
})
.always(() => {
this.setState({refreshing: false});
});
}
componentWillUnmount(){
if (this.deleteProjectRequest) this.deleteProjectRequest.abort();
2016-11-15 16:51:19 +00:00
if (this.refreshRequest) this.refreshRequest.abort();
}
getDefaultUploadState(){
return {
uploading: false,
editing: false,
2016-10-18 15:25:14 +00:00
error: "",
progress: 0,
files: [],
totalCount: 0,
uploadedCount: 0,
totalBytes: 0,
totalBytesSent: 0,
lastUpdated: 0
};
}
resetUploadState(){
this.setUploadState(this.getDefaultUploadState());
}
setUploadState(props){
this.setState(update(this.state, {
upload: {
$merge: props
}
}));
}
hasPermission(perm){
return this.state.data.permissions.indexOf(perm) !== -1;
}
componentDidMount(){
Dropzone.autoDiscover = false;
if (this.hasPermission("add")){
this.dz = new Dropzone(this.dropzone, {
paramName: "images",
url : 'TO_BE_CHANGED',
2019-06-27 15:29:46 +00:00
parallelUploads: 6,
uploadMultiple: false,
2018-03-31 17:08:56 +00:00
acceptedFiles: "image/*,text/*",
autoProcessQueue: false,
createImageThumbnails: false,
clickable: this.uploadButton,
chunkSize: 2147483647,
timeout: 2147483647,
headers: {
[csrf.header]: csrf.token
}
});
2016-10-21 14:42:46 +00:00
this.dz.on("addedfiles", files => {
let totalBytes = 0;
for (let i = 0; i < files.length; i++){
totalBytes += files[i].size;
files[i].deltaBytesSent = 0;
files[i].trackedBytesSent = 0;
files[i].retries = 0;
}
this.setUploadState({
editing: true,
totalCount: this.state.upload.totalCount + files.length,
files,
totalBytes: this.state.upload.totalBytes + totalBytes
});
})
.on("uploadprogress", (file, progress, bytesSent) => {
const now = new Date().getTime();
if (now - this.state.upload.lastUpdated > 500){
file.deltaBytesSent = bytesSent - file.deltaBytesSent;
file.trackedBytesSent += file.deltaBytesSent;
const totalBytesSent = this.state.upload.totalBytesSent + file.deltaBytesSent;
const progress = totalBytesSent / this.state.upload.totalBytes * 100;
this.setUploadState({
progress,
totalBytesSent,
lastUpdated: now
});
}
})
.on("complete", (file) => {
// Retry
const retry = () => {
const MAX_RETRIES = 10;
if (file.retries < MAX_RETRIES){
// Update progress
const totalBytesSent = this.state.upload.totalBytesSent - file.trackedBytesSent;
const progress = totalBytesSent / this.state.upload.totalBytes * 100;
this.setUploadState({
progress,
totalBytesSent,
});
file.status = Dropzone.QUEUED;
file.deltaBytesSent = 0;
file.trackedBytesSent = 0;
file.retries++;
this.dz.processQueue();
}else{
throw new Error(`Cannot upload ${file.name}, exceeded max retries (${MAX_RETRIES})`);
}
};
try{
if (file.status === "error"){
retry();
}else{
// Check response
let response = JSON.parse(file.xhr.response);
if (response.success){
// Update progress by removing the tracked progress and
// use the file size as the true number of bytes
let totalBytesSent = this.state.upload.totalBytesSent + file.size;
if (file.trackedBytesSent) totalBytesSent -= file.trackedBytesSent;
const progress = totalBytesSent / this.state.upload.totalBytes * 100;
this.setUploadState({
progress,
totalBytesSent,
uploadedCount: this.state.upload.uploadedCount + 1
});
this.dz.processQueue();
}else{
retry();
}
}
}catch(e){
this.setUploadState({error: `${e.message}`, uploading: false});
this.dz.cancelUpload();
}
})
.on("queuecomplete", () => {
const remainingFilesCount = this.state.upload.totalCount - this.state.upload.uploadedCount;
if (remainingFilesCount === 0){
// All files have uploaded!
this.setUploadState({uploading: false});
$.ajax({
url: `/api/projects/${this.state.data.id}/tasks/${this.dz._taskInfo.id}/commit/`,
contentType: 'application/json',
dataType: 'json',
type: 'POST'
}).done((task) => {
if (task && task.id){
this.newTaskAdded();
}else{
this.setUploadState({error: `Cannot create new task. Invalid response from server: ${JSON.stringify(task)}`});
}
}).fail(() => {
this.setUploadState({error: "Cannot create new task. Please try again later."});
});
}else if (this.dz.getQueuedFiles() === 0){
// Done but didn't upload all?
this.setUploadState({
totalCount: this.state.upload.totalCount - remainingFilesCount,
uploading: false,
error: `${remainingFilesCount} files cannot be uploaded. As a reminder, only images (.jpg, .png) and GCP files (.txt) can be uploaded. Try again.`
});
}
})
.on("reset", () => {
this.resetUploadState();
})
.on("dragenter", () => {
if (!this.state.upload.editing){
this.resetUploadState();
}
});
}
2019-08-29 02:16:39 +00:00
PluginsAPI.Dashboard.triggerAddNewTaskButton({projectId: this.state.data.id, onNewTaskAdded: this.newTaskAdded}, (button) => {
if (!button) return;
2019-09-07 18:35:30 +00:00
2019-08-29 02:16:39 +00:00
this.setState(update(this.state, {
buttons: {$push: [button]}
}));
});
}
2019-02-21 19:16:48 +00:00
newTaskAdded = () => {
this.setState({importing: false});
if (this.state.showTaskList){
this.taskList.refresh();
}else{
this.setState({showTaskList: true});
}
this.resetUploadState();
this.refresh();
}
setRef(prop){
return (domNode) => {
if (domNode != null) this[prop] = domNode;
}
}
2016-10-25 14:47:49 +00:00
toggleTaskList(){
const showTaskList = !this.state.showTaskList;
this.historyNav.toggleQSListItem("project_task_open", this.state.data.id, showTaskList);
2016-10-11 20:37:00 +00:00
this.setState({
showTaskList: showTaskList
2016-10-11 20:37:00 +00:00
});
}
2016-10-18 15:25:14 +00:00
closeUploadError(){
this.setUploadState({error: ""});
}
cancelUpload(e){
this.dz.removeAllFiles(true);
}
taskDeleted(){
2016-11-15 16:51:19 +00:00
this.refresh();
}
handleDelete(){
2016-11-15 16:51:19 +00:00
return $.ajax({
url: `/api/projects/${this.state.data.id}/`,
type: 'DELETE'
}).done(() => {
if (this.props.onDelete) this.props.onDelete(this.state.data.id);
});
}
2016-10-21 14:42:46 +00:00
handleTaskSaved(taskInfo){
this.dz._taskInfo = taskInfo; // Allow us to access the task info from dz
2019-06-27 15:19:52 +00:00
this.setUploadState({uploading: true, editing: false});
// Create task
const formData = {
name: taskInfo.name,
options: taskInfo.options,
processing_node: taskInfo.selectedNode.id,
auto_processing_node: taskInfo.selectedNode.key == "auto",
partial: true
};
2019-06-27 15:29:46 +00:00
if (taskInfo.resizeMode === ResizeModes.YES){
formData.resize_to = taskInfo.resizeSize;
}
$.ajax({
url: `/api/projects/${this.state.data.id}/tasks/`,
contentType: 'application/json',
data: JSON.stringify(formData),
dataType: 'json',
type: 'POST'
}).done((task) => {
if (task && task.id){
this.dz._taskInfo.id = task.id;
this.dz.options.url = `/api/projects/${this.state.data.id}/tasks/${task.id}/upload/`;
this.dz.processQueue();
}else{
this.setState({error: `Cannot create new task. Invalid response from server: ${JSON.stringify(task)}`});
this.handleTaskCanceled();
}
}).fail(() => {
this.setState({error: "Cannot create new task. Please try again later."});
this.handleTaskCanceled();
});
}
handleTaskCanceled = () => {
this.dz.removeAllFiles(true);
this.resetUploadState();
}
handleUpload = () => {
// Not a second click for adding more files?
if (!this.state.upload.editing){
this.handleTaskCanceled();
}
2016-10-21 14:42:46 +00:00
}
handleEditProject(){
this.editProjectDialog.show();
}
updateProject(project){
2016-11-15 16:51:19 +00:00
return $.ajax({
url: `/api/projects/${this.state.data.id}/`,
contentType: 'application/json',
data: JSON.stringify({
name: project.name,
description: project.descr,
}),
dataType: 'json',
type: 'PATCH'
}).done(() => {
this.refresh();
});
}
viewMap(){
2016-11-15 16:51:19 +00:00
location.href = `/map/project/${this.state.data.id}/`;
}
2019-02-20 21:42:20 +00:00
handleImportTask = () => {
this.setState({importing: true});
}
handleCancelImportTask = () => {
this.setState({importing: false});
}
2016-10-21 14:42:46 +00:00
render() {
2016-11-15 16:51:19 +00:00
const { refreshing, data } = this.state;
const numTasks = data.tasks.length;
return (
2016-11-15 16:51:19 +00:00
<li className={"project-list-item list-group-item " + (refreshing ? "refreshing" : "")}
2016-11-11 18:22:29 +00:00
href="javascript:void(0);"
ref={this.setRef("dropzone")}
>
<EditProjectDialog
ref={(domNode) => { this.editProjectDialog = domNode; }}
title="Edit Project"
saveLabel="Save Changes"
savingLabel="Saving changes..."
saveIcon="fa fa-edit"
2016-11-15 16:51:19 +00:00
projectName={data.name}
projectDescr={data.description}
saveAction={this.updateProject}
deleteAction={this.hasPermission("delete") ? this.handleDelete : undefined}
/>
2016-10-18 15:25:14 +00:00
<div className="row no-margin">
<ErrorMessage bind={[this, 'error']} />
2016-10-18 15:25:14 +00:00
<div className="btn-group pull-right">
{this.hasPermission("add") ?
2019-02-20 21:42:20 +00:00
<div className={"asset-download-buttons btn-group " + (this.state.upload.uploading ? "hide" : "")}>
<button type="button"
className="btn btn-primary btn-sm"
onClick={this.handleUpload}
ref={this.setRef("uploadButton")}>
2019-05-15 19:50:36 +00:00
<i className="glyphicon glyphicon-upload"></i>
Select Images and GCP
</button>
<button type="button"
className="btn btn-default btn-sm"
onClick={this.handleImportTask}>
2019-05-15 20:18:38 +00:00
<i className="glyphicon glyphicon-import"></i> Import
2019-05-15 19:50:36 +00:00
</button>
2019-09-07 18:35:30 +00:00
{this.state.buttons.map((button, i) => <React.Fragment key={i}>{button}</React.Fragment>)}
2019-05-15 19:50:36 +00:00
</div>
: ""}
2016-10-18 15:25:14 +00:00
<button disabled={this.state.upload.error !== ""}
type="button"
className={"btn btn-danger btn-sm " + (!this.state.upload.uploading ? "hide" : "")}
2016-10-18 15:25:14 +00:00
onClick={this.cancelUpload}>
<i className="glyphicon glyphicon-remove-circle"></i>
Cancel Upload
</button>
<button type="button" className="btn btn-default btn-sm" onClick={this.viewMap}>
<i className="fa fa-globe"></i> View Map
2016-10-18 15:25:14 +00:00
</button>
</div>
2016-10-11 20:37:00 +00:00
2016-10-25 14:47:49 +00:00
<span className="project-name">
2016-11-15 16:51:19 +00:00
{data.name}
2016-10-25 14:47:49 +00:00
</span>
<div className="project-description">
2016-11-15 16:51:19 +00:00
{data.description}
2016-10-25 14:47:49 +00:00
</div>
<div className="row project-links">
2016-11-15 16:51:19 +00:00
{numTasks > 0 ?
<span>
<i className='fa fa-tasks'>
</i> <a href="javascript:void(0);" onClick={this.toggleTaskList}>
2016-11-15 16:51:19 +00:00
{numTasks} Tasks <i className={'fa fa-caret-' + (this.state.showTaskList ? 'down' : 'right')}></i>
</a>
</span>
: ""}
<i className='fa fa-edit'>
</i> <a href="javascript:void(0);" onClick={this.handleEditProject}> Edit
2016-10-25 14:47:49 +00:00
</a>
</div>
2016-10-18 15:25:14 +00:00
</div>
2016-11-11 18:22:29 +00:00
<i className="drag-drop-icon fa fa-inbox"></i>
2016-10-18 15:25:14 +00:00
<div className="row">
{this.state.upload.uploading ? <UploadProgressBar {...this.state.upload}/> : ""}
2019-06-27 15:19:52 +00:00
2016-10-18 15:25:14 +00:00
{this.state.upload.error !== "" ?
<div className="alert alert-warning alert-dismissible">
<button type="button" className="close" aria-label="Close" onClick={this.closeUploadError}><span aria-hidden="true">&times;</span></button>
{this.state.upload.error}
</div>
2016-10-18 15:25:14 +00:00
: ""}
{this.state.upload.editing ?
<NewTaskPanel
onSave={this.handleTaskSaved}
onCancel={this.handleTaskCanceled}
filesCount={this.state.upload.totalCount}
showResize={true}
getFiles={() => this.state.upload.files }
2016-10-21 14:42:46 +00:00
/>
: ""}
2019-02-20 21:42:20 +00:00
{this.state.importing ?
<ImportTaskPanel
2019-02-21 19:16:48 +00:00
onImported={this.newTaskAdded}
2019-02-20 21:42:20 +00:00
onCancel={this.handleCancelImportTask}
projectId={this.state.data.id}
/>
: ""}
{this.state.showTaskList ?
<TaskList
ref={this.setRef("taskList")}
2016-11-15 16:51:19 +00:00
source={`/api/projects/${data.id}/tasks/?ordering=-created_at`}
onDelete={this.taskDeleted}
history={this.props.history}
/> : ""}
2016-10-18 15:25:14 +00:00
</div>
2016-10-11 20:37:00 +00:00
</li>
);
}
}
export default ProjectListItem;