/*!
 * @name 音乐下载器(解密版)
 * @description 使用全豆要接口的LX Music音源
 * @version 6
 * @author Toskysun
 */
const CACHE_TTL_MS = 21600000,
  CACHE_MAX_SIZE = 500,
  HTTP_URL_REGEX = /^https?:\/\//i,
  XINGHAI_MAIN_API =
    "https://music-api.gdstudio.xyz/api.php?use_xbridge3=true&loader_name=forest&need_sec_link=1&sec_link_scene=im&theme=light",
  XINGHAI_BACKUP_API = "https://music-dl.sayqz.com/api/",
  SUYIN_QQ_API = "https://oiapi.net/api/QQ_Music",
  SUYIN_QQ_KEY = "oiapi-ef6133b7-ac2f-dc7d-878c-d3e207a82575",
  SUYIN_163_API = "https://oiapi.net/api/Music_163",
  SUYIN_KUWO_API = "https://oiapi.net/api/Kuwo",
  SUYIN_MIGU_API = "https://api.xcvts.cn/api/music/migu",
  CHANGQING_URL_TEMPLATES = {
    tx: "http://175.27.166.236/kgqq/qq.php?type=mp3&id={id}&level={level}",
    wy: "http://175.27.166.236/wy/wy.php?type=mp3&id={id}&level={level}",
    kw: "https://musicapi.haitangw.net/music/kw.php?type=mp3&id={id}&level={level}",
    kg: "https://music.haitangw.cc/kgqq/kg.php?type=mp3&id={id}&level={level}",
    mg: "https://music.haitangw.cc/musicapi/mg.php?type=mp3&id={id}&level={level}",
  },
  NIANXIN_URL_TEMPLATES = {
    tx: "https://music.nxinxz.com/kgqq/tx.php?id={id}&level={level}&type=mp3",
    wy: "http://music.nxinxz.com/wy.php?id={id}&level={level}&type=mp3",
    kw: "http://music.nxinxz.com/kw.php?id={id}&level={level}&type=mp3",
    kg: "https://music.nxinxz.com/kgqq/kg.php?id={id}&level={level}&type=mp3",
    mg: "http://music.nxinxz.com/mg.php?id={id}&level={level}&type=mp3",
  },
  QISHUI_SOURCE_ID = "qsvip",
  QISHUI_SOURCE_NAME = "QishuiVIP",
  QISHUI_API_HTTPS = "https://api.vsaa.cn/api/music.qishui.vip",
  QISHUI_API_HTTP = "http://api.vsaa.cn/api/music.qishui.vip",
  QISHUI_PROXY_API = "https://proxy.qishui.vsaa.cn/qishui/proxy",
  PLATFORM_QUALITIES = {
    wy: ["24bit", "flac", "320k", "192k", "128k"],
    tx: ["24bit", "flac", "320k", "192k", "128k"],
    kw: ["24bit", "flac", "320k", "192k", "128k"],
    kg: ["24bit", "flac", "320k", "192k", "128k"],
    mg: ["24bit", "flac", "320k", "192k", "128k"],
  },
  PLATFORM_TO_XINGHAI = {
    wy: "netease",
    tx: "tencent",
    kw: "kuwo",
    kg: "kugou",
    mg: "migu",
  },
  QUALITY_TO_BR = {
    "128k": "128",
    "192k": "192",
    "320k": "320",
    flac: "740",
    flac24bit: "999",
    "24bit": "999",
  },
  PLATFORM_TO_XINGHAI_BACKUP = {
    wy: "netease",
    tx: "qq",
    kw: "kuwo",
  },
  QUALITY_TO_SUYIN_QQ_BR = {
    "128k": 0x7,
    "320k": 0x5,
    flac: 0x4,
    hires: 0x3,
    atmos: 0x2,
    master: 0x1,
    "24bit": 0x1,
  },
  QUALITY_TO_KUWO_BR = {
    flac: 0x1,
    "320k": 0x5,
    "128k": 0x7,
    "24bit": 0x1,
  },
  HIRES_QUALITY_SET = new Set(["24bit", "flac", "flac24bit", "hires", "master", "atmos"]),
  urlCache = new Map(),
  { EVENT_NAMES, request, on, send } = globalThis["lx"];
