Skip to content

Repository files navigation

English | 中文

kugou_api

A comprehensive Dart package for KuGou Music API with full API coverage, authentication, caching, and more.

Inspired by MakcRe/KuGouMusicApi Node.js project, ported to native Dart.

Requirements

  • Dart SDK ^3.11.4

Installation

dependencies:
  kugou_api: ^0.1.0

Or:

dart pub add kugou_api

Quick Start

Basic Usage

import 'package:kugou_api/kugou_api.dart';

void main() async {
  final api = KuGouApi();

  // Search songs
  final result = await api.search.songs(keyword: 'Jay Chou', page: 1, pageSize: 10);
  print(result);
}

Use Lite Platform

final api = KuGouApi(platform: Platform.lite);
// Note: Tokens are not interchangeable between different platforms

Proxy Configuration

final api = KuGouApi(proxy: 'http://127.0.0.1:7890');

Authentication

Password Login

final loginResult = await api.login.byPassword(
  username: 'your_username',
  password: 'your_password',
);

Captcha Login

final result = await api.login.sendCaptcha(phone: '13800138000');
if (result.success) {
  final loginResult = await api.login.byCaptcha(phone: '13800138000', captcha: '1234');
}

QR Code Login

await for (final state in api.login.qrCodeStream()) {
  if (state == QrCodeState.confirmed) break;
}

Auto Refresh Login

// Initialize with existing token
final api = KuGouApi(token: 'your_token', userid: 12345);

// Enable auto refresh (default: every 24 hours)
api.enableAutoRefresh(
  interval: Duration(hours: 24),
  onRefresh: (result) {
    print('Token refreshed: ${result.token}');
  },
  onError: (e) {
    print('Refresh failed: $e');
  },
);

// Ensure logged in
final result = await api.ensureLoggedIn();

// Disable auto refresh
api.disableAutoRefresh();

// Cleanup resources
api.dispose();

Cookie Management

Built-in CookieJar for automatic cookie handling:

// Option 1: Pass initial cookies
final api = KuGouApi(initialCookies: {
  'kugou.com': 'token=abc123; userid=42',
});

// Option 2: Set cookies manually
api.cookieJar.set(domain: 'kugou.com', name: 'token', value: 'abc123');

// Read cookies
final cookies = api.cookieJar.getCookiesForUrl('https://kugou.com/api');

Cookie Persistence

CookieJar provides serialize() / loadFromMap() methods for serialization. Users should handle persistence themselves:

import 'dart:io';
import 'dart:convert';

// Save
final data = api.cookieJar.serialize();
await File('cookies.json').writeAsString(jsonEncode(data));

// Restore
final json = jsonDecode(await File('cookies.json').readAsString()) as Map<String, dynamic>;
api.cookieJar.loadFromMap(json.map((k, v) => MapEntry(k, v as Map<String, dynamic>)));

Custom Configuration

final api = KuGouApi(
  platform: Platform.lite,
  proxy: 'http://127.0.0.1:7890',
  connectTimeout: Duration(seconds: 10),
  receiveTimeout: Duration(seconds: 30),
  logLevel: LogLevel.debug,
  logCallback: (level, msg) => print('[$level] $msg'),
  cacheMaxSize: 200,
  cacheTtl: Duration(minutes: 5),
  retryOptions: RetryOptions(maxAttempts: 3),
  token: 'your_token',
  userid: 12345,
  dfid: 'your_dfid',
  mid: 'your_mid',
);

Error Handling

try {
  final detail = await api.song.detail(hash: 'xxx');
} on KuGouApiException catch (e) {
  print('API error: status=${e.status}, code=${e.code}, message=${e.message}');
} on KuGouNetworkException catch (e) {
  print('Network error: ${e.message}');
}

Features

Search

  • Search songs (search.songs)
  • Search playlists (search.playlists)
  • Search albums (search.albums)
  • Search lyrics (search.lyrics)
  • Mixed search (search.mixed)
  • Mixed search v2 (search.mixedSearch)
  • Hot search list (search.hotDetail)
  • Hot search tabs (search.hotTab)
  • Search suggestions (search.suggest)
  • Search suggestions v2 (search.suggestV2)
  • Default search keyword (search.defaultWord)
  • Complex search (search.complex)
  • Lyric search (search_lyric)

