UNPKG

use-last-fm

Version:

Stream your current playing song from last.fm as a React hook.

88 lines (71 loc) 2.16 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var useSWR = _interopDefault(require('swr')); function parseSong(body, imageSize) { var _body$recenttracks$tr, _lastSong$Attr, _image$Text; if (!body) { return { status: 'connecting', song: null }; } var lastSong = (_body$recenttracks$tr = body.recenttracks.track) == null ? void 0 : _body$recenttracks$tr[0]; if (!lastSong || !((_lastSong$Attr = lastSong['@attr']) == null ? void 0 : _lastSong$Attr.nowplaying)) { return { status: 'idle', song: null }; } var image = lastSong.image.find(function (i) { return i.size === imageSize; }); return { status: 'playing', song: { name: lastSong.name, artist: lastSong.artist['#text'], art: (_image$Text = image == null ? void 0 : image['#text']) != null ? _image$Text : lastSong.image[0]['#text'], url: lastSong.url, album: lastSong.album['#text'] } }; } /** * Use Last.fm * @param username The username of the last.fm user to track * @param token Your API token * @param interval Optional, this is the interval between each request * @param imageSize The size of the image */ function useLastFM(username, token, interval, imageSize) { if (interval === void 0) { interval = 15 * 1000; } if (imageSize === void 0) { imageSize = 'extralarge'; } var endpoint = "//ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + username + "&api_key=" + token + "&format=json&limit=1"; var _useSWR = useSWR(endpoint, { refreshInterval: interval }), _useSWR$data = _useSWR.data, track = _useSWR$data === void 0 ? null : _useSWR$data, error = _useSWR.error; if (error) { return { status: 'error', song: null }; } try { return parseSong(track, imageSize); } catch (e) { return { status: 'error', song: null }; } } exports.useLastFM = useLastFM; //# sourceMappingURL=use-last-fm.cjs.development.js.map