Exemple #1
0
def YTMusicScrobble(ytmusic: YTMusic, connectionString: str,
                    user: str) -> None:
    mongoClient = MongoClient(connectionString)
    db = mongoClient['scrobble']
    scrobblerData = {
        "scrobblerId": '607f962eeafb5500062a4a68',
        "scrobblerUser": "******",
        "queuedRequests": [],
        "requestAttempts": 0
    }

    lastScrobbles = db['scrobbles'].find(
        {
            "user": scrobblerData['scrobblerUser']
        }, projection={
            "videoId": 1
        }).sort("time", DESCENDING).limit(1)
    lastScrobbleIds = [scrobble['videoId'] for scrobble in lastScrobbles]
    for i in range(4):
        ytmusicHistory = ytmusic.get_history()
        if len(ytmusicHistory) == 0:
            return
        historyVideoIds = [track['videoId'] for track in ytmusicHistory]
        matchStartIndex = len(historyVideoIds)
        endIndex = len(lastScrobbleIds)
        for i in range(len(historyVideoIds)):
            historySublist = historyVideoIds[i:i + endIndex]
            lastScrobbleSublist = lastScrobbleIds[0:len(historySublist)]
            if historySublist == lastScrobbleSublist:
                matchStartIndex = i
                break
        if matchStartIndex < 1:
            return
        elif matchStartIndex < 2:
            break
        else:
            print(f"Large number of scrobbles: {matchStartIndex}")
    # because ytmusic is so inconsistent with how they report history,
    # sometimes songs just disappear and we get the whole 200 songs in the
    # history at onces. So, if the length equals 200, just get the last song
    matchStartIndex = 1 if matchStartIndex == 200 else matchStartIndex
    location = None
    for i in reversed(range(matchStartIndex)):
        request = BuildRequest(ytmusicHistory[i], user)
        scrobbleId = PostScrobble(db, request)
        if scrobbleId:
            if location is None:
                location = GetLocationFromHomeAssistant(
                    homeassistantUrl,
                    homeassistantToken,
                    "person.michael",
                )
            ScrobbleAddLocation(db['scrobbles'], scrobbleId, location)
            LinkScrobblerSong(ytmusic, db, scrobbleId)
            print(f"{datetime.now().isoformat()}  Posted Scrobble")
    return
Exemple #2
0
def ytm_plsearch():
    cursor = db_connect()
    ytmusic = YTMusic('ytm_auth.json')

    term = request.form.get("term")

    recently_played = None
    results = None
    if term is None:
        try:
            recently_played = ytmusic.get_history()
            recently_played = ytm_attach_playlists(recently_played, cursor)
        except KeyError as ex:
            ex_type, ex_value, ex_trace = sys.exc_info()
            flash(
                "Failed to retrieve history: KeyError: " + str(ex) + "\n" +
                ("".join(
                    traceback.format_exception(ex_type, ex_value, ex_trace))),
                "error")
    else:
        sql = """
            SELECT DISTINCT ytm_playlist_entries.entry_name, ytm_playlist_entries.duration, 
                ytm_playlist_entries.artist_name, ytm_playlist_entries.album_name,
                ytm_playlist_entries.ytm_videoid AS videoId
            FROM ytm_playlist_entries
            LEFT JOIN ytm_playlists ON ytm_playlist_entries.ytm_playlistid = ytm_playlists.ytm_playlistid
            WHERE ytm_playlist_entries.deleted = 0
                AND ytm_playlists.deleted = 0
                AND (
                    ytm_playlist_entries.entry_name LIKE CONCAT('%%', %(term)s, '%%')
                    OR ytm_playlist_entries.artist_name LIKE CONCAT('%%', %(term)s, '%%')
                    OR ytm_playlist_entries.album_name LIKE CONCAT('%%', %(term)s, '%%')
                )
            ORDER BY ytm_playlist_entries.artist_name ASC, 
                ytm_playlist_entries.entry_name ASC, 
                ytm_playlist_entries.album_name ASC
        """
        params = {
            "term": term,
        }
        cursor.execute(sql, params)
        results = cursor.fetchall()
        results = ytm_attach_playlists(results, cursor)

    return render_template("ytm/plsearch.html",
                           history=recently_played,
                           results=results,
                           term=term,
                           ytm_list_artist_names=ytm_list_artist_names)
Exemple #3
0
while True:
    history = {}
    updatedHistory = {}
    setVariables = {}

    try:
        scrobblerInfo = db['scrobblers'].find_one({
            "name": "ytmusic history scrobbler",
            "user": scrobblerUser
        })
        history = scrobblerInfo['videoIds']
    except:
        print("Initializing data")

    if not history:
        updatedHistory = ytmusic.get_history()
        setVariables[videoIds] = [item['videoId'] for item in updatedHistory]

    else:
        try:
            requestsReady = False
            while not requestsReady:
                updatedHistory = ytmusic.get_history()
                updatedHistory, newRequests = GetLatestHistory(
                    updatedHistory, history, scrobblerUser,
                    GetLocationFromHomeAssistant(homeassistantUrl,
                                                 homeassistantToken,
                                                 "person.michael"))
                if len(newRequests) > 2 and requestAttempts < 4:
                    print(datetime.now().isoformat())
                    # print("<<< Too many requests! DUMP")
Exemple #4
0
import pylast
import datetime
import time
import json
from strsimpy.jaro_winkler import JaroWinkler

if not os.path.isdir('./logs'):
    os.mkdir('./logs')

logger = open(
    './logs/log_{}.txt'.format(datetime.datetime.now().strftime('%F')), 'a+')
logger.write('%s\n' % datetime.datetime.now())

############### YTM ###############
ytmusic = YTMusic('headers_auth.json')
history = ytmusic.get_history()
# print(history[0])

title = history[0]['title']
artist = history[0]['artists'][0]['name']
liked = history[0]['likeStatus'] == 'LIKE'

try:
    album = history[0]['album']['name']
except TypeError:
    logger.write('   ATTN: Album is not set\n')

logger.write('   YTM: Last song was %s by %s\n' % (title, artist))

############### LAST FM ###########
with open('logindata.json', 'r') as f: