Skip to content

types.py

This module contains all available type classes.

Album dataclass ¤

The Album class contains several information about an album.

Attributes:

Name Type Description
artist

The main artist of the album.

basic_tracks_data

A list that contains basic tracks data.

duration

The duration in seconds of the album.

genres

A list of genres of the album.

id

int The ID of the album.

label

The label of the album.

link

The Deezer link of the album.

record_type

The record type of the album.

release_date

The release date of the album.

title

The title of the album.

total_tracks

The total number of tracks in the album.

upc

The Universal Product Code (UPC) of the album.

download_cover(self, size: int = 250, quality: int = 80) -> bytes async ¤

Downloads the album cover.

Parameters:

Name Type Description Default
size int

The size of the album cover in pixels (should not exceed 1200).

250
quality int

The quality of the album cover (should be between 0 and 100).

80
Source code in deethon/types.py
async def download_cover(self, size: int = 250, quality: int = 80) -> bytes:
    """
    Downloads the album cover.

    Args:
        size: The size of the album cover in pixels (should not exceed 1200).
        quality: The quality of the album cover (should be between 0 and 100).
    """
    cover_url = self.get_cover_url(size, quality)
    response = await self._session._http.get(cover_url)
    return await response.read()

fetch(session: Session, album_id: int) -> Album async staticmethod ¤

Create a new album instance with the specified album ID.

Parameters:

Name Type Description Default
session Session

A Session instance.

required
album_id int

The Deezer album ID.

required

Exceptions:

Type Description
DeezerApiError

The Deezer API request replied with an error.

Source code in deethon/types.py
@staticmethod
async def fetch(session: Session, album_id: int) -> Album:
    """
    Create a new album instance with the specified album ID.

    Args:
        session: A [Session][deethon.session.Session] instance.
        album_id: The Deezer album ID.

    Raises:
        DeezerApiError: The Deezer API request replied with an error.

    """
    if album_id in _ALBUMS_CACHE:
        return _ALBUMS_CACHE[album_id]
    response = await session._http.get(f"http://api.deezer.com/album/{album_id}", proxy=session._proxy)
    r = await response.json()
    if "error" in r:
        raise errors.DeezerApiError(r["error"]["type"],
                                    r["error"]["message"],
                                    r["error"]["code"])

    album = Album(
        artist=Artist(
            id=r["artist"]["id"],
            name=r["artist"]["name"]
        ),
        basic_tracks_data=r["tracks"]["data"],
        duration=r["duration"],
        genres=[genre["name"] for genre in r["genres"]["data"]],
        id=r["id"],
        label=r["label"],
        link=r["link"],
        md5_image=r["md5_image"],
        record_type=r["record_type"],
        release_date=datetime.strptime(r["release_date"], "%Y-%m-%d"),
        title=r["title"],
        total_tracks=r["nb_tracks"],
        upc=r["upc"],
        _session=session
    )

    _ALBUMS_CACHE[album_id] = album
    return album

get_cover_url(self, size: int = 250, quality: int = 80) -> str ¤

Get the URL of the album cover.

Parameters:

Name Type Description Default
size int

The size of the album cover in pixels (should not exceed 1200).

250
quality int

The quality of the album cover (should be between 0 and 100).

80
Source code in deethon/types.py
def get_cover_url(self, size: int = 250, quality: int = 80) -> str:
    """
    Get the URL of the album cover.

    Args:
        size: The size of the album cover in pixels (should not exceed 1200).
        quality: The quality of the album cover (should be between 0 and 100).
    """
    return f"http://cdn-images.dzcdn.net/images/cover/{self.md5_image}/{size}x{size}-000000-{quality}-0-0.jpg"

Artist dataclass ¤

The Album class contains several information about an album.

Attributes:

Name Type Description
id int

The Deezer id of the artist.

name str

The name of the artist.

Quality ¤

An enumeration.

Track dataclass ¤

The Track class contains several information about a track.

Attributes:

Name Type Description
album Album

The album to which the track belongs in short format.

artist Artist

The main artist of the track.

artists list

A list of artists featured in the track.

bpm int

Beats per minute of the track.

disk_number int

The disc number of the track.

duration int

The duration of the track.

id int

The Deezer ID of the track.

isrc str

The International Standard Recording Code (ISRC) of the track.

link str

The Deezer link of the track.

number int

The position of the track.

preview_link str

The link to a 30 second preview of the track.

rank int

The rank of the track on Deezer

replaygain_track_gain str

The Replay Gain value of the track.

release_date datetime

The release date of the track.

title str

The title of the track.

title_short str

The short title of the track.

md5_origin str

The md5 origin of the track.

media_version str

The media version of the track.

