コード例 #1
0
ファイル: discogs.py プロジェクト: rpledger/turntabler
    def __init__(self, token=None, secret=None):
        self.token = token
        self.secret = secret
        self.url = None

        # Set unique user-agent
        user_agent = 'turntabler/0.1'

        # Instantiate discogs_client obj

        if token and secret:
            self.discogsclient = discogs_client.Client(
                user_agent,
                token=token,
                secret=secret,
                consumer_key=Config.DISCOGS_CONSUMER_KEY,
                consumer_secret=Config.DISCOGS_CONSUMER_SECRET)
        else:
            self.discogsclient = discogs_client.Client(
                user_agent,
                consumer_key=Config.DISCOGS_CONSUMER_KEY,
                consumer_secret=Config.DISCOGS_CONSUMER_SECRET)

        # Prepare the client with API consumer data
        # self.discogsclient.set_consumer_key(Config.DISCOGS_CONSUMER_KEY, Config.DISCOGS_CONSUMER_SECRET)

        # TODO: add callback_url when not using localhost

        self.user = None
コード例 #2
0
def configure():
    config_file = str(Path.home()) + "/.discognition-conf.yaml"

    if args.generateconfig is not None:  # generate configuration

        data = {
            'token': args.generateconfig[0],
            'directory': args.generateconfig[1]
        }

        with open(config_file, 'w') as outfile:
            yaml.dump(data, outfile, default_flow_style=False)

        print('created file: ' + config_file)

    try:
        config = yaml.safe_load(open(config_file))
        client = discogs_client.Client('discognition/' + __version__,
                                       user_token=config['token'])

    except:
        print(
            'You need to set your configuration file at "~/.discogs_conf.yaml"'
        )
        print(
            'You can do this by running "discognition -g TOKEN /PATH/TO/MUSIC/LIBRARY"'
        )
        exit()

    return {
        'config': config,
        'client': client,
    }
