Skip to content

Commit

Permalink
调整API调用逻辑,增强vgmdb.net搜索,增加API server设置选项
Browse files Browse the repository at this point in the history
  • Loading branch information
tumuyan committed Oct 1, 2023
1 parent efd0366 commit c3e756c
Show file tree
Hide file tree
Showing 2 changed files with 197 additions and 45 deletions.
174 changes: 142 additions & 32 deletions Api/vgmdb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.UI.WebControls;

namespace MusicBeePlugin.Api
{
Expand All @@ -24,34 +26,129 @@ class VGMdbAlbum
public string getName() { return name; }
private JObject SearchResult;

// use vgmdb.net website
public VGMdbAlbum(string url)
{
// 耗时操作
SearchResult = requestJObject(url, null);//解析专辑
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// request.ContentType = "application/x-www-form-urlencoded";

type = 0;
if (SearchResult != null && SearchResult.ContainsKey("results"))
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string retString = reader.ReadToEnd();

// < div id="coverart" style = "background-image: url('https://medium-media.vgm.io/albums/55/120455/120455-a2aed067614d.jpg')" title = "EUMU-015" ></ div >

string album_pattern = @"id=""coverart"" style=""background-image: url\('([^']+)";
RegexOptions options = RegexOptions.Multiline;
Regex album_regex = new Regex(album_pattern);
Match album_match = album_regex.Match(retString);

// < h1 >< span class="albumtitle" lang="en" style="display:inline">DIGIMON HISTORY 1999-2006 ALL THE BEST</span><span class="albumtitle" lang="ja" style="display:none"><em> / </em>DIGIMON HISTORY 1999-2006 ALL THE BEST</span><span class="albumtitle" lang="ja-Latn" style="display:none"><em> / </em>DIGIMON HISTORY 1999-2006 ALL THE BEST</span> </h1>
string name_pattern = @"class=""albumtitle""(.+?)>(.+?)(</span>)";
Regex name_regex = new Regex(album_pattern);

// <b><span title="Performer" class="artistname" lang="en" style="display:inline">Performer</span><span style="display:none"><em> / </em></span><span title="Performer" class="artistname" lang="ja" style="display:none">Performer</span></b>


if (album_match.Groups.Count > 0)
{
cover = SearchResult["picture_full"].ToString();
cover =album_match.Groups[1].Value;
type = 1;
if (String.IsNullOrEmpty(cover))


List<string> names = new List<string>();
foreach (Match m in Regex.Matches(retString, name_pattern, options))
{
cover = SearchResult["picture_small"].ToString();
type = 2;
if (String.IsNullOrEmpty(cover))
if (m.Groups.Count > 2)
{
cover = "";
type = 10;
string v = m.Groups[2].Value.Replace("<em> / </em>","").Trim();
if (!names.Contains(v))
{ names.Add(v);
name = name + " " + v;
}
}
}

// 只获取了一个封面,未获取artist
}
else
{
Console.WriteLine("[Error]Empty album SearchResult = "+SearchResult+ ", url = " + url );
}
}


// use vgmdb json api
public VGMdbAlbum(string url, string site)
{
url = url.Replace("https://vgmdb.net/album/", site + "/album/") + "?format=json";
// 耗时操作
SearchResult = requestJObject(url, null); //解析专辑
type = 0;
if (SearchResult != null && SearchResult.ContainsKey("name"))
{

if (SearchResult.ContainsKey("picture_full"))
{
cover = SearchResult["picture_full"].ToString();
type = 1;
}
else if (SearchResult.ContainsKey("picture_medium"))
{
cover = SearchResult["picture_medium"].ToString();
type = 2;
}
else if (SearchResult.ContainsKey("picture_small"))
{
cover = SearchResult["picture_small"].ToString();
type = 3;
}
else if (SearchResult.ContainsKey("covers"))
{
JArray covers = (JArray)SearchResult["covers"];
if (covers != null && covers.Count > 0)
{
JObject cover_obj = (JObject)covers[0];
if (cover_obj.ContainsKey("full"))
{
cover = cover_obj["full"].ToString();
type = 1;
}
else if (cover_obj.ContainsKey("medium"))
{
cover = cover_obj["medium"].ToString();
type = 2;
}
else if (cover_obj.ContainsKey("small"))
{
cover = cover_obj["small"].ToString();
type = 3;
}
else
{
type = 10;
}

artist = SearchResult["performers"].ToString();
if (String.IsNullOrEmpty(artist))
artist = "";
}
else
{
type = 10;
}
}

name = "" + SearchResult["name"].ToString() + "\n" + SearchResult["names"].ToString();
if (SearchResult.ContainsKey("performers"))
artist = SearchResult["performers"].ToString();
else if (SearchResult.ContainsKey("vocals"))
artist = SearchResult["vocals"].ToString();

name = "" + SearchResult["name"].ToString() + "\n" + SearchResult["names"].ToString();
}
else
{
Console.WriteLine("[Error]Empty album SearchResult = " + SearchResult + ", url = " + url);
}
}
}

