예제 #1
0
def playlistSongsChecker(user, once=0):
    update_status(user, "statusPlaylist", 0)
    time.sleep(15)
    previousDay = ""
    status = database.user_status(user)
    while(status == 1):
        global KILL
        if (KILL.get(user+"playlistSongThread", 0) == 1):
            del KILL[str(user)+"playlistSongThread"]
            break
        update_status(user, "statusPlaylist", 2)
        utc_time = datetime.now()
        local_time = utc_time.astimezone()
        lastUpdated = local_time.strftime("%Y-%m-%d")
        if previousDay != lastUpdated:
            with connection.cursor() as cursor:
                playlists = database.get_playlists(user)
                count = 0
                for playlist in playlists:
                    playlistSongs.main(user, playlist)
                    count = count + 1
                if(count == 0):
                    update_status(user, "statusPlaylist", 0)
                    return
                if(once == 1):
                    update_status(user, "statusPlaylist", 1)
                    return
            previousDay = lastUpdated
            update_status(user, "statusPlaylist", 1)
            time.sleep(3600)
        update_status(user, "statusPlaylist", 1)
        time.sleep(360)
        status = database.user_status(user)
    update_status(user, "statusPlaylist", 0)
예제 #2
0
def songIdUpdaterChecker(user, once=0):
    previousDay = ""
    status = database.user_status(user)
    time.sleep(15)
    while(status == 1):
        global KILL
        if (KILL.get(user+"songIdUpdaterThread", 0) == 1):
            del KILL[str(user)+"songIdUpdaterThread"]
            break
        time.sleep(300)
        utc_time = datetime.now()
        local_time = utc_time.astimezone()
        lastUpdated = local_time.strftime("%Y-%m-%d")
        if previousDay != lastUpdated:
            changeHistory = songIdUpdater(user)
            if changeHistory:
                log.info(str(changeHistory))
            if(once == 1):
                return
            previousDay = lastUpdated
            time.sleep(5000)
        time.sleep(500)
        status = database.user_status(user)
def start(request):
    spotifyID = request.session.get('spotify', False)
    if (spotifyID == False):
        return HttpResponse(status=401)
    with connection.cursor() as cursor:
        cursor.execute("UPDATE users SET enabled = 1 where user ='******'")
        user = database.user_status(spotifyID, 1)
        if (user[2] == 0):
            spotify.SpotifyThread(user)
            spotify.songIdUpdaterThread(user)
        if (user[3] == 0):
            spotify.playlistSongThread(spotifyID[0])

    url = '<meta http-equiv="Refresh" content="0; url=/spotify/analytics.html" />'
    return HttpResponse(url, content_type="text/html")
def playlistSubmission(request):
    spotifyID = request.session.get('spotify', False)
    if (spotifyID == False):
        return HttpResponse(status=401)
    response = ""
    try:
        playlist = request.POST.get("playlist")
        playlist = playlist.split("playlist/")[1].split("?")[0]
        url = 'https://api.spotify.com/v1/playlists/' + playlist + "?market=US"
        header = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": "Bearer " + credentials.refresh_token(spotifyID)
        }
        response = requests.get(url, headers=header).json()
        if (not response.get("href", False)):
            return HttpResponse(status=400)
    except:
        return HttpResponse(status=401)

    add = ("INSERT IGNORE INTO playlists"
           "(playlistID, name, lastUpdated)"
           "VALUES (%s, %s, %s)")
    data = (
        playlist,
        response.get('name'),
        "N/A",
    )
    cursor = connection.cursor()
    cursor.execute(add, data)
    add = ("INSERT IGNORE INTO playlistsUsers"
           "(user, playlistID)"
           "VALUES (%s, %s)")
    data = (
        spotifyID,
        playlist,
    )
    cursor.execute(add, data)
    status = database.user_status(spotifyID, 1)
    if (status[3] > 0):
        spotify.playlistSongThread(spotifyID, 1)
    else:
        spotify.playlistSongThread(spotifyID)
    url = '<meta http-equiv="Refresh" content="0; url=/spotify/analytics.html" />'
    return HttpResponse(url, content_type="text/html")
