Merge remote-tracking branch 'origin/master' into threedotsonvideohover

# Conflicts:
#	src/elements/Preview/Preview.js
This commit is contained in:
lukas 2021-01-26 17:38:35 +01:00
commit 009f21390e
86 changed files with 21507 additions and 1533 deletions

View File

@ -8,8 +8,9 @@ stages:
- deploy
cache:
key: "$CI_COMMIT_REF_SLUG" # use per branch caching
key: ${CI_COMMIT_REF_SLUG}
paths:
- .npm/
- node_modules/
include:
@ -21,7 +22,7 @@ variables:
Node_dependencies:
stage: prepare
script:
- npm install --progress=false
- npm ci --cache .npm --prefer-offline
Minimize:
stage: build
@ -67,20 +68,6 @@ Debian_Server:
- deb/OpenMediaCenter-*.deb
needs: ["Minimize"]
Electron_Client:
stage: packaging
image: electronuserland/builder:wine
script:
- npm run buildlinux
- npm run buildwin
artifacts:
expire_in: 2 days
paths:
- dist/*.rpm
- dist/*.deb
- dist/*.exe
needs: ["Minimize"]
Test_Server:
stage: deploy
image: luki42/alpineopenssh:latest

View File

@ -50,8 +50,8 @@ class Actor extends RequestBase {
// query the actors corresponding to video
$video_id = $_POST["videoid"];
$query = "SELECT actor_id, name, thumbnail FROM actors_videos
JOIN actors a on actors_videos.actor_id = a.id
$query = "SELECT a.actor_id, name, thumbnail FROM actors_videos
JOIN actors a on actors_videos.actor_id = a.actor_id
WHERE actors_videos.video_id=$video_id";
$result = $this->conn->query($query);
$this->commitMessage(json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC)));
@ -65,7 +65,9 @@ class Actor extends RequestBase {
WHERE actors_videos.actor_id=$actorid";
$result = $this->conn->query($query);
$reply = array("videos" => mysqli_fetch_all($result, MYSQLI_ASSOC));
$actorinfo = $this->conn->query("SELECT name, thumbnail, actor_id FROM actors WHERE actor_id=$actorid");
$reply = array("videos" => mysqli_fetch_all($result, MYSQLI_ASSOC), "info" => mysqli_fetch_assoc($actorinfo));
$this->commitMessage(json_encode($reply));
});

View File

@ -98,9 +98,9 @@ class Settings extends RequestBase {
WHERE 1";
if ($this->conn->query($query) === true) {
$this->commitMessage('{"success": true}');
$this->commitMessage('{"result": "success"}');
} else {
$this->commitMessage('{"success": true}');
$this->commitMessage('{"result": "success"}');
}
});
}
@ -127,9 +127,9 @@ class Settings extends RequestBase {
$cmd = 'php extractvideopreviews.php';
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, '/dev/zero', '/tmp/openmediacenterpid'));
$this->commitMessage('{"success": true}');
$this->commitMessage('{"result": "success"}');
} else {
$this->commitMessage('{"success": false}');
$this->commitMessage('{"result": "success"}');
}
});

View File

@ -34,7 +34,7 @@ class Video extends RequestBase {
$query = "SELECT movie_id,movie_name FROM videos
INNER JOIN video_tags vt on videos.movie_id = vt.video_id
INNER JOIN tags t on vt.tag_id = t.tag_id
WHERE t.tag_name = '$tag'
WHERE t.tag_id = '$tag'
ORDER BY likes DESC, create_date, movie_name";
}
}
@ -63,13 +63,13 @@ class Video extends RequestBase {
$idstring = implode(" OR ", $ids);
$return->tags = array();
$query = "SELECT t.tag_name FROM video_tags
$query = "SELECT t.tag_name,t.tag_id FROM video_tags
INNER JOIN tags t on video_tags.tag_id = t.tag_id
WHERE $idstring
GROUP BY t.tag_name";
GROUP BY t.tag_id";
$result = $this->conn->query($query);
while ($r = mysqli_fetch_assoc($result)) {
array_push($return->tags, $r);
array_push($return->tags, array('tag_name' => $r['tag_name'], 'tag_id' => $r['tag_id']));
}
$this->commitMessage(json_encode($return));
@ -123,10 +123,10 @@ class Video extends RequestBase {
// load tags of this video
$arr['tags'] = array();
$query = "SELECT t.tag_name FROM video_tags
$query = "SELECT t.tag_name, t.tag_id FROM video_tags
INNER JOIN tags t on video_tags.tag_id = t.tag_id
WHERE video_tags.video_id=$video_id
GROUP BY t.tag_name";
GROUP BY t.tag_id";
$result = $this->conn->query($query);
while ($r = mysqli_fetch_assoc($result)) {
array_push($arr['tags'], $r);
@ -147,8 +147,8 @@ class Video extends RequestBase {
}
// query the actors corresponding to video
$query = "SELECT actor_id, name, thumbnail FROM actors_videos
JOIN actors a on actors_videos.actor_id = a.id
$query = "SELECT a.actor_id, name, thumbnail FROM actors_videos
JOIN actors a on actors_videos.actor_id = a.actor_id
WHERE actors_videos.video_id=$video_id";
$result = $this->conn->query($query);
$arr['actors'] = mysqli_fetch_all($result, MYSQLI_ASSOC);

View File

@ -1,21 +0,0 @@
"use strict";
const builder = require("electron-builder");
const builds = {};
process.argv.slice(1).forEach(a => {
if (a === "--linux") {
builds.linux = [];
}
if (a === "--win") {
builds.win = [];
}
if (a === "--mac") {
builds.mac = [];
}
});
builder.build(builds).then(e => {
console.log(e);
}).catch(e => {
console.error(e);
});

View File

@ -1,6 +1,6 @@
create table if not exists actors
(
id int auto_increment
actor_id int auto_increment
primary key,
name varchar(50) null,
thumbnail mediumblob null
@ -43,7 +43,7 @@ create table if not exists actors_videos
actor_id int null,
video_id int null,
constraint actors_videos_actors_id_fk
foreign key (actor_id) references actors (id),
foreign key (actor_id) references actors (actor_id),
constraint actors_videos_videos_movie_id_fk
foreign key (video_id) references videos (movie_id)
);

View File

@ -2,12 +2,6 @@ server {
listen 8080 default_server;
listen [::]:8080 default_server;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php-fpm.sock;
}
root /var/www/openmediacenter;
index index.html;
@ -16,6 +10,12 @@ server {
error_log /var/log/nginx/openmediacenter.error.log;
location / {
try_files $uri $uri/ =404;
try_files $uri /index.html;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php-fpm.sock;
}
}

1
declaration.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module '*.css';

19522
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -18,30 +18,14 @@
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"typescript": "^4.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "CI=true react-scripts test --reporters=jest-junit --verbose --silent --coverage --reporters=default --colors",
"buildlinux": "node build.js --linux",
"buildwin": "node build.js --win",
"electron-dev": "electron ."
},
"build": {
"appId": "com.heili.openmediacenter",
"files": [
"build/**/*"
],
"directories": {
"buildResources": "assets"
},
"linux": {
"target": ["rpm","deb","snap","AppImage"]
},
"win": {
"target": ["nsis"]
}
"test": "CI=true react-scripts test --reporters=jest-junit --verbose --silent --coverage --reporters=default"
},
"jest": {
"collectCoverageFrom": [
@ -54,9 +38,23 @@
]
},
"proxy": "http://192.168.0.209",
"homepage": "./",
"homepage": "/",
"eslintConfig": {
"extends": "react-app"
"extends": [
"react-app",
"react-app/jest"
],
"overrides": [
{
"files": [
"**/*.ts?(x)"
],
"rules": {
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": "error"
}
}
]
},
"browserslist": {
"production": [
@ -73,12 +71,16 @@
"devDependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.2.2",
"electron": "^11.1.0",
"electron-builder": "^22.1.0",
"@testing-library/user-event": "^12.6.0",
"@types/react-router-dom": "^5.1.6",
"@types/react-router": "5.1.8",
"@types/jest": "^26.0.19",
"@types/node": "^12.19.9",
"@types/react": "^16.14.2",
"@types/react-dom": "^16.9.10",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest-junit": "^12.0.0",
"react-scripts": "^3.4.4"
"react-scripts": "4.0.1"
}
}

View File

