aggiunto similarity artist e poplocaleassoluta

This commit is contained in:
matteo
2019-02-19 23:31:07 +01:00
parent a4752a42da
commit 0340f45cd7
9 changed files with 274 additions and 28 deletions
+3
View File
@@ -62,6 +62,9 @@ low(new FileAsync(__dirname + '/db.json')) // production
// GET /videotrack
app.get('/videotrack', (req, res) => {
res.set({
'Access-Control-Allow-Origin': '*'
});
const videos = db.get('videos');
req.query.id ? res.send(videos.getById(req.query.id).value()) : res.send(videos.value())
});
+4
View File
@@ -7,6 +7,8 @@ import Search from './reccomenders/Search';
import fvitali from './reccomenders/fvitali';
import popGlobaleAssoluta from './reccomenders/popGlobaleAssoluta';
import Recent from './reccomenders/Recent';
import similarityArtist from './reccomenders/similarityArtist';
import popLocaleAss from './reccomenders/popLocaleAss';
// and so on..
@@ -40,7 +42,9 @@ class Suggestion extends Component {
<Route path='/search/:query' component={Search} />
<Route path='/video/:id/random' component={Random} />
<Route path='/video/:id/popGlobalAssoluta' component={popGlobaleAssoluta} />
<Route path='/video/:id/popLocaleAss' component={popLocaleAss} />
<Route path='/video/:id/recent' component={Recent} />
<Route path='/video/:id/similarityArtist' component={similarityArtist} />
{/* lasciare questo per ultimo */}
<Route component={Related} />
+2 -2
View File
@@ -42,7 +42,7 @@ class TopBar extends Component {
<Link to={{ pathname: `/video/${localStorage['lastId']}/related` }} className="text-light nav-link">Related</Link>
{<NavDropdown title="Similarity" id="basic-nav-dropdown" >
<Link to={{ pathname: `/video/${localStorage['lastId']}/...` }} className="text-dark nav-link">
<Link to={{ pathname: `/video/${localStorage['lastId']}/similarityArtist` }} className="text-dark nav-link">
Artist
</Link>
@@ -54,7 +54,7 @@ class TopBar extends Component {
</NavDropdown>}
{<NavDropdown title="Popolarità locale" id="basic-nav-dropdown" >
<Link to={{ pathname: `/video/${localStorage['lastId']}/...` }} className="text-dark nav-link">
<Link to={{ pathname: `/video/${localStorage['lastId']}/popLocaleAss` }} className="text-dark nav-link">
Assoluta
</Link>
+3 -1
View File
@@ -86,9 +86,11 @@ class VideoPlayer extends React.Component {
.then(
videoIdWatched => {
// post request to local db
let reason = new URLSearchParams(this.props.location.search).get("ref");
axios
.post('http://site1854.tw.cs.unibo.it/videotrack', {
id: videoIdWatched.toString()
id: videoIdWatched.toString(),
reason: reason || undefined
})
.then(
response => console.info(response.data),
+33 -23
View File
@@ -41,6 +41,8 @@ class Wikipedia extends Component {
return ( <Link to={{pathname:`/video/${value}`}}>{`${value}`}</Link>)
case "P2581":
return (<a target="_blank" rel="noopener noreferrer" href={`https://babelnet.org/synset?word=bn:${value}`}>{`${value}`}</a>)
case "P1827":
return (<a target="_blank" rel="noopener noreferrer" href={`https://musicbrainz.org/iswc/${value}`}>{`${value}`}</a>)
default:
return(`${value}`)
}
@@ -87,18 +89,18 @@ class Wikipedia extends Component {
}
findWikiPage = () => {
let wikiquery = `${'undefined' === typeof this.props.title ? this.props.title2.trim() : this.props.title.trim()} (${'undefined' === typeof this.props.artist ? this.props.artist2.trim() : this.props.artist.trim()} song)`;
console.info(wikiquery)
let wikiquery = `${'undefined' === typeof this.props.title ? ('undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2) : this.props.title.trim()} ${'undefined' === typeof this.props.title && 'undefined' === typeof this.props.title2 ? "" : `(${'undefined' === typeof this.props.artist ? this.props.artist2.trim() : this.props.artist.trim()} song)`}`;
return wikijs()
.find(wikiquery)
.then(res => {
console.info(res, 'a');
return Promise.all([res.fullInfo(), res.summary()]);
// return Promise.all([res.fullInfo(), res.links(), res.backlinks()]);
return Promise.all([res.fullInfo()]);
}) // find by props.title (props.artist song)
.then(wikipediaRes => this.setState({
wikipedia: {
"desc": wikipediaRes[1],
"info": wikipediaRes[0].general
// ,"links": wikipediaRes[1],
// "backlinks": wikipediaRes[2]
},
wikipediakeys: Object.keys(wikipediaRes[0].general),
isWikiLoaded: true
@@ -107,7 +109,7 @@ class Wikipedia extends Component {
componentDidMount() {
const musicbrainzBaseUrl = "https://musicbrainz.org/ws/2"; // more readable
// let timerId1;
let timerId1;
axios.get(wdk.getReverseClaims('P1651', this.props.videoId)) // P1651 is youtube_video_id property
.then(wikidataP1651Res => {
if (wikidataP1651Res.data.results.bindings.length) { // got a match
@@ -154,7 +156,7 @@ class Wikipedia extends Component {
else { //oof
axios.get(`${musicbrainzBaseUrl}/work`, {
params: {
'query': 'undefined' === typeof this.props.title ? 'undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2 : this.props.title,
'query': 'undefined' === typeof this.props.title ? ('undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2) : this.props.title,
'limit': 1,
'offset': 0,
'fmt': 'json'
@@ -180,7 +182,7 @@ class Wikipedia extends Component {
else if (musicbrainzWorkRes.data.relations.find(currentRel => currentRel.type === "wikidata")) { // found wikidata on music brainz
let wikidataUrl = musicbrainzWorkRes.data.relations.find(currentRel => currentRel.type === "wikidata");
let wikidataEntityRegEx = new RegExp("[^/]+$"); // match last part of url https://regex101.com/r/0wCQHY/1
this.getWikidataPage(wikidataEntityRegEx.exec(wikidataUrl.url.resource)) //.then(() => this.setState({ isWikiLoaded: true }));
this.getWikidataPage(wikidataEntityRegEx.exec(wikidataUrl.url.resource))
}
else { // oof
this.findWikiPage()
@@ -189,16 +191,27 @@ class Wikipedia extends Component {
)
})
}
}).finally(() => {
// let tmp = JSON.parse(localStorage['currentVideoInfo']);
// tmp.id = this.props.videoId;
// tmp.artist = this.state.wikipedia.info.artist;
// tmp.genre = this.state.wikidataQ[this.state.wikidata.claims["P136"][0].mainsnak.datavalue.value.id].labels.en.value;
// console.info(tmp)
// // localStorage.setItem('currentVideoInfo',JSON.stringify(tmp));
this.setState({ isLoaded: true })
});
return new Promise ((resolve,reject) => {
timerId1 = window.setInterval(()=>{
if(this.state.wikipedia
&& this.state.wikidataQ && this.state.wikidata)
resolve({
artist: this.state.wikipedia.info.artist.toString(),
genre: this.state.wikidataQ[this.state.wikidata.claims["P136"][0].mainsnak.datavalue.value.id].labels.en.value.toString()
})
}, 700)
})
}).then((res) => {
let tmp = JSON.parse(localStorage['currentVideoInfo']);
window.clearInterval(timerId1);
tmp = {
id: this.props.videoId.toString(),
artist: res.artist,
genre: res.genre
}
localStorage.setItem('currentVideoInfo',JSON.stringify(tmp));
})
.finally(()=>this.setState({ isLoaded: true }));
}
@@ -225,8 +238,6 @@ class Wikipedia extends Component {
</Col>;
} else {
return (
// <>
// {isWikiLoaded && wikipedia.desc}
<Table size="sm">
<tbody>
{isWikiLoaded &&
@@ -244,9 +255,9 @@ class Wikipedia extends Component {
${key[1].labels.en ? key[1].labels.en.value : ""} `}
</td>
<td>{
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value === "string" ?
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value === "string" ? // wikidata external
this.getExternalLink(key[0],wikidata.claims[key[0]][0].mainsnak.datavalue.value) :
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value.id === "string" ?
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value.id === "string" ? // wikidata Q
<><a target="_blank" rel="noopener noreferrer" href={`https://www.wikidata.org/wiki/${wikidata.claims[key[0]][0].mainsnak.datavalue.value.id}`}>
{`${this.state.wikidataQ[wikidata.claims[key[0]][0].mainsnak.datavalue.value.id].labels.en ?
this.state.wikidataQ[wikidata.claims[key[0]][0].mainsnak.datavalue.value.id].labels.en.value :
@@ -277,7 +288,6 @@ class Wikipedia extends Component {
}
</tbody>
</Table>
// </>
);
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ class Search extends React.Component {
return <React.Fragment>{this.state.error.message} -- {this.state.error.response.data.error.errors[0].reason} </React.Fragment>;
} else if (!this.state.isLoaded) {
return <Col className="text-center">
<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
<div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</Col>;
} else {
return (
+2 -1
View File
@@ -117,7 +117,8 @@ class fvitali extends React.Component {
key={item.videoID}
as="li" className="media mx-5 my-1 suggItem"
to={{
pathname: '/video/' + item.videoID,
pathname: `/video/${item.videoID}`,
search: '?ref=fvitali587'
}}>
<img
width={240}
+114
View File
@@ -0,0 +1,114 @@
import React from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Col, Media } from 'react-bootstrap';
class popLocaleAss extends React.Component {
state = {
isLoaded: false,
error: null,
res: null
}
// static getDerivedStateFromProps(nextProps, prevState) {
// }
componentDidMount() {
axios
.get('http://site1854.tw.cs.unibo.it/videotrack')
.then(res=>{
this.getThumbnailsNames(res.data.sort((a, b) => a.timesWatched - b.timesWatched).reverse());
}
,error=>this.setState({error}))
}
// shouldComponentUpdate(nextProps, nextState) {
// }
// componentDidUpdate(prevProps, prevState) {
// if (prevProps.match.params !== this.props.match.params) {
// this.setState({ isLoaded: false })
// }
// }
// componentWillUnmount() {
// }
getThumbnailsNames(reccomended) {
let idToLookFor = reccomended.map(item => item.id);
axios.get('https://www.googleapis.com/youtube/v3/videos', {
params: {
part: 'snippet',
id: idToLookFor.toString(),
key: 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig',
fields: 'items(id,snippet/thumbnails/medium,snippet/title,snippet/description)'
}
})
.then(
res1 => {
res1.data.items.map(resCurrentValue =>
Object.defineProperties(
reccomended.find(videoItem => {
return videoItem.id === resCurrentValue.id;
}),
{
'thumbnail':
{ value: resCurrentValue.snippet.thumbnails.medium.url },
'name':
{value: resCurrentValue.snippet.title},
'description':
{value: resCurrentValue.snippet.description }
})
);
this.setState({
isLoaded: true,
items: reccomended
});
})
}
render() {
if (this.state.error) {
return <React.Fragment>{this.state.error.message} -- {this.state.error.response.data.error.errors[0].reason} </React.Fragment>;
} else if (!this.state.isLoaded) {
return <Col className="text-center">
<div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</Col>;
} else {
return (
<ul className="list-unstyled">{
this.state.items.map(item => (
<Link
key={item.id.videoId}
as="li" className="media mx-5 my-1 suggItem"
to={{
pathname: '/video/' + item.id,
}}>
<img
width={240}
height={120}
className="align-self-center mr-3"
src={item.thumbnail}
alt={'Thumbnail of ' + item.name}
/>
<Media.Body>
<h5>{item.name}</h5>
<p>{item.description.substring(0,200)}</p>
<p>Visto: {item.timesWatched} volte <br />
Reccomender: popLocaleAss</p>
</Media.Body>
</Link>
))
}</ul>
);
}
}
}
export default popLocaleAss;
+112
View File
@@ -0,0 +1,112 @@
import React from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Col, Media } from 'react-bootstrap';
import { reject } from 'q';
class similarityArtist extends React.Component {
state = {
isLoaded: false,
error: null,
res: null
}
// static getDerivedStateFromProps(nextProps, prevState) {
// }
componentDidMount() {
let timerId1;
let promise = new Promise ((resolve,reject) => {
timerId1 = window.setInterval(()=>{
if(localStorage['lastId'] === JSON.parse(localStorage['currentVideoInfo']).id)
resolve(true)
},1000)
})
promise.then(()=>{
window.clearInterval(timerId1);
this.setState({artist: JSON.parse(localStorage['currentVideoInfo']).artist})
axios.get('https://www.googleapis.com/youtube/v3/search', {
params: {
'part': 'snippet',
'q': JSON.parse(localStorage['currentVideoInfo']).artist,
'videoEmbeddable': 'true',
'type': 'video',
'maxResults': 15,
'topicId': '/m/04rlf, /m/02jjt',
'key': 'AIzaSyA21Odw9UdfiOJnxvA_eDfOW0OxuUfHKig'
}
}).then(
res =>
this.setState({
res: res.data,
isLoaded: true
})
,
error => this.setState({
error
})
)
})
}
// shouldComponentUpdate(nextProps, nextState) {
// }
// componentDidUpdate(prevProps, prevState) {
// if (prevProps.match.params !== this.props.match.params) {
// this.setState({ isLoaded: false })
// }
// }
// componentWillUnmount() {
// }
render() {
if (this.state.error) {
return <React.Fragment>{this.state.error.message} -- {this.state.error.response.data.error.errors[0].reason} </React.Fragment>;
} else if (!this.state.isLoaded) {
return <Col className="text-center">
<div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</Col>;
} else {
return (
<>
<h4>Artist Similarity: {this.state.artist}</h4>
<ul className="list-unstyled">{
this.state.res.items.map(item => (
<Link
key={item.id.videoId}
as="li" className="media mx-5 my-1 suggItem"
to={{
pathname: '/video/' + item.id.videoId,
search:"?ref=similarityArtist"
}}>
<img
width={240}
height={120}
className="align-self-center mr-3"
src={item.snippet.thumbnails.medium.url}
alt={'Thumbnail of ' + item.snippet.title}
/>
<Media.Body>
<h5>{item.snippet.title}</h5>
<p>{item.snippet.description}</p>
<p>Reccomender: similarityArtist</p>
</Media.Body>
</Link>
))
}</ul>
</>
);
}
}
}
export default similarityArtist;