This commit is contained in:
Gregorio
2019-02-14 17:13:12 +01:00
14 changed files with 261 additions and 122 deletions
+1 -1
View File
@@ -1 +1 @@
AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg'
+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
});
+24 -13
View File
@@ -1,5 +1,5 @@
process.env['NODE_ENV'] = 'production'; process.env['NODE_ENV'] = 'production';
process.env.APIKEY = 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig'; //'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');
@@ -14,7 +14,7 @@ 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,9 +26,9 @@ 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,
@@ -42,27 +42,38 @@ 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 {
+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>
+12 -12
View File
@@ -8,8 +8,6 @@ import Card from "react-bootstrap/lib/Card";
import moment from 'moment'; import moment from 'moment';
import momentDurationFormat from 'moment-duration-format'; //eslint-disable-line no-unused-vars import momentDurationFormat from 'moment-duration-format'; //eslint-disable-line no-unused-vars
import './css/VideoInfo.scss'; import './css/VideoInfo.scss';
const ytclear = require('@c0b41/ytclear'); const ytclear = require('@c0b41/ytclear');
class VideoInfo extends React.Component { class VideoInfo extends React.Component {
@@ -79,39 +77,35 @@ class VideoInfo extends React.Component {
}), }),
]).then(axios.spread((responseA1,responseA2)=>{ ]).then(axios.spread((responseA1,responseA2)=>{
console.log(responseA1.data, responseA2.data); console.log(responseA1.data, responseA2.data);
})) }))
}), }),
error => { } error => { }
); );
} }
getInfoComments() { getInfoComments() {
return axios.all([ return axios.all([
axios.get('https://www.googleapis.com/youtube/v3/videos', { //Richiesta per tutte le info sul video axios.get('https://www.googleapis.com/youtube/v3/videos', { //Richiesta per tutte le info sul video
params: { params: {
'part': 'snippet,contentDetails,statistics,topicDetails', 'part': 'snippet,contentDetails,statistics,topicDetails',
'id': this.state.videoId, 'id': this.state.videoId,
'key': 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig' // process.env.APIKEY in production 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' // 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' in production
} }
}), axios.get('https://www.googleapis.com/youtube/v3/commentThreads', { //Richiesta per ottenere i commenti del video }), axios.get('https://www.googleapis.com/youtube/v3/commentThreads', { //Richiesta per ottenere i commenti del video
params: { params: {
'part': 'snippet', 'part': 'snippet',
'videoId': this.state.videoId, 'videoId': this.state.videoId,
'order': 'relevance', 'order': 'relevance',
'key': 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig' // process.env.APIKEY in production 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' // 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' in production
} }
})]) })])
.then(axios.spread((videosResponse, commentThreadResponse) => { .then(axios.spread((videosResponse, commentThreadResponse) => {
this.isArtistOrTitle(ytclear(videosResponse.data.items[0].snippet.title).split('-')); // this.isArtistOrTitle(ytclear(videosResponse.data.items[0].snippet.title).split('-'));
this.setState({ this.setState({
VideoDetails: videosResponse.data.items[0], VideoDetails: videosResponse.data.items[0],
comments: commentThreadResponse.data.items, comments: commentThreadResponse.data.items,
others: { others: {
artist: null, title2: ytclear(videosResponse.data.items[0].snippet.title).split('-')[1]
title: videosResponse.data.items[0].snippet.title
}, },
isLoaded: true isLoaded: true
}); });
@@ -127,6 +121,11 @@ class VideoInfo extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) { static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.videoId !== prevState.videoId) if(nextProps.videoId !== prevState.videoId)
return { videoId: nextProps.videoId }; return { videoId: nextProps.videoId };
else if(nextProps.location.state)
return { others: {
artist: nextProps.location.state.artist,
title: nextProps.location.state.title
}}
return null; return null;
} }
componentDidMount() { componentDidMount() {
@@ -157,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>
@@ -166,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,
}} }}
@@ -208,6 +207,7 @@ class VideoInfo extends React.Component {
<Tab className="text-white" eventKey="wikipedia" title="Wikipedia"> <Tab className="text-white" eventKey="wikipedia" title="Wikipedia">
<Wikipedia <Wikipedia
title={this.state.others.title} title={this.state.others.title}
title2={this.state.others.title2}
artist={this.state.others.artist} artist={this.state.others.artist}
videoId={this.state.videoId} videoId={this.state.videoId}
/> />
+26 -24
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,21 +36,21 @@ 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', {
params: { params: {
part: 'snippet', part: 'snippet',
id: idToLookFor.slice(0, 50).toString(), id: idToLookFor.slice(0, 50).toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', // process.env.APIKEY in production key: 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg', // 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' in production
fields: 'items(id,snippet/thumbnails/medium)' fields: 'items(id,snippet/thumbnails/medium)'
} }
}), }),
@@ -56,7 +59,7 @@ class VideoList extends React.Component {
params: { params: {
part: 'snippet', part: 'snippet',
id: idToLookFor.slice(50, 100).toString(), id: idToLookFor.slice(50, 100).toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', // process.env.APIKEY in production key: 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg', // 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' in production
fields: 'items(id,snippet/thumbnails/medium)' fields: 'items(id,snippet/thumbnails/medium)'
} }
}), }),
@@ -65,46 +68,45 @@ class VideoList extends React.Component {
params: { params: {
part: 'snippet', part: 'snippet',
id: idToLookFor.slice(100, finalChunk).toString(), id: idToLookFor.slice(100, finalChunk).toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', // process.env.APIKEY in production key: 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg', // 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg' in production
fields: 'items(id,snippet/thumbnails/medium)' fields: 'items(id,snippet/thumbnails/medium)'
} }
}) })
]) ])
.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';
+17 -15
View File
@@ -17,7 +17,9 @@ class Wikipedia extends Component {
isWikiLoaded: false, isWikiLoaded: false,
isWDataLoaded: false, isWDataLoaded: false,
isMBLoaded: false, isMBLoaded: false,
isLoaded: false isLoaded: false,
wikidatakeys: null,
wikipediakeys: null
}; };
ISO_8601toYYYY(a) { ISO_8601toYYYY(a) {
@@ -64,7 +66,7 @@ class Wikipedia extends Component {
if (wikidataP1651Res.data.results.bindings.length) { // got a match if (wikidataP1651Res.data.results.bindings.length) { // got a match
this.getWikidataPage(wdk.simplify.sparqlResults(wikidataP1651Res.data))// set in state wikidata this.getWikidataPage(wdk.simplify.sparqlResults(wikidataP1651Res.data))// set in state wikidata
.then(() => { .then(() => {
if (this.state.wikidata.claims.P435) { if (this.state.wikidata.claims.P435) { // p435 == musicbrainzWorkId
axios.get(`${musicbrainzBaseUrl}/work/${this.state.wikidata.claims.P435[0].mainsnak.datavalue.value}`, { // get musicbrainz info axios.get(`${musicbrainzBaseUrl}/work/${this.state.wikidata.claims.P435[0].mainsnak.datavalue.value}`, { // get musicbrainz info
params: { params: {
'inc': 'artist-rels url-rels', 'inc': 'artist-rels url-rels',
@@ -105,7 +107,7 @@ class Wikipedia extends Component {
else { //oof else { //oof
axios.get(`${musicbrainzBaseUrl}/work`, { axios.get(`${musicbrainzBaseUrl}/work`, {
params: { params: {
'query': this.state.props.title.trim(), 'query': 'undefined' === typeof this.state.props.title ? this.state.props.title2 : this.state.props.title,
'limit': 1, 'limit': 1,
'offset': 0, 'offset': 0,
'fmt': 'json' 'fmt': 'json'
@@ -131,7 +133,7 @@ class Wikipedia extends Component {
this.getWikidataPage(wikidataEntityRegEx.exec(a.url.resource)) //.then(() => this.setState({ isWikiLoaded: true })); this.getWikidataPage(wikidataEntityRegEx.exec(a.url.resource)) //.then(() => this.setState({ isWikiLoaded: true }));
} }
else { // oof else { // oof
wikijs().find(this.state.props.title).then(data => console.log('asd', data)) // find by props.title wikijs().find('undefined' === typeof this.state.props.title? this.state.props.title2.trim(): this.state.props.title.trim()).then(data => console.log('asd', data)) // find by props.title
} }
}) })
) )
@@ -145,13 +147,13 @@ class Wikipedia extends Component {
return { return {
props: { props: {
videoId: nextProps.videoId, videoId: nextProps.videoId,
artist: nextProps.artist,
title: nextProps.title
}, },
isWikiLoaded: false, isWikiLoaded: false,
isWDataLoaded: false, isWDataLoaded: false,
isMBLoaded: false, isMBLoaded: false,
isLoaded: false isLoaded: false,
wikidatakeys: null,
wikipediakeys: null
}; };
return null return null
} }
@@ -159,7 +161,7 @@ class Wikipedia extends Component {
componentDidMount() { componentDidMount() {
this.wrapper().then(()=>this.setState({isLoaded: true})); this.wrapper().finally(()=>this.setState({isLoaded: true}));
} }
@@ -168,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() {
@@ -189,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>
@@ -197,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" ?
@@ -212,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>)
+1 -1
View File
@@ -31,7 +31,7 @@ class RecommenderRandom extends Component{
'type' : 'video', //che contiene tutti i generi di musica 'type' : 'video', //che contiene tutti i generi di musica
'maxResults': '21', 'maxResults': '21',
'pageToken' : pageToken, 'pageToken' : pageToken,
'key': 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig' // process.env.APIKEY in production 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg'
} }
}).then( }).then(
response => { response => {
+1 -1
View File
@@ -33,7 +33,7 @@ class Related extends Component {
'relatedToVideoId' : this.state.videoId, 'relatedToVideoId' : this.state.videoId,
'type' : 'video', 'type' : 'video',
'maxResults' : '21', 'maxResults' : '21',
'key': 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig' // process.env.APIKEY in production 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg'
} }
}).then( }).then(
response => { response => {
+53 -17
View File
@@ -1,10 +1,13 @@
import React from 'react'; import React from 'react';
import axios from 'axios'; import axios from 'axios';
import { Card, Col } from 'react-bootstrap';
class Search extends React.Component { class Search extends React.Component {
state = { state = {
query: '', query: '',
isLoaded: false,
error: null,
res: null res: null
} }
@@ -16,20 +19,12 @@ class Search extends React.Component {
componentDidMount() { componentDidMount() {
console.log('called didmo'); console.log('called didmo');
} if (new RegExp("[0-9A-Za-z_-]{10}[048AEIMQUYcgkosw]").test(this.state.query.toString()))
axios.get('https://www.googleapis.com/youtube/v3/videos', {
// shouldComponentUpdate(nextProps, nextState) {
// }
componentDidUpdate(prevProps, prevState) {
console.log('called didup');
if(new RegExp("[0-9A-Za-z_-]{10}[048AEIMQUYcgkosw]").test(this.state.query.toString()))
axios.get('https://www.googleapis.com/youtube/v3/videos',{
params: { params: {
'part':'id', 'part': 'id',
'id': this.state.query, 'id': this.state.query,
'key': process.env.APIKEY ? process.env.APIKEY : 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg',
'field': 'pageInfo/resultsPerPage' 'field': 'pageInfo/resultsPerPage'
} }
}).then( }).then(
@@ -46,6 +41,38 @@ class Search extends React.Component {
this.youtubeSearch(); this.youtubeSearch();
} }
// shouldComponentUpdate(nextProps, nextState) {
// }
componentDidUpdate(prevProps, prevState) {
console.log('called didup');
if (prevState.query !== this.props.match.params.query)
if (new RegExp("[0-9A-Za-z_-]{10}[048AEIMQUYcgkosw]").test(this.state.query.toString()))
axios.get('https://www.googleapis.com/youtube/v3/videos', {
params: {
'part': 'id',
'id': this.state.query,
'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg',
'field': 'pageInfo/resultsPerPage'
}
}).then(
res => {
res.data.pageInfo.resultsPerPage ?
this.props.history.push('/video/' + this.state.query) :
this.youtubeSearch()
},
error => {
console.error(error)
this.setState({
error
})
}
)
else
this.youtubeSearch();
}
// componentWillUnmount() { // componentWillUnmount() {
// } // }
@@ -59,13 +86,14 @@ class Search extends React.Component {
'type': 'video', 'type': 'video',
'maxResults': 30, 'maxResults': 30,
'topicId': '/m/04rlf, /m/02jjt', 'topicId': '/m/04rlf, /m/02jjt',
'key': process.env.APIKEY ? process.env.APIKEY : 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig' 'key': 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg'
} }
}).then( }).then(
res => { res => {
console.log(res.data); console.log(res.data);
this.setState({ this.setState({
res: res.data res: res.data,
isLoaded: true
}) })
}, },
error => { console.error(error) } error => { console.error(error) }
@@ -73,12 +101,20 @@ class Search extends React.Component {
} }
render() { render() {
if (this.state.error) {
return <React.Fragment>Error: {this.state.error.message}</React.Fragment>;
} else if (!this.state.isLoaded) {
return <React.Fragment>Loading...</React.Fragment>;
} else {
return ( return (
<div> <Col>
<span>{this.state.query} keyword</span> {this.state.res.data.items.map(item => (<Card></Card>
</div>
))}
</Col>
); );
} }
}
} }
export default Search; export default Search;
+1 -1
View File
@@ -57,7 +57,7 @@ class fvitali extends React.Component {
params: { params: {
part: 'snippet', part: 'snippet',
id: idToLookFor.toString(), id: idToLookFor.toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', key: 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg',
fields: 'items(id,snippet/thumbnails/medium,snippet/title)' fields: 'items(id,snippet/thumbnails/medium,snippet/title)'
} }
}) })
+1 -1
View File
@@ -48,7 +48,7 @@ class popGlobaleAssoluta extends React.Component {
params: { params: {
part: 'snippet', part: 'snippet',
id: idToLookFor.toString(), id: idToLookFor.toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig', key: 'AIzaSyBYSHhu7AwZqT1JK3x4G8Yzs7iRqoS_QUg',
fields: 'items(id,snippet/thumbnails/medium,snippet/title)' fields: 'items(id,snippet/thumbnails/medium,snippet/title)'
} }
}) })