@ -1,31 +0,0 @@
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
const isDev = process.env.NODE_ENV === "development";
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({width: 1500, height: 880});
mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`);
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
console.log( process.env.NODE_ENV);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});

View File

@ -1,159 +0,0 @@
import React from 'react';
import HomePage from './pages/HomePage/HomePage';
import RandomPage from './pages/RandomPage/RandomPage';
import GlobalInfos from './utils/GlobalInfos';
// include bootstraps css
import 'bootstrap/dist/css/bootstrap.min.css';
import style from './App.module.css';
import SettingsPage from './pages/SettingsPage/SettingsPage';
import CategoryPage from './pages/CategoryPage/CategoryPage';
import {callAPI} from './utils/Api';
import {NoBackendConnectionPopup} from './elements/Popups/NoBackendConnectionPopup/NoBackendConnectionPopup';
/**
* The main App handles the main tabs and which content to show
*/
class App extends React.Component {
newElement = null;
constructor(props, context) {
super(props, context);
this.state = {
page: 'default',
generalSettingsLoaded: false,
passwordsupport: null,
mediacentername: 'OpenMediaCenter',
onapierror: false
};
// bind this to the method for being able to call methods such as this.setstate
this.changeRootElement = this.changeRootElement.bind(this);
this.returnToLastElement = this.returnToLastElement.bind(this);
// set the main navigation viewbinding to the singleton
GlobalInfos.setViewBinding(this.constructViewBinding());
}
initialAPICall(){
// this is the first api call so if it fails we know there is no connection to backend
callAPI('settings.php', {action: 'loadInitialData'}, (result) =>{
// set theme
GlobalInfos.enableDarkTheme(result.DarkMode);
this.setState({
generalSettingsLoaded: true,
passwordsupport: result.passwordEnabled,
mediacentername: result.mediacenter_name,
onapierror: false
});
// set tab title to received mediacenter name
document.title = result.mediacenter_name;
}, error => {
this.setState({onapierror: true});
});
}
componentDidMount() {
this.initialAPICall();
}
/**
* create a viewbinding to call APP functions from child elements
* @returns a set of callback functions
*/
constructViewBinding() {
return {
changeRootElement: this.changeRootElement,
returnToLastElement: this.returnToLastElement
};
}
/**
* load the selected component into the main view
* @returns {JSX.Element} body element of selected page
*/
MainBody() {
let page;
if (this.state.page === 'default') {
page = <HomePage/>;
this.mypage = page;
} else if (this.state.page === 'random') {
page = <RandomPage/>;
this.mypage = page;
} else if (this.state.page === 'settings') {
page = <SettingsPage/>;
this.mypage = page;
} else if (this.state.page === 'categories') {
page = <CategoryPage/>;
this.mypage = page;
} else if (this.state.page === 'video') {
// show videoelement if neccessary
page = this.newElement;
console.log(page);
} else if (this.state.page === 'lastpage') {
// return back to last page
page = this.mypage;
} else {
page = <div>unimplemented yet!</div>;
}
return (page);
}
render() {
const themeStyle = GlobalInfos.getThemeStyle();
// add the main theme to the page body
document.body.className = themeStyle.backgroundcolor;
return (
<div className={style.app}>
<div className={[style.navcontainer, themeStyle.backgroundcolor, themeStyle.textcolor, themeStyle.hrcolor].join(' ')}>
<div className={style.navbrand}>{this.state.mediacentername}</div>
<div className={[style.navitem, themeStyle.navitem, this.state.page === 'default' ? style.navitemselected : {}].join(' ')}
onClick={() => this.setState({page: 'default'})}>Home
</div>
<div className={[style.navitem, themeStyle.navitem, this.state.page === 'random' ? style.navitemselected : {}].join(' ')}
onClick={() => this.setState({page: 'random'})}>Random Video
</div>
<div className={[style.navitem, themeStyle.navitem, this.state.page === 'categories' ? style.navitemselected : {}].join(' ')}
onClick={() => this.setState({page: 'categories'})}>Categories
</div>
<div className={[style.navitem, themeStyle.navitem, this.state.page === 'settings' ? style.navitemselected : {}].join(' ')}
onClick={() => this.setState({page: 'settings'})}>Settings
</div>
</div>
{this.state.generalSettingsLoaded ? this.MainBody() : 'loading'}
{this.state.onapierror ? this.ApiError() : null}
</div>
);
}
/**
* render a new root element into the main body
*/
changeRootElement(element) {
this.newElement = element;
this.setState({
page: 'video'
});
}
/**
* return from page to the previous page before a change
*/
returnToLastElement() {
this.setState({
page: 'lastpage'
});
}
ApiError() {
// on api error show popup and retry and show again if failing..
return (<NoBackendConnectionPopup onHide={() => this.initialAPICall()}/>);
}
}
export default App;

View File

@ -16,6 +16,7 @@
.navitem:hover {
opacity: 1;
text-decoration: none;
transition: opacity .5s;
}

View File

@ -18,71 +18,6 @@ describe('<App/>', function () {
expect(wrapper.find('.navitem')).toHaveLength(4);
});
it('simulate video view change ', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
wrapper.instance().changeRootElement(<div id='testit'/>);
expect(wrapper.find('#testit')).toHaveLength(1);
});
it('test hide video again', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
wrapper.instance().changeRootElement(<div id='testit'/>);
expect(wrapper.find('#testit')).toHaveLength(1);
wrapper.instance().returnToLastElement();
expect(wrapper.find('HomePage')).toHaveLength(1);
});
it('test fallback to last loaded page', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
wrapper.find('.navitem').findWhere(t => t.text() === 'Random Video' && t.type() === 'div').simulate('click');
wrapper.instance().changeRootElement(<div id='testit'/>);
expect(wrapper.find('#testit')).toHaveLength(1);
wrapper.instance().returnToLastElement();
expect(wrapper.find('RandomPage')).toHaveLength(1);
});
it('test home click', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
wrapper.setState({page: 'wrongvalue'});
expect(wrapper.find('HomePage')).toHaveLength(0);
wrapper.find('.navitem').findWhere(t => t.text() === 'Home' && t.type() === 'div').simulate('click');
expect(wrapper.find('HomePage')).toHaveLength(1);
});
it('test category click', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
expect(wrapper.find('CategoryPage')).toHaveLength(0);
wrapper.find('.navitem').findWhere(t => t.text() === 'Categories' && t.type() === 'div').simulate('click');
expect(wrapper.find('CategoryPage')).toHaveLength(1);
});
it('test settings click', function () {
const wrapper = shallow(<App/>);
wrapper.setState({generalSettingsLoaded: true}); // simulate fetch to have already finisheed
expect(wrapper.find('SettingsPage')).toHaveLength(0);
wrapper.find('.navitem').findWhere(t => t.text() === 'Settings' && t.type() === 'div').simulate('click');
expect(wrapper.find('SettingsPage')).toHaveLength(1);
});
it('test initial fetch from api', done => {
global.fetch = global.prepareFetchApi({
generalSettingsLoaded: true,

124
src/App.tsx Normal file
View File

@ -0,0 +1,124 @@
import React from 'react';
import HomePage from './pages/HomePage/HomePage';
import RandomPage from './pages/RandomPage/RandomPage';
import GlobalInfos from './utils/GlobalInfos';
// include bootstraps css
import 'bootstrap/dist/css/bootstrap.min.css';
import style from './App.module.css';
import SettingsPage from './pages/SettingsPage/SettingsPage';
import CategoryPage from './pages/CategoryPage/CategoryPage';
import {callAPI} from './utils/Api';
import {NoBackendConnectionPopup} from './elements/Popups/NoBackendConnectionPopup/NoBackendConnectionPopup';
import {BrowserRouter as Router, NavLink, Route, Switch} from 'react-router-dom';
import Player from './pages/Player/Player';
import ActorOverviewPage from './pages/ActorOverviewPage/ActorOverviewPage';
import ActorPage from './pages/ActorPage/ActorPage';
import {SettingsTypes} from './types/ApiTypes';
interface state {
generalSettingsLoaded: boolean;
passwordsupport: boolean;
mediacentername: string;
onapierror: boolean;
}
/**
* The main App handles the main tabs and which content to show
*/
class App extends React.Component<{}, state> {
constructor(props: {}) {
super(props);
this.state = {
generalSettingsLoaded: false,
passwordsupport: false,
mediacentername: 'OpenMediaCenter',
onapierror: false
};
}
initialAPICall(): void {
// this is the first api call so if it fails we know there is no connection to backend
callAPI('settings.php', {action: 'loadInitialData'}, (result: SettingsTypes.initialApiCallData) => {
// set theme
GlobalInfos.enableDarkTheme(result.DarkMode);
this.setState({
generalSettingsLoaded: true,
passwordsupport: result.passwordEnabled,
mediacentername: result.mediacenter_name,
onapierror: false
});
// set tab title to received mediacenter name
document.title = result.mediacenter_name;
}, error => {
this.setState({onapierror: true});
});
}
componentDidMount(): void {
this.initialAPICall();
}
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
// add the main theme to the page body
document.body.className = themeStyle.backgroundcolor;
return (
<Router>
<div className={style.app}>
<div className={[style.navcontainer, themeStyle.backgroundcolor, themeStyle.textcolor, themeStyle.hrcolor].join(' ')}>
<div className={style.navbrand}>{this.state.mediacentername}</div>
<NavLink className={[style.navitem, themeStyle.navitem].join(' ')} to={'/'} activeStyle={{opacity: '0.85'}}>Home</NavLink>
<NavLink className={[style.navitem, themeStyle.navitem].join(' ')} to={'/random'} activeStyle={{opacity: '0.85'}}>Random
Video</NavLink>
<NavLink className={[style.navitem, themeStyle.navitem].join(' ')} to={'/categories'} activeStyle={{opacity: '0.85'}}>Categories</NavLink>
<NavLink className={[style.navitem, themeStyle.navitem].join(' ')} to={'/settings'} activeStyle={{opacity: '0.85'}}>Settings</NavLink>
</div>
{this.routing()}
</div>
{this.state.onapierror ? this.ApiError() : null}
</Router>
);
}
routing(): JSX.Element {
return (
<Switch>
<Route path="/random">
<RandomPage/>
</Route>
<Route path="/categories">
<CategoryPage/>
</Route>
<Route path="/settings">
<SettingsPage/>
</Route>
<Route exact path="/player/:id">
<Player/>
</Route>
<Route exact path="/actors">
<ActorOverviewPage/>
</Route>
<Route path="/actors/:id">
<ActorPage/>
</Route>
<Route path="/">
<HomePage/>
</Route>
</Switch>
);
}
ApiError(): JSX.Element {
// on api error show popup and retry and show again if failing..
return (<NoBackendConnectionPopup onHide={(): void => this.initialAPICall()}/>);
}
}
export default App;

View File

@ -22,6 +22,14 @@
background: white;
}
.navitem {
color: white;
}
.navitem:hover {
color: white;
}
.hrcolor {
border-color: rgba(255, 255, 255, .1);
}

View File

@ -2,6 +2,14 @@
* The coloring elements for light theme
*/
.navitem {
color: black;
}
.navitem:hover {
color: black;
}
.navitem::after {
background: black;
}

View File

@ -1,43 +0,0 @@
import style from './ActorTile.module.css';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faUser} from '@fortawesome/free-solid-svg-icons';
import React from 'react';
import GlobalInfos from '../../utils/GlobalInfos';
import ActorPage from '../../pages/ActorPage/ActorPage';
class ActorTile extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className={style.actortile} onClick={() => this.handleActorClick(this.props.actor)}>
<div className={style.actortile_thumbnail}>
{this.props.actor.thumbnail === null ? <FontAwesomeIcon style={{
lineHeight: '130px'
}} icon={faUser} size='5x'/> : 'dfdf' /* todo render picture provided here! */}
</div>
<div className={style.actortile_name}>{this.props.actor.name}</div>
</div>
);
}
/**
* event handling for actor tile click
*/
handleActorClick(actor) {
// if clicklistender is defined use this one
if (this.props.onClick) {
this.props.onClick(actor.id);
return;
}
// Redirect to actor page
GlobalInfos.getViewBinding().changeRootElement(<ActorPage actor={actor}/>);
}
}
export default ActorTile;

View File

@ -5,12 +5,12 @@
float: left;
height: 200px;
margin: 3px;
width: 130px;
transition: opacity ease 0.5s;
width: 130px;
}
.actortile:hover{
.actortile:hover {
opacity: 0.7;
transition: opacity ease 0.5s;
}

View File

@ -4,24 +4,13 @@ import ActorTile from './ActorTile';
describe('<ActorTile/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<ActorTile actor={{thumbnail: "-1", name: "testname", id: 3}}/>);
const wrapper = shallow(<ActorTile actor={{thumbnail: '-1', name: 'testname', id: 3}}/>);
wrapper.unmount();
});
it('simulate click', function () {
const wrapper = shallow(<ActorTile actor={{thumbnail: "-1", name: "testname", id: 3}}/>);
const func = jest.fn();
prepareViewBinding(func);
wrapper.simulate('click');
expect(func).toBeCalledTimes(1);
});
it('simulate click with custom handler', function () {
const func = jest.fn((_) => {});
const wrapper = shallow(<ActorTile actor={{thumbnail: "-1", name: "testname", id: 3}} onClick={() => func()}/>);
const wrapper = shallow(<ActorTile actor={{thumbnail: '-1', name: 'testname', id: 3}} onClick={() => func()}/>);
const func1 = jest.fn();
prepareViewBinding(func1);

View File

@ -0,0 +1,49 @@
import style from './ActorTile.module.css';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faUser} from '@fortawesome/free-solid-svg-icons';
import React from 'react';
import {Link} from 'react-router-dom';
import {ActorType} from '../../types/VideoTypes';
interface props {
actor: ActorType;
onClick?: (actor: ActorType) => void
}
class ActorTile extends React.Component<props> {
constructor(props: props) {
super(props);
this.state = {};
}
render(): JSX.Element {
if (this.props.onClick) {
return this.renderActorTile(this.props.onClick);
} else {
return (
<Link to={{pathname: '/actors/' + this.props.actor.actor_id}}>
{this.renderActorTile(() => {
})}
</Link>
);
}
}
renderActorTile(customclickhandler: (actor: ActorType) => void): JSX.Element {
console.log(this.props.actor);
return (
<div className={style.actortile} onClick={(): void => customclickhandler(this.props.actor)}>
<div className={style.actortile_thumbnail}>
{this.props.actor.thumbnail === null ? <FontAwesomeIcon style={{
lineHeight: '130px'
}} icon={faUser} size='5x'/> : 'dfdf' /* todo render picture provided here! */}
</div>
<div className={style.actortile_name}>{this.props.actor.name}</div>
</div>
);
}
}
export default ActorTile;

View File

@ -0,0 +1,8 @@
.button {
background-color: green;
border-radius: 5px;
border-width: 0;
color: white;
margin-right: 15px;
padding: 6px;
}

View File

@ -0,0 +1,32 @@
import {shallow} from 'enzyme';
import React from 'react';
import {Button} from './Button';
function prepareFetchApi(response) {
const mockJsonPromise = Promise.resolve(response);
const mockFetchPromise = Promise.resolve({
json: () => mockJsonPromise
});
return (jest.fn().mockImplementation(() => mockFetchPromise));
}
describe('<Button/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<Button onClick={() => {}} title='test'/>);
wrapper.unmount();
});
it('renders title', function () {
const wrapper = shallow(<Button onClick={() => {}} title='test1'/>);
expect(wrapper.text()).toBe('test1');
});
it('test onclick handling', () => {
const func = jest.fn();
const wrapper = shallow(<Button onClick={func} title='test1'/>);
wrapper.find('button').simulate('click');
expect(func).toHaveBeenCalledTimes(1);
});
});

View File

@ -0,0 +1,16 @@
import React from 'react';
import style from './Button.module.css';
interface ButtonProps {
title: string | JSX.Element;
onClick?: () => void;
color?: React.CSSProperties;
}
export function Button(props: ButtonProps): JSX.Element {
return (
<button className={style.button} style={props.color} onClick={props.onClick}>
{props.title}
</button>
);
}

View File

@ -2,14 +2,23 @@ import React from 'react';
import style from './InfoHeaderItem.module.css';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {Spinner} from 'react-bootstrap';
import {IconDefinition} from '@fortawesome/fontawesome-common-types';
interface props {
onClick?: () => void
backColor: string
icon: IconDefinition
text: string | number
subtext: string | number
}
/**
* a component to display one of the short quickinfo tiles on dashboard
*/
class InfoHeaderItem extends React.Component {
render() {
class InfoHeaderItem extends React.Component<props> {
render(): JSX.Element {
return (
<div onClick={() => {
<div onClick={(): void => {
// call clicklistener if defined
if (this.props.onClick != null) this.props.onClick();
}} className={style.infoheaderitem} style={{backgroundColor: this.props.backColor}}>

View File

@ -2,11 +2,16 @@ import React from 'react';
import style from './PageTitle.module.css';
import GlobalInfos from '../../utils/GlobalInfos';
interface props {
title: string;
subtitle: string | null;
}
/**
* Component for generating PageTitle with bottom Line
*/
class PageTitle extends React.Component {
render() {
class PageTitle extends React.Component<props> {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div className={style.pageheader + ' ' + themeStyle.backgroundcolor}>
@ -26,7 +31,7 @@ class PageTitle extends React.Component {
* use this for horizontal lines to use the current active theming
*/
export class Line extends React.Component {
render() {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<>

View File

@ -1,91 +0,0 @@
import PopupBase from '../PopupBase';
import React from 'react';
import ActorTile from '../../ActorTile/ActorTile';
import style from './AddActorPopup.module.css';
import {NewActorPopupContent} from '../NewActorPopup/NewActorPopup';
import {callAPI} from '../../../utils/Api';
/**
* Popup for Adding a new Actor to a Video
*/
class AddActorPopup extends React.Component {
constructor(props) {
super(props);
this.state = {
contentDefault: true,
actors: undefined
};
this.tileClickHandler = this.tileClickHandler.bind(this);
}
render() {
return (
<>
{/* todo render actor tiles here and add search field*/}
<PopupBase title='Add new Actor to Video' onHide={this.props.onHide} banner={
<button
className={style.newactorbutton}
onClick={() => {this.setState({contentDefault: false});}}>Create new Actor</button>}>
{this.resolvePage()}
</PopupBase>
</>
);
}
componentDidMount() {
// fetch the available actors
this.loadActors();
}
/**
* selector for current showing popup page
* @returns {JSX.Element}
*/
resolvePage() {
if (this.state.contentDefault) return (this.getContent());
else return (<NewActorPopupContent onHide={() => {
this.loadActors();
this.setState({contentDefault: true});
}}/>);
}
/**
* returns content for the newActor popup
* @returns {JSX.Element}
*/
getContent() {
if (this.state.actors) {
return (<div>
{this.state.actors.map((el) => (<ActorTile actor={el} onClick={this.tileClickHandler}/>))}
</div>);
} else {
return (<div>somekind of loading</div>);
}
}
/**
* event handling for ActorTile Click
*/
tileClickHandler(actorid) {
// fetch the available actors
callAPI('actor.php', {action: 'addActorToVideo', actorid: actorid, videoid: this.props.movie_id}, result => {
if (result.result === 'success') {
// return back to player page
this.props.onHide();
} else {
console.error('an error occured while fetching actors');
console.error(result);
}
});
}
loadActors() {
callAPI('actor.php', {action: 'getAllActors'}, result => {
this.setState({actors: result});
});
}
}
export default AddActorPopup;

View File

@ -1,11 +1,19 @@
.newactorbutton {
background-color: green;
border-radius: 5px;
border-width: 0;
color: white;
margin-right: 15px;
margin-top: 12px;
padding: 6px;
background-color: green;
width: 140px;
width: 140px;
}
.searchinput {
float: left;
width: 120px;
}
.searchbar {
margin-bottom: 13px;
}

View File

@ -31,7 +31,7 @@ describe('<AddActorPopup/>', function () {
});
it('test api call and insertion of actor tiles', function () {
global.callAPIMock([{id: 1, actorname: 'test'}, {id: 2, actorname: 'test2'}]);
global.callAPIMock([{id: 1, name: 'test'}, {id: 2, name: 'test2'}]);
const wrapper = shallow(<AddActorPopup/>);
@ -40,12 +40,12 @@ describe('<AddActorPopup/>', function () {
it('simulate actortile click', function () {
const func = jest.fn();
const wrapper = shallow(<AddActorPopup onHide={() => {func()}}/>);
const wrapper = shallow(<AddActorPopup onHide={() => {func();}} movie_id={1}/>);
global.callAPIMock({result: 'success'});
wrapper.setState({actors: [{id: 1, actorname: 'test'}]}, () => {
wrapper.find('ActorTile').props().onClick();
wrapper.setState({actors: [{actor_id: 1, name: 'test'}]}, () => {
wrapper.find('ActorTile').dive().simulate('click');
expect(callAPI).toHaveBeenCalledTimes(1);
@ -55,12 +55,12 @@ describe('<AddActorPopup/>', function () {
it('test failing actortile click', function () {
const func = jest.fn();
const wrapper = shallow(<AddActorPopup onHide={() => {func()}}/>);
const wrapper = shallow(<AddActorPopup onHide={() => {func();}}/>);
global.callAPIMock({result: 'nosuccess'});
wrapper.setState({actors: [{id: 1, actorname: 'test'}]}, () => {
wrapper.find('ActorTile').props().onClick();
wrapper.setState({actors: [{actor_id: 1, name: 'test'}]}, () => {
wrapper.find('ActorTile').dive().simulate('click');
expect(callAPI).toHaveBeenCalledTimes(1);
@ -68,4 +68,10 @@ describe('<AddActorPopup/>', function () {
expect(func).toHaveBeenCalledTimes(0);
});
});
it('test no actor on loading', function () {
const wrapper = shallow(<AddActorPopup/>);
expect(wrapper.find('PopupBase').find('ActorTile')).toHaveLength(0);
});
});

View File

@ -0,0 +1,160 @@
import PopupBase from '../PopupBase';
import React from 'react';
import ActorTile from '../../ActorTile/ActorTile';
import style from './AddActorPopup.module.css';
import {NewActorPopupContent} from '../NewActorPopup/NewActorPopup';
import {callAPI} from '../../../utils/Api';
import {ActorType} from '../../../types/VideoTypes';
import {GeneralSuccess} from '../../../types/GeneralTypes';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faFilter, faTimes} from '@fortawesome/free-solid-svg-icons';
import {Button} from '../../GPElements/Button';
interface props {
onHide: () => void;
movie_id: number;
}
interface state {
contentDefault: boolean;
actors: ActorType[];
filter: string;
filtervisible: boolean;
}
/**
* Popup for Adding a new Actor to a Video
*/
class AddActorPopup extends React.Component<props, state> {
// filterfield anchor, needed to focus after filter btn click
private filterfield: HTMLInputElement | null | undefined;
constructor(props: props) {
super(props);
this.state = {
contentDefault: true,
actors: [],
filter: '',
filtervisible: false
};
this.tileClickHandler = this.tileClickHandler.bind(this);
this.filterSearch = this.filterSearch.bind(this);
}
render(): JSX.Element {
return (
<>
{/* todo render actor tiles here and add search field*/}
<PopupBase title='Add new Actor to Video' onHide={this.props.onHide} banner={
<button
className={style.newactorbutton}
onClick={(): void => {
this.setState({contentDefault: false});
}}>Create new Actor</button>}>
{this.resolvePage()}
</PopupBase>
</>
);
}
componentDidMount(): void {
// fetch the available actors
this.loadActors();
}
/**
* selector for current showing popup page
* @returns {JSX.Element}
*/
resolvePage(): JSX.Element {
if (this.state.contentDefault) return (this.getContent());
else return (<NewActorPopupContent onHide={(): void => {
this.loadActors();
this.setState({contentDefault: true});
}}/>);
}
/**
* returns content for the newActor popup
* @returns {JSX.Element}
*/
getContent(): JSX.Element {
if (this.state.actors.length !== 0) {
return (
<>
<div className={style.searchbar}>
{
this.state.filtervisible ?
<>
<input className={'form-control mr-sm-2 ' + style.searchinput}
type='text' placeholder='Filter' value={this.state.filter}
onChange={(e): void => {
this.setState({filter: e.target.value});
}}
ref={(input): void => {this.filterfield = input;}}/>
<Button title={<FontAwesomeIcon style={{
verticalAlign: 'middle',
lineHeight: '130px'
}} icon={faTimes} size='1x'/>} color={{backgroundColor: 'red'}} onClick={(): void => {
this.setState({filter: '', filtervisible: false});
}}/>
</> :
<Button title={<span>Filter <FontAwesomeIcon style={{
verticalAlign: 'middle',
lineHeight: '130px'
}} icon={faFilter} size='1x'/></span>} color={{backgroundColor: 'cornflowerblue', color: 'white'}} onClick={(): void => {
this.setState({filtervisible: true}, () => {
// focus filterfield after state update
this.filterfield?.focus();
});
}}/>
}
</div>
{this.state.actors.filter(this.filterSearch).map((el) => (<ActorTile actor={el} onClick={this.tileClickHandler}/>))}
</>
);
} else {
return (<div>somekind of loading</div>);
}
}
/**
* event handling for ActorTile Click
*/
tileClickHandler(actor: ActorType): void {
// fetch the available actors
callAPI<GeneralSuccess>('actor.php', {
action: 'addActorToVideo',
actorid: actor.actor_id,
videoid: this.props.movie_id
}, result => {
if (result.result === 'success') {
// return back to player page
this.props.onHide();
} else {
console.error('an error occured while fetching actors: ' + result);
}
});
}
/**
* load the actors from backend and set state
*/
loadActors(): void {
callAPI<ActorType[]>('actor.php', {action: 'getAllActors'}, result => {
this.setState({actors: result});
});
}
/**
* filter the actor array for search matches
* @param actor
*/
private filterSearch(actor: ActorType): boolean {
return actor.name.toLowerCase().includes(this.state.filter.toLowerCase());
}
}
export default AddActorPopup;

View File

@ -34,7 +34,7 @@ describe('<AddTagPopup/>', function () {
});
it('test addtag', done => {
const wrapper = shallow(<AddTagPopup/>);
const wrapper = shallow(<AddTagPopup movie_id={1}/>);
global.fetch = prepareFetchApi({result: 'success'});
@ -57,7 +57,7 @@ describe('<AddTagPopup/>', function () {
});
it('test failing addTag', done => {
const wrapper = shallow(<AddTagPopup/>);
const wrapper = shallow(<AddTagPopup movie_id={1}/>);
global.fetch = prepareFetchApi({result: 'fail'});

View File

@ -2,33 +2,47 @@ import React from 'react';
import Tag from '../../Tag/Tag';
import PopupBase from '../PopupBase';
import {callAPI} from '../../../utils/Api';
import {TagType} from '../../../types/VideoTypes';
import {GeneralSuccess} from '../../../types/GeneralTypes';
interface props {
onHide: () => void;
submit: (tagId: number, tagName: string) => void;
movie_id: number;
}
interface state {
items: TagType[];
}
/**
* component creates overlay to add a new tag to a video
*/
class AddTagPopup extends React.Component {
constructor(props, context) {
super(props, context);
class AddTagPopup extends React.Component<props, state> {
constructor(props: props) {
super(props);
this.state = {items: []};
}
componentDidMount() {
callAPI('tags.php', {action: 'getAllTags'}, (result) => {
componentDidMount(): void {
callAPI('tags.php', {action: 'getAllTags'}, (result: TagType[]) => {
console.log(result);
this.setState({
items: result
});
});
}
render() {
render(): JSX.Element {
return (
<PopupBase title='Add a Tag to this Video:' onHide={this.props.onHide}>
{this.state.items ?
this.state.items.map((i) => (
<Tag onclick={() => {
this.addTag(i.tag_id, i.tag_name);
}}>{i.tag_name}</Tag>
<Tag tagInfo={i}
onclick={(): void => {
this.addTag(i.tag_id, i.tag_name);
}}/>
)) : null}
</PopupBase>
);
@ -39,8 +53,8 @@ class AddTagPopup extends React.Component {
* @param tagid tag id to add
* @param tagname tag name to add
*/
addTag(tagid, tagname) {
callAPI('tags.php', {action: 'addTag', id: tagid, movieid: this.props.movie_id}, result => {
addTag(tagid: number, tagname: string): void {
callAPI('tags.php', {action: 'addTag', id: tagid, movieid: this.props.movie_id}, (result: GeneralSuccess) => {
if (result.result !== 'success') {
console.log('error occured while writing to db -- todo error handling');
console.log(result.result);

View File

@ -22,7 +22,7 @@ describe('<NewActorPopupContent/>', () => {
global.callAPIMock({});
const func = jest.fn();
const wrapper = shallow(<NewActorPopupContent onHide={() => {func()}}/>);
const wrapper = shallow(<NewActorPopupContent onHide={() => {func();}}/>);
// manually set typed in actorname
wrapper.instance().value = 'testactorname';

View File

@ -2,12 +2,17 @@ import React from 'react';
import PopupBase from '../PopupBase';
import style from './NewActorPopup.module.css';
import {callAPI} from '../../../utils/Api';
import {GeneralSuccess} from '../../../types/GeneralTypes';
interface NewActorPopupProps {
onHide: () => void;
}
/**
* creates modal overlay to define a new Tag
*/
class NewActorPopup extends React.Component {
render() {
class NewActorPopup extends React.Component<NewActorPopupProps> {
render(): JSX.Element {
return (
<PopupBase title='Add new Tag' onHide={this.props.onHide} height='200px' width='400px'>
<NewActorPopupContent onHide={this.props.onHide}/>
@ -16,21 +21,17 @@ class NewActorPopup extends React.Component {
}
}
export class NewActorPopupContent extends React.Component {
constructor(props, context) {
super(props, context);
export class NewActorPopupContent extends React.Component<NewActorPopupProps> {
value: string | undefined;
this.props = props;
}
render() {
render(): JSX.Element {
return (
<>
<div>
<input type='text' placeholder='Actor Name' onChange={(v) => {
<input type='text' placeholder='Actor Name' onChange={(v): void => {
this.value = v.target.value;
}}/></div>
<button className={style.savebtn} onClick={() => this.storeselection()}>Save</button>
<button className={style.savebtn} onClick={(): void => this.storeselection()}>Save</button>
</>
);
}
@ -38,11 +39,11 @@ export class NewActorPopupContent extends React.Component {
/**
* store the filled in form to the backend
*/
storeselection() {
storeselection(): void {
// check if user typed in name
if (this.value === '' || this.value === undefined) return;
callAPI('actor.php', {action: 'createActor', actorname: this.value}, (result) => {
callAPI('actor.php', {action: 'createActor', actorname: this.value}, (result: GeneralSuccess) => {
if (result.result !== 'success') {
console.log('error occured while writing to db -- todo error handling');
console.log(result.result);

View File

@ -3,8 +3,6 @@ import React from 'react';
import {shallow} from 'enzyme';
import '@testing-library/jest-dom';
import NewTagPopup from './NewTagPopup';
import {NoBackendConnectionPopup} from '../NoBackendConnectionPopup/NoBackendConnectionPopup';
import {getBackendDomain} from '../../../utils/Api';
describe('<NewTagPopup/>', function () {
it('renders without crashing ', function () {
@ -24,6 +22,8 @@ describe('<NewTagPopup/>', function () {
}
});
wrapper.instance().value = 'testvalue';
wrapper.find('button').simulate('click');
expect(global.fetch).toHaveBeenCalledTimes(1);

View File

@ -2,24 +2,25 @@ import React from 'react';
import PopupBase from '../PopupBase';
import style from './NewTagPopup.module.css';
import {callAPI} from '../../../utils/Api';
import {GeneralSuccess} from '../../../types/GeneralTypes';
interface props {
onHide: () => void
}
/**
* creates modal overlay to define a new Tag
*/
class NewTagPopup extends React.Component {
constructor(props, context) {
super(props, context);
class NewTagPopup extends React.Component<props> {
private value: string = '';
this.props = props;
}
render() {
render(): JSX.Element {
return (
<PopupBase title='Add new Tag' onHide={this.props.onHide} height='200px' width='400px'>
<div><input type='text' placeholder='Tagname' onChange={(v) => {
<div><input type='text' placeholder='Tagname' onChange={(v): void => {
this.value = v.target.value;
}}/></div>
<button className={style.savebtn} onClick={() => this.storeselection()}>Save</button>
<button className={style.savebtn} onClick={(): void => this.storeselection()}>Save</button>
</PopupBase>
);
}
@ -27,8 +28,8 @@ class NewTagPopup extends React.Component {
/**
* store the filled in form to the backend
*/
storeselection() {
callAPI('tags.php', {action: 'createTag', tagname: this.value}, result => {
storeselection(): void {
callAPI('tags.php', {action: 'createTag', tagname: this.value}, (result: GeneralSuccess) => {
if (result.result !== 'success') {
console.log('error occured while writing to db -- todo error handling');
console.log(result.result);

View File

@ -1,7 +1,7 @@
import React from "react";
import PopupBase from "../PopupBase";
import style from "../NewActorPopup/NewActorPopup.module.css";
import {setCustomBackendDomain} from "../../../utils/Api";
import React from 'react';
import PopupBase from '../PopupBase';
import style from '../NewActorPopup/NewActorPopup.module.css';
import {setCustomBackendDomain} from '../../../utils/Api';
interface NBCProps {
onHide: (_: void) => void
@ -11,10 +11,10 @@ export function NoBackendConnectionPopup(props: NBCProps): JSX.Element {
return (
<PopupBase title='No connection to backend API!' onHide={props.onHide} height='200px' width='600px'>
<div>
<input type='text' placeholder='http://192.168.0.2' onChange={(v) => {
<input type='text' placeholder='http://192.168.0.2' onChange={(v): void => {
setCustomBackendDomain(v.target.value);
}}/></div>
<button className={style.savebtn} onClick={() => props.onHide()}>Refresh</button>
<button className={style.savebtn} onClick={(): void => props.onHide()}>Refresh</button>
</PopupBase>
);
}

View File

@ -1,9 +1,9 @@
.popup {
border: 3px #3574fe solid;
border-radius: 18px;
min-height: 80%;
height: fit-content;
left: 20%;
min-height: 80%;
opacity: 0.95;
position: absolute;
top: 10%;
@ -11,7 +11,7 @@
z-index: 2;
}
.header{
.header {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
@ -20,20 +20,20 @@
.title {
cursor: move;
float: left;
font-size: x-large;
margin-left: 15px;
margin-top: 10px;
opacity: 1;
float: left;
width: 60%;
}
.banner {
width: 40%;
float: left;
display: flex;
flex-direction: row;
float: left;
justify-content: flex-end;
width: 40%;
}
.content {

View File

@ -1,6 +1,6 @@
import {shallow} from "enzyme";
import React from "react";
import PopupBase from "./PopupBase";
import {shallow} from 'enzyme';
import React from 'react';
import PopupBase from './PopupBase';
describe('<PopupBase/>', function () {
it('renders without crashing ', function () {

View File

@ -1,13 +1,24 @@
import GlobalInfos from '../../utils/GlobalInfos';
import style from './PopupBase.module.css';
import {Line} from '../PageTitle/PageTitle';
import React from 'react';
import React, {RefObject} from 'react';
interface props {
width?: string;
height?: string;
banner?: JSX.Element;
title: string;
onHide: () => void
}
/**
* wrapper class for generic types of popups
*/
class PopupBase extends React.Component {
constructor(props) {
class PopupBase extends React.Component<props> {
private wrapperRef: RefObject<HTMLDivElement>;
private framedimensions: { minHeight: string | undefined; width: string | undefined; height: string | undefined };
constructor(props: props) {
super(props);
this.state = {items: []};
@ -25,7 +36,7 @@ class PopupBase extends React.Component {
};
}
componentDidMount() {
componentDidMount(): void {
document.addEventListener('mousedown', this.handleClickOutside);
document.addEventListener('keyup', this.keypress);
@ -35,13 +46,13 @@ class PopupBase extends React.Component {
}
}
componentWillUnmount() {
componentWillUnmount(): void {
// remove the appended listeners
document.removeEventListener('mousedown', this.handleClickOutside);
document.removeEventListener('keyup', this.keypress);
}
render() {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div style={this.framedimensions} className={[style.popup, themeStyle.thirdbackground].join(' ')} ref={this.wrapperRef}>
@ -61,8 +72,8 @@ class PopupBase extends React.Component {
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
handleClickOutside(event: MouseEvent): void {
if (this.wrapperRef && this.wrapperRef.current && !this.wrapperRef.current.contains(event.target as Node)) {
this.props.onHide();
}
}
@ -71,7 +82,7 @@ class PopupBase extends React.Component {
* key event handling
* @param event keyevent
*/
keypress(event) {
keypress(event: KeyboardEvent): void {
// hide if escape is pressed
if (event.key === 'Escape') {
this.props.onHide();
@ -81,16 +92,17 @@ class PopupBase extends React.Component {
/**
* make the element drag and droppable
*/
dragElement() {
dragElement(): void {
let xOld = 0, yOld = 0;
const elmnt = this.wrapperRef.current;
if(elmnt === null) return;
if (elmnt === null) return;
if (elmnt.firstChild === null) return;
elmnt.firstChild.onmousedown = dragMouseDown;
(elmnt.firstChild as HTMLDivElement).onmousedown = dragMouseDown;
function dragMouseDown(e) {
function dragMouseDown(e: MouseEvent): void {
e.preventDefault();
// get the mouse cursor position at startup:
xOld = e.clientX;
@ -100,7 +112,7 @@ class PopupBase extends React.Component {
document.onmousemove = elementDrag;
}
function elementDrag(e) {
function elementDrag(e: MouseEvent): void {
e.preventDefault();
// calculate the new cursor position:
const dx = xOld - e.clientX;
@ -108,11 +120,12 @@ class PopupBase extends React.Component {
xOld = e.clientX;
yOld = e.clientY;
// set the element's new position:
if (elmnt === null) return;
elmnt.style.top = (elmnt.offsetTop - dy) + 'px';
elmnt.style.left = (elmnt.offsetLeft - dx) + 'px';
}
function closeDragElement() {
function closeDragElement(): void {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;

View File

@ -1,104 +0,0 @@
import React from 'react';
import style from './Preview.module.css';
import Player from '../../pages/Player/Player';
import {Spinner} from 'react-bootstrap';
import GlobalInfos from '../../utils/GlobalInfos';
import {callAPIPlain} from '../../utils/Api';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faEllipsisV} from '@fortawesome/free-solid-svg-icons';
/**
* Component for single preview tile
* floating side by side
*/
class Preview extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
previewpicture: null,
name: null,
optionsvisible: false
};
}
componentDidMount() {
callAPIPlain('video.php', {action: 'readThumbnail', movieid: this.props.movie_id}, (result) => {
this.setState({
previewpicture: result,
name: this.props.name
});
});
}
render() {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div className={style.videopreview + ' ' + themeStyle.secbackground + ' ' + themeStyle.preview}>
<div className={style.quickactions} onClick={() => this.setState({optionsvisible: true})}>
<FontAwesomeIcon style={{
verticalAlign: 'middle',
fontSize: '25px'
}} icon={faEllipsisV} size='1x'/>
</div>
<div className={style.previewtitle + ' ' + themeStyle.lighttextcolor}>{this.state.name}</div>
<div className={style.previewpic} onClick={() => this.itemClick()}>
{this.state.previewpicture !== null ?
<img className={style.previewimage}
src={this.state.previewpicture}
alt='Pic loading.'/> :
<span className={style.loadAnimation}><Spinner animation='border'/></span>}
</div>
<div className={style.previewbottom}>
</div>
{this.popupvisible()}
</div>
);
}
popupvisible() {
if (this.state.optionsvisible)
return (<div>heeyyho</div>);
else
return null;
}
/**
* handle the click event of a tile
*/
itemClick() {
console.log('item clicked!' + this.state.name);
GlobalInfos.getViewBinding().changeRootElement(
<Player movie_id={this.props.movie_id}/>);
}
}
/**
* Component for a Tag-name tile (used in category page)
*/
export class TagPreview extends React.Component {
render() {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div
className={style.videopreview + ' ' + style.tagpreview + ' ' + themeStyle.secbackground + ' ' + themeStyle.preview}
onClick={() => this.itemClick()}>
<div className={style.tagpreviewtitle + ' ' + themeStyle.lighttextcolor}>
{this.props.name}
</div>
</div>
);
}
/**
* handle the click event of a Tag tile
*/
itemClick() {
this.props.categorybinding(this.props.name);
}
}
export default Preview;

View File

@ -0,0 +1,79 @@
import React from 'react';
import style from './Preview.module.css';
import {Spinner} from 'react-bootstrap';
import {Link} from 'react-router-dom';
import GlobalInfos from '../../utils/GlobalInfos';
import {callAPIPlain} from '../../utils/Api';
interface PreviewProps {
name: string;
movie_id: number;
}
interface PreviewState {
previewpicture: string | null;
}
/**
* Component for single preview tile
* floating side by side
*/
class Preview extends React.Component<PreviewProps, PreviewState> {
constructor(props: PreviewProps) {
super(props);
this.state = {
previewpicture: null
};
}
componentDidMount(): void {
callAPIPlain('video.php', {action: 'readThumbnail', movieid: this.props.movie_id}, (result) => {
this.setState({
previewpicture: result
});
});
}
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<Link to={'/player/' + this.props.movie_id}>
<div className={style.videopreview + ' ' + themeStyle.secbackground + ' ' + themeStyle.preview}>
<div className={style.previewtitle + ' ' + themeStyle.lighttextcolor}>{this.props.name}</div>
<div className={style.previewpic}>
{this.state.previewpicture !== null ?
<img className={style.previewimage}
src={this.state.previewpicture}
alt='Pic loading.'/> :
<span className={style.loadAnimation}><Spinner animation='border'/></span>}
</div>
<div className={style.previewbottom}>
</div>
</div>
</Link>
);
}
}
/**
* Component for a Tag-name tile (used in category page)
*/
export class TagPreview extends React.Component<{ name: string }> {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div
className={style.videopreview + ' ' + style.tagpreview + ' ' + themeStyle.secbackground + ' ' + themeStyle.preview}>
<div className={style.tagpreviewtitle + ' ' + themeStyle.lighttextcolor}>
{this.props.name}
</div>
</div>
);
}
}
export default Preview;

View File

@ -5,23 +5,10 @@ import Preview, {TagPreview} from './Preview';
describe('<Preview/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<Preview/>);
const wrapper = shallow(<Preview movie_id={1}/>);
wrapper.unmount();
});
it('click event triggered', () => {
const func = jest.fn();
const wrapper = shallow(<Preview/>);
prepareViewBinding(func);
wrapper.find('.videopreview').simulate('click');
//callback to open player should have called
expect(func).toHaveBeenCalledTimes(1);
});
it('picture rendered correctly', done => {
const mockSuccessResponse = 'testsrc';
const mockJsonPromise = Promise.resolve(mockSuccessResponse);
@ -30,7 +17,7 @@ describe('<Preview/>', function () {
});
global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);
const wrapper = shallow(<Preview name='test'/>);
const wrapper = shallow(<Preview name='test' movie_id={1}/>);
// now called 1 times
expect(global.fetch).toHaveBeenCalledTimes(1);
@ -48,7 +35,7 @@ describe('<Preview/>', function () {
});
it('spinner loads correctly', function () {
const wrapper = shallow(<Preview/>);
const wrapper = shallow(<Preview movie_id={1}/>);
// expect load animation to be visible
expect(wrapper.find('.loadAnimation')).toHaveLength(1);
@ -66,24 +53,5 @@ describe('<TagPreview/>', function () {
const wrapper = shallow(<TagPreview name='test'/>);
expect(wrapper.find('.tagpreviewtitle').text()).toBe('test');
});
it('click event triggered', function () {
const func = jest.fn();
const wrapper = shallow(<TagPreview/>);
wrapper.setProps({
categorybinding: () => {
func();
}
});
// first call of fetch is getting of available tags
expect(func).toHaveBeenCalledTimes(0);
wrapper.find('.videopreview').simulate('click');
// now called 1 times
expect(func).toHaveBeenCalledTimes(1);
});
});

View File

@ -1,6 +1,9 @@
.sideinfo {
border: 2px #3574fe solid;
border-radius: 20px;
}
.sideinfogeometry {
float: left;
margin-left: 15px;
margin-top: 25px;

View File

@ -2,13 +2,20 @@ import React from 'react';
import style from './SideBar.module.css';
import GlobalInfos from '../../utils/GlobalInfos';
interface SideBarProps {
hiddenFrame?: boolean;
width?: string;
}
/**
* component for sidebar-info
*/
class SideBar extends React.Component {
render() {
class SideBar extends React.Component<SideBarProps> {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (<div className={style.sideinfo + ' ' + themeStyle.secbackground}>
const classnn = style.sideinfogeometry + ' ' + (this.props.hiddenFrame === undefined ? style.sideinfo + ' ' + themeStyle.secbackground : '');
return (<div className={classnn} style={{width: this.props.width}}>
{this.props.children}
</div>);
}
@ -18,7 +25,7 @@ class SideBar extends React.Component {
* The title of the sidebar
*/
export class SideBarTitle extends React.Component {
render() {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div className={style.sidebartitle + ' ' + themeStyle.subtextcolor}>{this.props.children}</div>
@ -30,7 +37,7 @@ export class SideBarTitle extends React.Component {
* An item of the sidebar
*/
export class SideBarItem extends React.Component {
render() {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<div

View File

@ -1,35 +0,0 @@
import React from 'react';
import styles from './Tag.module.css';
import CategoryPage from '../../pages/CategoryPage/CategoryPage';
import GlobalInfos from '../../utils/GlobalInfos';
/**
* A Component representing a single Category tag
*/
class Tag extends React.Component {
render() {
return (
<button className={styles.tagbtn} onClick={() => this.TagClick()}
data-testid='Test-Tag'>{this.props.children}</button>
);
}
/**
* click handling for a Tag
*/
TagClick() {
const tag = this.props.children.toString().toLowerCase();
if (this.props.onclick) {
this.props.onclick(tag);
return;
}
// call callback functin to switch to category page with specified tag
GlobalInfos.getViewBinding().changeRootElement(
<CategoryPage category={tag}/>);
}
}
export default Tag;

View File

@ -6,33 +6,20 @@ import {shallow} from 'enzyme';
describe('<Tag/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<Tag>test</Tag>);
const wrapper = shallow(<Tag tagInfo={{tag_name: 'testname', tag_id: 1}}/>);
wrapper.unmount();
});
it('renders childs correctly', function () {
const wrapper = shallow(<Tag>test</Tag>);
const wrapper = shallow(<Tag tagInfo={{tag_name: 'test', tag_id: 1}}/>);
expect(wrapper.children().text()).toBe('test');
});
it('click event triggered and setvideo callback called', function () {
global.fetch = prepareFetchApi({});
const func = jest.fn();
prepareViewBinding(func);
const wrapper = shallow(<Tag>test</Tag>);
expect(func).toBeCalledTimes(0);
wrapper.simulate('click');
expect(func).toBeCalledTimes(1);
});
it('test custom onclick function', function () {
const func = jest.fn();
const wrapper = shallow(<Tag
tagInfo={{tag_name: 'test', tag_id: 1}}
onclick={() => {func();}}>test</Tag>);
expect(func).toBeCalledTimes(0);

47
src/elements/Tag/Tag.tsx Normal file
View File

@ -0,0 +1,47 @@
import React from 'react';
import styles from './Tag.module.css';
import {Link} from 'react-router-dom';
import {TagType} from '../../types/VideoTypes';
interface props {
onclick?: (_: string) => void
tagInfo: TagType
}
/**
* A Component representing a single Category tag
*/
class Tag extends React.Component<props> {
render(): JSX.Element {
if (this.props.onclick) {
return this.renderButton();
} else {
return (
<Link to={'/categories/' + this.props.tagInfo.tag_id}>
{this.renderButton()}
</Link>
);
}
}
renderButton(): JSX.Element {
return (
<button className={styles.tagbtn} onClick={(): void => this.TagClick()}
data-testid='Test-Tag'>{this.props.tagInfo.tag_name}</button>
);
}
/**
* click handling for a Tag
*/
TagClick(): void {
if (this.props.onclick) {
// call custom onclick handling
this.props.onclick(this.props.tagInfo.tag_name); // todo check if param is neccessary
return;
}
}
}
export default Tag;

View File

@ -1,33 +1,41 @@
import React from 'react';
import Preview from '../Preview/Preview';
import style from './VideoContainer.module.css';
import {VideoTypes} from '../../types/ApiTypes';
interface props {
data: VideoTypes.VideoUnloadedType[]
}
interface state {
loadeditems: VideoTypes.VideoUnloadedType[];
selectionnr: number;
}
/**
* A videocontainer storing lots of Preview elements
* includes scroll handling and loading of preview infos
*/
class VideoContainer extends React.Component {
class VideoContainer extends React.Component<props, state> {
// stores current index of loaded elements
loadindex = 0;
loadindex: number = 0;
constructor(props, context) {
super(props, context);
this.data = props.data;
constructor(props: props) {
super(props);
this.state = {
loadeditems: [],
selectionnr: null
selectionnr: 0
};
}
componentDidMount() {
componentDidMount(): void {
document.addEventListener('scroll', this.trackScrolling);
this.loadPreviewBlock(16);
}
render() {
render(): JSX.Element {
return (
<div className={style.maincontent}>
{this.state.loadeditems.map(elem => (
@ -44,7 +52,7 @@ class VideoContainer extends React.Component {
);
}
componentWillUnmount() {
componentWillUnmount(): void {
this.setState({});
// unbind scroll listener when unmounting component
document.removeEventListener('scroll', this.trackScrolling);
@ -54,13 +62,13 @@ class VideoContainer extends React.Component {
* load previews to the container
* @param nr number of previews to load
*/
loadPreviewBlock(nr) {
loadPreviewBlock(nr: number): void {
console.log('loadpreviewblock called ...');
let ret = [];
for (let i = 0; i < nr; i++) {
// only add if not end
if (this.data.length > this.loadindex + i) {
ret.push(this.data[this.loadindex + i]);
if (this.props.data.length > this.loadindex + i) {
ret.push(this.props.data[this.loadindex + i]);
}
}
@ -78,7 +86,7 @@ class VideoContainer extends React.Component {
/**
* scroll event handler -> load new previews if on bottom
*/
trackScrolling = () => {
trackScrolling = (): void => {
// comparison if current scroll position is on bottom --> 200 is bottom offset to trigger load
if (window.innerHeight + document.documentElement.scrollTop + 200 >= document.documentElement.offsetHeight) {
this.loadPreviewBlock(8);

View File

@ -3,7 +3,7 @@ import ReactDOM from 'react-dom';
import App from './App';
// don't allow console logs within production env
global.console.log = process.env.NODE_ENV !== "development" ? (s) => {} : global.console.log;
global.console.log = process.env.NODE_ENV !== 'development' ? (s: string | number | boolean): void => {} : global.console.log;
ReactDOM.render(
<React.StrictMode>

View File

@ -0,0 +1,6 @@
.container {
float: left;
margin-right: 20px;
padding-left: 20px;
width: 70%;
}

View File

@ -0,0 +1,43 @@
import {shallow} from 'enzyme';
import React from 'react';
import ActorOverviewPage from './ActorOverviewPage';
describe('<ActorOverviewPage/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<ActorOverviewPage/>);
wrapper.unmount();
});
it('test inerstion of actor tiles', function () {
const wrapper = shallow(<ActorOverviewPage/>);
wrapper.setState({
actors: [{
thumbnail: '',
name: 'testname',
actor_id: 42
}]
});
expect(wrapper.find('ActorTile')).toHaveLength(1);
});
it('test newtagpopup visibility', function () {
const wrapper = shallow(<ActorOverviewPage/>);
expect(wrapper.find('NewActorPopup')).toHaveLength(0);
wrapper.find('SideBar').find('Button').simulate('click');
expect(wrapper.find('NewActorPopup')).toHaveLength(1);
});
it('test popup hiding', function () {
const wrapper = shallow(<ActorOverviewPage/>);
wrapper.setState({NActorPopupVisible: true});
wrapper.find('NewActorPopup').props().onHide();
expect(wrapper.find('NewActorPopup')).toHaveLength(0);
});
});

View File

@ -0,0 +1,57 @@
import React from 'react';
import {callAPI} from '../../utils/Api';
import {ActorType} from '../../types/VideoTypes';
import ActorTile from '../../elements/ActorTile/ActorTile';
import PageTitle from '../../elements/PageTitle/PageTitle';
import SideBar from '../../elements/SideBar/SideBar';
import style from './ActorOverviewPage.module.css';
import {Button} from '../../elements/GPElements/Button';
import NewActorPopup from '../../elements/Popups/NewActorPopup/NewActorPopup';
interface props {
}
interface state {
actors: ActorType[];
NActorPopupVisible: boolean
}
class ActorOverviewPage extends React.Component<props, state> {
constructor(props: props) {
super(props);
this.state = {
actors: [],
NActorPopupVisible: false
};
this.fetchAvailableActors();
}
render(): JSX.Element {
return (
<>
<PageTitle title='Actors' subtitle={this.state.actors.length + ' Actors'}/>
<SideBar>
<Button title='Add Actor' onClick={(): void => this.setState({NActorPopupVisible: true})}/>
</SideBar>
<div className={style.container}>
{this.state.actors.map((el) => (<ActorTile actor={el}/>))}
</div>
{this.state.NActorPopupVisible ?
<NewActorPopup onHide={(): void => {
this.setState({NActorPopupVisible: false});
this.fetchAvailableActors(); // refetch actors
}}/> : null}
</>
);
}
fetchAvailableActors(): void {
callAPI<ActorType[]>('actor.php', {action: 'getAllActors'}, result => {
this.setState({actors: result});
});
}
}
export default ActorOverviewPage;

View File

@ -1,51 +0,0 @@
import React from 'react';
import PageTitle from '../../elements/PageTitle/PageTitle';
import SideBar, {SideBarTitle} from '../../elements/SideBar/SideBar';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faUser} from '@fortawesome/free-solid-svg-icons';
import style from './ActorPage.module.css';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {callAPI} from '../../utils/Api';
class ActorPage extends React.Component {
constructor(props) {
super(props);
this.state = {data: undefined};
}
render() {
return (
<>
<PageTitle title={this.props.actor.name} subtitle={this.state.data ? this.state.data.length + ' videos' : null}/>
<SideBar>
<div className={style.pic}>
<FontAwesomeIcon style={{color: 'white'}} icon={faUser} size='10x'/>
</div>
<SideBarTitle>Attention: This is an early preview!</SideBarTitle>
</SideBar>
{this.state.data ?
<VideoContainer
data={this.state.data}/> :
<div>No Data found!</div>}
</>
);
}
componentDidMount() {
this.getActorInfo();
}
/**
* request more actor info from backend
*/
getActorInfo() {
// todo 2020-12-4: fetch to db
callAPI('actor.php', {action: 'getActorInfo', actorid: this.props.actor.actor_id}, result => {
console.log(result);
this.setState({data: result.videos ? result.videos : []});
});
}
}
export default ActorPage;

View File

@ -1,4 +1,9 @@
.pic {
text-align: center;
margin-bottom: 25px;
text-align: center;
}
.overviewbutton {
float: right;
margin-top: 25px;
}

View File

@ -1,12 +1,27 @@
import {shallow} from 'enzyme';
import React from 'react';
import ActorPage from './ActorPage';
import {ActorPage} from './ActorPage';
describe('<ActorPage/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<ActorPage actor={{id: 5, name: 'usr1'}}/>);
const wrapper = shallow(<ActorPage match={{params: {id: 10}}}/>);
wrapper.unmount();
});
it('fetch infos', function () {
callAPIMock({
videos: [{
movie_id: 0,
movie_name: 'test'
}], info: {
thumbnail: '',
name: '',
actor_id: 0
}
});
const wrapper = shallow(<ActorPage match={{params: {id: 10}}}/>);
expect(wrapper.find('VideoContainer')).toHaveLength(1);
});
});

View File

@ -0,0 +1,81 @@
import React from 'react';
import PageTitle from '../../elements/PageTitle/PageTitle';
import SideBar, {SideBarTitle} from '../../elements/SideBar/SideBar';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faUser} from '@fortawesome/free-solid-svg-icons';
import style from './ActorPage.module.css';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {callAPI} from '../../utils/Api';
import {ActorType} from '../../types/VideoTypes';
import {Link, withRouter} from 'react-router-dom';
import {RouteComponentProps} from 'react-router';
import {Button} from '../../elements/GPElements/Button';
import {ActorTypes, VideoTypes} from '../../types/ApiTypes';
interface state {
data: VideoTypes.VideoUnloadedType[],
actor: ActorType
}
/**
* empty default props with id in url
*/
interface props extends RouteComponentProps<{ id: string }> {
}
/**
* info page about a specific actor and a list of all its videos
*/
export class ActorPage extends React.Component<props, state> {
constructor(props: props) {
super(props);
this.state = {data: [], actor: {actor_id: 0, name: '', thumbnail: ''}};
}
render(): JSX.Element {
return (
<>
<PageTitle title={this.state.actor.name} subtitle={this.state.data ? this.state.data.length + ' videos' : null}>
<span className={style.overviewbutton}>
<Link to='/actors'>
<Button onClick={(): void => {}} title='Go to Actor overview'/>
</Link>
</span>
</PageTitle>
<SideBar>
<div className={style.pic}>
<FontAwesomeIcon style={{color: 'white'}} icon={faUser} size='10x'/>
</div>
<SideBarTitle>Attention: This is an early preview!</SideBarTitle>
</SideBar>
{this.state.data.length !== 0 ?
<VideoContainer
data={this.state.data}/> :
<div>No Data found!</div>}
</>
);
}
componentDidMount(): void {
this.getActorInfo();
}
/**
* request more actor info from backend
*/
getActorInfo(): void {
callAPI('actor.php', {
action: 'getActorInfo',
actorid: this.props.match.params.id
}, (result: ActorTypes.videofetchresult) => {
this.setState({
data: result.videos ? result.videos : [],
actor: result.info
});
});
}
}
export default withRouter(ActorPage);

View File

@ -1,140 +0,0 @@
import React from 'react';
import SideBar, {SideBarTitle} from '../../elements/SideBar/SideBar';
import Tag from '../../elements/Tag/Tag';
import videocontainerstyle from '../../elements/VideoContainer/VideoContainer.module.css';
import {TagPreview} from '../../elements/Preview/Preview';
import NewTagPopup from '../../elements/Popups/NewTagPopup/NewTagPopup';
import PageTitle, {Line} from '../../elements/PageTitle/PageTitle';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {callAPI} from '../../utils/Api';
/**
* Component for Category Page
* Contains a Tag Overview and loads specific Tag videos in VideoContainer
*/
class CategoryPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
loadedtags: [],
selected: null
};
}
componentDidMount() {
// check if predefined category is set
if (this.props.category) {
this.fetchVideoData(this.props.category);
} else {
this.loadTags();
}
}
/**
* render the Title and SideBar component for the Category page
* @returns {JSX.Element} corresponding jsx element for Title and Sidebar
*/
renderSideBarATitle() {
return (
<>
<PageTitle
title='Categories'
subtitle={!this.state.selected ? this.state.loadedtags.length + ' different Tags' : this.state.selected}/>
<SideBar>
<SideBarTitle>Default Tags:</SideBarTitle>
<Tag onclick={(tag) => {this.loadTag(tag);}}>All</Tag>
<Tag onclick={(tag) => {this.loadTag(tag);}}>FullHd</Tag>
<Tag onclick={(tag) => {this.loadTag(tag);}}>LowQuality</Tag>
<Tag onclick={(tag) => {this.loadTag(tag);}}>HD</Tag>
<Line/>
<button data-testid='btnaddtag' className='btn btn-success' onClick={() => {
this.setState({popupvisible: true});
}}>Add a new Tag!
</button>
</SideBar></>
);
}
render() {
return (
<>
{this.renderSideBarATitle()}
{this.state.selected ?
<>
{this.videodata ?
<VideoContainer
data={this.videodata}/> : null}
<button data-testid='backbtn' className='btn btn-success'
onClick={this.loadCategoryPageDefault}>Back
</button>
</> :
<div className={videocontainerstyle.maincontent}>
{this.state.loadedtags ?
this.state.loadedtags.map((m) => (
<TagPreview
key={m.tag_name}
name={m.tag_name}
tag_id={m.tag_id}
categorybinding={this.loadTag}/>
)) :
'loading'}
</div>
}
{this.state.popupvisible ?
<NewTagPopup show={this.state.popupvisible}
onHide={() => {
console.error("setstatecalled!");
this.setState({popupvisible: false});
this.loadTags();
}}/> :
null
}
</>
);
}
/**
* load a specific tag into a new previewcontainer
* @param tagname
*/
loadTag = (tagname) => {
this.fetchVideoData(tagname);
};
/**
* fetch data for a specific tag from backend
* @param tag tagname
*/
fetchVideoData(tag) {
callAPI('video.php', {action: 'getMovies', tag: tag}, result => {
this.videodata = result;
this.setState({selected: null}); // needed to trigger the state reload correctly
this.setState({selected: tag});
});
}
/**
* go back to the default category overview
*/
loadCategoryPageDefault = () => {
this.setState({selected: null});
this.loadTags();
};
/**
* load all available tags from db.
*/
loadTags() {
callAPI('tags.php', {action: 'getAllTags'}, result => {
this.setState({loadedtags: result});
});
}
}
export default CategoryPage;

View File

@ -1,4 +1,4 @@
import {mount, shallow} from 'enzyme';
import {shallow} from 'enzyme';
import React from 'react';
import CategoryPage from './CategoryPage';
@ -8,22 +8,6 @@ describe('<CategoryPage/>', function () {
wrapper.unmount();
});
it('test tag fetch call', done => {
global.fetch = global.prepareFetchApi(['first', 'second']);
const wrapper = shallow(<CategoryPage/>);
expect(global.fetch).toHaveBeenCalledTimes(1);
process.nextTick(() => {
//callback to close window should have called
expect(wrapper.state().loadedtags.length).toBe(2);
global.fetch.mockClear();
done();
});
});
it('test new tag popup', function () {
const wrapper = shallow(<CategoryPage/>);
@ -33,63 +17,31 @@ describe('<CategoryPage/>', function () {
expect(wrapper.find('NewTagPopup')).toHaveLength(1);
});
it('test setpage callback', done => {
global.fetch = global.prepareFetchApi([{}, {}]);
it('test add popup', function () {
const wrapper = shallow(<CategoryPage/>);
wrapper.setState({
loadedtags: [
{
tag_name: 'testname',
tag_id: 42
}
]
});
wrapper.find('TagPreview').dive().find('div').first().simulate('click');
process.nextTick(() => {
// expect callback to have loaded correct tag
expect(wrapper.state().selected).toBe('testname');
global.fetch.mockClear();
done();
});
expect(wrapper.find('NewTagPopup')).toHaveLength(0);
wrapper.setState({popupvisible: true});
expect(wrapper.find('NewTagPopup')).toHaveLength(1);
});
it('test back to category view callback', function () {
it('test hiding of popup', function () {
const wrapper = shallow(<CategoryPage/>);
wrapper.setState({popupvisible: true});
wrapper.find('NewTagPopup').props().onHide();
expect(wrapper.find('NewTagPopup')).toHaveLength(0);
});
it('test setting of subtitle', function () {
const wrapper = shallow(<CategoryPage/>);
wrapper.setState({
selected: 'test'
});
expect(wrapper.state().selected).not.toBeNull();
wrapper.find('[data-testid="backbtn"]').simulate('click');
expect(wrapper.state().selected).toBeNull();
});
expect(wrapper.find('PageTitle').props().subtitle).not.toBe('testtitle');
it('load categorypage with predefined tag', function () {
const func = jest.fn();
CategoryPage.prototype.fetchVideoData = func;
shallow(<CategoryPage category='fullhd'/>);
expect(func).toBeCalledTimes(1);
});
it('test sidebar tag clicks', function () {
const func = jest.fn();
const wrapper = shallow(<CategoryPage category='fullhd'/>);
wrapper.instance().loadTag = func;
expect(func).toBeCalledTimes(0);
wrapper.find('SideBar').find('Tag').forEach(e => {
e.dive().simulate('click');
});
expect(func).toBeCalledTimes(4);
wrapper.instance().setSubTitle('testtitle');
// test if prop of title is set correctly
expect(wrapper.find('PageTitle').props().subtitle).toBe('testtitle');
});
});

View File

@ -0,0 +1,82 @@
import React from 'react';
import SideBar, {SideBarTitle} from '../../elements/SideBar/SideBar';
import Tag from '../../elements/Tag/Tag';
import NewTagPopup from '../../elements/Popups/NewTagPopup/NewTagPopup';
import PageTitle, {Line} from '../../elements/PageTitle/PageTitle';
import {Route, Switch} from 'react-router-dom';
import {DefaultTags} from '../../types/GeneralTypes';
import {CategoryViewWR} from './CategoryView';
import TagView from './TagView';
interface CategoryPageState {
popupvisible: boolean;
subtitle: string;
}
/**
* Component for Category Page
* Contains a Tag Overview and loads specific Tag videos in VideoContainer
*/
class CategoryPage extends React.Component<{}, CategoryPageState> {
constructor(props: {}) {
super(props);
this.state = {
popupvisible: false,
subtitle: ''
};
this.setSubTitle = this.setSubTitle.bind(this);
}
render(): JSX.Element {
return (
<>
<PageTitle
title='Categories'
subtitle={this.state.subtitle}/>
<SideBar>
<SideBarTitle>Default Tags:</SideBarTitle>
<Tag tagInfo={DefaultTags.all}/>
<Tag tagInfo={DefaultTags.fullhd}/>
<Tag tagInfo={DefaultTags.hd}/>
<Tag tagInfo={DefaultTags.lowq}/>
<Line/>
<button data-testid='btnaddtag' className='btn btn-success' onClick={(): void => {
this.setState({popupvisible: true});
}}>Add a new Tag!
</button>
</SideBar>
<Switch>
<Route path='/categories/:id'>
<CategoryViewWR setSubTitle={this.setSubTitle}/>
</Route>
<Route path='/categories'>
<TagView setSubTitle={this.setSubTitle}/>
</Route>
</Switch>
{this.state.popupvisible ?
<NewTagPopup onHide={(): void => {
this.setState({popupvisible: false});
// this.loadTags();
}}/> :
null
}
</>
);
}
/**
* set the subtitle of this page
* @param subtitle string as subtitle
*/
setSubTitle(subtitle: string): void {
this.setState({subtitle: subtitle});
}
}
export default CategoryPage;

View File

@ -0,0 +1,24 @@
import {shallow} from 'enzyme';
import React from 'react';
import {CategoryView} from './CategoryView';
describe('<CategoryView/>', function () {
function instance() {
return shallow(<CategoryView match={{params: {id: 10}}}/>);
}
it('renders without crashing ', function () {
const wrapper = instance();
wrapper.unmount();
});
it('test backbutton', function () {
const wrapper = instance();
const func = jest.fn();
wrapper.setProps({history: {push: func}});
expect(func).toHaveBeenCalledTimes(0);
wrapper.find('button').simulate('click');
expect(func).toHaveBeenCalledTimes(1);
});
});

View File

@ -0,0 +1,75 @@
import {RouteComponentProps} from 'react-router';
import React from 'react';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {callAPI} from '../../utils/Api';
import {withRouter} from 'react-router-dom';
import {VideoTypes} from '../../types/ApiTypes';
interface CategoryViewProps extends RouteComponentProps<{ id: string }> {
setSubTitle: (title: string) => void
}
interface CategoryViewState {
loaded: boolean
}
/**
* plain class (for unit testing only)
*/
export class CategoryView extends React.Component<CategoryViewProps, CategoryViewState> {
private videodata: VideoTypes.VideoUnloadedType[] = [];
constructor(props: CategoryViewProps) {
super(props);
this.state = {
loaded: false
};
}
componentDidMount(): void {
this.fetchVideoData(parseInt(this.props.match.params.id));
}
componentDidUpdate(prevProps: Readonly<CategoryViewProps>, prevState: Readonly<CategoryViewState>): void {
// trigger video refresh if id changed
if (prevProps.match.params.id !== this.props.match.params.id) {
this.setState({loaded: false});
this.fetchVideoData(parseInt(this.props.match.params.id));
}
}
render(): JSX.Element {
return (
<>
{this.state.loaded ?
<VideoContainer
data={this.videodata}/> : null}
<button data-testid='backbtn' className='btn btn-success'
onClick={(): void => {
this.props.history.push('/categories');
}}>Back to Categories
</button>
</>
);
}
/**
* fetch data for a specific tag from backend
* @param id tagid
*/
fetchVideoData(id: number): void {
callAPI<VideoTypes.VideoUnloadedType[]>('video.php', {action: 'getMovies', tag: id}, result => {
this.videodata = result;
this.setState({loaded: true});
this.props.setSubTitle(this.videodata.length + ' Videos');
});
}
}
/**
* export with react Router wrapped (default use)
*/
export const CategoryViewWR = withRouter(CategoryView);

View File

@ -0,0 +1,17 @@
import {shallow} from 'enzyme';
import React from 'react';
import TagView from './TagView';
describe('<TagView/>', function () {
it('renders without crashing ', function () {
const wrapper = shallow(<TagView/>);
wrapper.unmount();
});
it('test Tag insertion', function () {
const wrapper = shallow(<TagView/>);
wrapper.setState({loadedtags: [{tag_name: 'test', tag_id: 42}]});
expect(wrapper.find('TagPreview')).toHaveLength(1);
});
});

View File

@ -0,0 +1,54 @@
import {TagType} from '../../types/VideoTypes';
import React from 'react';
import videocontainerstyle from '../../elements/VideoContainer/VideoContainer.module.css';
import {Link} from 'react-router-dom';
import {TagPreview} from '../../elements/Preview/Preview';
import {callAPI} from '../../utils/Api';
interface TagViewState {
loadedtags: TagType[];
}
interface props {
setSubTitle: (title: string) => void
}
class TagView extends React.Component<props, TagViewState> {
constructor(props: props) {
super(props);
this.state = {loadedtags: []};
}
componentDidMount(): void {
this.loadTags();
}
render(): JSX.Element {
return (
<>
<div className={videocontainerstyle.maincontent}>
{this.state.loadedtags ?
this.state.loadedtags.map((m) => (
<Link to={'/categories/' + m.tag_id}><TagPreview
key={m.tag_id}
name={m.tag_name}/></Link>
)) :
'loading'}
</div>
</>
);
}
/**
* load all available tags from db.
*/
loadTags(): void {
callAPI<TagType[]>('tags.php', {action: 'getAllTags'}, result => {
this.setState({loadedtags: result});
this.props.setSubTitle(result.length + ' different Tags');
});
}
}
export default TagView;

View File

@ -1,142 +0,0 @@
import React from 'react';
import SideBar, {SideBarItem, SideBarTitle} from '../../elements/SideBar/SideBar';
import Tag from '../../elements/Tag/Tag';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import style from './HomePage.module.css';
import PageTitle, {Line} from '../../elements/PageTitle/PageTitle';
import {callAPI} from '../../utils/Api';
/**
* The home page component showing on the initial pageload
*/
class HomePage extends React.Component {
/** keyword variable needed temporary store search keyword */
keyword = '';
constructor(props, context) {
super(props, context);
this.state = {
sideinfo: {
videonr: null,
fullhdvideonr: null,
hdvideonr: null,
sdvideonr: null,
tagnr: null
},
subtitle: 'All Videos',
data: [],
selectionnr: 0
};
}
componentDidMount() {
// initial get of all videos
this.fetchVideoData('All');
this.fetchStartData();
}
/**
* fetch available videos for specified tag
* this function clears all preview elements an reloads gravity with tag
*
* @param tag tag to fetch videos
*/
fetchVideoData(tag) {
callAPI('video.php', {action: 'getMovies', tag: tag}, (result) => {
this.setState({
data: []
});
this.setState({
data: result,
selectionnr: result.length,
tag: tag + ' Videos'
});
});
}
/**
* fetch the necessary data for left info box
*/
fetchStartData() {
callAPI('video.php', {action: 'getStartData'}, (result) => {
this.setState({
sideinfo: {
videonr: result['total'],
fullhdvideonr: result['fullhd'],
hdvideonr: result['hd'],
sdvideonr: result['sd'],
tagnr: result['tags']
}
});
});
}
/**
* search for a keyword in db and update previews
*
* @param keyword The keyword to search for
*/
searchVideos(keyword) {
console.log('search called');
callAPI('video.php', {action: 'getSearchKeyWord', keyword: keyword}, (result) => {
this.setState({
data: []
});
this.setState({
data: result,
selectionnr: result.length,
tag: 'Search result: ' + keyword
});
});
}
render() {
return (
<>
<PageTitle
title='Home Page'
subtitle={this.state.subtitle + ' - ' + this.state.selectionnr}>
<form className={'form-inline ' + style.searchform} onSubmit={(e) => {
e.preventDefault();
this.searchVideos(this.keyword);
}}>
<input data-testid='searchtextfield' className='form-control mr-sm-2'
type='text' placeholder='Search'
onChange={(e) => {
this.keyword = e.target.value;
}}/>
<button data-testid='searchbtnsubmit' className='btn btn-success' type='submit'>Search</button>
</form>
</PageTitle>
<SideBar>
<SideBarTitle>Infos:</SideBarTitle>
<Line/>
<SideBarItem><b>{this.state.sideinfo.videonr}</b> Videos Total!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.fullhdvideonr}</b> FULL-HD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.hdvideonr}</b> HD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.sdvideonr}</b> SD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.tagnr}</b> different Tags!</SideBarItem>
<Line/>
<SideBarTitle>Default Tags:</SideBarTitle>
<Tag onclick={() => this.fetchVideoData('All')}>All</Tag>
<Tag onclick={() => this.fetchVideoData('FullHd')}>FullHd</Tag>
<Tag onclick={() => this.fetchVideoData('LowQuality')}>LowQuality</Tag>
<Tag onclick={() => this.fetchVideoData('HD')}>HD</Tag>
</SideBar>
{this.state.data.length !== 0 ?
<VideoContainer
data={this.state.data}/> :
<div>No Data found!</div>}
<div className={style.rightinfo}>
</div>
</>
);
}
}
export default HomePage;

View File

@ -1,7 +1,8 @@
import {shallow} from 'enzyme';
import React from 'react';
import HomePage from './HomePage';
import {HomePage} from './HomePage';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {SearchHandling} from './SearchHandling';
describe('<HomePage/>', function () {
it('renders without crashing ', function () {
@ -54,23 +55,15 @@ describe('<HomePage/>', function () {
});
});
it('test form submit', done => {
global.fetch = global.prepareFetchApi([{}, {}]);
it('test form submit', () => {
const func = jest.fn();
const wrapper = shallow(<HomePage/>);
wrapper.setProps({history: {push: () => func()}});
const fakeEvent = {preventDefault: () => console.log('preventDefault')};
wrapper.find('.searchform').simulate('submit', fakeEvent);
expect(wrapper.state().selectionnr).toBe(0);
process.nextTick(() => {
// state to be set correctly with response
expect(wrapper.state().selectionnr).toBe(2);
global.fetch.mockClear();
done();
});
expect(func).toHaveBeenCalledTimes(1);
});
it('test no backend connection behaviour', done => {
@ -123,3 +116,24 @@ describe('<HomePage/>', function () {
testBtn(tags.first());
});
});
describe('<SearchHandling/>', () => {
it('renders without crashing', function () {
const wrapper = shallow(<SearchHandling match={{params: {name: 'testname'}}}/>);
wrapper.unmount();
});
it('renders videos correctly into container', function () {
const wrapper = shallow(<SearchHandling match={{params: {name: 'testname'}}}/>);
wrapper.setState({
data: [{
movie_id: 42,
movie_name: 'testname'
}]
});
// expect video container to be visible
expect(wrapper.find('VideoContainer')).toHaveLength(1);
});
});

View File

@ -0,0 +1,148 @@
import React from 'react';
import SideBar, {SideBarItem, SideBarTitle} from '../../elements/SideBar/SideBar';
import Tag from '../../elements/Tag/Tag';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import style from './HomePage.module.css';
import PageTitle, {Line} from '../../elements/PageTitle/PageTitle';
import {callAPI} from '../../utils/Api';
import {Route, Switch, withRouter} from 'react-router-dom';
import {RouteComponentProps} from 'react-router';
import SearchHandling from './SearchHandling';
import {VideoTypes} from '../../types/ApiTypes';
interface props extends RouteComponentProps {}
interface state {
sideinfo: {
videonr: number,
fullhdvideonr: number,
hdvideonr: number,
sdvideonr: number,
tagnr: number
},
subtitle: string,
data: VideoTypes.VideoUnloadedType[],
selectionnr: number
}
/**
* The home page component showing on the initial pageload
*/
export class HomePage extends React.Component<props, state> {
/** keyword variable needed temporary store search keyword */
keyword = '';
constructor(props: props) {
super(props);
this.state = {
sideinfo: {
videonr: 0,
fullhdvideonr: 0,
hdvideonr: 0,
sdvideonr: 0,
tagnr: 0
},
subtitle: 'All Videos',
data: [],
selectionnr: 0
};
}
componentDidMount(): void {
// initial get of all videos
this.fetchVideoData('All');
this.fetchStartData();
}
/**
* fetch available videos for specified tag
* this function clears all preview elements an reloads gravity with tag
*
* @param tag tag to fetch videos
*/
fetchVideoData(tag: string): void {
callAPI('video.php', {action: 'getMovies', tag: tag}, (result: VideoTypes.VideoUnloadedType[]) => {
this.setState({
data: []
});
this.setState({
data: result,
selectionnr: result.length,
subtitle: `${tag} Videos`
});
});
}
/**
* fetch the necessary data for left info box
*/
fetchStartData(): void {
callAPI('video.php', {action: 'getStartData'}, (result: VideoTypes.startDataType) => {
this.setState({
sideinfo: {
videonr: result['total'],
fullhdvideonr: result['fullhd'],
hdvideonr: result['hd'],
sdvideonr: result['sd'],
tagnr: result['tags']
}
});
});
}
render(): JSX.Element {
return (
<>
<Switch>
<Route path='/search/:name'>
<SearchHandling/>
</Route>
<Route path='/'>
<PageTitle
title='Home Page'
subtitle={this.state.subtitle + ' - ' + this.state.selectionnr}>
<form className={'form-inline ' + style.searchform} onSubmit={(e): void => {
e.preventDefault();
this.props.history.push('/search/' + this.keyword);
}}>
<input data-testid='searchtextfield' className='form-control mr-sm-2'
type='text' placeholder='Search'
onChange={(e): void => {
this.keyword = e.target.value;
}}/>
<button data-testid='searchbtnsubmit' className='btn btn-success' type='submit'>Search</button>
</form>
</PageTitle>
<SideBar>
<SideBarTitle>Infos:</SideBarTitle>
<Line/>
<SideBarItem><b>{this.state.sideinfo.videonr}</b> Videos Total!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.fullhdvideonr}</b> FULL-HD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.hdvideonr}</b> HD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.sdvideonr}</b> SD Videos!</SideBarItem>
<SideBarItem><b>{this.state.sideinfo.tagnr}</b> different Tags!</SideBarItem>
<Line/>
<SideBarTitle>Default Tags:</SideBarTitle>
<Tag tagInfo={{tag_name: 'All', tag_id: -1}} onclick={(): void => this.fetchVideoData('All')}/>
<Tag tagInfo={{tag_name: 'FullHd', tag_id: -1}} onclick={(): void => this.fetchVideoData('FullHd')}/>
<Tag tagInfo={{tag_name: 'LowQuality', tag_id: -1}} onclick={(): void => this.fetchVideoData('LowQuality')}/>
<Tag tagInfo={{tag_name: 'HD', tag_id: -1}} onclick={(): void => this.fetchVideoData('HD')}/>
</SideBar>
{this.state.data.length !== 0 ?
<VideoContainer
data={this.state.data}/> :
<div>No Data found!</div>}
<div className={style.rightinfo}>
</div>
</Route>
</Switch>
</>
);
}
}
export default withRouter(HomePage);

View File

@ -0,0 +1,70 @@
import {RouteComponentProps} from 'react-router';
import React from 'react';
import {withRouter} from 'react-router-dom';
import {callAPI} from '../../utils/Api';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import PageTitle from '../../elements/PageTitle/PageTitle';
import SideBar from '../../elements/SideBar/SideBar';
import {VideoTypes} from '../../types/ApiTypes';
interface params {
name: string;
}
interface props extends RouteComponentProps<params> {}
interface state {
data: VideoTypes.VideoUnloadedType[];
}
export class SearchHandling extends React.Component<props, state> {
constructor(props: props) {
super(props);
this.state = {
data: []
};
}
componentDidMount(): void {
this.searchVideos(this.props.match.params.name);
}
render(): JSX.Element {
return (
<>
<PageTitle title='Search' subtitle={this.props.match.params.name + ': ' + this.state.data.length}/>
<SideBar hiddenFrame/>
{this.getVideoData()}
</>
);
}
/**
* get videocontainer if data loaded
*/
getVideoData(): JSX.Element {
if (this.state.data.length !== 0) {
return (
<VideoContainer data={this.state.data}/>
);
} else {
return (<div>No Data found!</div>);
}
}
/**
* search for a keyword in db and update previews
*
* @param keyword The keyword to search for
*/
searchVideos(keyword: string): void {
callAPI('video.php', {action: 'getSearchKeyWord', keyword: keyword}, (result: VideoTypes.VideoUnloadedType[]) => {
this.setState({
data: result
});
});
}
}
export default withRouter(SearchHandling);

View File

@ -24,24 +24,16 @@
margin-top: 13px;
}
.button {
border-radius: 5px;
border-width: 0;
color: white;
margin-right: 15px;
padding: 6px;
}
.actorAddTile {
color: white;
cursor: pointer;
float: left;
padding-left: 25px;
padding-top: 50px;
cursor: pointer;
color: white;
transition: opacity ease 0.5s;
}
.actorAddTile:hover{
.actorAddTile:hover {
opacity: 0.7;
transition: opacity ease 0.5s;
}

View File

@ -1,16 +1,22 @@
import {shallow} from 'enzyme';
import React from 'react';
import Player from './Player';
import {Player} from './Player';
import {callAPI} from '../../utils/Api';
describe('<Player/>', function () {
// help simulating id passed by url
function instance() {
return shallow(<Player match={{params: {id: 10}}}/>);
}
it('renders without crashing ', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
wrapper.unmount();
});
it('plyr insertion', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
wrapper.setState({
sources: [
@ -26,11 +32,11 @@ describe('<Player/>', function () {
});
function simulateLikeButtonClick() {
const wrapper = shallow(<Player/>);
const wrapper = instance();
// initial fetch for getting movie data
expect(global.fetch).toHaveBeenCalledTimes(1);
wrapper.find('.videoactions').find('button').first().simulate('click');
wrapper.find('.videoactions').find('Button').first().simulate('click');
// fetch for liking
expect(global.fetch).toHaveBeenCalledTimes(2);
@ -70,28 +76,28 @@ describe('<Player/>', function () {
});
it('show tag popup', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
expect(wrapper.find('AddTagPopup')).toHaveLength(0);
// todo dynamic button find without index
wrapper.find('.videoactions').find('button').at(1).simulate('click');
wrapper.find('.videoactions').find('Button').at(1).simulate('click');
// addtagpopup should be showing now
expect(wrapper.find('AddTagPopup')).toHaveLength(1);
});
it('test delete button', done => {
const wrapper = shallow(<Player/>);
const wrapper = instance();
const func = jest.fn();
prepareViewBinding(func);
wrapper.setProps({history: {goBack: jest.fn()}});
global.fetch = prepareFetchApi({result: 'success'});
wrapper.find('.videoactions').find('button').at(2).simulate('click');
wrapper.find('.videoactions').find('Button').at(2).simulate('click');
process.nextTick(() => {
// refetch is called so fetch called 3 times
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(func).toHaveBeenCalledTimes(1);
expect(wrapper.instance().props.history.goBack).toHaveBeenCalledTimes(1);
global.fetch.mockClear();
done();
@ -99,19 +105,20 @@ describe('<Player/>', function () {
});
it('hide click ', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
const func = jest.fn();
prepareViewBinding(func);
wrapper.setProps({history: {goBack: func}});
expect(func).toHaveBeenCalledTimes(0);
wrapper.find('.closebutton').simulate('click');
// addtagpopup should be showing now
// backstack should be popped once
expect(func).toHaveBeenCalledTimes(1);
});
it('inserts Tags correctly', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
expect(wrapper.find('Tag')).toHaveLength(0);
@ -165,7 +172,7 @@ describe('<Player/>', function () {
});
it('showspopups correctly', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
wrapper.setState({popupvisible: true}, () => {
// is the AddTagpopu rendered?
@ -180,13 +187,13 @@ describe('<Player/>', function () {
it('quickadd tag correctly', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
global.callAPIMock({result: 'success'});
wrapper.setState({suggesttag: [{tag_name: 'test', tag_id: 1}]}, () => {
// mock funtion should have not been called
expect(callAPI).toBeCalledTimes(0);
wrapper.find('Tag').findWhere(p => p.text() === 'test').parent().dive().simulate('click');
wrapper.find('Tag').findWhere(p => p.props().tagInfo.tag_name === 'test').dive().simulate('click');
// mock function should have been called once
expect(callAPI).toBeCalledTimes(1);
@ -198,13 +205,13 @@ describe('<Player/>', function () {
});
it('test adding of already existing tag', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
global.callAPIMock({result: 'success'});
wrapper.setState({suggesttag: [{tag_name: 'test', tag_id: 1}], tags: [{tag_name: 'test', tag_id: 1}]}, () => {
// mock funtion should have not been called
expect(callAPI).toBeCalledTimes(0);
wrapper.find('Tag').findWhere(p => p.text() === 'test').last().parent().dive().simulate('click');
wrapper.find('Tag').findWhere(p => p.props().tagInfo.tag_name === 'test').last().dive().simulate('click');
// mock function should have been called once
expect(callAPI).toBeCalledTimes(1);
@ -217,7 +224,7 @@ describe('<Player/>', function () {
});
function generatetag() {
const wrapper = shallow(<Player/>);
const wrapper = instance();
expect(wrapper.find('Tag')).toHaveLength(0);
@ -233,7 +240,7 @@ describe('<Player/>', function () {
}
it('test addactor popup showing', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
expect(wrapper.find('AddActorPopup')).toHaveLength(0);
@ -244,7 +251,7 @@ describe('<Player/>', function () {
});
it('test hiding of addactor popup', function () {
const wrapper = shallow(<Player/>);
const wrapper = instance();
wrapper.instance().addActor();
expect(wrapper.find('AddActorPopup')).toHaveLength(1);
@ -253,4 +260,36 @@ describe('<Player/>', function () {
expect(wrapper.find('AddActorPopup')).toHaveLength(0);
});
it('test addtagpopup hiding', function () {
const wrapper = instance();
wrapper.setState({popupvisible: true});
expect(wrapper.find('AddTagPopup')).toHaveLength(1);
wrapper.find('AddTagPopup').props().onHide();
expect(wrapper.find('AddTagPopup')).toHaveLength(0);
});
it('test insertion of actor tiles', function () {
const wrapper = instance();
wrapper.setState({
actors: [{
thumbnail: '',
name: 'testname',
actor_id: 42
}]
});
expect(wrapper.find('ActorTile')).toHaveLength(1);
});
it('test Addactor button', function () {
const wrapper = instance();
expect(wrapper.state().actorpopupvisible).toBe(false);
wrapper.find('.actorAddTile').simulate('click');
expect(wrapper.state().actorpopupvisible).toBe(true);
});
});

View File

@ -12,16 +12,37 @@ import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faPlusCircle} from '@fortawesome/free-solid-svg-icons';
import AddActorPopup from '../../elements/Popups/AddActorPopup/AddActorPopup';
import ActorTile from '../../elements/ActorTile/ActorTile';
import GlobalInfos from '../../utils/GlobalInfos';
import {withRouter} from 'react-router-dom';
import {callAPI, getBackendDomain} from '../../utils/Api';
import {RouteComponentProps} from 'react-router';
import {GeneralSuccess} from '../../types/GeneralTypes';
import {ActorType, TagType} from '../../types/VideoTypes';
import PlyrJS from 'plyr';
import {Button} from '../../elements/GPElements/Button';
import {VideoTypes} from '../../types/ApiTypes';
interface myprops extends RouteComponentProps<{ id: string }> {}
interface mystate {
sources?: PlyrJS.SourceInfo,
movie_id: number,
movie_name: string,
likes: number,
quality: number,
length: number,
tags: TagType[],
suggesttag: TagType[],
popupvisible: boolean,
actorpopupvisible: boolean,
actors: ActorType[]
}
/**
* Player page loads when a video is selected to play and handles the video view
* and actions such as tag adding and liking
*/
class Player extends React.Component {
options = {
export class Player extends React.Component<myprops, mystate> {
options: PlyrJS.Options = {
controls: [
'play-large', // The large play button in the center
'play', // Play/pause playback
@ -38,130 +59,31 @@ class Player extends React.Component {
]
};
constructor(props, context) {
super(props, context);
constructor(props: myprops) {
super(props);
this.state = {
sources: null,
movie_id: null,
movie_name: null,
likes: null,
quality: null,
length: null,
movie_id: -1,
movie_name: '',
likes: 0,
quality: 0,
length: 0,
tags: [],
suggesttag: [],
popupvisible: false,
actorpopupvisible: false
actorpopupvisible: false,
actors: []
};
this.quickAddTag = this.quickAddTag.bind(this);
}
componentDidMount() {
componentDidMount(): void {
// initial fetch of current movie data
this.fetchMovieData();
}
/**
* quick add callback to add tag to db and change gui correctly
* @param tagId id of tag to add
* @param tagName name of tag to add
*/
quickAddTag(tagId, tagName) {
callAPI('tags.php', {action: 'addTag', id: tagId, movieid: this.props.movie_id}, (result) => {
if (result.result !== 'success') {
console.error('error occured while writing to db -- todo error handling');
console.error(result.result);
} else {
// check if tag has already been added
const tagIndex = this.state.tags.map(function (e) {
return e.tag_name;
}).indexOf(tagName);
// only add tag if it isn't already there
if (tagIndex === -1) {
// update tags if successful
let array = [...this.state.suggesttag]; // make a separate copy of the array (because of setState)
const quickaddindex = this.state.suggesttag.map(function (e) {
return e.tag_id;
}).indexOf(tagId);
// check if tag is available in quickadds
if (quickaddindex !== -1) {
array.splice(quickaddindex, 1);
this.setState({
tags: [...this.state.tags, {tag_name: tagName}],
suggesttag: array
});
} else {
this.setState({
tags: [...this.state.tags, {tag_name: tagName}]
});
}
}
}
});
}
/**
* handle the popovers generated according to state changes
* @returns {JSX.Element}
*/
handlePopOvers() {
return (
<>
{this.state.popupvisible ?
<AddTagPopup onHide={() => {this.setState({popupvisible: false});}}
submit={this.quickAddTag}
movie_id={this.state.movie_id}/> :
null
}
{
this.state.actorpopupvisible ?
<AddActorPopup onHide={() => {
this.refetchActors();
this.setState({actorpopupvisible: false});
}} movie_id={this.state.movie_id}/> : null
}
</>
);
}
/**
* generate sidebar with all items
*/
assembleSideBar() {
return (
<SideBar>
<SideBarTitle>Infos:</SideBarTitle>
<Line/>
<SideBarItem><b>{this.state.likes}</b> Likes!</SideBarItem>
{this.state.quality !== 0 ?
<SideBarItem><b>{this.state.quality}p</b> Quality!</SideBarItem> : null}
{this.state.length !== 0 ?
<SideBarItem><b>{Math.round(this.state.length / 60)}</b> Minutes of length!</SideBarItem> : null}
<Line/>
<SideBarTitle>Tags:</SideBarTitle>
{this.state.tags.map((m) => (
<Tag key={m.tag_name}>{m.tag_name}</Tag>
))}
<Line/>
<SideBarTitle>Tag Quickadd:</SideBarTitle>
{this.state.suggesttag.map((m) => (
<Tag
key={m.tag_name}
onclick={() => {
this.quickAddTag(m.tag_id, m.tag_name);
}}>
{m.tag_name}
</Tag>
))}
</SideBar>
);
}
render() {
render(): JSX.Element {
return (
<div id='videocontainer'>
<PageTitle
@ -178,25 +100,18 @@ class Player extends React.Component {
options={this.options}/> :
<div>not loaded yet</div>}
<div className={style.videoactions}>
<button className={style.button} style={{backgroundColor: 'green'}} onClick={() => this.likebtn()}>
Like this Video!
</button>
<button className={style.button} style={{backgroundColor: '#3574fe'}} onClick={() => this.setState({popupvisible: true})}>
Give this Video a Tag
</button>
<button className={style.button} style={{backgroundColor: 'red'}} onClick={() => {
this.deleteVideo();
}}>Delete Video
</button>
<Button onClick={(): void => this.likebtn()} title='Like this Video!' color={{backgroundColor: 'green'}}/>
<Button onClick={(): void => this.setState({popupvisible: true})} title='Give this Video a Tag' color={{backgroundColor: '#3574fe'}}/>
<Button title='Delete Video' onClick={(): void => {this.deleteVideo();}} color={{backgroundColor: 'red'}}/>
</div>
{/* rendering of actor tiles */}
<div className={style.actorcontainer}>
{this.state.actors ?
this.state.actors.map((actr) => (
this.state.actors.map((actr: ActorType) => (
<ActorTile actor={actr}/>
)) : <></>
}
<div className={style.actorAddTile} onClick={() => {
<div className={style.actorAddTile} onClick={(): void => {
this.addActor();
}}>
<div className={style.actorAddTile_thumbnail}>
@ -208,7 +123,7 @@ class Player extends React.Component {
</div>
</div>
</div>
<button className={style.closebutton} onClick={() => this.closebtn()}>Close</button>
<button className={style.closebutton} onClick={(): void => this.closebtn()}>Close</button>
{
// handle the popovers switched on and off according to state changes
this.handlePopOvers()
@ -217,11 +132,115 @@ class Player extends React.Component {
);
}
/**
* generate sidebar with all items
*/
assembleSideBar(): JSX.Element {
return (
<SideBar>
<SideBarTitle>Infos:</SideBarTitle>
<Line/>
<SideBarItem><b>{this.state.likes}</b> Likes!</SideBarItem>
{this.state.quality !== 0 ?
<SideBarItem><b>{this.state.quality}p</b> Quality!</SideBarItem> : null}
{this.state.length !== 0 ?
<SideBarItem><b>{Math.round(this.state.length / 60)}</b> Minutes of length!</SideBarItem> : null}
<Line/>
<SideBarTitle>Tags:</SideBarTitle>
{this.state.tags.map((m: TagType) => (
<Tag tagInfo={m}/>
))}
<Line/>
<SideBarTitle>Tag Quickadd:</SideBarTitle>
{this.state.suggesttag.map((m: TagType) => (
<Tag
tagInfo={m}
key={m.tag_name}
onclick={(): void => {
this.quickAddTag(m.tag_id, m.tag_name);
}}/>
))}
</SideBar>
);
}
/**
* quick add callback to add tag to db and change gui correctly
* @param tagId id of tag to add
* @param tagName name of tag to add
*/
quickAddTag(tagId: number, tagName: string): void {
callAPI('tags.php', {
action: 'addTag',
id: tagId,
movieid: this.props.match.params.id
}, (result: GeneralSuccess) => {
if (result.result !== 'success') {
console.error('error occured while writing to db -- todo error handling');
console.error(result.result);
} else {
// check if tag has already been added
const tagIndex = this.state.tags.map(function (e: TagType) {
return e.tag_name;
}).indexOf(tagName);
// only add tag if it isn't already there
if (tagIndex === -1) {
// update tags if successful
let array = [...this.state.suggesttag]; // make a separate copy of the array (because of setState)
const quickaddindex = this.state.suggesttag.map(function (e: TagType) {
return e.tag_id;
}).indexOf(tagId);
// check if tag is available in quickadds
if (quickaddindex !== -1) {
array.splice(quickaddindex, 1);
this.setState({
tags: [...this.state.tags, {tag_name: tagName, tag_id: tagId}],
suggesttag: array
});
} else {
this.setState({
tags: [...this.state.tags, {tag_name: tagName, tag_id: tagId}]
});
}
}
}
});
}
/**
* handle the popovers generated according to state changes
* @returns {JSX.Element}
*/
handlePopOvers(): JSX.Element {
return (
<>
{this.state.popupvisible ?
<AddTagPopup onHide={(): void => {
this.setState({popupvisible: false});
}}
submit={this.quickAddTag}
movie_id={this.state.movie_id}/> :
null
}
{
this.state.actorpopupvisible ?
<AddActorPopup onHide={(): void => {
this.refetchActors();
this.setState({actorpopupvisible: false});
}} movie_id={this.state.movie_id}/> : null
}
</>
);
}
/**
* fetch all the required infos of a video from backend
*/
fetchMovieData() {
callAPI('video.php', {action: 'loadVideo', movieid: this.props.movie_id}, result => {
fetchMovieData(): void {
callAPI('video.php', {action: 'loadVideo', movieid: this.props.match.params.id}, (result: VideoTypes.loadVideoType) => {
this.setState({
sources: {
type: 'video',
@ -243,7 +262,6 @@ class Player extends React.Component {
suggesttag: result.suggesttag,
actors: result.actors
});
console.log(this.state);
});
}
@ -251,8 +269,8 @@ class Player extends React.Component {
/**
* click handler for the like btn
*/
likebtn() {
callAPI('video.php', {action: 'addLike', movieid: this.props.movie_id}, result => {
likebtn(): void {
callAPI('video.php', {action: 'addLike', movieid: this.props.match.params.id}, (result: GeneralSuccess) => {
if (result.result === 'success') {
// likes +1 --> avoid reload of all data
this.setState({likes: this.state.likes + 1});
@ -267,18 +285,18 @@ class Player extends React.Component {
* closebtn click handler
* calls callback to viewbinding to show previous page agains
*/
closebtn() {
GlobalInfos.getViewBinding().returnToLastElement();
closebtn(): void {
this.props.history.goBack();
}
/**
* delete the current video and return to last page
*/
deleteVideo() {
callAPI('video.php', {action: 'deleteVideo', movieid: this.props.movie_id}, result => {
deleteVideo(): void {
callAPI('video.php', {action: 'deleteVideo', movieid: this.props.match.params.id}, (result: GeneralSuccess) => {
if (result.result === 'success') {
// return to last element if successful
GlobalInfos.getViewBinding().returnToLastElement();
this.props.history.goBack();
} else {
console.error('an error occured while liking');
console.error(result);
@ -289,15 +307,19 @@ class Player extends React.Component {
/**
* show the actor add popup
*/
addActor() {
addActor(): void {
this.setState({actorpopupvisible: true});
}
refetchActors() {
callAPI('actor.php', {action: 'getActorsOfVideo', videoid: this.props.movie_id}, result => {
/**
* fetch the available video actors again
*/
refetchActors(): void {
callAPI<ActorType[]>('actor.php', {action: 'getActorsOfVideo', videoid: this.props.match.params.id}, result => {
this.setState({actors: result});
});
}
}
export default Player;
export default withRouter(Player);

View File

@ -5,13 +5,25 @@ import Tag from '../../elements/Tag/Tag';
import PageTitle from '../../elements/PageTitle/PageTitle';
import VideoContainer from '../../elements/VideoContainer/VideoContainer';
import {callAPI} from '../../utils/Api';
import {TagType} from '../../types/VideoTypes';
import {VideoTypes} from '../../types/ApiTypes';
interface state {
videos: VideoTypes.VideoUnloadedType[];
tags: TagType[];
}
interface GetRandomMoviesType {
rows: VideoTypes.VideoUnloadedType[];
tags: TagType[];
}
/**
* Randompage shuffles random viedeopreviews and provides a shuffle btn
*/
class RandomPage extends React.Component {
constructor(props, context) {
super(props, context);
class RandomPage extends React.Component<{}, state> {
constructor(props: {}) {
super(props);
this.state = {
videos: [],
@ -19,11 +31,11 @@ class RandomPage extends React.Component {
};
}
componentDidMount() {
componentDidMount(): void {
this.loadShuffledvideos(4);
}
render() {
render(): JSX.Element {
return (
<div>
<PageTitle title='Random Videos'
@ -32,7 +44,7 @@ class RandomPage extends React.Component {
<SideBar>
<SideBarTitle>Visible Tags:</SideBarTitle>
{this.state.tags.map((m) => (
<Tag key={m.tag_name}>{m.tag_name}</Tag>
<Tag key={m.tag_id} tagInfo={m}/>
))}
</SideBar>
@ -40,7 +52,7 @@ class RandomPage extends React.Component {
<VideoContainer
data={this.state.videos}>
<div className={style.Shufflebutton}>
<button onClick={() => this.shuffleclick()} className={style.btnshuffle}>Shuffle</button>
<button onClick={(): void => this.shuffleclick()} className={style.btnshuffle}>Shuffle</button>
</div>
</VideoContainer>
:
@ -53,7 +65,7 @@ class RandomPage extends React.Component {
/**
* click handler for shuffle btn
*/
shuffleclick() {
shuffleclick(): void {
this.loadShuffledvideos(4);
}
@ -61,8 +73,8 @@ class RandomPage extends React.Component {
* load random videos from backend
* @param nr number of videos to load
*/
loadShuffledvideos(nr) {
callAPI('video.php', {action: 'getRandomMovies', number: nr}, result => {
loadShuffledvideos(nr: number): void {
callAPI<GetRandomMoviesType>('video.php', {action: 'getRandomMovies', number: nr}, result => {
console.log(result);
this.setState({videos: []}); // needed to trigger rerender of main videoview

View File

@ -8,7 +8,7 @@
width: 40%;
}
.customapiform{
.customapiform {
margin-top: 15px;
width: 40%;
}

View File

@ -29,6 +29,13 @@ describe('<GeneralSettings/>', function () {
it('test savesettings', done => {
const wrapper = shallow(<GeneralSettings/>);
wrapper.setState({
passwordsupport: true,
videopath: '',
tvshowpath: '',
mediacentername: '',
tmdbsupport: true
});
global.fetch = global.prepareFetchApi({success: true});
@ -47,6 +54,13 @@ describe('<GeneralSettings/>', function () {
it('test failing savesettings', done => {
const wrapper = shallow(<GeneralSettings/>);
wrapper.setState({
passwordsupport: true,
videopath: '',
tvshowpath: '',
mediacentername: '',
tmdbsupport: true
});
global.fetch = global.prepareFetchApi({success: false});

View File

@ -7,37 +7,59 @@ import {faArchive, faBalanceScaleLeft, faRulerVertical} from '@fortawesome/free-
import {faAddressCard} from '@fortawesome/free-regular-svg-icons';
import {version} from '../../../package.json';
import {callAPI, setCustomBackendDomain} from '../../utils/Api';
import {SettingsTypes} from '../../types/ApiTypes';
import {GeneralSuccess} from '../../types/GeneralTypes';
interface state {
passwordsupport: boolean,
tmdbsupport: boolean,
customapi: boolean,
videopath: string,
tvshowpath: string,
mediacentername: string,
password: string,
apipath: string,
videonr: number,
dbsize: number,
difftagnr: number,
tagsadded: number
}
interface props {}
/**
* Component for Generalsettings tag on Settingspage
* handles general settings of mediacenter which concerns to all pages
*/
class GeneralSettings extends React.Component {
constructor(props) {
class GeneralSettings extends React.Component<props, state> {
constructor(props: props) {
super(props);
this.state = {
passwordsupport: false,
tmdbsupport: null,
tmdbsupport: false,
customapi: false,
videopath: '',
tvshowpath: '',
mediacentername: '',
password: '',
apipath: '',
videonr: null,
dbsize: null,
difftagnr: null,
tagsadded: null
videonr: 0,
dbsize: 0,
difftagnr: 0,
tagsadded: 0
};
}
componentDidMount() {
componentDidMount(): void {
this.loadSettings();
}
render() {
render(): JSX.Element {
const themeStyle = GlobalInfos.getThemeStyle();
return (
<>
@ -47,7 +69,7 @@ class GeneralSettings extends React.Component {
subtext='Videos in Gravity'
icon={faArchive}/>
<InfoHeaderItem backColor='yellow'
text={this.state.dbsize !== undefined ? this.state.dbsize + ' MB' : undefined}
text={this.state.dbsize !== undefined ? this.state.dbsize + ' MB' : ''}
subtext='Database size'
icon={faRulerVertical}/>
<InfoHeaderItem backColor='green'
@ -60,7 +82,7 @@ class GeneralSettings extends React.Component {
icon={faBalanceScaleLeft}/>
</div>
<div className={style.GeneralForm + ' ' + themeStyle.subtextcolor}>
<Form data-testid='mainformsettings' onSubmit={(e) => {
<Form data-testid='mainformsettings' onSubmit={(e): void => {
e.preventDefault();
this.saveSettings();
}}>
@ -68,14 +90,14 @@ class GeneralSettings extends React.Component {
<Form.Group as={Col} data-testid='videpathform'>
<Form.Label>Video Path</Form.Label>
<Form.Control type='text' placeholder='/var/www/html/video' value={this.state.videopath}
onChange={(ee) => this.setState({videopath: ee.target.value})}/>
onChange={(ee): void => this.setState({videopath: ee.target.value})}/>
</Form.Group>
<Form.Group as={Col} data-testid='tvshowpath'>
<Form.Label>TV Show Path</Form.Label>
<Form.Control type='text' placeholder='/var/www/html/tvshow'
value={this.state.tvshowpath}
onChange={(e) => this.setState({tvshowpath: e.target.value})}/>
onChange={(e): void => this.setState({tvshowpath: e.target.value})}/>
</Form.Group>
</Form.Row>
@ -84,7 +106,7 @@ class GeneralSettings extends React.Component {
id='custom-switch-api'
label='Use custom API url'
checked={this.state.customapi}
onChange={() => {
onChange={(): void => {
if (this.state.customapi) {
setCustomBackendDomain('');
}
@ -97,7 +119,7 @@ class GeneralSettings extends React.Component {
<Form.Label>API Backend url</Form.Label>
<Form.Control type='text' placeholder='https://127.0.0.1'
value={this.state.apipath}
onChange={(e) => {
onChange={(e): void => {
this.setState({apipath: e.target.value});
setCustomBackendDomain(e.target.value);
}}/>
@ -110,7 +132,7 @@ class GeneralSettings extends React.Component {
data-testid='passwordswitch'
label='Enable Password support'
checked={this.state.passwordsupport}
onChange={() => {
onChange={(): void => {
this.setState({passwordsupport: !this.state.passwordsupport});
}}
/>
@ -119,7 +141,7 @@ class GeneralSettings extends React.Component {
<Form.Group data-testid='passwordfield'>
<Form.Label>Password</Form.Label>
<Form.Control type='password' placeholder='**********' value={this.state.password}
onChange={(e) => this.setState({password: e.target.value})}/>
onChange={(e): void => this.setState({password: e.target.value})}/>
</Form.Group> : null
}
@ -129,7 +151,7 @@ class GeneralSettings extends React.Component {
data-testid='tmdb-switch'
label='Enable TMDB video grabbing support'
checked={this.state.tmdbsupport}
onChange={() => {
onChange={(): void => {
this.setState({tmdbsupport: !this.state.tmdbsupport});
}}
/>
@ -140,7 +162,7 @@ class GeneralSettings extends React.Component {
data-testid='darktheme-switch'
label='Enable Dark-Theme'
checked={GlobalInfos.isDarkTheme()}
onChange={() => {
onChange={(): void => {
GlobalInfos.enableDarkTheme(!GlobalInfos.isDarkTheme());
this.forceUpdate();
// todo initiate rerender
@ -150,7 +172,7 @@ class GeneralSettings extends React.Component {
<Form.Group className={style.mediacenternameform} data-testid='nameform'>
<Form.Label>The name of the Mediacenter</Form.Label>
<Form.Control type='text' placeholder='Mediacentername' value={this.state.mediacentername}
onChange={(e) => this.setState({mediacentername: e.target.value})}/>
onChange={(e): void => this.setState({mediacentername: e.target.value})}/>
</Form.Group>
<Button variant='primary' type='submit'>
@ -168,8 +190,8 @@ class GeneralSettings extends React.Component {
/**
* inital load of already specified settings from backend
*/
loadSettings() {
callAPI('settings.php', {action: 'loadGeneralSettings'}, (result) => {
loadSettings(): void {
callAPI('settings.php', {action: 'loadGeneralSettings'}, (result: SettingsTypes.loadGeneralSettingsType) => {
this.setState({
videopath: result.video_path,
tvshowpath: result.episode_path,
@ -189,7 +211,7 @@ class GeneralSettings extends React.Component {
/**
* save the selected and typed settings to the backend
*/
saveSettings() {
saveSettings(): void {
callAPI('settings.php', {
action: 'saveGeneralSettings',
password: this.state.passwordsupport ? this.state.password : '-1',
@ -198,8 +220,8 @@ class GeneralSettings extends React.Component {
mediacentername: this.state.mediacentername,
tmdbsupport: this.state.tmdbsupport,
darkmodeenabled: GlobalInfos.isDarkTheme().toString()
}, (result) => {
if (result.success) {
}, (result: GeneralSuccess) => {
if (result.result) {
console.log('successfully saved settings');
// todo 2020-07-10: popup success
} else {

View File

@ -1,13 +1,24 @@
import React from 'react';
import style from './MovieSettings.module.css';
import {callAPI} from '../../utils/Api';
import {GeneralSuccess} from '../../types/GeneralTypes';
import {SettingsTypes} from '../../types/ApiTypes';
interface state {
text: string[]
startbtnDisabled: boolean
}
interface props {}
/**
* Component for MovieSettings on Settingspage
* handles settings concerning to movies in general
*/
class MovieSettings extends React.Component {
constructor(props) {
class MovieSettings extends React.Component<props, state> {
myinterval: number = -1;
constructor(props: props) {
super(props);
this.state = {
@ -16,23 +27,24 @@ class MovieSettings extends React.Component {
};
}
componentDidMount() {
this.myinterval = setInterval(this.updateStatus, 1000);
componentDidMount(): void {
this.myinterval = window.setInterval(this.updateStatus, 1000);
}
componentWillUnmount() {
clearInterval(this.myinterval);
componentWillUnmount(): void {
if (this.myinterval !== -1)
clearInterval(this.myinterval);
}
render() {
render(): JSX.Element {
return (
<>
<button disabled={this.state.startbtnDisabled}
className='btn btn-success'
onClick={() => {this.startReindex();}}>Reindex Movie
onClick={(): void => {this.startReindex();}}>Reindex Movie
</button>
<button className='btn btn-warning'
onClick={() => {this.cleanupGravity();}}>Cleanup Gravity
onClick={(): void => {this.cleanupGravity();}}>Cleanup Gravity
</button>
<div className={style.indextextarea}>{this.state.text.map(m => (
<div className='textarea-element'>{m}</div>
@ -44,7 +56,7 @@ class MovieSettings extends React.Component {
/**
* starts the reindex process of the videos in the specified folder
*/
startReindex() {
startReindex(): void {
// clear output text before start
this.setState({text: []});
@ -52,9 +64,9 @@ class MovieSettings extends React.Component {
console.log('starting');
callAPI('settings.php', {action: 'startReindex'}, (result) => {
callAPI('settings.php', {action: 'startReindex'}, (result: GeneralSuccess): void => {
console.log(result);
if (result.success) {
if (result.result === 'success') {
console.log('started successfully');
} else {
console.log('error, reindex already running');
@ -62,17 +74,17 @@ class MovieSettings extends React.Component {
}
});
if (this.myinterval) {
if (this.myinterval !== -1) {
clearInterval(this.myinterval);
}
this.myinterval = setInterval(this.updateStatus, 1000);
this.myinterval = window.setInterval(this.updateStatus, 1000);
}
/**
* This interval function reloads the current status of reindexing from backend
*/
updateStatus = () => {
callAPI('settings.php', {action: 'getStatusMessage'}, (result) => {
updateStatus = (): void => {
callAPI('settings.php', {action: 'getStatusMessage'}, (result: SettingsTypes.getStatusMessageType) => {
if (result.contentAvailable === true) {
console.log(result);
// todo 2020-07-4: scroll to bottom of div here
@ -93,7 +105,7 @@ class MovieSettings extends React.Component {
/**
* send request to cleanup db gravity
*/
cleanupGravity() {
cleanupGravity(): void {
callAPI('settings.php', {action: 'cleanupGravity'}, (result) => {
this.setState({
text: ['successfully cleaned up gravity!']

View File

@ -26,6 +26,7 @@
.SettingSidebarElement {
background-color: #919fd9;
border-radius: 7px;
color: black;
font-weight: bold;
margin: 10px 5px 5px;
padding: 5px;

View File

@ -7,34 +7,4 @@ describe('<RandomPage/>', function () {
const wrapper = shallow(<SettingsPage/>);
wrapper.unmount();
});
it('simulate topic clicka', function () {
const wrapper = shallow(<SettingsPage/>);
simulateSideBarClick('General', wrapper);
expect(wrapper.state().currentpage).toBe('general');
expect(wrapper.find('.SettingsContent').find('GeneralSettings')).toHaveLength(1);
simulateSideBarClick('Movies', wrapper);
expect(wrapper.state().currentpage).toBe('movies');
expect(wrapper.find('.SettingsContent').find('MovieSettings')).toHaveLength(1);
simulateSideBarClick('TV Shows', wrapper);
expect(wrapper.state().currentpage).toBe('tv');
expect(wrapper.find('.SettingsContent').find('span')).toHaveLength(1);
});
function simulateSideBarClick(name, wrapper) {
wrapper.find('.SettingSidebarElement').findWhere(it =>
it.text() === name &&
it.type() === 'div').simulate('click');
}
it('simulate unknown topic', function () {
const wrapper = shallow(<SettingsPage/>);
wrapper.setState({currentpage: 'unknown'});
expect(wrapper.find('.SettingsContent').text()).toBe('unknown button clicked');
});
});

View File

@ -3,59 +3,44 @@ import MovieSettings from './MovieSettings';
import GeneralSettings from './GeneralSettings';
import style from './SettingsPage.module.css';
import GlobalInfos from '../../utils/GlobalInfos';
type SettingsPageState = {
currentpage: string
}
import {NavLink, Redirect, Route, Switch} from 'react-router-dom';
/**
* The Settingspage handles all kinds of settings for the mediacenter
* and is basically a wrapper for child-tabs
*/
class SettingsPage extends React.Component<{}, SettingsPageState> {
constructor(props: Readonly<{}> | {}, context?: any) {
super(props, context);
this.state = {
currentpage: 'general'
};
}
/**
* load the selected tab
* @returns {JSX.Element|string} the jsx element of the selected tab
*/
getContent(): JSX.Element | string {
switch (this.state.currentpage) {
case 'general':
return <GeneralSettings/>;
case 'movies':
return <MovieSettings/>;
case 'tv':
return <span/>; // todo this page
default:
return 'unknown button clicked';
}
}
render() : JSX.Element {
class SettingsPage extends React.Component {
render(): JSX.Element {
const themestyle = GlobalInfos.getThemeStyle();
return (
<div>
<div className={style.SettingsSidebar + ' ' + themestyle.secbackground}>
<div className={style.SettingsSidebarTitle + ' ' + themestyle.lighttextcolor}>Settings</div>
<div onClick={() => this.setState({currentpage: 'general'})}
className={style.SettingSidebarElement}>General
</div>
<div onClick={() => this.setState({currentpage: 'movies'})}
className={style.SettingSidebarElement}>Movies
</div>
<div onClick={() => this.setState({currentpage: 'tv'})}
className={style.SettingSidebarElement}>TV Shows
</div>
<NavLink to='/settings/general'>
<div className={style.SettingSidebarElement}>General</div>
</NavLink>
<NavLink to='/settings/movies'>
<div className={style.SettingSidebarElement}>Movies</div>
</NavLink>
<NavLink to='/settings/tv'>
<div className={style.SettingSidebarElement}>TV Shows</div>
</NavLink>
</div>
<div className={style.SettingsContent}>
{this.getContent()}
<Switch>
<Route path="/settings/general">
<GeneralSettings/>
</Route>
<Route path="/settings/movies">
<MovieSettings/>
</Route>
<Route path="/settings/tv">
<span/>
</Route>
<Route path="/settings">
<Redirect to='/settings/general'/>
</Route>
</Switch>
</div>
</div>
);

View File

@ -42,24 +42,24 @@ global.prepareViewBinding = (func) => {
return {
changeRootElement: func,
returnToLastElement: func
}
};
};
}
};
global.callAPIMock = (resonse) => {
const helpers = require("./utils/Api");
helpers.callAPI = jest.fn().mockImplementation((_, __, func1) => {func1(resonse)});
}
const helpers = require('./utils/Api');
helpers.callAPI = jest.fn().mockImplementation((_, __, func1) => {func1(resonse);});
};
// code to run before each test
global.beforeEach(() => {
// empty fetch response implementation for each test
global.fetch = prepareFetchApi({});
// todo with callAPIMock
})
});
global.afterEach(() => {
// clear all mocks after each test
jest.resetAllMocks();
})
});

66
src/types/ApiTypes.ts Normal file
View File

@ -0,0 +1,66 @@
import {ActorType, TagType} from './VideoTypes';
export namespace VideoTypes {
export interface loadVideoType {
movie_url: string
thumbnail: string
movie_id: number
movie_name: string
likes: number
quality: number
length: number
tags: TagType[]
suggesttag: TagType[]
actors: ActorType[]
}
export interface startDataType {
total: number;
fullhd: number;
hd: number;
sd: number;
tags: number;
}
export interface VideoUnloadedType {
movie_id: number;
movie_name: string
}
}
export namespace SettingsTypes {
export interface initialApiCallData {
DarkMode: boolean;
passwordEnabled: boolean;
mediacenter_name: string;
}
export interface loadGeneralSettingsType {
video_path: string,
episode_path: string,
mediacenter_name: string,
password: string,
passwordEnabled: boolean,
TMDB_grabbing: boolean,
videonr: number,
dbsize: number,
difftagnr: number,
tagsadded: number
}
export interface getStatusMessageType {
contentAvailable: boolean;
message: string;
}
}
export namespace ActorTypes {
/**
* result of actor fetch
*/
export interface videofetchresult {
videos: VideoTypes.VideoUnloadedType[];
info: ActorType;
}
}

16
src/types/GeneralTypes.ts Normal file
View File

@ -0,0 +1,16 @@
import {TagType} from './VideoTypes';
export interface GeneralSuccess {
result: string
}
interface TagarrayType {
[_: string]: TagType
}
export const DefaultTags: TagarrayType = {
all: {tag_id: 1, tag_name: 'all'},
fullhd: {tag_id: 2, tag_name: 'fullhd'},
lowq: {tag_id: 3, tag_name: 'lowquality'},
hd: {tag_id: 4, tag_name: 'hd'}
};

13
src/types/VideoTypes.ts Normal file
View File

@ -0,0 +1,13 @@
/**
* type accepted by Tag component
*/
export interface TagType {
tag_name: string
tag_id: number
}
export interface ActorType {
thumbnail: string;
name: string;
actor_id: number;
}

View File

@ -23,7 +23,7 @@ export function getBackendDomain(): string {
* set a custom backend domain
* @param domain a url in format [http://x.x.x.x/somanode]
*/
export function setCustomBackendDomain(domain: string) {
export function setCustomBackendDomain(domain: string): void {
customBackendURL = domain;
}
@ -38,9 +38,9 @@ function getAPIDomain(): string {
* interface how an api request should look like
*/
interface ApiBaseRequest {
action: string,
action: string | number,
[_: string]: string
[_: string]: string | number | boolean
}
/**
@ -51,7 +51,7 @@ function buildFormData(args: ApiBaseRequest): FormData {
const req = new FormData();
for (const i in args) {
req.append(i, args[i]);
req.append(i, (args[i].toString()));
}
return req;
}
@ -63,8 +63,7 @@ function buildFormData(args: ApiBaseRequest): FormData {
* @param callback the callback with json reply from backend
* @param errorcallback a optional callback if an error occured
*/
export function callAPI(apinode: string, fd: ApiBaseRequest, callback: (_: object) => void, errorcallback: (_: object) => void = (_: object) => {
}): void {
export function callAPI<T>(apinode: string, fd: ApiBaseRequest, callback: (_: T) => void, errorcallback: (_: string) => void = (_: string): void => {}): void {
fetch(getAPIDomain() + apinode, {method: 'POST', body: buildFormData(fd)})
.then((response) => response.json()
.then((result) => {
@ -78,7 +77,7 @@ export function callAPI(apinode: string, fd: ApiBaseRequest, callback: (_: objec
* @param fd the object to send to backend
* @param callback the callback with PLAIN text reply from backend
*/
export function callAPIPlain(apinode: string, fd: ApiBaseRequest, callback: (_: any) => void): void {
export function callAPIPlain(apinode: string, fd: ApiBaseRequest, callback: (_: string) => void): void {
fetch(getAPIDomain() + apinode, {method: 'POST', body: buildFormData(fd)})
.then((response) => response.text()
.then((result) => {

View File

@ -7,7 +7,6 @@ import lighttheme from '../AppLightTheme.module.css';
*/
class StaticInfos {
#darktheme = true;
#viewbinding = () => {console.warn('Viewbinding not set now!');};
/**
* check if the current theme is the dark theme
@ -32,22 +31,6 @@ class StaticInfos {
getThemeStyle() {
return this.isDarkTheme() ? darktheme : lighttheme;
}
/**
* set the global Viewbinding for the main Navigation
* @param cb
*/
setViewBinding(cb) {
this.#viewbinding = cb;
}
/**
* return the Viewbinding for main navigation
* @returns {StaticInfos.viewbinding}
*/
getViewBinding() {
return this.#viewbinding;
}
}
const GlobalInfos = new StaticInfos();

View File

@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "ES5",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
@ -12,14 +12,16 @@
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
"jsx": "react-jsx"
},
"include": [
"declaration.d.ts",
"src"
]
}