1.0.0 • Published 2 years ago

@soundhub/soundhub_vk v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

SoundHub AudioAPI

An unofficial Audio API for VK.COM. This npm module using as part in SoundHub project.

Installation

Install VK-IO via npm or yarn

yarn add vk-io
// or
npm install vk-io

Install SoundHub VK Audio API package

yarn add soundhub_vk
// or
npm install soundhub_vk

Getting Started

Do auth with VK-IO

const { VK } = require("vk-io");
const VKClient = new VK({ token: "xxxxxxxxxxx" });

Create an API

const credits = {
    username: "xxxxxxxxxxx",
    password: "xxxxxxxxxxx",
    user:     "xxxxxxxxxxx" // Your user_id
};

const AudioAPI = require("soundhub_vk");
const API = await new AudioHTTP(VKClient).login(credits);

You awesome!!

Full example

const credits = {
    username: "xxxxxxxxxxx",
    password: "xxxxxxxxxxx",
    token:    "xxxxxxxxxxx",
    user:     "xxxxxxxxxxx" // Your user_id
};

const { VK } = require("vk-io");
const AudioAPI = require("soundhub_vk");

const run = async () => {
    const VKClient = new VK({ token: credits.token });
    const API = await new AudioAPI(VKClient).login(credits);

    const { audios: my_audios, count } = await API.audio.getAll();
    console.log(my_audios);
    console.log(`Wow, I have ${count} audio!`);
};

run();

Usage

The API splitted into 5 parts: audio, playlists, search, artists, recommendations. To use each of this you must to specify part which you would to use. Example:

const { audios } = await API.audio.get();
const { playlists } = await API.playlists.get();
const search = await API.search.query("Queen");
const artsits = await API.artists.get("Queen");
const recommendations = await API.recoms.loadRecoms();
const explore = await API.recoms.loadExplore();

Recommendation for optimizing the requests

Each URL storing separately from audio object and needs to single request (10 audios per request). This is increased time of request and flooding to vk servers. To avoid this, read below.

I highly recomends you to set in parameters of each function fetching raw audio object. This returns audio full audio objects with "raw" array, but without URL's. Then you can use audio.fetch(raw) in any time. This method allows you to reduce the request time (1300ms -> 300ms average, you can check tests manually) and avoid flooding to vk servers. Here is another example:

const { audios } = await API.audio.get({ raw: true });
const [full] = await API.audio.parse([audio[0].raw]);

/*
    A certain scientific PlayMusicLogic(full)
*/

Play .m3u8 files with hls.js

VK uses .m3u8 file formats for music. So you can use hls.js package to play it.

Example:

const Hls = require("hls.js");

const sound = new Audio();
const hls = new Hls();

const { audios } = await API.audio.get({ raw: true });
const parsed = await API.audio.parse([audio[0].raw]);

hls.attachMedia(sound);
hls.on(hlsjs.Events.MEDIA_ATTACHED, hls.loadSource(parsed[0].url));

sound.addEventListener("canplaythrough", () => sound.play());

Downloading audio (Breaking Change from 1.2.0)

Also you can fetch .m3u8 links manually using ffmpeg. See example:

import AudioAPIHLS from "soundhub_vk/lib/hls";

const { audios } = await API.audio.get();

const instance = new AudioAPIHLS(params?);

// Events
instance.once("processing", () => console.log("Start processing..."));
instance.on("progress", progress => console.log(progress));

const output = await instance.download(audios[0].url, ffmpegPath, outputPath);

Params object:

params = {
    name: string, // name of output file (default: name of first chunk's file)
    chunksFolder: string, // folder to store downloaded chunks. Chunks deletes automatically after processing (default: "hls")
    delete: boolean, // resolve buffer and delete output file (default: false)
    concurrency: Number // number of parallel downloadings (default: 5)
};

Now let's see each part.

Audio

FunctionParamsDescription
getowner_id?playlist_id?access_hash?count?Returns the list of first %count% audios
getCountowner_id?playlist_id?access_hash?Returns a count audios of user/community
getFromWallowner_idpost_idReturns the list of audios from wall post
addAudio objectAdd audio in "My Audios"
deleteAudio objectDelete audio from "My Audios"
editAudio objectparamsEdit the audio file if it available. In params you can to specify fields: title?: string, performer?: string, privacy?: number
reorderaudio_idnext_audio_idowner_id?Reorder audios in playlist
uploadpathUpload audio file
parsearray of audiosFetch full audio objects (with URL, etc.)

Playlists

FunctionParamsDescription
getaccess_hash?offset?owner_id?Returns the list of first playlists by offset
getPlaylistowner_idplaylist_idlist?access_hash?Return a single playlist object. Boolean list meaning parsing audios in playlist, but it takes a longer time. access_hash forces list = true automatically if you want to load third-party playlists (general page or search for example)
getByIdowner_idplaylist_idlist?access_hash?count?The same asgetPlaylist(), but better for getting of user/community playlists. You can to specify count in params to splice audios in list for faster loading
getCountowner_id?Return the count of playlists of user/community
getByBlockblocksection?Return playlists by block and section
getFromWallowner_id?playlist_idFetching playlist from wall
createtitledescription?cover?Create new playlist.Cover must be a path to cover file
editplaylist_idtitle?description?cover?Edit the existing playlist
deletePlaylist objectDelete playlist
followPlaylist objectFollow playlist
reorderplaylist_idprev_playlist_idReorder playlists
addSongAudio objectPlaylist objectAdd song to playlist
removeSongAudio objectPlaylist objectRemove song from playlist
followPlaylist objectFollow playlist
reorderSongsAudiosplaylist_idforce?Reorder songs in playlist.Audios: string (it must be string of full_ids, you can use join() for example, see example in unit-tests)force saving you from full cleaning of playlist if you make mistake with Audios string. If you really wish to clean playlist you must to specify force: true

Search

Pay your attention to more object!

more object is a object that contain information for continuing searching. You can't load more results without this object.

FunctionParamsDescription
queryqReturns the artists, playlists, audios andmore object by query
withMoremore objectReturns more results bymore object
hintsqReturn search hints
inAudiosqowner_idcount?Returns a list of finded audios of user/community

Artists

FunctionArgumentsDescription
getartistparams?Get artist page. Returns the popular audios, playlists collections, similar artists.artist param must be an endpoint, not full name. You can get endpoint at link field of search.query for example. You can specify list: false in params to fetch artist information only
collectionslinkParse collections inside collections page
similarartistGet similar artists

You can see how to get full list of audio or playlists of artist in jest testing file.

Recommendations

FunctionParamsDescription
loadExplore-Load full explore page
loadRecoms-Load full recoms page
collections-Returns the collections offering by VK
newAlbums-Returns the new albums
artists-Returns the daily recommendation artists
releases-Returns the list of audios of new releases
chart-Returns the list of VK Chart
officialPlaylists-Returns the list of official collections of playlists splitted to categories
dailycount?Returns the list of daily audios
weeklycount?Returns the list of weekly audios

The explore and recoms sections caching and updating every hour itself for make loading faster.

Contribution

You can feel free to open issues tickets or PR to help me with this API.

Conclusion

You can check jest tests to check more functional or see examples.