function noop() {}
function httpRequest(
  param,
  httpOptions = {
    method: "GET",
  }
) {
  return new Promise((callback, callback1) => {
    request(
      param,
      {
        timeout: 0x7d0,
        ...httpOptions,
      },
      (xerror, xresponse) => {
        if (xerror) return callback1(new Error("Request error: " + xerror["message"]));
        let temp = xresponse?.["body"];
        if (typeof temp === "string") {
          const result = temp["trim"]();
          if (
            result["startsWith"]("{") ||
            result["startsWith"]("[") ||
            result["startsWith"]("\x22")
          )
            try {
              temp = JSON["parse"](result);
            } catch (parseError) {}
        }
        callback({
          statusCode: xresponse?.["statusCode"] ?? 0,
          headers: xresponse?.["headers"] || {},
          body: temp,
        });
      }
    );
  });
}
async function httpGet(xurl, queryParams = {}) {
  const result1 = Object["keys"](queryParams)
      ["filter"]((item) => queryParams[item] !== undefined && queryParams[item] !== null)
      ["map"]((item1) => encodeURIComponent(item1) + "=" + encodeURIComponent(queryParams[item1]))
      ["join"]("&"),
    temp1 = xurl["includes"]("?") ? "&" : "?",
    temp2 = "" + xurl + (result1 ? temp1 + result1 : ""),
    temp3 = await httpRequest(temp2, {
      method: "GET",
      timeout: 0x7d0,
    });
  if (temp3["statusCode"] >= 400) throw new Error("HTTP error: " + temp3["statusCode"]);
  return temp3["body"];
}
function buildQueryString(queryParams = {}) {
  const result2 = Object["keys"](queryParams)
    ["filter"]((item2) => queryParams[item2] !== undefined && queryParams[item2] !== null)
    ["map"](
      (item3) =>
        encodeURIComponent(String(item3)) + "=" + encodeURIComponent(String(queryParams[item3]))
    );
  return result2["length"] ? "?" + result2["join"]("&") : "";
}
async function httpGetWithFallback(param1, options = {}, timeoutMs = 5000) {
  const temp4 = param1 === QISHUI_API_HTTPS ? [QISHUI_API_HTTPS, QISHUI_API_HTTP] : [param1];
  let temp5 = null;
  for (const temp6 of temp4) {
    try {
      const temp7 = "" + temp6 + buildQueryString(options),
        temp8 = await httpRequest(temp7, {
          method: "GET",
          timeout: timeoutMs,
        });
      if (temp8["statusCode"] >= 400) throw new Error("HTTP " + temp8["statusCode"]);
      return temp8["body"];
    } catch (fetchError) {
      temp5 = fetchError;
    }
  }
  throw temp5 || new Error("Qishui VIP request failed");
}
async function httpPost(param2, postBody = {}, timeoutMs = 5000) {
  const temp9 = await httpRequest(param2, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: postBody,
    timeout: timeoutMs,
  });
  if (temp9["statusCode"] >= 400) throw new Error("HTTP error: " + temp9["statusCode"]);
  return temp9["body"];
}
function getSongId(param3) {
  return (param3?.["id"] ||
    param3?.["songmid"] ||
    param3?.["songId"] ||
    param3?.["hash"] ||
    param3?.["rid"] ||
    param3?.["mid"] ||
    param3?.["strMediaMid"] ||
    param3?.["mediaId"] ||
    "")["toString"]();
}
function normalizeQuality(param4) {
  switch (String(param4 || "")["toLowerCase"]()) {
    case "128k":
      return "low";
    case "320k":
      return "standard";
    case "flac":
      return "lossless";
    case "flac24bit":
      return "flac24bit";
    default:
      return "128k";
  }
}
function normalizeSongInfo(param5) {
  const temp10 = param5?.["id"] || param5?.["vid"] ? String(param5["id"] || param5["vid"]) : "";
  return {
    id: temp10,
    songmid: temp10,
    hash: temp10,
    name: param5?.["name"] ? String(param5["name"]) : "Unknown Song",
    singer: param5?.["artists"] ? String(param5["artists"]) : "Unknown Artist",
    albumName: param5?.["album"] ? String(param5["album"]) : "",
    duration: param5?.["duration"] ? Math["floor"](Number(param5["duration"]) / 1000) : 0,
    pic: param5?.["cover"] || param5?.["pic"] ? String(param5["cover"] || param5["pic"]) : "",
    _raw: param5 || {},
  };
}
function getFirstData(xdata) {
  const temp11 = xdata?.["data"];
  if (Array["isArray"](temp11)) return temp11[0] || null;
  if (temp11 && typeof temp11 === "object" && temp11[0]) return temp11[0];
  return null;
}
async function qishuiSearch(param6, pageNum = 1, pageSize = 30) {
  if (!param6)
    return {
      isEnd: !![],
      list: [],
    };
  const temp12 = await httpGetWithFallback(
      QISHUI_API_HTTPS,
      {
        act: "search",
        keywords: param6,
        page: pageNum,
        pagesize: pageSize,
        type: "music",
      },
      15000
    ),
    temp13 = Array["isArray"](temp12?.["data"]?.["lists"]) ? temp12["data"]["lists"] : [],
    temp14 = temp12?.["data"]?.["total"] ? Number(temp12["data"]["total"]) : temp13["length"];
  return {
    isEnd: temp13["length"] < pageSize,
    list: temp13["map"](normalizeSongInfo),
    total: temp14,
  };
}
async function qishuiGetUrl(param7, param8) {
  const result3 = getSongId(param7);
  if (!result3) throw new Error("Qishui VIP missing song ID");
  const temp15 = await httpGetWithFallback(
      QISHUI_API_HTTPS,
      {
        act: "song",
        id: result3,
        quality: normalizeQuality(param8),
      },
      20000
    ),
    result4 = getFirstData(temp15);
  if (!result4?.["url"]) throw new Error("Qishui VIP did not return a usable URL");
  if (result4["ekey"]) {
    const temp16 = await httpPost(
      QISHUI_PROXY_API,
      {
        url: result4["url"],
        key: result4["ekey"],
        filename: result4["filename"] || "KMusic",
        ext: result4["fileExtension"] ? String(result4["fileExtension"]) : "aac",
      },
      60000
    );
    if (Number(temp16?.["code"]) === 200 && temp16?.["url"]) return String(temp16["url"]);
    throw new Error("Qishui VIP proxy decryption failed");
  }
  return String(result4["url"]);
}
async function qishuiGetLyric(param9) {
  const result5 = getSongId(param9);
  if (!result5)
    return {
      lyric: "",
    };
  const temp17 = await httpGetWithFallback(
      QISHUI_API_HTTPS,
      {
        act: "song",
        id: result5,
      },
      15000
    ),
    result6 = getFirstData(temp17);
  return {
    lyric: result6?.["lyric"] ? String(result6["lyric"]) : "",
  };
}
async function qishuiHandler(param10, searchParams = {}) {
  if (param10 === "musicSearch" || param10 === "search") {
    const temp18 = searchParams?.["keyword"] ? String(searchParams["keyword"]) : "",
      temp19 = searchParams?.["page"] ? Number(searchParams["page"]) : 1,
      temp20 = searchParams?.["pagesize"] ? Number(searchParams["pagesize"]) : 30;
    return qishuiSearch(temp18, temp19, temp20);
  }
  if (param10 === "musicUrl") {
    if (!searchParams?.["musicInfo"]) throw new Error("Incomplete request parameters");
    const temp21 = await qishuiGetUrl(searchParams["musicInfo"], searchParams["type"]);
    return validateUrl(temp21, "Qishui VIP");
  }
  if (param10 === "lyric") return qishuiGetLyric(searchParams?.["musicInfo"] || {});
  throw new Error("action not supported");
}
function selectQuality(param11, param12) {
  if (param11 === "24bit") return "24bit";
  const temp22 = Array["isArray"](param12) ? param12 : ["128k"],
    result7 = String(param11 || "128k")["toLowerCase"]();
  if (temp22["includes"](result7)) return result7;
  const arr = ["flac24bit", "flac", "320k", "192k", "128k"];
  let result8 = arr["indexOf"](result7);
  result8 < 0 && (result8 = arr["length"] - 1);
  for (let temp23 = result8; temp23 < arr["length"]; temp23++) {
    if (temp22["includes"](arr[temp23])) return arr[temp23];
  }
  for (let temp24 = arr["length"] - 1; temp24 >= 0; temp24--) {
    if (temp22["includes"](arr[temp24])) return arr[temp24];
  }
  return temp22[0] || "128k";
}
function normalizeKeyword(param13) {
  if (!param13) return "";
  return String(param13)
    ["replace"](/\(\s*Live\s*\)/gi, "")
    ["replace"](/\([^)]*\)/g, "")
    ["replace"](/\s+/g, "")
    ["replace"](/[^\w\u4e00-\u9fa5]/g, "")
    ["trim"]()
    ["toLowerCase"]();
}
function buildSearchKeywords(param14) {
  const arr1 = [],
    temp25 = param14?.["name"] || "",
    temp26 = param14?.["albumName"] || param14?.["album"] || "",
    temp27 = param14?.["singer"] || "";
  if (temp25 && temp26) {
    const result9 = normalizeKeyword(temp25 + temp26);
    result9 &&
      arr1["push"]({
        keyword: result9,
        strict: !![],
      });
  }
  if (temp25 && temp27) {
    const result10 = normalizeKeyword(temp25 + temp27);
    result10 &&
      arr1["push"]({
        keyword: result10,
        strict: !![],
      });
  }
  if (temp25) {
    const result11 = normalizeKeyword(temp25);
    result11 &&
      arr1["push"]({
        keyword: result11,
        strict: ![],
      });
  }
  return arr1;
}
function titleMatch(param15, param16) {
  const result13 = normalizeKeyword(param15),
    result14 = normalizeKeyword(param16);
  if (!result13 || !result14) return !![];
  return result13["includes"](result14) || result14["includes"](result13);
}
function songInfoMatch(xdata1, param17) {
  const temp29 = xdata1?.["song"] || xdata1?.["data"]?.["song"] || "",
    temp30 = xdata1?.["singer"] || xdata1?.["data"]?.["singer"] || "",
    temp31 = xdata1?.["album"] || xdata1?.["data"]?.["album"] || "";
  if (!titleMatch(temp29, param17?.["name"] || "")) return ![];
  if (param17?.["singer"] && temp30 && !titleMatch(temp30, param17["singer"])) return ![];
  if (
    (param17?.["albumName"] || param17?.["album"]) &&
    temp31 &&
    !titleMatch(temp31, param17["albumName"] || param17["album"])
  )
    return ![];
  return !![];
}
function songTitleMatch(param18, param19) {
  if (!titleMatch(param18?.["title"] || "", param19?.["name"] || "")) return ![];
  if (
    param19?.["singer"] &&
    param18?.["artist"] &&
    !titleMatch(param18["artist"], param19["singer"])
  )
    return ![];
  if (
    (param19?.["albumName"] || param19?.["album"]) &&
    param18?.["album"] &&
    !titleMatch(param18["album"], param19["albumName"] || param19["album"])
  )
    return ![];
  return !![];
}
function parseMessageSongInfo(param20) {
  if (!param20) return null;
  const helpers = {},
    result16 = String(param20)["split"]("\x0a");
  for (const temp33 of result16) {
    (temp33["startsWith"]("Song Name: ") &&
      (helpers["song"] = temp33["replace"]("Song Name: ", "")["trim"]()),
      temp33["startsWith"]("Artist: ") &&
        (helpers["singer"] = temp33["replace"]("Artist: ", "")["trim"]()),
      temp33["startsWith"]("Album: ") &&
        (helpers["album"] = temp33["replace"]("Album: ", "")["trim"]()));
  }
  return helpers["song"] ? helpers : null;
}
function getHashOrMid(param21) {
  return param21?.["hash"] ?? param21?.["songmid"] ?? param21?.["id"] ?? null;
}
function getQQSongId(param22) {
  const temp34 =
    param22?.["meta"]?.["qq"]?.["mid"] ||
    param22?.["meta"]?.["mid"] ||
    param22?.["songmid"] ||
    (typeof param22?.["id"] === "string" && !/^\d+$/["test"](param22["id"]) ? param22["id"] : null);
  if (temp34)
    return {
      type: "mid",
      value: temp34,
    };
  const temp35 =
    param22?.["meta"]?.["qq"]?.["songid"] ||
    param22?.["meta"]?.["songid"] ||
    (typeof param22?.["id"] === "number"
      ? param22["id"]
      : typeof param22?.["id"] === "string" && /^\d+$/["test"](param22["id"])
        ? Number(param22["id"])
        : null);
  if (temp35)
    return {
      type: "songid",
      value: temp35,
    };
  return null;
}
function qualityToNetease(param23) {
  const result17 = String(param23 || "128k")["toLowerCase"]();
  if (
    result17 === "flac" ||
    result17 === "flac24bit" ||
    result17 === "hires" ||
    result17 === "master" ||
    result17 === "atmos"
  )
    return "lossless";
  if (result17 === "320k" || result17 === "192k") return "exhigh";
  return "standard";
}
function getPlatformSongId(param24, param25) {
  if (param24 === "kg")
    return (
      param25?.["hash"] ||
      param25?.["songmid"] ||
      param25?.["id"] ||
      param25?.["rid"] ||
      param25?.["mid"] ||
      null
    );
  if (param24 === "tx") {
    const result18 = getQQSongId(param25);
    if (result18?.["value"]) return result18["value"];
  }
  return (
    param25?.["songmid"] ||
    param25?.["id"] ||
    param25?.["songId"] ||
    param25?.["rid"] ||
    param25?.["hash"] ||
    null
  );
}
function buildTemplateUrl(param26, param27, param28, param29, param30) {
  const temp36 = param29[param26];
  if (!temp36) throw new Error(param30 + " does not support this platform");
  const result19 = getPlatformSongId(param26, param28);
  if (!result19) throw new Error(param30 + " missing songId");
  const result20 = qualityToNetease(param27);
  return temp36["replace"]("{id}", encodeURIComponent(String(result19)))["replace"](
    "{level}",
    encodeURIComponent(result20)
  );
}
function buildCacheKey(param31, param32, cacheSuffix = "") {
  const temp37 = param32?.["name"] || "",
    temp38 = param32?.["singer"] || "",
    temp39 = param32?.["albumName"] || param32?.["album"] || "";
  return param31 + "_" + temp37 + "_" + temp38 + "_" + temp39 + "_" + cacheSuffix;
}
function getCachedUrl(param33) {
  const result21 = urlCache["get"](param33);
  if (!result21) return null;
  if (Date["now"]() - result21["timestamp"] >= CACHE_TTL_MS)
    return (urlCache["delete"](param33), null);
  return result21["url"];
}
function setCachedUrl(param34, param35) {
  urlCache["set"](param34, {
    url: param35,
    timestamp: Date["now"](),
  });
  if (urlCache["size"] > CACHE_MAX_SIZE) {
    const temp40 = urlCache["keys"]()["next"]()["value"];
    temp40 !== undefined && urlCache["delete"](temp40);
  }
}
function validateUrl(text, param36) {
  if (!text || typeof text !== "string") throw new Error(param36 + " returned empty URL");
  if (!HTTP_URL_REGEX["test"](text["trim"]())) throw new Error(param36 + " invalid URL format");
  return text;
}
function getMobileUserAgent() {
  return "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1";
}
async function xinghaiMainGetUrl(param37, param38, param39, param40) {
  const temp41 = PLATFORM_TO_XINGHAI[param37];
  if (!temp41) throw new Error("Xinghai Main API does not support this platform");
  const temp42 = param38 ?? getHashOrMid(param40);
  if (!temp42) throw new Error("Missing songId");
  const result22 = selectQuality(param39, ["128k", "192k", "320k", "flac", "flac24bit"]),
    temp43 = QUALITY_TO_BR[result22];
  if (!temp43) throw new Error("Xinghai Main API quality mapping failed");
  const temp44 =
      XINGHAI_MAIN_API +
      "&types=url&source=" +
      temp41 +
      "&id=" +
      encodeURIComponent(temp42) +
      "&br=" +
      temp43,
    temp45 = await httpRequest(temp44, {
      method: "GET",
      headers: {
        "User-Agent": "LX-Music-Mobile",
        Accept: "application/json",
      },
    }),
    temp46 = temp45["body"];
  if (!temp46 || typeof temp46 !== "object" || !temp46["url"])
    throw new Error(temp46?.["message"] || "Xinghai Main API did not return a usable URL");
  return temp46["url"];
}
async function xinghaiBackupGetUrl(param41, param42, param43, param44) {
  const temp47 = PLATFORM_TO_XINGHAI_BACKUP[param41];
  if (!temp47) throw new Error("Xinghai Backup API does not support this platform");
  const temp48 = param42 ?? getHashOrMid(param44);
  if (!temp48) throw new Error("Missing songId");
  const result23 = selectQuality(param43, ["128k", "192k", "320k", "flac", "flac24bit"]);
  return (
    XINGHAI_BACKUP_API +
    "?source=" +
    encodeURIComponent(temp47) +
    "&id=" +
    encodeURIComponent(temp48) +
    "&type=url&br=" +
    encodeURIComponent(result23)
  );
}
async function huibqGetUrl(param45, param46, param47, param48) {
  const temp49 = param48?.["hash"] ?? param48?.["songmid"];
  if (!temp49) throw new Error("Huibq missing hash/songmid");
  const result24 = selectQuality(param47, ["320k", "128k"]),
    temp50 =
      HUIBQ_API +
      "/url/" +
      param45 +
      "/" +
      encodeURIComponent(temp49) +
      "/" +
      encodeURIComponent(result24),
    temp51 = await httpRequest(temp50, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "User-Agent": getMobileUserAgent(),
        "X-Request-Key": HUIBQ_REQUEST_KEY,
      },
    }),
    temp52 = temp51["body"];
  if (!temp52 || typeof temp52 !== "object" || Number["isNaN"](Number(temp52["code"])))
    throw new Error("Huibq returned invalid response");
  switch (Number(temp52["code"])) {
    case 0:
      if (!temp52["url"]) throw new Error("Huibq returned empty URL");
      return temp52["url"];
    case 1:
      throw new Error("Huibq block ip");
    case 2:
      throw new Error("Huibq get music url failed");
    case 4:
      throw new Error("Huibq too many requests");
    case 5:
      throw new Error("Huibq param error");
    case 6:
      throw new Error("Huibq internal server error");
    default:
      throw new Error(temp52["message"] || "Huibq unknown error");
  }
}
async function lingchuanGetUrl(param49, param50, param51, param52) {
  const temp53 = param52?.["hash"] ?? param52?.["songmid"];
  if (!temp53) throw new Error("Lingchuan missing hash/songmid");
  const result25 = selectQuality(param51, ["320k", "128k"]),
    temp54 =
      LINGCHUAN_API +
      "/url?source=" +
      encodeURIComponent(param49) +
      "&songId=" +
      encodeURIComponent(temp53) +
      "&quality=" +
      encodeURIComponent(result25),
    temp55 = await httpRequest(temp54, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "User-Agent": getMobileUserAgent(),
      },
      follow_max: 0x5,
    }),
    temp56 = temp55["body"];
  if (!temp56 || typeof temp56 !== "object" || Number["isNaN"](Number(temp56["code"])))
    throw new Error("Lingchuan returned invalid response");
  switch (Number(temp56["code"])) {
    case 200:
      if (!temp56["url"]) throw new Error("Lingchuan returned empty URL");
      return temp56["url"];
    case 403:
      throw new Error("Lingchuan 403 forbidden");
    case 429:
      throw new Error("Lingchuan 429 rate limit");
    case 500:
      throw new Error("Lingchuan 500 " + (temp56["message"] || "server error"));
    default:
      throw new Error(temp56["message"] || "Lingchuan unknown error");
  }
}
function extractQQUrl(xerror1) {
  if (xerror1?.["music"]) return xerror1["music"];
  if (xerror1?.["url"]) return xerror1["url"];
  if (xerror1?.["message"]) {
    const result26 = String(xerror1["message"])["match"](/Audio link[：:](.+?)(?:\n|$)/);
    if (result26 && result26[1]) return result26[1]["trim"]();
  }
  throw new Error("Suyin QQ did not find audio link");
}
function qualityToSuyinQQ(param53) {
  const result28 = String(param53 || "128k")["toLowerCase"]();
  if (result28 === "flac24bit") return "hires";
  if (result28 === "192k") return "320k";
  if (QUALITY_TO_SUYIN_QQ_BR[result28]) return result28;
  return "128k";
}
async function suyinQQGetUrl(param54, param55) {
  const result29 = getQQSongId(param54);
  if (!result29) throw new Error("Suyin QQ missing songmid/id");
  const result30 = qualityToSuyinQQ(param55),
    temp58 = QUALITY_TO_SUYIN_QQ_BR[result30] || QUALITY_TO_SUYIN_QQ_BR["128k"],
    result31 = [temp58, 4, 5, 7]
      ["filter"](
        (param56, param57, param58) => param58["indexOf"](param56) === param57 && param56 >= temp58
      )
      ["sort"]((param59, param60) => param59 - param60);
  let temp59 = null;
  for (const temp60 of result31) {
    try {
      const requestParams = {
        key: SUYIN_QQ_KEY,
        type: "json",
        br: temp60,
        n: 0x1,
      };
      result29["type"] === "mid"
        ? (requestParams["mid"] = result29["value"])
        : (requestParams["songid"] = result29["value"]);
      const temp61 = await httpGet(SUYIN_QQ_API, requestParams);
      return extractQQUrl(temp61);
    } catch (requestError) {
      temp59 = requestError;
    }
  }
  throw new Error("Suyin QQ all quality attempts failed: " + (temp59?.["message"] || "unknown"));
}
async function suyin163GetUrl(param61) {
  const temp62 = param61?.["songmid"] || param61?.["id"];
  if (!temp62) throw new Error("Suyin 163 missing songmid/id");
  const temp63 = await httpGet(SUYIN_163_API, {
    id: temp62,
  });
  if (temp63?.["code"] === 0 && temp63?.["data"]) {
    const temp64 = Array["isArray"](temp63["data"]) ? temp63["data"][0] : temp63["data"];
    if (temp64?.["url"]) return temp64["url"];
  }
  throw new Error("Suyin 163 acquisition failed");
}
async function suyinKuwoSearch(param62, param63, targetSong = null) {
  const temp65 = await httpGet(SUYIN_KUWO_API, {
    msg: param62,
    n: 0x1,
    br: param63,
  });
  if (temp65?.["data"]?.["url"]) {
    if (targetSong && !songInfoMatch(temp65, targetSong))
      throw new Error("Suyin Kuwo song info mismatch");
    return temp65["data"]["url"];
  }
  if (temp65?.["message"]) {
    const result32 = String(temp65["message"])["match"](/Music link[：:](\S+)/);
    if (result32 && result32[1]) {
      if (targetSong) {
        const result33 = parseMessageSongInfo(temp65["message"]);
        if (result33 && !songInfoMatch(result33, targetSong))
          throw new Error("Suyin Kuwo song info mismatch");
      }
      return result32[1];
    }
  }
  throw new Error("Suyin Kuwo did not find link");
}
async function suyinKuwoGetUrl(param64, param65) {
  if (!param64?.["name"]) throw new Error("Suyin Kuwo requires song name");
  const result34 = buildCacheKey("kw", param64, param65),
    result35 = getCachedUrl(result34);
  if (result35) return result35;
  const result36 = selectQuality(param65, ["flac", "320k", "128k"]),
    temp66 = QUALITY_TO_KUWO_BR[result36] || 1,
    result37 = buildSearchKeywords(param64);
  let temp67 = null;
  for (const temp68 of result37) {
    try {
      const temp69 = await suyinKuwoSearch(
        temp68["keyword"],
        temp66,
        temp68["strict"] ? param64 : null
      );
      if (temp69) return (setCachedUrl(result34, temp69), temp69);
    } catch (searchError) {
      temp67 = searchError;
    }
  }
  throw new Error("Suyin Kuwo failed: " + (temp67?.["message"] || "unknown"));
}
async function suyinMiguGetUrl(param66) {
  if (!param66?.["name"]) throw new Error("Suyin Migu requires song name");
  const result38 = buildCacheKey("mg", param66),
    result39 = getCachedUrl(result38);
  if (result39) return result39;
  const result40 = buildSearchKeywords(param66);
  let temp70 = null;
  for (const temp71 of result40) {
    try {
      const temp72 = await httpGet(SUYIN_MIGU_API, {
        gm: temp71["keyword"],
        n: 0x1,
        num: 0x1,
        type: "json",
      });
      if (temp72?.["code"] === 200 && temp72?.["musicInfo"]) {
        if (temp71["strict"] && !songTitleMatch(temp72, param66))
          throw new Error("Suyin Migu song info mismatch");
        return (setCachedUrl(result38, temp72["musicInfo"]), temp72["musicInfo"]);
      }
    } catch (searchError) {
      temp70 = searchError;
    }
  }
  throw new Error("Suyin Migu failed: " + (temp70?.["message"] || "unknown"));
}
async function suyinGetUrl(param67, param68, param69, param70) {
  switch (param67) {
    case "tx":
      return suyinQQGetUrl(param70, param69);
    case "wy":
      return suyin163GetUrl(param70);
    case "kw":
      return suyinKuwoGetUrl(param70, param69);
    case "mg":
      return suyinMiguGetUrl(param70);
    default:
      throw new Error("Suyin does not support this platform");
  }
}
async function changqingGetUrl(param71, param72, param73, param74) {
  return buildTemplateUrl(param71, param73, param74, CHANGQING_URL_TEMPLATES, "Changqing SVIP");
}
async function nianxinGetUrl(param75, param76, param77, param78) {
  return buildTemplateUrl(param75, param77, param78, NIANXIN_URL_TEMPLATES, "Nianxin SVIP");
}
const SOURCE_HANDLERS = {
  xinghai: {
    name: "Xinghai Main",
    fn: xinghaiMainGetUrl,
  },
  xinghaiBackup: {
    name: "Xinghai Backup",
    fn: xinghaiBackupGetUrl,
  },
  huibq: {
    name: "Huibq",
    fn: huibqGetUrl,
  },
  lingchuan: {
    name: "Lingchuan",
    fn: lingchuanGetUrl,
  },
  suyinQQ: {
    name: "Suyin QQ",
    fn: (param79, param80, param81, param82) => suyinGetUrl("tx", param80, param81, param82),
  },
  suyin163: {
    name: "Suyin 163",
    fn: (param83, param84, param85, param86) => suyinGetUrl("wy", param84, param85, param86),
  },
  suyinSearch: {
    name: "Suyin Search",
    fn: (param87, param88, param89, param90) => suyinGetUrl("kw", param88, param89, param90),
  },
  suyinMigu: {
    name: "Suyin Migu",
    fn: (param91, param92, param93, param94) => suyinGetUrl("mg", param92, param93, param94),
  },
  changqingVip: {
    name: "Changqing SVIP",
    fn: changqingGetUrl,
  },
  nianxinVip: {
    name: "Nianxin SVIP",
    fn: nianxinGetUrl,
  },
};
function buildSourceChain(param95, param96, param97) {
  const arr2 = [];
  return (
    SOURCE_HANDLERS["xinghai"] && arr2["push"](SOURCE_HANDLERS["xinghai"]),
    SOURCE_HANDLERS["huibq"] && arr2["push"](SOURCE_HANDLERS["huibq"]),
    param95 === "wy" && SOURCE_HANDLERS["suyin163"] && arr2["push"](SOURCE_HANDLERS["suyin163"]),
    param95 === "tx" && SOURCE_HANDLERS["suyinQQ"] && arr2["push"](SOURCE_HANDLERS["suyinQQ"]),
    param95 === "kw" &&
      SOURCE_HANDLERS["suyinSearch"] &&
      arr2["push"](SOURCE_HANDLERS["suyinSearch"]),
    param95 === "mg" && SOURCE_HANDLERS["suyinMigu"] && arr2["push"](SOURCE_HANDLERS["suyinMigu"]),
    SOURCE_HANDLERS["lingchuan"] && arr2["push"](SOURCE_HANDLERS["lingchuan"]),
    SOURCE_HANDLERS["changqingVip"] && arr2["push"](SOURCE_HANDLERS["changqingVip"]),
    SOURCE_HANDLERS["nianxinVip"] && arr2["push"](SOURCE_HANDLERS["nianxinVip"]),
    arr2
  );
}
async function getUrlWithFallback(param98, param99, param100) {
  if (!param98 || typeof param98 !== "string" || !PLATFORM_QUALITIES[param98])
    throw new Error("Invalid platform parameter");
  if (!param99 || typeof param99 !== "object") throw new Error("Invalid song info");
  const temp73 = param100 || "128k",
    result41 = selectQuality(temp73, PLATFORM_QUALITIES[param98]),
    result42 = getHashOrMid(param99),
    result43 = HIRES_QUALITY_SET["has"](temp73["toLowerCase"]()),
    result44 = buildSourceChain(param98, result43, result41);
  if (!result44["length"]) throw new Error("No available fallback chain found");
  const arr3 = [];
  try {
    const temp74 = await Promise["any"](
      result44["slice"](0, 3)["map"](async (item4) => {
        const temp75 = await item4["fn"](param98, result42, result41, param99);
        return validateUrl(temp75, item4["name"]);
      })
    );
    if (temp74) return temp74;
  } catch (apiError) {
    apiError["errors"] &&
      apiError["errors"]["forEach"]((xerror2) => arr3["push"](xerror2["message"]));
  }
  for (const temp76 of result44["slice"](3)) {
    try {
      const temp77 = await temp76["fn"](param98, result42, result41, param99);
      return validateUrl(temp77, temp76["name"]);
    } catch (lyricError) {
      arr3["push"](temp76["name"] + ":\x20" + lyricError["message"]);
      continue;
    }
  }
  throw new Error("All sources failed: " + arr3["join"](";\x20"));
}
const sourceConfig = {},
  PLATFORM_NAMES = {
    wy: "Netease Cloud Music",
    tx: "QQ Music",
    kw: "Kuwo Music",
    kg: "Kugou Music",
    mg: "Migu Music",
  };