Song

  • Get song URL (song.url)
  • Get song detail (song.detail)
  • Song ranking (song.ranking)
  • Song climax (song.climax)
  • Song ranking filter (song.rankingFilter)
  • Get song URL (new) (song_url_new)

Lyric

  • Lyric search (lyric.search)
  • Get lyrics (lyric.get)

Login

  • Password login (login.byPassword)
  • Send captcha (login.sendCaptcha)
  • Captcha login (login.byCaptcha)
  • QR code login (login.qrCodeStream)
  • Device login (login.deviceLogin)
  • Device kick (login.deviceKick)
  • Open platform login (login.openplatLogin)
  • Token login (login_token)
  • WeChat login create (login.wxCreate)
  • WeChat login check (login.wxCheck)

Ranking

  • Ranking list (rank.list)
  • Ranking info (rank.info)
  • Ranking audio (rank.audio)
  • Ranking top (rank.top)
  • Ranking history (rank.vol)

Playlist

  • Get playlist detail (playlist.detail)
  • Get playlist tracks (playlist.tracks)
  • Playlist categories (playlist.tags)
  • Similar playlists (playlist.similar)
  • Playlist list (playlist.top)
  • Favorite/Create playlist (playlist.add)
  • Add tracks to playlist (playlist.addTracks)
  • Remove tracks from playlist (playlist.removeTracks)
  • Delete playlist (playlist.delete)
  • Playlist effect (playlist.effect)
  • Get all playlist tracks (playlist_track_all)
  • Get all playlist tracks new (playlist.trackAllNew)

Album

  • Album detail (album.detail)
  • Album old detail (album.oldDetail)
  • New albums (album.top)
  • Album songs (album.songs)
  • Album shop (album.shop)

Artist

  • Get artist detail (artist.detail)
  • Get artist songs (artist.audios)
  • Get artist albums (artist.albums)
  • Get artist list (artist.list)
  • Follow artist (artist.follow)
  • Unfollow artist (artist.unfollow)
  • Get artist MVs (artist.videos)
  • Get followed artist new songs (artist.followNewSongs)
  • Get artist honors (artist.honour)

Recommend

  • Daily recommend (recommend.everyday)
  • AI recommend (recommend.ai)
  • New songs (recommend.newSongs)
  • Daily recommend friends (recommend.everydayFriend)
  • History recommend (recommend.everydayHistory)
  • Style recommend (recommend.everydayStyleRecommend)

Comment

  • Song comments (comment.music)
  • Comment count (comment.count)
  • Floor comments (comment.floor)
  • Comment hot words (comment.hotWord)
  • Classified comments (comment.classify)
  • Album comments (comment.album)
  • Playlist comments (comment.playlist)

User

  • Get user detail (user.detail)
  • Get user playlists (user.playlists)
  • Get user listening history (user.history)
  • Get user VIP info (user.vipDetail)
  • Favorite count (user.favoriteCount)
  • Follow artist (user.follow)
  • Submit listening history (user.uploadHistory)
  • Listening time report (user.listenTimeAdd)
  • User follow messages (user.followMessage)
  • User listening ranking (user.listen)
  • User cloud (user.cloud)
  • User cloud URL (user.cloudUrl)
  • User video favorites (user.videoCollect)
  • User video likes (user.videoLove)

FM

  • FM categories (fm.classes)
  • FM songs (fm.songs)
  • Personal FM (fm.personal)
  • FM recommend (fm.recommend)
  • FM image (fm.image)

IP Zone

  • IP content list (ip.content)
  • IP detail (ip.detail)
  • IP playlists (ip.playlist)
  • IP zone categories (ip.zone)
  • IP zone home (ip.zoneHome)

Top Card

  • Top card (top.card)
  • Youth card (top.cardYouth)
  • IP top (top.ip)
  • Top playlist (top.playlist)
  • Top songs (top.song)

Images

  • Get album and artist images (images.albumImages)
  • Get artist images (images.audioImages)

Music Library

  • Music library recommend (yueku.recommend)
  • Music library banner (yueku.banner)
  • Music library FM (yueku.fm)

