Skip to content

Commit

Permalink
Upload file module
Browse files Browse the repository at this point in the history
  • Loading branch information
kingiw committed Dec 24, 2019
1 parent d923a4a commit 34e2c17
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 5 deletions.
56 changes: 52 additions & 4 deletions controllers/dashboard.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package controllers

import (
"fmt"
"strconv"

"github.com/microsoft/mouselog/detect"
"github.com/microsoft/mouselog/fileutils"
"github.com/microsoft/mouselog/trace"
"github.com/microsoft/mouselog/util"
)
Expand Down Expand Up @@ -38,7 +42,7 @@ func listTraceFiles(path string) []*trace.Session {
kv := util.SortMapsByKey(&m)
for _, v := range *kv {
res = append(res, v.Key.(*trace.Session))
}
}

return res
}
Expand Down Expand Up @@ -66,10 +70,54 @@ func (c *ApiController) ListTraces() {
}
table := ss.Traces[(perPage * page):last]

c.Data["json"] = map[string]interface{} {
c.Data["json"] = map[string]interface{}{
"traces": table,
"page": page,
"total": len(ss.Traces),
"page": page,
"total": len(ss.Traces),
}
c.ServeJSON()
}

func (c *ApiController) UploadFile() {
sessionId := c.StartSession().SessionID()
fmt.Printf("[SessionId %s]\n", sessionId)

fileCount := 0
success := 0
message := ""

for {
fmt.Println("file" + strconv.Itoa(fileCount))
_, header, err := c.GetFile("file" + strconv.Itoa(fileCount))
if err != nil {
break
}
filename := header.Filename
file, err := header.Open()
if err != nil {
panic(err)
}

traces, errMsg := fileutils.JsonParser(file)
if errMsg != "" {
message += fmt.Sprintf("\n%s: %s", filename, errMsg)
success = -1
} else {
for _, trace := range traces {
// Use Filename as SessionId
ss := getOrCreateSs(header.Filename)
if len(trace.Events) != 0 {
ss.AddTrace(&trace)
}
}
}
fmt.Printf("[Filename: %s]\n", header.Filename)
fileCount++
}

c.Data["json"] = map[string]interface{}{
"success": success,
"message": message,
}
c.ServeJSON()
}
28 changes: 28 additions & 0 deletions fileutils/fileutils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package fileutils

import (
"encoding/json"
"io/ioutil"
"mime/multipart"

"github.com/microsoft/mouselog/trace"
)

type JsonFile struct {
Data []trace.Trace `json:"data"`
}

func JsonParser(file multipart.File) (traces []trace.Trace, errMsg string) {
content, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
defer file.Close()
t := JsonFile{}
err = json.Unmarshal(content, &t)
if err != nil {
return nil, "Cannot decode JSON file."
}
traces = t.Data
return traces, ""
}
1 change: 1 addition & 0 deletions routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ func initAPI() {
beego.Router("/api/list-traces", &controllers.ApiController{}, "GET:ListTraces")

beego.Router("/api/list-rules", &controllers.ApiController{}, "GET:ListRules")
beego.Router("/api/upload-file", &controllers.ApiController{}, "POST:UploadFile")
}
3 changes: 2 additions & 1 deletion web/src/DashboardPage.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React from "react";
import * as Setting from "./Setting";
import * as Shared from "./Shared";
import {Table, Row, Col, Typography, Tag} from 'antd';
import {Link} from "react-router-dom";
import Canvas from "./Canvas";
import * as Backend from "./Backend";
import TraceTable from "./TraceTable";
import UploadFile from "./UploadFile";

const {Text} = Typography;

Expand Down Expand Up @@ -122,6 +122,7 @@ class DashboardPage extends React.Component {
<div>
<Table rowSelection={rowRadioSelection} columns={columns} dataSource={this.state.sessions} size="small"
bordered title={() => 'Sessions'}/>
<UploadFile />
</div>
);
}
Expand Down
95 changes: 95 additions & 0 deletions web/src/UploadFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import React from "react"
import * as Setting from "./Setting";
import {Icon, Button, Upload, message} from 'antd'

class UploadFile extends React.Component {
state = {
fileList: [],
uploading: false,
};

handleUpload = () => {
const { fileList } = this.state;
// A form must be created for uploaded the files
const formData = new FormData();

for (let i = 0; i < fileList.length; ++i) {
formData.append(`file${i}`, fileList[i]);
}

this.setState({
uploading: true,
});

fetch(`${Setting.ServerUrl}/api/upload-file`, {
method: 'POST',
credentials: "include",
body: formData,
})
.then(res => res.json())
.then(
res => {
if (res.success === 0)
{
message.success('All files are upload successfully');
} else {
message.error(`Error:\n${res.message}`)
}
this.setState({
fileList: [],
uploading: false,
});
}
)
.catch(
err => {
this.setState({uploading: false})
message.error('upload failed')
}
);
};

render() {
const { uploading, fileList } = this.state;
const props = {
onRemove: file => {
this.setState(state => {
const index = state.fileList.indexOf(file);
const newFileList = state.fileList.slice();
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
});
},
beforeUpload: file => {
this.setState(state => ({
fileList: [...state.fileList, file],
}));
return false;
},
fileList,
};

return (
<div>
<Upload {...props}>
<Button>
<Icon type="upload" /> Select File
</Button>
</Upload>
<Button
type="primary"
onClick={this.handleUpload}
disabled={fileList.length === 0}
loading={uploading}
style={{ marginTop: 16 }}
>
{uploading ? 'Uploading' : 'Start Upload'}
</Button>
</div>
);
}
}

export default UploadFile;

0 comments on commit 34e2c17

Please sign in to comment.