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'; process.env['NODE_ENV'] = 'production';
'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' = 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg'; //'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' = 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg';
const express = require('express'); const express = require('express');
const compression = require('compression') const compression = require('compression')
const bodyParser = require('body-parser'); 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.use(bodyParser.json()) // parse application/json
app.get('/a', (req, res) => { app.get('/a', (req, res) => {
res.send(process.env); res.send(process.env);
}); });
@@ -26,14 +26,14 @@ low(new FileAsync(__dirname + '/db.json')) // production
db._.mixin(lodashId); db._.mixin(lodashId);
// DATABASE ROUTES // DATABASE ROUTES
// ============== // ==============
app.post('/test',(req,res)=>{ app.post('/test', (req, res) => {
// "reason": { // "reason": {
// "fitali": req.body.reason.toString() === "fvitali" ? 1:0, // "fitali": req.body.reason.toString() === "fvitali" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0, // "": req.body.reason.toString() === "" ? 1:0,
// "": req.body.reason.toString() === "" ? 1:0, // "": req.body.reason.toString() === "" ? 1:0,
// } // }
// try { // try {
// let test = table.updateById(req.body.id, { }) // let test = table.updateById(req.body.id, { })
// } // }
@@ -42,39 +42,50 @@ low(new FileAsync(__dirname + '/db.json')) // production
res.send(req.body); res.send(req.body);
}); });
// ============== // ==============
// GET /videotrack/:id? // GET /globpop
app.get('/globpop', (req, res) => { 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? // OPTIONS /videotrack
app.get('/videotrack/:id?', (req, res) => { 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'); 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 // POST /videotrack
app.post('/videotrack', (req, res) => { app.post('/videotrack', (req, res) => {
const videos = db.get('videos'); const videos = db.get('videos');
const row = videos.getById(req.body.id); const row = videos.getById(req.body.id);
if(row.value()) { if (row.value()) {
row row
.update('timesWatched',(n) => ++n) .update('timesWatched', (n) => ++n)
.update('lastWatched',() => new Date().toISOString()) .update('lastWatched', () => new Date().toISOString())
.write() .write()
.then(output => res.send(output)) .then(output => res.send(output))
} else { } else {
let newRow = { let newRow = {
"id": req.body.id.toString(), "id": req.body.id.toString(),
"timesWatched": 1, "timesWatched": 1,
"lastWatched": new Date().toISOString(), "lastWatched": new Date().toISOString(),
} }
videos.push(newRow).last().write().then(output => res.send(output)) videos.push(newRow).last().write().then(output => res.send(output))
} }
}); });
// Set db default values // Set db default values
return db.defaults({ videos: [] }).write(); return db.defaults({ videos: [] }).write();
}) })
+5 -4
View File
@@ -61,8 +61,8 @@ static getDerivedStateFromProps(nextProps, prevState) {
xs="12" xs="12"
lg={this.state.isInfoToggled ? { span: 5, order: 1 } : { span: 3, order: 1 }} lg={this.state.isInfoToggled ? { span: 5, order: 1 } : { span: 3, order: 1 }}
className="p-0 p-sm-0" className="p-0 p-sm-0"
style={{ 'overflow': "auto", 'max-height': this.state.playerHeight }} > style={{ 'overflow': "auto", 'maxHeight': this.state.playerHeight }} >
<div class="d-flex justify-content-center"> <div className="d-flex justify-content-center">
<Button <Button
variant="outline-light" variant="outline-light"
onClick={() => this.setState({ isInfoToggled: !this.state.isInfoToggled })} onClick={() => this.setState({ isInfoToggled: !this.state.isInfoToggled })}
@@ -79,10 +79,11 @@ static getDerivedStateFromProps(nextProps, prevState) {
</Collapse> </Collapse>
</Col> </Col>
</ReactHeight> </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> <Switch>
<Route exact path='/' component={VideoList} /> <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>} /> <Route render={() => <div>URL not found</div>} />
</Switch> </Switch>
</Row> </Row>
+2 -2
View File
@@ -156,7 +156,7 @@ class VideoInfo extends React.Component {
} else { } else {
return ( return (
<React.Fragment> <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"> <Tabs defaultActiveKey="video" id="tabs">
<Tab className="text-white" eventKey="video" title="Video"> <Tab className="text-white" eventKey="video" title="Video">
<p> <p>
@@ -165,7 +165,7 @@ class VideoInfo extends React.Component {
<b>Channel name: </b>{VideoDetails.snippet.channelTitle}<br /> <b>Channel name: </b>{VideoDetails.snippet.channelTitle}<br />
<b>Description: </b><Linkify>{VideoDetails.snippet.description}</Linkify><br /> <b>Description: </b><Linkify>{VideoDetails.snippet.description}</Linkify><br />
<b>Tags: </b>{VideoDetails.snippet.tags ? <b>Tags: </b>{VideoDetails.snippet.tags ?
VideoDetails.snippet.tags.map(tag => (<Link VideoDetails.snippet.tags.map((tag,i) => (<Link key={i}
to={{ to={{
pathname: '/search/' + tag, pathname: '/search/' + tag,
}} }}
+24 -22
View File
@@ -6,22 +6,25 @@ import './css/VideoList.css';
/*eslint no-console: ["error", { allow: ["warn", "error", "info"] }] */ /*eslint no-console: ["error", { allow: ["warn", "error", "info"] }] */
class VideoList extends React.Component { class VideoList extends React.Component {
constructor(props) { state = {
super(props);
this.state = {
error: null, error: null,
isLoaded: false, isLoaded: false,
items: [], items: [],
headers: null headers: null
}; };
this.getThumbnails = this.getThumbnails.bind(this);
}
componentDidMount() { 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( axios.get('http://site1825.tw.cs.unibo.it/video.json').then(
response => { response => {
this.shuffleArray(response.data); 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 // Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow // instead of a catch() block so that we don't swallow
@@ -33,14 +36,14 @@ class VideoList extends React.Component {
error error
}); });
} }
); )
} }
// METODI // METODI
getThumbnails(videoItems) { getThumbnails(videoItems) {
let idToLookFor = videoItems.map(item => item.videoID); let idToLookFor = videoItems.map(item => item.videoID);
let finalChunk = (videoItems.length % 50) + 100; let finalChunk = (videoItems.length % 50) + 100;
axios return axios
.all([ .all([
// chain 3 parallel get // chain 3 parallel get
axios.get('https://www.googleapis.com/youtube/v3/videos', { axios.get('https://www.googleapis.com/youtube/v3/videos', {
@@ -72,39 +75,38 @@ class VideoList extends React.Component {
]) ])
.then( .then(
axios.spread((res1, res2, res3) => { axios.spread((res1, res2, res3) => {
let allres = [].concat( [...res1.data.items,...res2.data.items,...res3.data.items]
res1.data.items, .map(resCurrentValue =>
res2.data.items,
res3.data.items
);
allres.map(resCurrentValue => {
Object.defineProperty( Object.defineProperty(
videoItems.find(videoItem => { videoItems.find(videoItem => {
return videoItem.videoID === resCurrentValue.id; return videoItem.videoID === resCurrentValue.id;
}), }),
'thumbnail', 'thumbnail',
{ value: resCurrentValue.snippet.thumbnails.medium.url } { value: resCurrentValue.snippet.thumbnails.medium.url,
); enumerable: true }
}); )
);
this.setState({ this.setState({
isLoaded: true, isLoaded: true,
items: videoItems items: videoItems
}); });
return new Promise((resolve, reject) => resolve(videoItems))
}) })
); )
} }
shuffleArray(videoarray) { shuffleArray(videoArray) {
for (let i = videoarray.length - 1; i > 0; i--) { for (let i = videoArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); 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. // Durstenfeld shuffle.
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
} }
render() { render() {
const { error, isLoaded, items, headers } = this.state; const { error, isLoaded, items } = this.state;
if (error) { if (error) {
return ( return (
<React.Fragment> <React.Fragment>
+2 -2
View File
@@ -86,12 +86,12 @@ class VideoPlayer extends React.Component {
videoIdWatched => { videoIdWatched => {
// post request to local db // post request to local db
axios axios
.post('http://localhost:8000/videotrack', { .post('http://site1854.tw.cs.unibo.it/videotrack', {
id: videoIdWatched.toString() id: videoIdWatched.toString()
}) })
.then( .then(
response => console.info(response.data), 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 // local storage logic for recent reccomender//tmp è il video che devo inserire sulla lista
let tmp = JSON.parse(localStorage.getItem('lastWatched')) let tmp = JSON.parse(localStorage.getItem('lastWatched'))
+1 -1
View File
@@ -1,5 +1,5 @@
import React, { Component } from 'react'; 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 { Switch, Route } from 'react-router';
import Random from '../reccomenders/Random'; import Random from '../reccomenders/Random';
import Related from '../reccomenders/Related'; import Related from '../reccomenders/Related';
+8 -8
View File
@@ -161,7 +161,7 @@ class Wikipedia extends Component {
componentDidMount() { 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) { componentDidUpdate(prevProps, prevState) {
if (prevState.props.videoId !== this.state.props.videoId) if (prevProps.videoId !== this.state.props.videoId)
this.wrapper().then(()=>this.setState({isLoaded: true})); this.wrapper().finally(()=>this.setState({isLoaded: true}));
} }
// componentWillUnmount() { // componentWillUnmount() {
@@ -191,7 +191,7 @@ class Wikipedia extends Component {
<tbody> <tbody>
{ isWikiLoaded && { isWikiLoaded &&
this.state.wikipediakeys.map(key => ( this.state.wikipediakeys.map(key => (
<tr> <tr key={key}>
<td>{key}</td> <td>{key}</td>
<td>{wikipedia.info[key].toLocaleString()}</td> <td>{wikipedia.info[key].toLocaleString()}</td>
</tr> </tr>
@@ -199,7 +199,7 @@ class Wikipedia extends Component {
} }
{ isWDataLoaded && { isWDataLoaded &&
this.state.wikidatakeys.map(key => ( this.state.wikidatakeys.map(key => (
<tr> <tr key={key}>
<td>{`${key} - ${wikidata.claims[key][0].mainsnak.datatype}`}</td> <td>{`${key} - ${wikidata.claims[key][0].mainsnak.datatype}`}</td>
<td>{ <td>{
typeof wikidata.claims[key][0].mainsnak.datavalue.value === "string" ? typeof wikidata.claims[key][0].mainsnak.datavalue.value === "string" ?
@@ -214,14 +214,14 @@ class Wikipedia extends Component {
)) ))
} }
{ isMBLoaded && { isMBLoaded &&
musicbrainz.relations.map(relation => { musicbrainz.relations.map((relation,i) => {
if (relation["target-type"] === "artist") if (relation["target-type"] === "artist")
return (<tr> return (<tr key={i}>
<td>{relation.type}</td> <td>{relation.type}</td>
<td>{relation.artist.name}</td> <td>{relation.artist.name}</td>
</tr>); </tr>);
else if (relation["target-type"] === "url") else if (relation["target-type"] === "url")
return (<tr> return (<tr key={i}>
<td>{relation.type}</td> <td>{relation.type}</td>
<td><a href={relation.url.resource}>{relation.type}</a></td> <td><a href={relation.url.resource}>{relation.type}</a></td>
</tr>) </tr>)