seperate component for file drop and upload

correct save position of uploaded files
then parse video file
This commit is contained in:
lukas 2021-09-23 17:38:20 +02:00
parent d3bd810a1a
commit a92ce73806
6 changed files with 173 additions and 77 deletions

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"io" "io"
"openmediacenter/apiGo/api/api" "openmediacenter/apiGo/api/api"
"openmediacenter/apiGo/database"
"openmediacenter/apiGo/videoparser"
"os" "os"
) )
@ -12,45 +14,49 @@ func addUploadHandler() {
fmt.Println("we are in file upload handler") fmt.Println("we are in file upload handler")
fmt.Printf("permission: %s\n", ctx.PermID().String()) fmt.Printf("permission: %s\n", ctx.PermID().String())
// get path where to store videos to
mSettings, PathPrefix, _ := database.GetSettings()
req := ctx.GetRequest() req := ctx.GetRequest()
mr, err := req.MultipartReader() mr, err := req.MultipartReader()
if err != nil { if err != nil {
return return
} }
length := req.ContentLength //length := req.ContentLength
fmt.Println(length)
for { for {
part, err := mr.NextPart() part, err := mr.NextPart()
if err == io.EOF { if err == io.EOF {
fmt.Println("part is eof")
break break
} }
fmt.Println(part.FormName()) //var read int64
//var p float32
var read int64
var p float32
// todo check where we want to place this file // todo check where we want to place this file
dst, err := os.OpenFile(part.FileName(), os.O_WRONLY|os.O_CREATE, 0644) vidpath := PathPrefix + mSettings.VideoPath + part.FileName()
dst, err := os.OpenFile(vidpath, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil { if err != nil {
return return
} }
fmt.Printf("Uploading file %s\n", part.FileName())
// so now loop through every appended file and upload // so now loop through every appended file and upload
buffer := make([]byte, 100000) buffer := make([]byte, 100000)
for { for {
cBytes, err := part.Read(buffer) cBytes, err := part.Read(buffer)
if cBytes > 0 { if cBytes > 0 {
read = read + int64(cBytes) //read = read + int64(cBytes)
p = float32(read) / float32(length) * 100 //p = float32(read) / float32(length) * 100
fmt.Printf("progress: %v \n", p) //fmt.Printf("progress: %v \n", p)
dst.Write(buffer[0:cBytes]) dst.Write(buffer[0:cBytes])
} }
if err == io.EOF { if err == io.EOF {
fmt.Println(cBytes) fmt.Printf("Finished uploading file %s\n", part.FileName())
fmt.Println("eof this file")
videoparser.InitDeps(&mSettings)
videoparser.ProcessVideo(part.FileName())
break break
} }
} }
@ -58,6 +64,6 @@ func addUploadHandler() {
_ = dst.Close() _ = dst.Close()
} }
ctx.Text("finished") ctx.Text("finished all files")
}) })
} }

View File

@ -11,7 +11,7 @@ import (
"strings" "strings"
) )
var mSettings types.SettingsType var mSettings *types.SettingsType
var mExtDepsAvailable *ExtDependencySupport var mExtDepsAvailable *ExtDependencySupport
// default Tag ids // default Tag ids
@ -32,20 +32,22 @@ type VideoAttributes struct {
Width uint Width uint
} }
func ReIndexVideos(path []string, sett types.SettingsType) { func InitDeps(sett *types.SettingsType) {
mSettings = sett mSettings = sett
// check if the extern dependencies are available // check if the extern dependencies are available
mExtDepsAvailable = checkExtDependencySupport() mExtDepsAvailable = checkExtDependencySupport()
fmt.Printf("FFMPEG support: %t\n", mExtDepsAvailable.FFMpeg) fmt.Printf("FFMPEG support: %t\n", mExtDepsAvailable.FFMpeg)
fmt.Printf("MediaInfo support: %t\n", mExtDepsAvailable.MediaInfo) fmt.Printf("MediaInfo support: %t\n", mExtDepsAvailable.MediaInfo)
}
func ReIndexVideos(path []string) {
// filter out those urls which are already existing in db // filter out those urls which are already existing in db
nonExisting := filterExisting(path) nonExisting := filterExisting(path)
fmt.Printf("There are %d videos not existing in db.\n", len(*nonExisting)) fmt.Printf("There are %d videos not existing in db.\n", len(*nonExisting))
for _, s := range *nonExisting { for _, s := range *nonExisting {
processVideo(s) ProcessVideo(s)
} }
AppendMessage("reindex finished successfully!") AppendMessage("reindex finished successfully!")
@ -92,8 +94,8 @@ func filterExisting(paths []string) *[]string {
return &resultarr return &resultarr
} }
func processVideo(fileNameOrig string) { func ProcessVideo(fileNameOrig string) {
fmt.Printf("Processing %s video-", fileNameOrig) fmt.Printf("Processing %s video\n", fileNameOrig)
// match the file extension // match the file extension
r := regexp.MustCompile(`\.[a-zA-Z0-9]+$`) r := regexp.MustCompile(`\.[a-zA-Z0-9]+$`)

View File

@ -49,7 +49,8 @@ func StartReindex() bool {
} }
// start reindex process // start reindex process
AppendMessage("Starting Reindexing!") AppendMessage("Starting Reindexing!")
go ReIndexVideos(files, mSettings) InitDeps(&mSettings)
go ReIndexVideos(files)
return true return true
} }

View File

