Skip to content

Commit

Permalink
added Deezer support
Browse files Browse the repository at this point in the history
  • Loading branch information
artyshko committed Mar 16, 2019
1 parent f7d9325 commit f1b1a4c
Show file tree
Hide file tree
Showing 3 changed files with 211 additions and 1 deletion.
73 changes: 73 additions & 0 deletions deezer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import requests

class Deezer(object):

def __init__(self):

'''
Init function
Creating deezer object
:return: None
'''

self.__url = 'http://api.deezer.com/'


def getSongInfo(self, id):

try:

response = requests.get(f'{self.__url}/track/{id}').json()

return ({
'uri' : f"D{response['id']}T",
'name' : response['title'],
'artist' : [response['artist']['name']],
'album' : response['album']['title'],
'image' : response['album']['cover_xl'],
'duration_ms' : response['duration']
})

except: return None

def getAlbum(self, id):

try:

response = requests.get(f'{self.__url}/album/{id}').json()

alb = {
'name':response['title'],
'artist':response['artist']['name'],
'copyright': None,
'image':response['cover_xl'],
}

tracks = []

for item in response['tracks']['data']:

tracks.append({
'uri' : f"D{item['id']}T",
'name' : item['title'],
'artist' : [item['artist']['name']],
'album' : alb['name'],
'image' : alb['image'],
'preview_url' : item['preview'],
'duration_ms' : item['duration']
})

alb.setdefault(
'tracks', tracks
)

return alb

except: return None

if __name__ == '__main__':

deezer = Deezer()
data = deezer.getSongInfo('636758392')

print(data)
63 changes: 63 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from youtube import Youtube
from editor import TagEditor
from lastfm import LastFM
from deezer import Deezer
import sys, getopt, shutil
import os

Expand All @@ -22,6 +23,7 @@ def __init__(self):
self.__spotify = Spotify()
self.__editor = TagEditor()
self.__last = LastFM()
self.__deezer = Deezer()


def __downloadMusicFromYoutube(self, name, uri, dur):
Expand Down Expand Up @@ -59,6 +61,9 @@ def getData(self, uri):
def getLastFMTags(self, name):
return self.__last.get(name)

def getDeezerTags(self, id):
return self.__deezer.getSongInfo(id)

def getYoutubeMusicInfo(self, url):
return self.__youtube.getNameFromYoutube(url)

Expand Down Expand Up @@ -302,12 +307,70 @@ def downloadFromYoutubeMusic(self, url, info):
else:
return False, None

def downloadByDeezerID(self, uri):
#get info
info = self.__deezer.getSongInfo(uri)

if info:

fixed_name = f'{info["artist"][0]} - {info["name"]}'
fixed_name = fixed_name.replace('.','')
fixed_name = fixed_name.replace(',','')
fixed_name = fixed_name.replace("'",'')
fixed_name = fixed_name.replace("/","")

#finding and download from YouTube and tagging
if self.__downloadMusicFromYoutube(fixed_name, info['uri'], info['duration_ms']):

self.__editor.setTags(
data=info
)

cachepath = os.getcwd() + '/cache'
fullpath = os.getcwd() + '/Downloads'

#logging
logging.info(f'CACHEPATH {cachepath}')
logging.info(f'FULLPATH {fullpath}')

if not os.path.exists(fullpath):
os.makedirs(fullpath)

os.rename(
f"{cachepath}/{info['uri']}/{info['uri']}.png",
f"{fullpath}/{info['uri']}.png"
)
#logging
logging.info(f"MOVE TO Downloads/{info['uri']}.png")

os.rename(
f"{cachepath}/{info['uri']}/{info['uri']}.mp3",
f"{fullpath}/{info['uri']}.mp3"
)
#logging
logging.info(f"MOVE TO Downloads/{info['uri']}.mp3")

#deleting cache
try:
shutil.rmtree(f"cache/{info['uri']}")
#logging
logging.info(f"DELETED cache/{info['uri']}")
except:
#logging
logging.error(f"DELETING cache/{info['uri']}")

return True
return False

def search(self, query):
return self.__spotify.search(query=query)

def getAlbum(self, uri):
return self.__spotify.getAlbum(uri)

def getAlbumDeezer(self, id):
return self.__deezer.getAlbum(id)



class CLI(object):
Expand Down
76 changes: 75 additions & 1 deletion telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def DL_SPOTIFY_ALBUM(self, message, user):

for data, i in zip(album['tracks'], range(count)):
#logging
logging.info(f'ALBUM {i+1}/{count} | {data["artist"][0]} - {data["name"]}')
logging.info(f'S-ALBUM {i+1}/{count} | {data["artist"][0]} - {data["name"]}')

if self.downloader.downloadBySpotifyUri(data['uri']):

Expand Down Expand Up @@ -390,6 +390,41 @@ def DL_YOUTUBE_MUSIC(self, message, user):

return True

def DL_DEEZER_ALBUM(self, message, user):

uri = message

data = self.downloader.getAlbumDeezer(uri)
path = f"Downloads/{uri}.png"


downloadAlbumImage(data['image'], path)
logging.info(f'Downloaded {path}')

self.bot.sendPhoto(
chat_id=user,
photo=open(path,'rb'),
text=f'Album <b>{data["name"]}</b> by <b>{data["artist"]}</b>'
)

logging.info(f'Sended {path}')
album = data
count = len(album['tracks'])

for data, i in zip(album['tracks'], range(count)):
#logging
logging.info(f'D-ALBUM {i+1}/{count} | {data["artist"][0]} - {data["name"]}')

if self.downloader.downloadByDeezerID(str(data['uri'][1:-1])):

self.sendSong(data=data, user=user)

os.remove(path)
#logging
logging.info(f'DELETED {path}')

return True


def sendSong(self, data, user):

Expand Down Expand Up @@ -489,6 +524,12 @@ def classify(self, message):
elif str(message) == '/status':
return 'status'

elif str(message).find('deezer.com/track/') > 0:
return 'dtrack'

elif str(message).find('deezer.com/album/') > 0:
return 'dalbum'

else:
return 'text'

Expand Down Expand Up @@ -577,6 +618,39 @@ def controller(self, message, id):

return self.DL_QUERY(message, user=id)

elif type == 'dtrack':

#logging
logging.info(f'DEEZER TRACK DETECTED')

track = str(str(message).split('/track/')[1]).split('?')[0]
data = self.downloader.getDeezerTags(track)

if data:

#logging
logging.info(f'SONG {data["artist"][0]} - {data["name"]}')

if self.downloader.downloadByDeezerID(track):

return self.sendSong(data=data, user=id)

else:

#logging
logging.error(f'SENDED "Something went wrong" MESSAGE')
self.bot.sendSticker(id,sticker=open(f"Data/s3.webp",'rb'),)
self.bot.sendText(id,text='Couldn\'t find that:(')

return False

elif type == 'dalbum':

#logging
logging.info(f'DEEZER ALBUM DETECTED')
album = str(str(message).split('album/')[1]).split('?')[0]

return self.DL_DEEZER_ALBUM(album, id)

elif type == 'link':

Expand Down

0 comments on commit f1b1a4c

Please sign in to comment.