Expand All @@ -67,7 +164,9 @@ static private List<string> vgmdb_advancedsearch(string artist, string album)
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string data = "action=advancedsearch&platformmodifier=contain_and&collectionmodifier=0&tracklistmodifier=is&sortby=albumtitle&orderby=ASC&dosearch=Search Albums Now"
+ "&albumtitles=" + album + "&artistalias=" + artist;
+ "&albumtitles=" + album;
if(!String.IsNullOrEmpty(artist))
data+= "&artistalias=" + artist;
// request.ContentLength = data.Length;

StreamWriter writer = new StreamWriter(request.GetRequestStream());
Expand All @@ -81,13 +180,20 @@ static private List<string> vgmdb_advancedsearch(string artist, string album)
// href =\"https://vgmdb.net/album/67360\"

foreach (Match match in Regex.Matches(retString, pattern))
album_urls.Add(match.Value.Replace("https://vgmdb.net/album/", "http://vgmdb.info/album/") + "?format=json");
album_urls.Add(match.Value);
// album_urls.Add(match.Value.Replace("https://vgmdb.net/album/", "http://vgmdb.info/album/") + "?format=json");

if (album_urls.Count > 0)
return album_urls;
else if (!String.IsNullOrEmpty(artist))
return vgmdb_advancedsearch("", album);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}

return album_urls;
}

Expand All @@ -105,7 +211,14 @@ public vgmdb()