コード例 #3
0
ファイル: sensor.py プロジェクト: zezo010/home-assistant
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Discogs sensor."""
    import discogs_client

    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

    try:
        discogs_client = discogs_client.Client(SERVER_SOFTWARE,
                                               user_token=token)

        discogs_data = {
            'user': discogs_client.identity().name,
            'folders': discogs_client.identity().collection_folders,
            'collection_count': discogs_client.identity().num_collection,
            'wantlist_count': discogs_client.identity().num_wantlist
        }
    except discogs_client.exceptions.HTTPError:
        _LOGGER.error("API token is not valid")
        return

    sensors = []
    for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
        sensors.append(DiscogsSensor(discogs_data, name, sensor_type))

    add_entities(sensors, True)
コード例 #4
0
ファイル: discogsutil.py プロジェクト: Rucia1/Peppy
 def __init__(self):
     """ Initializer. Create Discogs Client """
     
     self.peppy_player_user_agent = "PeppyPlayer +https://github.com/project-owner/Peppy"
     self.peppy_player_token = "RtZmsbvvoXVQxBwXtYDkbNIOXWkeGILJeyriGmDL"
     
     self.client = discogs_client.Client(self.peppy_player_user_agent, user_token=self.peppy_player_token)
コード例 #5
0
 def setUp(self):
     """
     Setup process.
     """
     client = discogs_client.Client('ExampleApplication/0.1',
                                    user_token="wuYMABvmUDdOMXerFacIXQBQJJphFkPgtivGgfLW")
     self.processor = process.ProcessMap(client, "test_countries.txt")
コード例 #6
0
def get_discogs_client():
    user_token = os.environ.get('DISCOGS_USER_TOKEN')
    if not user_token:
        msg = 'You must set DISCOGS_USER_TOKEN value in your environment variables'
        cprint(msg, 'red')
        return
    return discogs_client.Client('JazzGraph/0.1', user_token=user_token)
コード例 #7
0
ファイル: discogs.py プロジェクト: JasperKirton/metadb
def scrape(query):

    mbid = query['mbid']
    artist = query['artist']
    title = query['recording']

    if not artist or not title:
        raise Exception("Artist and recording strings are required")
    print("Scraping recording information for", mbid, "-", artist, "-", title)

    title_simple = re.sub(r'\W+', '', title.lower())

    data = None
    try:
        d = discogs_client.Client('AB_Discogs/0.1', user_token=DISCOGS_KEY)
        results = d.search(artist=artist, track=title)
        data = []
        #i = 0
        for r in results:
            #i += 1
            for t in r.tracklist:
                track_simple = re.sub(r'\W+', '', t.data['title'].lower())
                #print i, track_simple, "-->", title_simple, "MATCH" if title_simple == track_simple else ""
                if title_simple == track_simple:
                    data.append(r.data)
                    break

    except ApiException as ex:
        raise

    if data:
        return data, TYPE
コード例 #8
0
ファイル: views.py プロジェクト: wurscht/audiowurscht
def upload_view(request):
    if not request.user.is_authenticated:
        return render(request, 'registration/login_error.html')
    discogs = discogs_client.Client(
        'ExampleApplication/0.1',
        user_token="FLDeuZyRaYLvakXhVNTUgMfTWmBnlabfrBFhGvaM")
    current_user = request.user
    if request.method == "POST":
        song_info = mutagen.File(request.FILES["mysong"])
        artist = "".join(song_info["TPE1"].text)
        results = discogs.search(artist.split("/")[0], type='artist')
        band_pic = results[0].images[0]["uri"]

        song = Song.objects.create(title="".join(song_info["TIT2"].text),
                                   artist="".join(song_info["TPE1"].text),
                                   album="".join(song_info["TALB"].text),
                                   path=request.FILES["mysong"],
                                   tracknumber="".join(song_info["TRCK"].text),
                                   picture=band_pic)

        song.user.add(current_user)
        song.save()
        redirect("upload")

    return render(request, "song_upload.html")
コード例 #9
0
def scrape(query):

    mbid = query['mbid']
    artist = query['artist']
    release = query['release']
    year = query['year']

    if not artist or not release or not year:
        raise Exception(
            "Artist, release, and year information is required. Query: %s" %
            json.dumps(query))
    print "Scraping recording information for", mbid + ":", artist, "-", release, "-", year
    artist = artist.decode('utf8')
    release = release.decode('utf8')

    release_simple = re.sub(r'\W+', '', release.lower())
    year = year.split('-')[0]

    data = None
    try:
        d = discogs_client.Client('AB_Discogs/0.1', user_token=DISCOGS_KEY)
        results = d.search(artist=artist, release_title=release)

        data = [
            r.data for r in results
            if 'year' in r.data and r.data['year'] == year
        ]

    except ApiException as ex:
        raise

    return data, TYPE
コード例 #10
0
ファイル: renew_data.py プロジェクト: borsukvasyl/Coursework
def save_data(filename):
    """
    Saves requested data to filename
    :param filename: filename where data will be saved
    :return: None
    """
    with open(filename, "w") as file:
        file.write("style\n")

        # creating client
        client = discogs_client.Client(
            'ExampleApplication/0.1',
            user_token="wuYMABvmUDdOMXerFacIXQBQJJphFkPgtivGgfLW")
        a = process.ProcessMap(client, "countries.txt")

        # saving additional data
        a.request_additional(type="release", year=2016)
        result = []
        for element in a._elements:
            result.append(element.additional)
        file.write("{}\n".format(str(result)))
        print(result)

        # reading key elements
        with open("styles.txt", "r") as file:
            styles = [line.strip() for line in file.readlines()]

        # saving main data
        for style in styles:
            a.request_values("", type="release", year=2016, style=style)
            result = []
            for element in a._elements:
                result.append(element.value)
            file.write("{}\t{}\n".format(style, result))
            print("{} {}".format(style, result))
コード例 #11
0
 def get_discogs_api_object(self):
     if self.discogs_api:
         return self.discogs_api
     else:
         self.discogs_api = discogs_client.Client(
             'ExampleApplication/0.1', user_token=self.DISCOGS_KEY)
         return self.discogs_api
コード例 #12
0
def build_mapchart():
    client = discogs_client.Client(
        'ExampleApplication/0.1',
        user_token="wuYMABvmUDdOMXerFacIXQBQJJphFkPgtivGgfLW")

    type = request.args.get('type', 0, type=str)
    style = request.args.get('style', 0, type=str)
    year = int(request.args.get('year', 0, type=int))
    is_percentage = request.args.get("percentage", 0, type=str)

    process = map_process.ProcessMap(client, "countries.txt")
    process.request_values("",
                           read_file="style-countries.txt",
                           type=type,
                           style=style,
                           year=year)
    if is_percentage == "true":
        process.request_additional("",
                                   read_file="style-countries.txt",
                                   type=type,
                                   year=year)
        data = process.percentage_list()
        data.insert(0, ["Country", "Percentage"])
    else:
        data = process.values_list()
        data.insert(0, ["Country", "Releases"])
    print(data)
    return jsonify(result=data)
コード例 #13
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Discogs sensor."""
    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

    try:
        _discogs_client = discogs_client.Client(SERVER_SOFTWARE,
                                                user_token=token)

        discogs_data = {
            "user": _discogs_client.identity().name,
            "folders": _discogs_client.identity().collection_folders,
            "collection_count": _discogs_client.identity().num_collection,
            "wantlist_count": _discogs_client.identity().num_wantlist,
        }
    except discogs_client.exceptions.HTTPError:
        _LOGGER.error("API token is not valid")
        return

    monitored_conditions = config[CONF_MONITORED_CONDITIONS]
    entities = [
        DiscogsSensor(discogs_data, name, description)
        for description in SENSOR_TYPES
        if description.key in monitored_conditions
    ]

    add_entities(entities, True)
