Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding MusicBrainz OAuth2 support #2298

Closed
wants to merge 8 commits into from
Closed
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 80 additions & 9 deletions beetsplug/mbcollection.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@

import re

from rauth import OAuth2Service
import json

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The right thing to do here is probably to import these exception names so we can use them, like this: https://github.com/beetbox/beets/blob/master/beetsplug/beatport.py#L26-L27

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about it, but I am using rauth lib and these are from requests_oauthlib.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, of course; that makes sense. So perhaps it would make sense to use the exceptions from rauth instead, or to switch to requests_oauthlib if it's not too different?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was searching for rauth description of exception names, but with no luck. The project's documentation isn't very good. Probably gonna switch to requests_oauthlib.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds great! Sorry for pointing you at the wrong library initially.

SUBMISSION_CHUNK_SIZE = 200
UUID_REGEX = r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$'


def mb_call(func, *args, **kwargs):
"""Call a MusicBrainz API function and catch exceptions.
"""
Expand All @@ -53,16 +55,27 @@ def submit_albums(collection_id, release_ids):


class MusicBrainzCollectionPlugin(BeetsPlugin):
def __init__(self):
def __init__(self, client_id, client_secret, token=None, refresh_token=None):
super(MusicBrainzCollectionPlugin, self).__init__()
config['musicbrainz']['pass'].redact = True
musicbrainzngs.auth(
config['musicbrainz']['user'].as_str(),
config['musicbrainz']['pass'].as_str(),
self.service = OAuth2Service(
client_id=client_id,
client_secret=client_secret,
authorize_url="https://musicbrainz.org/oauth2/authorize",
access_token_url="https://musicbrainz.org/oauth2/token",
base_url="https://musicbrainz.org/"
)
self.config.add({'auto': False})
if self.config['auto']:
self.import_stages = [self.imported]
self.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
self.params = {'response_type': 'code',
'redirect_uri': self.redirect_uri}

def authorize_url(self):
return self.service.get_authorize_url(**self.params)

def get_token(self, code):
session = service.get_raw_access_token(data={'code': code, 'redirect_uri': self.redirect_uri,
'grant_type': 'authorization_code', 'token_type': 'bearer'})
t = session.json()
return t['access_token'], t['refresh_token']

def commands(self):
mbupdate = Subcommand('mbupdate',
Expand Down Expand Up @@ -112,3 +125,61 @@ def update_album_list(self, album_list):
)
submit_albums(collection_id, album_ids)
self._log.info(u'...MusicBrainz collection updated.')


class OAuth(BeetsPlugin):
def __init__(self):
super(OAuth, self).__init__()
self.config.add({
'client_id': 'qLYLK0LlrhifkgXq0N-J4w', # Needs to be generated
'client_secret': 'XPiJdmSkh6uJDoWguo-J7g',
'tokenfile': 'oauth2_token.json'
})
self.config['client_id'].redact = True
self.config['client_secret'].redact = True
self.client = None
self.register_listener('import_begin', self.setup)

def setup(self, session=None):
client_id = self.config['client_id'].as_str()
secret = self.config['client_secret'].as_str()
try:
with open(self.tokenfile()) as f:
tokendata = json.load(f)
except IOError:
token, refresh_token = self.authenticate(client_id, secret)
else:
token = tokendata['token']
refresh_token = tokendata['refresh_token']

self.client = MusicBrainzCollectionPlugin(client_id, secret, token, refresh_token)

def authenticate(self, client_id, secret):
auth_client = MusicBrainzCollectionPlugin(client_id, secret)
try:
url = auth_client.authorize_url()
except Exception as e:
self._log.debug(u'authentication error: {0}', e)
raise beets.ui.UserError(u'Token request failed')

beets.ui.print_(u"To authenticate, visit:")
beets.ui.print_(url)

data = beets.ui.input_(u"Enter the string displayed in your browser:")

try:
token, refresh_token = auth_client.get_token(data)
except AUTH_ERRORS as e:
self._log.debug(u'authentication error: {0}', e)
raise beets.ui.UserError(u'Token request failed')

with open(tokenfile(), 'w') as f:
json.dump({'token': token, 'refresh_token': refresh_token}, f)

return token

@staticmethod
def tokenfile():
from os import path
basedir = path.abspath(path.dirname(__file__))
return "".join([basedir, '/token.json'])