Long Audio/Audiobook

  • Audiobook album detail (longaudio.albumDetail)
  • Audiobook album songs (longaudio.albumAudios)
  • Daily recommend (longaudio.dailyRecommend)
  • Ranking recommend (longaudio.rankRecommend)
  • VIP recommend (longaudio.vipRecommend)
  • Weekly recommend (longaudio.weekRecommend)

Video

  • Get video detail (video.detail)
  • Get video privilege (video.privilege)
  • Get video URL (video.url)
  • Get song MV (video.audioMv)
  • Get audio MV detail (video.audioDetail)

Scene

  • Scene music list (scene.lists)
  • Scene music list V2 (scene.listsV2)
  • Get scene modules (scene.module)
  • Get scene module info (scene.moduleInfo)
  • Get scene music list (scene.audioList)
  • Get scene music (scene.music)
  • Get scene playlist list (scene.collectionList)
  • Get scene video list (scene.videoList)

Sheet Music

  • Song sheets (sheet.collection)
  • Sheet collection detail (sheet.collectionDetail)
  • Sheet detail (sheet.detail)
  • Hot sheets (sheet.hot)
  • Sheet list (sheet.list)

Theme

  • Get theme music (theme.music)
  • Get theme music detail (theme.musicDetail)
  • Get theme playlists (theme.playlist)
  • Get theme playlist tracks (theme.playlistTrack)

Misc

  • Get artist list (misc.singerList)
  • New songs (misc.latestSongs)
  • Get server time (misc.serverNow)
  • Get privilege info (misc.privilegeLite)
  • Shuffle recommend (misc.brush)
  • Register device (misc.registerDev)
  • Send captcha (captcha_sent)
  • PC radio (misc.pcDiantai)
  • AI recommend (ai_recommend)

Youth Channel

  • Get all user channels (youth.channelAll)
  • Channel recommend (youth.channelAmway)
  • Channel detail (youth.channelDetail)
  • Similar channels (youth.channelSimilar)
  • Channel subscribe (youth.channelSubscribe)
  • Channel music story (youth.channelSong)
  • Channel music story detail (youth.channelSongDetail)
  • Claim VIP (youth.dayVip)
  • VIP upgrade (youth.dayVipUpgrade)
  • Dynamic (youth.dynamic$)
  • Recent dynamic (youth.dynamicRecent)
  • Listen song (youth.listenSong)
  • Monthly VIP record (youth.monthVipRecord)
  • Union VIP (youth.unionVip)
  • VIP (youth.vip)
  • User song (youth.userSong)

Audio Extension

  • Accompaniment matching (audio_accompany_matching)
  • KTV count (audio_ktv_total)
  • Related audio (audio_related)

Signature Algorithm

This library includes six KuGou API signature/encryption algorithms:

  • Android Signature - Default algorithm using Android client salt
  • Web Signature - Web algorithm for QR code login etc.
  • Register Signature - Register-specific algorithm
  • Playlist AES Encrypt/Decrypt - AES-CBC with 6-char random key, base64 I/O
  • RSA Encrypt 2 - RSA with PKCS1 v1.5 padding
  • SHA1 Hash - SHA1 hash function

POST request signatures automatically include the request body (JSON encoded) in the signature calculation.

Known Limitations

  • Some endpoints require login (e.g., IpApi.zoneHome), use CookieJar to pass initial cookies or login first
  • CookieJar does not include file persistence, users should save serialize() output themselves

Disclaimer

  1. This project is for learning purposes only. Please respect copyright and do not use this project for commercial or illegal purposes!
  2. This project may generate copyrighted data during use. The project does not own the copyright of such data. To avoid infringement, users must clear any copyrighted data generated within 24 hours.
  3. The user is responsible for any direct, indirect, special, incidental, or consequential damages arising from the use of this project.
  4. Do not use this project in violation of local laws and regulations. The user bears full responsibility for any violations.
  5. Music platforms work hard - please respect copyright and support legitimate sources.
  6. This project is for technical feasibility exploration only and does not accept any commercial cooperation or donations.
  7. If the official music platform finds this project inappropriate, please contact to have it modified or removed.

License

BSD 3-Clause "New" or "Revised" License

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages