WebPlayer/js/main.js
2022-12-14 16:10:56 +08:00

595 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

window.onload = function(){
createlist();
setInterval(checkplay, 3000);
}
// Title Controller
class TitleStat{
constructor( originTitle ){
this.originTitle = originTitle;
// this.TempTitle = this.TargetTitle;
}
GlobalInterval = null;
OriginTitle = document.title;
TargetTitle = "";
// TempTitle = ""; // Used to determine if the title has changed
SCROLL_SPEED = 1000;
ActivateStat = false;
getActivateStat() {
return this.ActivateStat;
}
activate(){
this.ActivateStat = true;
}
deactivate() {
this.ActivateStat = false;
}
setTargetTitle( title ){
this.TargetTitle = title;
// console.log( this );
}
setScrollSpeed( speed ){
this.SCROLL_SPEED = speed;
}
setOriginTitle( title ){
this.originTitle = title;
}
setTitleManual( title ){
document.title = title;
}
startLoop(){
this.activate();
clearInterval(this.GlobalInterval);
this.TempTitle = this.TargetTitle;
if ( this.TempTitle.length < 10 ){
this.noScrollTitle();
} else {
window.userdefines_title = {
"TempTitle": this.TargetTitle + " ",
}
this.GlobalInterval = setInterval(this.scorllTheTitle, this.SCROLL_SPEED);
}
}
stopLoop(){
clearInterval(this.GlobalInterval);
}
reset(){
this.stopLoop();
delete window.userdefines_title;
document.title = this.OriginTitle;
this.deactivate();
}
noScrollTitle() {
console.log("使用的是非滚动标题!");
if( document.getElementById("Player").paused == false ){
document.title = "[▶️] " + this.TempTitle;
}else{
document.title = "[⏸] " + this.TempTitle;
}
}
scorllTheTitle() {
// console.log("Title Scroll!"); //Debug
// if ( this.TempTitle == undefined ) {
// console.warn( "this.TempTitle undefined" );
// console.log( this );
// this.TempTitle = this.TargetTitle;
// }
// 此处的this指的是window对象
if( document.getElementById("Player").paused == false ){
document.title = "[▶️] " + this.userdefines_title.TempTitle.substring(0,20) + "...";
}else{
document.title = "[⏸] " + this.userdefines_title.TempTitle.substring(0,20) + "...";
}
this.userdefines_title.TempTitle = this.userdefines_title.TempTitle.substring(1) + this.userdefines_title.TempTitle.substring(0,1);
}
}
// Title Control
// var originTitle = document.title;
let TitleControl = new TitleStat(document.title);
// TitleControl.setTargetTitle("Song!");
window.onblur = () => {
// document.title = "Song!";
// TitleControl.setTargetTitle("Song!")
console.log("您已离开播放器!");
TitleControl.setScrollSpeed(500);
TitleControl.setTargetTitle(document.getElementById("nowplay").innerHTML);
TitleControl.startLoop();
}
window.onfocus = () => {
// document.title = originTitle;
console.log("您已回到播放器!");
TitleControl.reset();
}
// 搜索音乐
function getsongs(){
document.getElementById("reslist").innerHTML = "";
var search = document.getElementById("search-song");
var reslist = document.getElementById("reslist");
var urls = `http://150.158.7.169:3000/search?keywords=${search.value}`
var xhr = new XMLHttpRequest();
xhr.open("GET", urls);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
//console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
//console.log(obj.result.songs);
console.log(obj);
var list = obj.result.songs;
//for(i = 0; i < obj.result.songs.length; i++){
for(var i = 0; i < list.length; i++){
artiststr = getArtist(list[i]);
console.log({"songid":list[i].id, "songname":list[i].name, "artist":artiststr});
if(list[i].fee == 0 || list[i].fee == 8){
reslist.innerHTML += `<li id="listitem"><a href="javascript:void(0)" onclick="javascript:playmusic(${list[i].id}, '${list[i].name}', '${artiststr}')">${list[i].name} - ${getArtist(list[i])}</a>` +
`<span class="">` +
`<button type="button" id="playbtn" onclick="javascript:addlist(${list[i].id}, '${list[i].name}', '${artiststr}')">加入播放列表</button>` +
`</span></li>`;
}else{
reslist.innerHTML += `<li id="listitem">${list[i].name} - ${getArtist(list[i])}`+
`<span class="">` +
`<button type="button" id="disablebtn" onclick="javascript:jumpTo163CM(${list[i].id})">跳转到网易云</button>` +
`</span></li>`;
}
}
}else{
//alert(xhr.statusText);
console.warn("WARNNINGAPI服务器响应失败");
}
}
document.getElementById("keyword").innerHTML = search.value;
}
// 获取艺术家
function getArtist(obj){
var artiststr = "";
var artistd = obj.artists;
for(var i = 0; i < artistd.length; i++){
if(i != artistd.length - 1){
artiststr += artistd[i].name + "/";
}else{
artiststr += artistd[i].name;
}
}
return artiststr;
}
// 播放音乐
function playmusic(playid, songname, artist){
document.getElementById("nowplay").innerHTML = `${songname} - ${artist}`
url = `https://music.163.com/song/media/outer/url?id=${playid}.mp3`;
document.getElementById("Player").setAttribute('src',url);
// 选中后自动播放
document.getElementById("Player").play();
// 插入到历史记录
inserthistory(playid, songname, artist);
}
// 队列 -- Writtrn By Copilot & Web
function Queue(){
this.items = [];
Queue.prototype.nqueue = (element) => {
this.items.push(element);
}
Queue.prototype.dequeue = () => {
return this.items.shift();
}
Queue.prototype.front = () => {
return this.items[0];
}
Queue.prototype.isEmpty = () => {
return this.items.length == 0;
}
Queue.prototype.clear = () => {
this.items = [];
}
Queue.prototype.size = () => {
return this.items.length;
}
Queue.prototype.toString = () => {
var str = "";
for(var i = 0; i < this.items.length; i++){
str += this.items[i] + " ";
}
return str;
}
}
// 列表
function List(){
this.items = [];
List.prototype.insertRear = (element) => {
this.items.push(element);
}
List.prototype.deleteItem = (loc) => {
if(loc == undefined) {
return false;
}
this.items.splice(loc, 1);
return true;
}
List.prototype.isEmpty = () => {
return this.items.length == 0;
}
List.prototype.clear = () => {
this.items = [];
}
List.prototype.size = () => {
return this.items.length;
}
List.prototype.getElem = (loc) => {
if(loc < 0 || loc == undefined){
return undefined;
}
if(this.isEmpty()){
return false;
}
return this.items[loc];
}
// CodeGeeX Written
List.prototype.locate = (items) => {
for(var i = 0; i < this.items.length; i++){
if(items == this.items[i]){
return i;
} else {
return undefined;
}
}
}
List.prototype.getLength = () => {
return this.items.length;
}
}
// 创建播放列表
function createlist(){
// 构造队列
// list = new Queue();
list = new List();
nowPlay = 0;
}
// 添加到播放列表
function addlist(songid, songname, artist){
// list.nqueue({"songid":songid, "songname":songname, "artist":artist});
for (var i = 0; i < list.getLength(); i++) {
if(list.getElem(i).songid == songid){
console.log(`${songname} - ${artist} 已存在于播放列表`);
return;
}
}
list.insertRear({"songid":songid, "songname":songname, "artist":artist});
console.log(`${songname} - ${artist} 已被加入播放列表`);
}
// 播放下一首
function playnext(){
if(list.isEmpty()){
console.log("音乐列表已经播放完毕了哦,快加入新的音乐吧~");
alert("音乐列表已经播放完毕了哦,快加入新的音乐吧~");
return;
}
// var next = list.dequeue();
if(nowPlay >= (list.size() - 1)){
nowPlay = 0;
}else{
nowPlay += 1;
}
var next = list.getElem(nowPlay);
playmusic(next.songid, next.songname, next.artist);
if ( TitleControl.getActivateStat() == true ) {
TitleControl.reset();
TitleControl.setTitleManual("Loading...");
TitleControl.setTargetTitle(next.songname + " - " + next.artist);
TitleControl.startLoop();
}
}
// 检测是否播放完毕
function checkplay(){
// 为了防止播放列表结束以后一直调用playnext产生过多的alart所以需要检测播放列表是否为空
if(!list.isEmpty()){
if(document.getElementById("Player").ended){
// 播放完毕后自动播放下一首
playnext();
}
}else{
//clearInterval(checkplay);
}
}
// 播放列表
function playthelist(){
if(list.isEmpty()){
console.log("音乐列表没有歌曲哦,快加入新的音乐吧~");
alert("音乐列表没有歌曲哦,快加入新的音乐吧~");
return;
}
// var next = list.dequeue();
var next = list.getElem(0);
playmusic(next.songid, next.songname, next.artist);
}
// 获取播放列表
function getplaylist(){
//var playlist = document.getElementById("playlist");
//playlist.innerHTML = "";
var reslist = document.getElementById("reslist");
reslist.innerHTML = "";
for(var i = 0; i < list.size(); i++){
reslist.innerHTML += `<li>${list.items[i].songname} - ${list.items[i].artist}<span class="btn-series"><button type="button" id="delbtn" onclick="javascript:RemoveItemFromListByID(${i})">删除</button></span></li>`;
//console.log(`${list.items[i].songname} - ${list.items[i].artist}`);
}
document.getElementById('keyword').innerHTML = "当前播放列表";
}
/* // -- Writtrn By Copilot
function RemoveItemFromList(songid){
for(var i = 0; i < list.size(); i++){
if(list.items[i].songid == songid){
list.items.splice(i, 1);
break;
}
}
getplaylist();
}
*/
// 删除指定序号的音乐 -- Writtrn By Copilot
function RemoveItemFromListByID(uid){
list.items.splice(uid, 1);
getplaylist();
}
// 插入音乐到历史记录 -- Writtrn By Copilot
function inserthistory(songid, songname, artist){
// 从本地获取历史记录
var historyList = JSON.parse(localStorage.getItem("historyList"));
// 判断是否有历史记录
if(historyList == null){
historyList = []; // 创建一个空数组
}
var flag = false; // 标记是否已经存在
// 判断是否已经存在
for(var i = 0; i < historyList.length; i++){
// 如果已经存在,则更新播放时间
if(historyList[i].songid == songid){
flag = true;
break;
}
}
// 如果不存在,则插入
if(!flag){
// historyList.push({"songid":songid, "songname":songname, "artist":artist, "playtime":new Date().getTime()});
historyList.push({"songid":songid, "songname":songname, "artist":artist});
}
// 存储到本地
localStorage.setItem("historyList", JSON.stringify(historyList));
}
// 获取历史记录 -- Writtrn By Copilot
function gethistory(){
var historyList = JSON.parse(localStorage.getItem("historyList"));
if(historyList == null){
historyList = [];
}
var reslist = document.getElementById("reslist");
reslist.innerHTML = "";
for(var i = 0; i < historyList.length; i++){
reslist.innerHTML += `<li>${historyList[i].songname} - ${historyList[i].artist}` +
`<span class="btn-series">` +
`<button type="button" id="delbtn" onclick="javascript:deleteHistory(${i})">删除</button>` +
`<button type="button" id="playbtn" onclick="javascript:addlist(${historyList[i].songid}, '${historyList[i].songname}', '${historyList[i].artist}')">加入播放列表</button></li>` +
`</span>`;
}
document.getElementById('keyword').innerHTML = "历史记录";
}
// 清空历史记录 -- Writtrn By Copilot
function removehistory(){
localStorage.removeItem("historyList");
gethistory();
}
// 当点击清空列表的时候进行一次确认,如果确认之后再进行删除操作。
function ClearList(){
var Choose = confirm("确定清空歌单吗?(此操作不可逆!)")
if(Choose == true){
removehistory();
console.log("The History List Has been cleared.");
return true;
}else{
console.log("List Clear Canceled!");
return false;
}
}
// 添加所有歌曲到播放列表
function addAllHistorytoPlayList(){
var historyList = JSON.parse(localStorage.getItem("historyList"));
if(historyList == null){
historyList = [];
}
var reslist = document.getElementById("reslist");
reslist.innerHTML = "";
for(var i = 0; i < historyList.length; i++){
addlist(historyList[i].songid, historyList[i].songname, historyList[i].artist);
console.log(`${historyList[i].songname} - ${historyList[i].artist} is add to list.`);
}
alert("已把历史记录插入到了播放列表");
// Planning to Code...
}
// 清空播放列表
function ClearthePlaylist(){
if(!list.isEmpty()){
list.clear();
console.log("List Cleared!");
}else{
console.log("List is empty, not need to clear.")
}
}
function convertHist2CloudList(origin){
// var temp = JSON.parse(origin);
var result = []
for (var i = 0; i < origin.length; i++) {
result.push({
"name" : origin[i].songname,
"id" : origin[i].songid,
"author": origin[i].artist
});
}
return result;
}
// 推送到云播放列表
function PushToCloud(){
// Cloud Prepareing...
var server_api = "http://localhost:8080/musiccloud.php?option=upload";
var xhr = new XMLHttpRequest();
var historyList = JSON.parse(localStorage.getItem("historyList"));
var list_id = document.getElementById("listid").value;
var msg = JSON.stringify({
"list_id": list_id,
"length": historyList.length,
"list": convertHist2CloudList(historyList)
});
var data = new FormData();
data.append("payload", msg);
xhr.open("POST", server_api, true);
xhr.send(data);
xhr.onreadystatechange = function(){
var obj = JSON.parse(xhr.responseText);
if(obj.statusCode == 0){
alert("sucess!")
console.log("Success! listID is " + obj.list_id);
}else{
if(obj.statusCode == -1){
alert("This ListID has been used, please change another one.");
} else {
alert("Upload failed! Try yo upload again.")
}
console.log("Send Failed.");
}
}
}
// 拉取云播放列表
function PullToCloud(){
// Cloud Prepareing...
var listid = document.getElementById("listid").value;
// var server_api = `http://localhost:12345/getMusicList?listid=${listid}`;
var server_api = `http://localhost:8080/musiccloud.php?option=getlist&list=${listid}`;
var xhr = new XMLHttpRequest();
xhr.open("GET", server_api, true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
if(obj.statusCode == 0){
// title
document.getElementById('keyword').innerHTML = `列表(${obj.list_id}`;
// list
var reslist = document.getElementById("reslist");
reslist.innerHTML = "";
for(var i = 0; i < obj.list.length; i++){
reslist.innerHTML += `<li>${obj.list[i].name} - ${obj.list[i].author}` +
`<span class="">` +
`<button type="button" id="playbtn" onclick="javascript:addlist(${obj.list[i].id}, '${obj.list[i].name}', '${obj.list[i].author}')">加入播放列表</button>` +
`</span></li>`;
}
}else{
;
}
}
}
function deleteCloudList(){
//code...
console.log("No working...")
}
function deleteHistory( count ) {
// get HistoryList from LocalStorage
var historyList = JSON.parse( localStorage.getItem( "historyList" ) );
// is null?
if( historyList == null ){
// failed
}
// if count is smaller than List length, throw error
if ( count > historyList.length ){
console.log( "本次删除无效!\nThis deletion is invaild." );
return;
}
// console log output
console.log(`${historyList[count].songname} - ${historyList[count].artist} (位于 ${count}) 已从历史记录删除.`)
// find the item and delete it.
historyList.splice( count, 1 );
// Refresh the page
var reslist = document.getElementById( "reslist" );
reslist.innerHTML = "";
for( var i = 0; i < historyList.length; i++ ){
reslist.innerHTML += `<li>${historyList[i].songname} - ${historyList[i].artist}` +
`<span class="btn-series">` +
`<button type="button" id="delbtn" onclick="javascript:deleteHistory(${i})">删除</button>` +
`<button type="button" id="playbtn" onclick="javascript:addlist(${historyList[i].songid}, '${historyList[i].songname}', '${historyList[i].artist}')">加入播放列表</button>` +
`</span></li>`;
}
document.getElementById( 'keyword' ).innerHTML = "历史记录";
// put the HistoryList back into the LocalStorage
localStorage.setItem( "historyList", JSON.stringify( historyList ) );
}
function jumpTo163CM( songid ) {
console.log("因为没钱,所以放不了,要不你自己去官网开会员听?");
if ( confirm( "因为没钱,所以放不了,要不你自己去官网开会员听?" ) ){
window.open( 'https://music.163.com/#/song?id=' + songid );
console.log("感谢你的理解!^_^");
} else {
console.log("好吧,那我也没有办法了,总之是放不了。\(sad")
}
}