Search code examples
oauth-2.0spotifyopenmediavault

Using OAuth2.0 in Python Script on OpenMediaVault


I am not sure wether this is the right form and i am pretty new to this stuff, so please bear with me...

Currently, I am trying to automate a few things in my home. One thing is related to Spotify. To do that i wrote a python script, which works good on my laptop, but when I transfer it over to my NAS-Server (OpenMediaVault6) the script doesn't work. I want it there for task scheduling.

I think I know where the problem is, but I don't know how to fix it. In the python script I have to get an access token from spotify. For that I need to authenticate myself in a browser, but on a NAS-Server that is not possible as far as I know.

I tried to solve it with a Client Credentials Flow, but I need to access my user information.

This is a simplified code:

import spotipy


CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
REDIRECT_URI = "http://localhost:8888/callback"
USER_ID = "user_id"
SCOPE = "user-read-private user-read-email"

token = spotipy.util.prompt_for_user_token(USER_ID, SCOPE, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)

print(token)

Does anyone have a smart idea how to get this running on the NAS?

Thansk in advance.


Solution

  • For future refernce (Solution motivated by @Ximzend):

    Apparently is the Refresh Token, which is provided with the Access Token, vaild until revoken from the user. So one can access the Cache, where both and the time for the Access Token to expire is saved and generate a new Access Token without having to authorize again. So basically, generate the Access Token once on a normal PC/System and then copy the Cache to the NAS-Server such that this Script can access it.

    It's something like that then:

    import json
    import requests
    import base64
    
    CLIENT_ID = "client_id"
    CLIENT_SECRET = "client_secret"
    
    with open(".cache-<user_id>", 'r') as cach:
        data = cach.read()
    cache = json.loads(data)
    
    REFRESH_TOKEN = cache['refresh_token']
    
    def get_new_token():
        authorization = base64.b64encode(bytes(CLIENT_ID + ":" + CLIENT_SECRET, "ISO-8859-1")).decode("ascii")
    
        endpoint = "https://accounts.spotify.com/api/token"
        headers = {
            "Authorization": f"Basic {authorization}",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "refresh_token": REFRESH_TOKEN,
            "grant_type": "refresh_token"
        }
    
        response = requests.post(endpoint, headers=headers, data=data)
    
        return response.json()["access_token"]
    
    ACCESS_TOKEN = get_new_token()
    

    I am running that code daily on my NAS and sending myself the new Access Token per Report to my Mail, just to check, wether it's still working so that my other scripts, which depend on the token and run weekly, can still work.