94e43bd2c83b5cee930a2d6976222696060a510a
   1#! /bin/python
   2
   3import requests, json, collections
   4
   5id = "censored"
   6secret = "censored"
   7Token = collections.namedtuple('token', ['access', 'refresh', 'err'])
   8
   9def refresh() :
  10
  11    authfile = open('./.auth', 'r+')        # current refresh token is kept in .auth
  12    rt = authfile.read().splitlines()[0];
  13
  14    params = {'client_id':id,
  15            'client_secret':secret,
  16            'grant_type':"refresh_token",
  17            'refresh_token':rt}
  18
  19    data = json.loads(requests.post(url = "https://accounts.spotify.com/api/token", data = params).text)
  20    try:
  21        authfile.write(data['refresh_token']);  # refresh token is not updated if delta t < 3600ms
  22    except:
  23        pass
  24        # print("Refresh token unchanged")
  25    return(data['access_token']);
  26
  27header = {'Authorization': "Authorization: Bearer " + refresh()}
  28response = requests.get("https://api.spotify.com/v1/me/player/recently-played", headers = header).text
  29data = json.loads(response)
  30# open('./sampleoutput.json', 'w').write(response);     # for debugging
  31print("\"" + data['items'][0]['track']['name'] + "\" by " + data['items'][0]['track']['artists'][0]['name']);