(Object["keys"](PLATFORM_QUALITIES)["forEach"]((item5) => {
  sourceConfig[item5] = {
    name: PLATFORM_NAMES[item5],
    type: "music",
    actions: ["musicUrl"],
    qualitys: PLATFORM_QUALITIES[item5],
  };
}),
  (sourceConfig[QISHUI_SOURCE_ID] = {
    name: QISHUI_SOURCE_NAME,
    type: "music",
    actions: ["musicSearch", "musicUrl", "lyric"],
    qualitys: ["128k", "320k", "flac", "flac24bit"],
  }),
  on(EVENT_NAMES["request"], ({ action: action, source: source, info: info }) => {
    if (source === QISHUI_SOURCE_ID) return qishuiHandler(action, info);
    if (action !== "musicUrl") return Promise["reject"](new Error("action not supported"));
    if (!info?.["musicInfo"]) return Promise["reject"](new Error("Incomplete request parameters"));
    return getUrlWithFallback(source, info["musicInfo"], info["type"] || "128k")
      ["then"]((param101) => Promise["resolve"](param101))
      ["catch"]((param102) => Promise["reject"](param102));
  }),
  send(EVENT_NAMES["inited"], {
    openDevTools: ![],
    sources: sourceConfig,
  }),
  noop("Initialization complete, aggregated audio source ready"));
