xref: /MusicFree/src/utils/getSimilarMusic.ts (revision 6f73e807144af9b496f38d87ede85146d6bf98f4)
13991724eS猫头猫import PluginManager from '@/core/pluginManager';
23991724eS猫头猫import minDistance from './minDistance';
33991724eS猫头猫
43991724eS猫头猫/**
53991724eS猫头猫 *
63991724eS猫头猫 * @param musicItem 音乐类型
73991724eS猫头猫 * @param type 媒体类型
83991724eS猫头猫 * @param abortFunction 如果函数为true,则中断
93991724eS猫头猫 * @returns
103991724eS猫头猫 */
113991724eS猫头猫export default async function <T extends ICommon.SupportMediaType>(
123991724eS猫头猫    musicItem: IMusic.IMusicItem,
133991724eS猫头猫    type: T = 'music' as T,
143991724eS猫头猫    abortFunction?: () => boolean,
153991724eS猫头猫): Promise<ICommon.SupportMediaItemBase[T] | null> {
163991724eS猫头猫    const keyword = musicItem.alias || musicItem.title;
173991724eS猫头猫    const plugins = PluginManager.getSearchablePlugins(type);
183991724eS猫头猫
193991724eS猫头猫    let distance = Infinity;
203991724eS猫头猫    let minDistanceMusicItem;
213991724eS猫头猫    let targetPlugin;
223991724eS猫头猫
233991724eS猫头猫    const startTime = Date.now();
243991724eS猫头猫
253991724eS猫头猫    for (let plugin of plugins) {
26*6f73e807S猫头猫        // 超时时间:8s
273991724eS猫头猫        if (abortFunction?.() || Date.now() - startTime > 8000) {
283991724eS猫头猫            break;
293991724eS猫头猫        }
303991724eS猫头猫        if (plugin.name === musicItem.platform) {
313991724eS猫头猫            continue;
323991724eS猫头猫        }
333991724eS猫头猫        const results = await plugin.methods
343991724eS猫头猫            .search(keyword, 1, type)
353991724eS猫头猫            .catch(() => null);
363991724eS猫头猫
373991724eS猫头猫        // 取前两个
383991724eS猫头猫        const firstTwo = results?.data?.slice(0, 2) || [];
393991724eS猫头猫
403991724eS猫头猫        for (let item of firstTwo) {
413991724eS猫头猫            if (item.title === keyword && item.artist === musicItem.artist) {
423991724eS猫头猫                distance = 0;
433991724eS猫头猫                minDistanceMusicItem = item;
443991724eS猫头猫                targetPlugin = plugin;
453991724eS猫头猫                break;
463991724eS猫头猫            } else {
473991724eS猫头猫                const dist =
483991724eS猫头猫                    minDistance(keyword, musicItem.title) +
493991724eS猫头猫                    minDistance(item.artist, musicItem.artist);
503991724eS猫头猫                if (dist < distance) {
513991724eS猫头猫                    distance = dist;
523991724eS猫头猫                    minDistanceMusicItem = item;
533991724eS猫头猫                    targetPlugin = plugin;
543991724eS猫头猫                }
553991724eS猫头猫            }
563991724eS猫头猫        }
573991724eS猫头猫
583991724eS猫头猫        if (distance === 0) {
593991724eS猫头猫            break;
603991724eS猫头猫        }
613991724eS猫头猫    }
623991724eS猫头猫    if (minDistanceMusicItem && targetPlugin) {
633991724eS猫头猫        return minDistanceMusicItem as ICommon.SupportMediaItemBase[T];
643991724eS猫头猫    }
653991724eS猫头猫
663991724eS猫头猫    return null;
673991724eS猫头猫}
68