コード例 #14
0
def new_client_authorization():
    CONSUMER_KEY = 'dRWuEIUFudONhVsYyoPa'
    CONSUMER_SECRET = 'YBREVPKyCdoUBUdvYerSHruZMMcENONj'
    d = discogs_client.Client(USER_AGENT)
    d.set_consumer_key(CONSUMER_KEY, CONSUMER_SECRET)
    token, secret, url = d.get_authorize_url()

    print(' ==Request Token== ')
    print(f'    * ouath_token        = {token}')
    print(f'    * ouath_token_secret = {secret}')
    print()
    print(f'Retrieve authentication token from: {url}')

    accepted = ''
    while accepted.lower() != 'y':
        print()
        accepted = input('Token ready? [y/n] :')

    oauth_verifier = input('Verification code: ')

    try:
        access_token, access_secret = d.get_access_token(oauth_verifier)
    except HTTPError:
        print('Unable to authenticate.')
        sys.exit(1)

    return d
コード例 #15
0
    def request_review(self, album_name):
        # connect to Discogs
        d = discogs_client.Client(self.app_name, user_token=self.user_token)

        # search Discogs for album
        results = d.search(album_name, type='release')
        search_results = []
        if len(results) == 0:
            print("Could not find album.")
        else:
            # extract artist's name
            artist = results[0].artists[0]
            artist_name = artist.name
            try:
                # search Pitchfork for review
                p = pitchfork.search(artist_name, album_name)
                search_results.append(artist_name)
                search_results.append(p.album())
                search_results.append(p.label())
                search_results.append(p.score())
            except Exception:
                print("Album not found in Pitchfork.")
                pass
            
        return search_results
コード例 #16
0
ファイル: models.py プロジェクト: mateuszdargacz/player
 def connect_to_api(self):
     d = discogs_client.Client(
         'MusicApp', user_token='lYZxOrAPASUOlpDrZMPaMdnWZczHZVoAoECIBjTM')
     results = d.search(artist=self.artist,
                        track=self.title,
                        type='master',
                        format='album')
     return results
コード例 #17
0
ファイル: discogsutil.py プロジェクト: whenthelight/Peppy
 def __init__(self, t):
     """ Initializer. Create Discogs Client 
     
     :param t: token
     """
     self.peppy_player_user_agent = "PeppyPlayer +https://github.com/project-owner/Peppy"
     self.client = discogs_client.Client(self.peppy_player_user_agent,
                                         user_token=t)
コード例 #18
0
    def init_client(self, token):
        """ Initialize Discogs Client 
        
        :param token: the API token
        """

        self.client = discogs_client.Client(self.peppy_player_user_agent,
                                            user_token=token)
コード例 #19
0
 def Init(self):
     if filename:
         with open(filename, 'r') as f:
             data = json.load(f)
             self.key = data["discogskey"]
             self.secret = data["discogssecret"]
             self.token = data["discogstoken"]
             self.d = discogs_client.Client('Bot', user_token=self.token)
コード例 #20
0
def _build_discogs_instance():

    DEVELOPER_KEY = read_credentials(CREDENTIALS_FILE)

    discogs = discogs_client.Client('SpinYoRecords',
                                    user_token=DEVELOPER_KEY)

    return discogs