@ -0,0 +1,57 @@
.container {
}
.dropArea {
border: 2px dashed #ccc;
border-radius: 20px;
width: 480px;
font-family: sans-serif;
margin: 100px auto;
padding: 20px;
background-color: grey;
}
.dropArea:hover{
cursor: pointer;
}
.dropArea.highlight {
border-color: purple;
}
p {
margin-top: 0;
}
.myForm {
margin-bottom: 10px;
}
.gallery {
margin-top: 10px;
}
.gallery img {
width: 150px;
margin-bottom: 10px;
margin-right: 10px;
vertical-align: middle;
}
.button {
display: inline-block;
padding: 10px;
background: #ccc;
cursor: pointer;
border-radius: 5px;
border: 1px solid #ccc;
}
.button:hover {
background: #ddd;
}
.fileElem {
display: none;
}

View File

@ -0,0 +1,84 @@
import style from './DropZone.module.css';
import React, {useState} from 'react';
import {cookie} from '../../utils/context/Cookie';
export const DropZone = (): JSX.Element => {
const [ondrag, setDrag] = useState(0);
const [percent, setpercent] = useState(0.0);
const uploadFile = (f: FileList): void => {
let xhr = new XMLHttpRequest(); // create XMLHttpRequest
let data = new FormData(); // create formData object
for (let i = 0; i < f.length; i++) {
const file = f.item(i);
if (file) {
data.append('file' + i, file);
}
}
xhr.onload = function (): void {
console.log(this.responseText); // whatever the server returns
};
xhr.upload.onprogress = function (e): void {
console.log(e.loaded / e.total);
setpercent((e.loaded * 100.0) / e.total);
};
xhr.open('post', '/api/video/fileupload'); // open connection
xhr.setRequestHeader('Accept', 'multipart/form-data');
const tkn = cookie.Load();
if (tkn) {
xhr.setRequestHeader('Token', tkn.Token);
}
xhr.send(data); // send data
};
return (
<div
className={style.dropArea + (ondrag > 0 ? ' ' + style.highlight : '')}
onDragEnter={(e): void => {
e.preventDefault();
e.stopPropagation();
setDrag(ondrag + 1);
}}
onDragLeave={(e): void => {
e.preventDefault();
e.stopPropagation();
setDrag(ondrag - 1);
}}
onDragOver={(e): void => {
e.stopPropagation();
e.preventDefault();
}}
onDrop={(e): void => {
setDrag(0);
e.preventDefault();
e.stopPropagation();
uploadFile(e.dataTransfer.files);
}}
onClick={(): void => {
let input = document.createElement('input');
input.type = 'file';
input.multiple = true;
input.onchange = function (): void {
if (input.files) {
console.log(input.files);
uploadFile(input.files);
}
};
input.click();
}}>
<div className={style.myForm}>
<p>To upload new Videos darg and drop them here or click to select some...</p>
<div style={{width: '100%', height: 5, marginTop: 3}}>
<div style={{width: percent + '%', backgroundColor: 'green', height: 5}} />
</div>
</div>
</div>
);
};

View File

@ -1,8 +1,8 @@
import React, {BaseSyntheticEvent, useState} from 'react'; import React from 'react';
import style from './MovieSettings.module.css'; import style from './MovieSettings.module.css';
import {APINode, callAPI} from '../../utils/Api'; import {APINode, callAPI} from '../../utils/Api';
import {GeneralSuccess} from '../../types/GeneralTypes'; import {GeneralSuccess} from '../../types/GeneralTypes';
import {cookie} from '../../utils/context/Cookie'; import {DropZone} from '../../elements/DropZone/DropZone';
interface state { interface state {
text: string[]; text: string[];
@ -124,7 +124,7 @@ class MovieSettings extends React.Component<Props, state> {
</div> </div>
))} ))}
</div> </div>
<FileHandler /> <DropZone />
</> </>
); );
} }
@ -164,57 +164,3 @@ class MovieSettings extends React.Component<Props, state> {
} }
export default MovieSettings; export default MovieSettings;
const FileHandler = (): JSX.Element => {
const [file, setfile] = useState<File | null>(null);
const [percent, setpercent] = useState(0.0);
const uploadFile = (): void => {
let xhr = new XMLHttpRequest(); // create XMLHttpRequest
let data = new FormData(); // create formData object
if (!file) {
return;
}
data.append('file', file);
xhr.onload = function (): void {
console.log(this.responseText); // whatever the server returns
};
xhr.upload.onprogress = function (e): void {
console.log(e.loaded / e.total);
setpercent((e.loaded * 100.0) / e.total);
};
xhr.open('post', '/api/video/fileupload'); // open connection
xhr.setRequestHeader('Accept', 'multipart/form-data');
const tkn = cookie.Load();
if (tkn) {
xhr.setRequestHeader('Token', tkn.Token);
}
xhr.send(data); // send data
};
return (
<div style={{backgroundColor: 'white'}}>
<input
onChange={(e: BaseSyntheticEvent): void => {
console.log(e);
if (e.target) {
console.log(e.target.files[0]);
setfile(e.target.files[0]);
// setfile(e.target.files[0]);
}
}}
type='file'
name='Select file to upload'
/>
<button onClick={(): void => uploadFile()}>upload</button>
<div style={{width: '100%', height: 5, marginTop: 3}}>
<div style={{width: percent + '%', backgroundColor: 'green', height: 5}} />
</div>
</div>
);
};