예제 #5
0
def realTimeSpotify(user, hybrid):
    try:
        update_status(user, "statusSong", 0)
        time.sleep(10)
        status = database.user_status(user)
        if (status != 1):
            return
        url = 'https://api.spotify.com/v1/me/player/currently-playing?market=US'
        header = {"Accept": "application/json",
                  "Content-Type": "application/json", "Authorization": "Bearer " + authorize(user)}
        previous = " "
        while(status == 1):
            workerCount = database.scanWorkers(WORKER)
            killThreads(workerCount, user)
            global KILL
            if (KILL.get(user+"SpotifyThread", 0) == 1):
                del KILL[str(user)+"SpotifyThread"]
                break
            update_status(user, "statusSong", 2)
            try:
                response = requests.get(url, headers=header)
                if("the access token expired" in str.lower(response.text)):
                    header = {"Accept": "application/json",
                              "Content-Type": "application/json", "Authorization": "Bearer " + authorize(user)}
                    response = requests.get(url, headers=header)
                elif("no content" in str.lower(response.reason)):
                    log.debug("Nothing is Playing: " + str(user))
                    update_status(user, "statusSong", 1)
                    time.sleep(60)
                elif(response.json().get("is_playing") and
                     "ad" in str.lower(response.json().get("currently_playing_type", "false"))):
                    log.debug("Ignoring Ad: " + str(user))
                    update_status(user, "statusSong", 1)
                    time.sleep(30)
                elif(response.json().get("is_playing") and
                     "episode" in str.lower(response.json().get("currently_playing_type", "false"))):
                    log.debug("Ignoring Podcast: " + str(user))
                    update_status(user, "statusSong", 1)
                    time.sleep(90)
                elif(response.json().get("is_playing") and
                     "unknown" in str.lower(response.json().get("currently_playing_type", "false"))):
                    log.warning("Unknown Error: " +
                                str(user) + " : " + str(response.json()))
                    update_status(user, "statusSong", 1)
                    time.sleep(45)
                else:
                    response = response.json()
                    if(response.get("is_playing")):
                        if(response.get("item").get("is_local") == False and hybrid == True):
                            log.debug("Hybrid Mode: " + str(user) +
                                      ": Local Song Not Playing")
                            update_status(user, "statusSong", 1)
                            time.sleep(60)
                        else:
                            track = response.get("item").get("name")
                            if(previous != track):
                                if(response.get("item").get("is_local")):
                                    response["item"]["id"] = ":" + response.get("item").get("uri").replace("%2C", "").replace(
                                        "+", "").replace("%28", "").replace(":", "")[12:30] + response.get("item").get("uri")[-3:]
                                    for i in range(0, len(response.get("item").get("artists"))):
                                        response["item"]["artists"][i]["id"] = (
                                            (":" + (response.get("item").get("artists")[i].get("name"))).zfill(22))[:22]
                                if(int(response.get("progress_ms")) > 30000):
                                    previous = track
                                    utc_time = datetime.fromtimestamp(
                                        response.get('timestamp')/1000, timezone.utc)
                                    response["utc_timestamp"] = utc_time.strftime(
                                        "%Y%m%d%H%M%S")
                                    response["utc_timePlayed"] = utc_time.strftime(
                                        "%Y-%m-%d %H:%M:%S")
                                    database.database_input(user, response)
                                    log.debug(
                                        "Song Counted as Played: " + str(track))
                                    update_status(user, "statusSong", 1)
                                    time.sleep(25)
                            if(int(response.get("progress_ms")) > 30000):
                                time.sleep(10)
                    else:
                        log.debug("Nothing is Playing: " + str(user))
                        update_status(user, "statusSong", 1)
                        time.sleep(60)
                update_status(user, "statusSong", 1)
                time.sleep(5)
            except:
                log.exception("Song Lookup Failure: " + str(user))
                log.warning(str(response))
                update_status(user, "statusSong", 1)
                time.sleep(60)
            status = database.user_status(user)
    except:
        log.exception("Realtime Song Failure: " + str(user))
        update_status(user, "statusSong", 1)
        time.sleep(60)
    update_status(user, "statusSong", 0)
예제 #6
0
def historySpotify(user):
    try:
        update_status(user, "statusSong", 0)
        time.sleep(10)
        status = database.user_status(user)
        if (status != 1):
            return
        url = "https://api.spotify.com/v1/me/player/recently-played?limit=50"
        header = {"Accept": "application/json",
                  "Content-Type": "application/json", "Authorization": "Bearer " + authorize(user)}
        while(status == 1):
            workerCount = database.scanWorkers(WORKER)
            killThreads(workerCount, user)
            global KILL
            if (KILL.get(user+"SpotifyThread", 0) == 1):
                del KILL[str(user)+"SpotifyThread"]
                break
            update_status(user, "statusSong", 2)
            try:
                response = requests.get(url, headers=header)
                if("the access token expired" in str.lower(response.text)):
                    header = {"Accept": "application/json",
                              "Content-Type": "application/json", "Authorization": "Bearer " + authorize(user)}
                    response = requests.get(url, headers=header)
                else:
                    newSongs = False
                    response = response.json()
                    query = "SELECT id,timestamp,timePlayed,songID,user FROM `listeningHistory`  where user ='******' ORDER BY `listeningHistory`.`timePlayed`  DESC  LIMIT 50"
                    listeningHistory = []
                    with connection.cursor() as cursor:
                        cursor.execute(query)
                        listenTemp = []
                        for song in cursor:
                            for listened in response.get("items"):
                                utc_time = datetime.fromisoformat(
                                    listened.get('played_at').split(".")[0].replace("Z", ""))
                                timestamp = utc_time.strftime("%Y%m%d%H%M%S")
                                # https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date/40769643#40769643
                                listened["utc_timestamp"] = utc_time.strftime(
                                    "%Y%m%d%H%M%S")
                                listened["utc_timePlayed"] = utc_time.strftime(
                                    "%Y-%m-%d %H:%M:%S")
                                if(int(timestamp) == song[1]):
                                    listenTemp.append(listened)
                        for listened in response.get("items"):
                            tracked = False
                            for temp in listenTemp:
                                if(listened.get('played_at') == temp.get('played_at')):
                                    tracked = True
                            if(not tracked):
                                utc_time = datetime.fromisoformat(
                                    listened.get('played_at').split(".")[0].replace("Z", ""))
                                # https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date/40769643#40769643
                                listened["utc_timestamp"] = utc_time.strftime(
                                    "%Y%m%d%H%M%S")
                                listened["utc_timePlayed"] = utc_time.strftime(
                                    "%Y-%m-%d %H:%M:%S")
                                listened["item"] = listened.get("track")
                                log.info("History: " + str(user) + ": " +
                                         database.database_input(user, listened).get("track").get("name"))
                                newSongs = True
                    if (newSongs == False):
                        log.debug("No New Songs: " + str(user))
                update_status(user, "statusSong", 1)
                time.sleep(1200)
            except:
                log.exception("Song Lookup Failure: " + str(user))
                log.warning(str(response))
                update_status(user, "statusSong", 1)
                time.sleep(60)
            status = database.user_status(user)
    except:
        log.exception("History Song Failure: " + str(user))
        update_status(user, "statusSong", 1)
        time.sleep(60)
    update_status(user, "statusSong", 0)