private void loadAlbum(object url)
{
VGMdbAlbum album = new VGMdbAlbum(url.ToString());
String[] u = (String[])url;
// VGMdbAlbum album = new VGMdbAlbum(url.ToString(),"http://vgmdb.info");

VGMdbAlbum album = null;
if (u.Length<2 || u[1] == null || u[1].Trim().Length < 1)
album = new VGMdbAlbum(u[0]);
else
album = new VGMdbAlbum(u[0], u[1]);
lock (list_vgmdb)
{
list_vgmdb.Add(album);
Expand All @@ -120,28 +233,24 @@ private void loadAlbum(object url)



public String getCover(String Artist, String Album)
public String getCover(String Artist, String Album, String api_server)
{
if (Album.Replace(" ", "").Length < 1)
return null;
// 从API取回搜索结构

List<string> album_urls;

if (!String.IsNullOrEmpty(Artist))
{
album_urls = vgmdb_advancedsearch(Artist, Album);
}
else
{
album_urls = new List<string>();
}
List<string> album_urls = vgmdb_advancedsearch(Artist, Album);


// 如果高级搜索失败,使用专辑名称再次搜索
if (album_urls.Count < 1)
{
string SearchUrl = String.Format("http://vgmdb.info/search/albums?q={0}", Album).Replace("&", "%26") + "&format=json";


string SearchUrl=null;
if (api_server.Trim().Length < 1)
SearchUrl = String.Format(api_server + "http://vgmdb.info/search/albums?q={0}", Album).Replace("&", "%26") + "&format=json";
else
SearchUrl = String.Format(api_server + "/search/albums?q={0}", Album).Replace("&", "%26") + "&format=json";
JObject SearchResult = requestJObject(SearchUrl, null);//解析搜索结果
if (SearchResult == null)
{
Expand All @@ -167,7 +276,8 @@ public String getCover(String Artist, String Album)

for (int i = 0; i < SongList.Count; i++)
{
album_urls.Add("http://vgmdb.info/" + SongList[i]["link"].ToString() + "?format=json");
album_urls.Add("https://vgmdb.net/" + SongList[i]["link"].ToString());
// album_urls.Add("http://vgmdb.info/" + SongList[i]["link"].ToString() + "?format=json");
}
}

Expand All @@ -184,7 +294,7 @@ public String getCover(String Artist, String Album)

for (int i = 0; i < count_load_album; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(loadAlbum), album_urls[i]);
ThreadPool.QueueUserWorkItem(new WaitCallback(loadAlbum),new String[]{ album_urls[i],api_server});
}

event_load_album.WaitOne(Timeout.Infinite, true);
Expand Down
68 changes: 55 additions & 13 deletions Main.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
#define CONFIG_API_SERVER
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;
Expand Down Expand Up @@ -29,6 +30,7 @@ public partial class Plugin
private MusicBeeApiInterface mbApiInterface;
private PluginInfo about = new PluginInfo();
private static CookieContainer myCookieContainer = new CookieContainer();
private string api_server = "";


public PluginInfo Initialise(IntPtr apiInterfacePtr)
Expand All @@ -48,40 +50,80 @@ public PluginInfo Initialise(IntPtr apiInterfacePtr)
about.MinInterfaceVersion = MinInterfaceVersion;
about.MinApiRevision = MinApiRevision;
about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);
about.ConfigurationPanelHeight = 0; // height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be passed to the Configure function

// loadCookie("os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true;NMTID=00Om_v;", "http://music.163.com");
#if CONFIG_API_SERVER
about.ConfigurationPanelHeight = 40; // height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be passed to the Configure function
loadConfig();
#else
about.ConfigurationPanelHeight = 0;
// loadCookie("os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true;NMTID=00Om_v;", "http://music.163.com");
#endif
return about;
}

private string loadConfig()
{
// string api_server;
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath() + "VGMdb_album_Config.conf";
if (File.Exists(dataPath))
api_server = File.ReadAllText(dataPath);
else
api_server = "http://vgmdb.info";
Console.WriteLine("Load api_server=" + api_server);
return api_server;
}


public bool Configure(IntPtr panelHandle)
{
// save any persistent settings in a sub-folder of this path
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath();
//string dataPath = mbApiInterface.Setting_GetPersistentStoragePath() + "VGMdb_album_Config.conf";
//if (File.Exists(dataPath))
// api_server = File.ReadAllText(dataPath);
//else
// api_server = "http://vgmdb.info";

// panelHandle will only be set if you set about.ConfigurationPanelHeight to a non-zero value
// keep in mind the panel width is scaled according to the font the user has selected
// if about.ConfigurationPanelHeight is set to 0, you can display your own popup window
if (panelHandle != IntPtr.Zero)
{
Panel configPanel = (Panel)Panel.FromHandle(panelHandle);
#if CONFIG_API_SERVER
Label prompt = new Label();
prompt.AutoSize = true;
prompt.Location = new Point(0, 0);
prompt.Text = "prompt:";
prompt.Location = new Point(0, 6);
prompt.Text = "API Server:";
TextBox textBox = new TextBox();
textBox.Bounds = new Rectangle(60, 0, 100, textBox.Height);
textBox.Bounds = new Rectangle(prompt.Width+30, 0, 300, textBox.Height);
textBox.Text = api_server;
textBox.TextChanged += new EventHandler(textBox_TextChanged); // 绑定 TextChanged 事件
configPanel.Controls.AddRange(new Control[] { prompt, textBox });
#endif
}
return false;
}

// called by MusicBee when the user clicks Apply or Save in the MusicBee Preferences screen.
// its up to you to figure out whether anything has changed and needs updating
public void SaveSettings()


private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
string oldValue = textBox.Tag?.ToString() ?? "";
api_server = textBox.Text;
// textBox.Tag = api_server;
Console.WriteLine($"api_server changed \"{oldValue}\" -> \"{api_server}\"");
}


// called by MusicBee when the user clicks Apply or Save in the MusicBee Preferences screen.
// its up to you to figure out whether anything has changed and needs updating
public void SaveSettings()
{
// save any persistent settings in a sub-folder of this path
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath();
#if CONFIG_API_SERVER
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath() + "VGMdb_album_Config.conf";
File.WriteAllText(dataPath, api_server);
#endif
}

// MusicBee is closing the plugin (plugin is being disabled by user or MusicBee is shutting down)
Expand Down Expand Up @@ -152,7 +194,7 @@ public string RetrieveArtwork(string sourceFileUrl, string albumArtist, string a
// 专辑名称同样需要预处理
Console.WriteLine("RetrieveArtwork Provider = " + provider + ", Artist = " + Artist + ", album = " + album);
// return new _163().getCover(Artist, album);
// return new vgmdb().getCover(Artist, album);
// return new vgmdb().getCover(Artist, album, api_server);
return new qq().getCover(Artist, album);
// return new DoubanApi().getCover(Artist, album);
}
Expand Down

0 comments on commit c3e756c

Please sign in to comment.