fixed errors and warnings

This commit is contained in:
matteo
2019-02-14 17:01:45 +01:00
parent dab303c617
commit 18b0dbcc39
8 changed files with 165 additions and 64 deletions
+87
View File
@@ -0,0 +1,87 @@
process.env['NODE_ENV'] = 'production';
const express = require('express');
const compression = require('compression')
const bodyParser = require('body-parser');
const low = require('lowdb');
const lodashId = require('lodash-id');
const FileAsync = require('lowdb/adapters/FileAsync');
const app = express(); // app is an instance of express
app.use(compression()); // enables gzip compression
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
// Create database instance and start server
// const adapter = new FileAsync(__dirname + '/db.json');
low(new FileAsync(__dirname + '/db.json')) // production
.then(db => {
db._.mixin(lodashId);
// DATABASE ROUTES
// ==============
app.post('/test', (req, res) => {
// "reason": {
// "fitali": req.body.reason.toString() === "fvitali" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// }
// try {
// let test = table.updateById(req.body.id, { })
// }
// catch(e) {
// }
res.send(req.body);
});
// ==============
// GET /globpop
app.get('/globpop', (req, res) => {
req.query.id ? res.send(req.query.id) : res.status(400).send('Bad Request');
});
// OPTIONS /videotrack
app.options('/videotrack', (req, res) => {
res.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': 600
})
res.status(200).end();
})
// GET /videotrack
app.get('/videotrack', (req, res) => {
const videos = db.get('videos');
req.query.id ? res.send(videos.getById(req.query.id).value()) : res.send(videos.value())
});
// POST /videotrack
app.post('/videotrack', (req, res) => {
const videos = db.get('videos');
const row = videos.getById(req.body.id);
if (row.value()) {
row
.update('timesWatched', (n) => ++n)
.update('lastWatched', () => new Date().toISOString())
.write()
.then(output => res.send(output))
} else {
let newRow = {
"id": req.body.id.toString(),
"timesWatched": 1,
"lastWatched": new Date().toISOString(),
}
videos.push(newRow).last().write().then(output => res.send(output))
}
});
// Set db default values
return db.defaults({ videos: [] }).write();
})
.then(() => {
app.listen(8000, () => console.log('listen on 8000')); // bind to port 8000 as required from specs
});
+36 -25
View File
@@ -1,5 +1,5 @@
process.env['NODE_ENV'] = 'production';
'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' = 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg';
//'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' = 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg';
const express = require('express');
const compression = require('compression')
const bodyParser = require('body-parser');
@@ -13,8 +13,8 @@ app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-f
app.use(bodyParser.json()) // parse application/json
app.get('/a', (req, res) => {
res.send(process.env);
app.get('/a', (req, res) => {
res.send(process.env);
});
@@ -26,14 +26,14 @@ low(new FileAsync(__dirname + '/db.json')) // production
db._.mixin(lodashId);
// DATABASE ROUTES
// ==============
// ==============
app.post('/test',(req,res)=>{
// "reason": {
// "fitali": req.body.reason.toString() === "fvitali" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// }
app.post('/test', (req, res) => {
// "reason": {
// "fitali": req.body.reason.toString() === "fvitali" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0,
// }
// try {
// let test = table.updateById(req.body.id, { })
// }
@@ -42,39 +42,50 @@ low(new FileAsync(__dirname + '/db.json')) // production
res.send(req.body);
});
// ==============
// ==============
// GET /videotrack/:id?
// GET /globpop
app.get('/globpop', (req, res) => {
req.query.id ? res.send(req.query.id):res.status(400).send('Bad Request');
req.query.id ? res.send(req.query.id) : res.status(400).send('Bad Request');
});
// GET /videotrack/:id?
app.get('/videotrack/:id?', (req, res) => {
// OPTIONS /videotrack
app.options('/videotrack', (req, res) => {
res.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': 600
})
res.status(200).end();
})
// GET /videotrack
app.get('/videotrack', (req, res) => {
const videos = db.get('videos');
req.params.id ? res.send(videos.getById(req.params.id).value()) : res.send(videos.value())
req.query.id ? res.send(videos.getById(req.query.id).value()) : res.send(videos.value())
});
// POST /videotrack
app.post('/videotrack', (req, res) => {
const videos = db.get('videos');
const row = videos.getById(req.body.id);
if(row.value()) {
const videos = db.get('videos');
const row = videos.getById(req.body.id);
if (row.value()) {
row
.update('timesWatched',(n) => ++n)
.update('lastWatched',() => new Date().toISOString())
.write()
.then(output => res.send(output))
.update('timesWatched', (n) => ++n)
.update('lastWatched', () => new Date().toISOString())
.write()
.then(output => res.send(output))
} else {
let newRow = {
"id": req.body.id.toString(),
"id": req.body.id.toString(),
"timesWatched": 1,
"lastWatched": new Date().toISOString(),
}
videos.push(newRow).last().write().then(output => res.send(output))
}
});
// Set db default values
return db.defaults({ videos: [] }).write();
})
+5 -4
View File
@@ -61,8 +61,8 @@ static getDerivedStateFromProps(nextProps, prevState) {
xs="12"
lg={this.state.isInfoToggled ? { span: 5, order: 1 } : { span: 3, order: 1 }}
className="p-0 p-sm-0"
style={{ 'overflow': "auto", 'max-height': this.state.playerHeight }} >
<div class="d-flex justify-content-center">
style={{ 'overflow': "auto", 'maxHeight': this.state.playerHeight }} >
<div className="d-flex justify-content-center">
<Button
variant="outline-light"
onClick={() => this.setState({ isInfoToggled: !this.state.isInfoToggled })}
@@ -79,10 +79,11 @@ static getDerivedStateFromProps(nextProps, prevState) {
</Collapse>
</Col>
</ReactHeight>
<Row style={{ "max-height": `calc(98vh - ${this.state.blackbgHeight}px - ${this.state.navHeight}px)` }} className='mt-1 downSection'>
<Row style={{ "maxHeight": `calc(98vh - ${this.state.blackbgHeight}px - ${this.state.navHeight}px)` }} className='mt-1 downSection'>
<Switch>
<Route exact path='/' component={VideoList} />
<Route path={["/video/:id", "/search/:query"]} component={Suggestion} />
<Route path={"/video/:id"} component={Suggestion} />
<Route path={"/search/:query"} component={Suggestion} />
<Route render={() => <div>URL not found</div>} />
</Switch>
</Row>
+2 -2
View File
@@ -156,7 +156,7 @@ class VideoInfo extends React.Component {
} else {
return (
<React.Fragment>
<span class="h5 text-white">{VideoDetails.snippet.title}</span>
<span className="h5 text-white">{VideoDetails.snippet.title}</span>
<Tabs defaultActiveKey="video" id="tabs">
<Tab className="text-white" eventKey="video" title="Video">
<p>
@@ -165,7 +165,7 @@ class VideoInfo extends React.Component {
<b>Channel name: </b>{VideoDetails.snippet.channelTitle}<br />
<b>Description: </b><Linkify>{VideoDetails.snippet.description}</Linkify><br />
<b>Tags: </b>{VideoDetails.snippet.tags ?
VideoDetails.snippet.tags.map(tag => (<Link
VideoDetails.snippet.tags.map((tag,i) => (<Link key={i}
to={{
pathname: '/search/' + tag,
}}
+24 -22
View File
@@ -6,22 +6,25 @@ import './css/VideoList.css';
/*eslint no-console: ["error", { allow: ["warn", "error", "info"] }] */
class VideoList extends React.Component {
constructor(props) {
super(props);
this.state = {
state = {
error: null,
isLoaded: false,
items: [],
headers: null
};
this.getThumbnails = this.getThumbnails.bind(this);
}
componentDidMount() {
localStorage['fixedVideoList'] ?
this.setState({
items: this.shuffleArray(JSON.parse(localStorage.getItem('fixedVideoList'))),
isLoaded: true
}) :
axios.get('http://site1825.tw.cs.unibo.it/video.json').then(
response => {
this.shuffleArray(response.data);
this.getThumbnails(response.data);
this.getThumbnails(response.data)
.then(videoList => localStorage.setItem('fixedVideoList',JSON.stringify(videoList)));
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
@@ -33,14 +36,14 @@ class VideoList extends React.Component {
error
});
}
);
)
}
// METODI
getThumbnails(videoItems) {
let idToLookFor = videoItems.map(item => item.videoID);
let finalChunk = (videoItems.length % 50) + 100;
axios
return axios
.all([
// chain 3 parallel get
axios.get('https://www.googleapis.com/youtube/v3/videos', {
@@ -72,39 +75,38 @@ class VideoList extends React.Component {
])
.then(
axios.spread((res1, res2, res3) => {
let allres = [].concat(
res1.data.items,
res2.data.items,
res3.data.items
);
allres.map(resCurrentValue => {
[...res1.data.items,...res2.data.items,...res3.data.items]
.map(resCurrentValue =>
Object.defineProperty(
videoItems.find(videoItem => {
return videoItem.videoID === resCurrentValue.id;
}),
'thumbnail',
{ value: resCurrentValue.snippet.thumbnails.medium.url }
);
});
{ value: resCurrentValue.snippet.thumbnails.medium.url,
enumerable: true }
)
);
this.setState({
isLoaded: true,
items: videoItems
});
return new Promise((resolve, reject) => resolve(videoItems))
})
);
)
}
shuffleArray(videoarray) {
for (let i = videoarray.length - 1; i > 0; i--) {
shuffleArray(videoArray) {
for (let i = videoArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[videoarray[i], videoarray[j]] = [videoarray[j], videoarray[i]]; // eslint-disable-line no-param-reassign
[videoArray[i], videoArray[j]] = [videoArray[j], videoArray[i]]; // eslint-disable-line no-param-reassign
}
return videoArray
// Durstenfeld shuffle.
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
}
render() {
const { error, isLoaded, items, headers } = this.state;
const { error, isLoaded, items } = this.state;
if (error) {
return (
<React.Fragment>
+2 -2
View File
@@ -86,12 +86,12 @@ class VideoPlayer extends React.Component {
videoIdWatched => {
// post request to local db
axios
.post('http://localhost:8000/videotrack', {
.post('http://site1854.tw.cs.unibo.it/videotrack', {
id: videoIdWatched.toString()
})
.then(
response => console.info(response.data),
error => console.info(error, videoIdWatched.toString())
error => console.error(error, videoIdWatched.toString())
);
// local storage logic for recent reccomender//tmp è il video che devo inserire sulla lista
let tmp = JSON.parse(localStorage.getItem('lastWatched'))
+1 -1
View File
@@ -1,5 +1,5 @@
import React, { Component } from 'react';
import { Row, Col, Button, Collapse } from 'react-bootstrap';
import { Row } from 'react-bootstrap';
import { Switch, Route } from 'react-router';
import Random from '../reccomenders/Random';
import Related from '../reccomenders/Related';
+8 -8
View File
@@ -161,7 +161,7 @@ class Wikipedia extends Component {
componentDidMount() {
this.wrapper().then(()=>this.setState({isLoaded: true}));
this.wrapper().finally(()=>this.setState({isLoaded: true}));
}
@@ -170,8 +170,8 @@ class Wikipedia extends Component {
// }
componentDidUpdate(prevProps, prevState) {
if (prevState.props.videoId !== this.state.props.videoId)
this.wrapper().then(()=>this.setState({isLoaded: true}));
if (prevProps.videoId !== this.state.props.videoId)
this.wrapper().finally(()=>this.setState({isLoaded: true}));
}
// componentWillUnmount() {
@@ -191,7 +191,7 @@ class Wikipedia extends Component {
<tbody>
{ isWikiLoaded &&
this.state.wikipediakeys.map(key => (
<tr>
<tr key={key}>
<td>{key}</td>
<td>{wikipedia.info[key].toLocaleString()}</td>
</tr>
@@ -199,7 +199,7 @@ class Wikipedia extends Component {
}
{ isWDataLoaded &&
this.state.wikidatakeys.map(key => (
<tr>
<tr key={key}>
<td>{`${key} - ${wikidata.claims[key][0].mainsnak.datatype}`}</td>
<td>{
typeof wikidata.claims[key][0].mainsnak.datavalue.value === "string" ?
@@ -214,14 +214,14 @@ class Wikipedia extends Component {
))
}
{ isMBLoaded &&
musicbrainz.relations.map(relation => {
musicbrainz.relations.map((relation,i) => {
if (relation["target-type"] === "artist")
return (<tr>
return (<tr key={i}>
<td>{relation.type}</td>
<td>{relation.artist.name}</td>
</tr>);
else if (relation["target-type"] === "url")
return (<tr>
return (<tr key={i}>
<td>{relation.type}</td>
<td><a href={relation.url.resource}>{relation.type}</a></td>
</tr>)