コード例 #21
0
ファイル: release.py プロジェクト: AP-e/nofuture
def make_client():
    """Initialise single-user authorised discogs client."""
    user_token = os.environ.get('DISCOGS_USER_TOKEN')
    if user_token is None:
        user_token = DISCOGS_USER_TOKEN
    if user_token is None:
        raise ValueError('You must specify a valid discogs user token')
    return discogs_client.Client(DISCOGS_USER_AGENT, user_token=user_token)
コード例 #22
0
def fetchMatching(request, record_name):
    #d = discogs.Client('ExampleApplication/0.1')
    d = discogs.Client('ExampleApplication/0.1',
                       user_token="kjSzomrwGYmaghjNUbTnTCLtEwlpETrtDkLTKAnF")
    results = d.search(record_name, type='release')
    response = '{"data":[{ "name": "' + results[
        0].title + '", "artist": "' + results[0].artists[
            0].name + '", "year": "' + str(results[0].year) + '" }]}'
    return HttpResponse(response)
コード例 #23
0
ファイル: release_info.py プロジェクト: atphy/fullstack
    def list(self, request):
        d = discogs_client.Client(
            'Fullstack/0.1 +@:[email protected]',
            user_token="EMIDOqyOnyXKSDQGfzjhruBlRDBvBVaZnIDcaTOd")
        release_id = self.request.query_params.get("release", None)
        results = d.release(release_id)
        print(results)

        return Response(results.data)
コード例 #24
0
def get_releases():
    try:
        discogs_cl = discogs_client.Client("PricelistDiscogs/0.9.1",
                                           user_token=developer_token)
        return discogs_cl.user(user).collection_folders[0]
    except HTTPError:
        print(
            'paste your user/token in arguments or edit "lib/credentials.py"')
        quit()
コード例 #25
0
def index(request):
    d = discogs.Client('ExampleApplication/0.1')
    d = discogs.Client('ExampleApplication/0.1',
                       user_token="kjSzomrwGYmaghjNUbTnTCLtEwlpETrtDkLTKAnF")
    results = d.search('Stockholm By Night', type='release')
    print(results.pages)
    sivut = results.pages
    artist = results[0].artists[0]
    nimi = artist.name
    print(artist.name)
    master_release = d.master(120735)

    print(artist.id)
    print(master_release.main_release)
    print(master_release.title)
    print(master_release.tracklist)
    return HttpResponse(
        "Hello, world. You're at the discogs index. Artisti on " + nimi)
コード例 #26
0
ファイル: discogs.py プロジェクト: baloothebear4/mDisplay
    def __init__(self):
        self.discogsclient = discogs_client.Client(user_agent,
                                                   user_token=consumer_token)
        # fetch the identity object for the current logged in user.
        user = self.discogsclient.identity()

        print()
        print(' == User ==')
        print('    * username           = {0}'.format(user.username))
コード例 #27
0
ファイル: Discogs.py プロジェクト: sarog/XDM-main-plugin-repo
 def __init__(self, instance):
     super(Discogs, self).__init__(instance)
     # https://github.com/discogs/discogs_client
     self.d = discogs_client.Client(
         user_agent,
         consumer_key=self.oauth.consumer_key,
         consumer_secret=self.oauth.consumer_secret,
         token=self.oauth.resource_owner_key,
         secret=self.oauth.resource_owner_secret)
コード例 #28
0
 def main_find(self):
     d = discogs_client.Client('JMoney/0.1', user_token=self.var_token)
     results = d.search(self.var_name,
                        artist=self.var_artist,
                        album=self.var_album,
                        type=self.var_type,
                        country=self.var_country)
     self.var_result = results.page(1)
     if self.PRINT_RESULT == 1:
         print(self.var_result)
コード例 #29
0
def get_discogs_client():
    """gets authed discogs client

    Returns:
        authed discogs client
    """
    discogs = discogs_client.Client(
        user_agent=current_app.config['APP_NAME'],
        user_token=current_app.config['DISCOGS_USER_TOKEN'])
    return discogs
コード例 #30
0
    def __init__(self, dummy_response):
        # we need a dummy client here ;-(
        client = discogs.Client('Dummy Client - just for unit testing')

        self.dummy_response = dummy_response
        self.content = self.convert(json.loads(dummy_response.content))

        self.release = discogs.Release(client, self.content['resp']['release'])

        DiscogsAlbum.__init__(self, self.release)