composer Optional[list[str]]

The author of the track.

author Optional[list[str]]

A list of one or more authors of the track.

lyrics Optional[str]

The lyrics of the track.

lyrics_sync Optional[list[dict[str, str]]]

The synchronized lyrics of the track.

lyrics_copyrights Optional[str]

Copyright information of the lyrics.

lyrics_writers Optional[list[str]]

A list of writers of the lyrics.

fetch(session: Session, track_id: int) -> Track async staticmethod ¤

Create a new track instance with the specified track ID.

Parameters:

Name Type Description Default
session Session

A Session instance.

required
track_id int

The Deezer track ID.

required

Exceptions:

Type Description
DeezerApiError

The Deezer API request replied with an error.

Source code in deethon/types.py
@staticmethod
async def fetch(session: Session, track_id: int) -> Track:
    """
    Create a new track instance with the specified track ID.

    Args:
        session: A [Session][deethon.session.Session] instance.
        track_id: The Deezer track ID.

    Raises:
        DeezerApiError: The Deezer API request replied with an error.

    """
    if track_id in _TRACKS_CACHE:
        return _TRACKS_CACHE[track_id]

    response = await session._http.get(f"http://api.deezer.com/track/{track_id}", proxy=session._proxy)
    r = await response.json()
    if "error" in r:
        raise errors.DeezerApiError(r["error"]["type"],
                                    r["error"]["message"],
                                    r["error"]["code"])

    s = await session._get_api(
        consts.METHOD_PAGE_TRACK, {"sng_id": track_id}
    )
    md5_origin = s["DATA"]["MD5_ORIGIN"]
    media_version = s["DATA"]["MEDIA_VERSION"]

    if isinstance(s["DATA"]["SNG_CONTRIBUTORS"], list):
        composer = None
        author = None
    else:
        composer = s["DATA"]["SNG_CONTRIBUTORS"].get("composer")
        author = s["DATA"]["SNG_CONTRIBUTORS"].get("author")

    copyright = s["DATA"]["COPYRIGHT"]

    if "LYRICS" in r.keys():
        lyrics = s["LYRICS"].get('LYRICS_TEXT')
        lyrics_sync = s["LYRICS"].get('LYRICS_SYNC_JSON')
        lyrics_copyrights = s["LYRICS"].get('LYRICS_COPYRIGHTS')
        lyrics_writers = s["LYRICS"].get('LYRICS_WRITERS').split(', ')
    else:
        lyrics = None
        lyrics_sync = None
        lyrics_copyrights = None
        lyrics_writers = None

    track = Track(
        album=await Album.fetch(session, r["album"]["id"]),
        artist=Artist(r["artist"]["id"], r["artist"]["name"]),
        artists=[Artist(artist["id"], artist["name"])
                 for artist in r['contributors']],
        bpm=r["bpm"],
        disk_number=r["disk_number"],
        duration=r["duration"],
        id=r["id"],
        isrc=r["isrc"],
        link=r["link"],
        number=r["track_position"],
        preview_link=r["preview"],
        rank=r["rank"],
        replaygain_track_gain=f"{((r['gain'] + 18.4) * -1):.2f} dB",
        release_date=datetime.strptime(r["release_date"], "%Y-%m-%d"),
        title=r["title"],
        title_short=r["title_short"],
        md5_origin=md5_origin,
        media_version=media_version,
        copyright=copyright,
        composer=composer,
        author=author,
        lyrics=lyrics,
        lyrics_sync=lyrics_sync,
        lyrics_copyrights=lyrics_copyrights,
        lyrics_writers=lyrics_writers
    )

    _TRACKS_CACHE[track.id] = track
    return track

get_stream_url(self, quality: Quality) -> str ¤

Get the direct download url of the track.

Parameters:

Name Type Description Default
quality Quality

The preferred quality.

required

Returns:

Type Description
str

The direct download url.

Source code in deethon/types.py
def get_stream_url(self, quality: Quality) -> str:
    """
    Get the direct download url of the track.

    Args:
        quality: The preferred quality.

    Returns:
        The direct download url.
    """

    data = b"\xa4".join(
        a.encode() for a in [self.md5_origin, quality.value,
                             str(self.id), self.media_version]
    )
    data = b"\xa4".join(
        [md5(data).hexdigest().encode(), data]) + b"\xa4"
    if len(data) % 16:
        data += b"\x00" * (16 - len(data) % 16)
    c = AES.new(b"jo6aey6haid2Teih", AES.MODE_ECB)
    hashs = b2a_hex(c.encrypt(data)).decode()
    return f"http://e-cdn-proxy-{self.md5_origin[0]}.dzcdn.net/api/1/{hashs}"