示例#1
0
    def __init__(self, headers: Dict[str, str] = None):
        super().__init__(headers or {})

        config = self.get_configs()

        if "CardMarket" not in config.sections():
            LOGGER.warning("CardMarket section not established. Skipping requests")
            self.__keys_found = False
            return

        os.environ["MKM_APP_TOKEN"] = config.get("CardMarket", "app_token")
        os.environ["MKM_APP_SECRET"] = config.get("CardMarket", "app_secret")
        os.environ["MKM_ACCESS_TOKEN"] = ""
        os.environ["MKM_ACCESS_TOKEN_SECRET"] = ""

        if not (os.environ["MKM_APP_TOKEN"] and os.environ["MKM_APP_SECRET"]):
            LOGGER.warning("CardMarket keys values missing. Skipping requests")
            self.__keys_found = False
            return

        self.__keys_found = True

        self.connection = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])
        self.set_map = {}
        self.__init_set_map()
    def __init__(self, config_file):
        self.config_file = config_file

        with open(self.config_file) as oauth_details:
            token = yaml.load(oauth_details, Loader=yaml.FullLoader)

        os.environ['MKM_APP_TOKEN'] = token['app_token']
        os.environ['MKM_APP_SECRET'] = token['app_secret']
        os.environ['MKM_ACCESS_TOKEN'] = token['access_token']
        os.environ['MKM_ACCESS_TOKEN_SECRET'] = token['access_token_secret']

        self.mkm = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])
示例#3
0
 def __init__(self, card):
     self.mkm = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])
     self.card = card
示例#4
0
def build_output_file(sf_cards: List[Dict[str, Any]], set_code: str,
                      skip_keys: bool) -> Dict[str, Any]:
    """
    Compile the entire XYZ.json file and pass it off to be written out
    :param skip_keys: Skip building TCGPlayer & MKM components
    :param sf_cards: Scryfall cards
    :param set_code: Set code
    :return: Completed JSON file
    """
    if not skip_keys and os.environ["MKM_APP_TOKEN"] and os.environ[
            "MKM_APP_SECRET"]:
        MKM_API.set(Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"]))

    output_file: Dict[str, Any] = {}

    # Get the set config from Scryfall
    set_config = scryfall.download(scryfall.SCRYFALL_API_SETS + set_code)
    if set_config["object"] == "error":
        LOGGER.error(
            "Set Config for {} was not found, skipping...".format(set_code))
        return {"cards": [], "tokens": []}

    output_file["name"] = set_config["name"]
    output_file["code"] = set_config["code"].upper()
    output_file["releaseDate"] = set_config["released_at"]
    output_file["type"] = set_config["set_type"]
    output_file["keyruneCode"] = (pathlib.Path(
        set_config["icon_svg_uri"]).name.split(".")[0].upper())

    # Try adding MKM Set Name
    # Then store the card data for future pulling
    if MKM_API.get(None):
        mkm_resp = MKM_API.get().market_place.expansions(game=1)
        if mkm_resp.status_code != 200:
            LOGGER.error(
                "Unable to download MKM correctly: {}".format(mkm_resp))
        else:
            for set_content in mkm_resp.json()["expansion"]:
                if (set_content["enName"].lower()
                        == output_file["name"].lower()
                        or set_content["abbreviation"].lower()
                        == output_file["code"].lower()):
                    output_file["mcmId"] = set_content["idExpansion"]
                    output_file["mcmName"] = set_content["enName"]
                    break

        initialize_mkm_set_cards(output_file.get("mcmId", None))

    # Add translations to the files
    try:
        output_file["translations"] = wizards.get_translations(
            output_file["code"])
    except KeyError:
        LOGGER.warning(
            "Unable to find set translations for {}".format(set_code))

    # Add optionals if they exist
    if "mtgo_code" in set_config.keys():
        output_file["mtgoCode"] = set_config["mtgo_code"].upper()

    if "parent_set_code" in set_config.keys():
        output_file["parentCode"] = set_config["parent_set_code"].upper()

    if "block" in set_config.keys():
        output_file["block"] = set_config["block"]

    if "digital" in set_config.keys():
        output_file["isOnlineOnly"] = set_config["digital"]

    if "foil_only" in set_config.keys():
        output_file["isFoilOnly"] = set_config["foil_only"]

    if set_code.upper() in mtgjson4.NON_ENGLISH_SETS:
        output_file["isForeignOnly"] = True

    # Add booster info based on boosters resource (manually maintained for the time being)
    with mtgjson4.RESOURCE_PATH.joinpath("boosters.json").open(
            "r", encoding="utf-8") as f:
        json_dict: Dict[str, List[Any]] = json.load(f)
        if output_file["code"] in json_dict.keys():
            output_file["boosterV3"] = json_dict[output_file["code"].upper()]

    # Add V3 code for some backwards compatibility
    with mtgjson4.RESOURCE_PATH.joinpath("gatherer_set_codes.json").open(
            "r", encoding="utf-8") as f:
        json_dict = json.load(f)
        if output_file["code"] in json_dict.keys():
            output_file["codeV3"] = json_dict[output_file["code"]]

    # Declare the version of the build in the output file
    output_file["meta"] = {
        "version": mtgjson4.__VERSION__,
        "date": mtgjson4.__VERSION_DATE__,
        "pricesDate": mtgjson4.__PRICE_UPDATE_DATE__,
    }

    LOGGER.info("Starting cards for {}".format(set_code))

    card_holder: List[MTGJSONCard] = convert_to_mtgjson(sf_cards)
    card_holder = add_start_flag_and_count_modified(set_code,
                                                    set_config["search_uri"],
                                                    card_holder)

    # Address duplicates in un-sets
    card_holder = uniquify_duplicates_in_set(card_holder)

    # Move bogus tokens out
    card_holder, added_tokens = transpose_tokens(card_holder)

    if not skip_keys:
        # Add MTGStocks data in
        card_holder = add_stocks_data(card_holder)

    # Add TCGPlayer information
    if "tcgplayer_id" in set_config.keys():
        output_file["tcgplayerGroupId"] = set_config["tcgplayer_id"]
        if not skip_keys:
            add_purchase_fields(output_file["tcgplayerGroupId"], card_holder)

    # Set Sizes
    output_file["baseSetSize"] = scryfall.get_base_set_size(set_code.upper())
    output_file["totalSetSize"] = len(sf_cards)

    output_file["cards"] = card_holder

    LOGGER.info("Finished cards for {}".format(set_code))

    # Handle tokens
    LOGGER.info("Starting tokens for {}".format(set_code))
    sf_tokens: List[Dict[str, Any]] = scryfall.get_set("t" + set_code)
    output_file["tokens"] = build_mtgjson_tokens(sf_tokens + added_tokens)
    LOGGER.info("Finished tokens for {}".format(set_code))

    # Cleanups and UUIDs
    mtgjson_card.DUEL_DECK_LAND_MARKED.set(False)
    mtgjson_card.DUEL_DECK_SIDE_COMP.set("a")

    for card in sorted(output_file["cards"]):
        card.final_card_cleanup()
    for token in output_file["tokens"]:
        token.final_card_cleanup(is_card=False)

    # Add Variations to each entry, as well as mark alternatives
    add_variations_and_alternative_fields(output_file["cards"], output_file)

    return output_file
示例#5
0
 def __init__(self):
     self.api = Mkm(
         _API_MAP['2.0']['api'],
         _API_MAP['2.0'][os.environ.get('ENVIRONMENT', 'api_root')])
     self.user_account = self.api.account_management.account().json()
示例#6
0
def mkm():
    return Mkm(_API_MAP["1.1"]["api"], _API_MAP["1.1"]["api_sandbox_root"])
示例#7
0
from mkmsdk.mkm import Mkm
from mkmsdk.api_map import _API_MAP
from os import environ

app_token = "8E8kK8bxbENRJGBC"
app_secret = "hS2A0OJiSxABc41woFSHFoGMiL1yh6JP"
mkm_sandbox = Mkm(_API_MAP["1.1"]["api"], _API_MAP["1.1"]["api_sandbox_root"])


def get_sets_on_mkm():
    response = mkm_sandbox.market_place.expansion(game="1")
    return response.json()


def get_cards_from_set_on_mkm(set_name):
    response = mkm_sandbox.market_place.expansion_singles(game="1",
                                                          name=set_name)
    return response.json()


def get_card_from_id_on_mkm(product_id):
    response = mkm_sandbox.market_place.product(product=product_id)
    return response.json()


def set_env():
    environ["MKM_APP_TOKEN"] = app_token
    environ["MKM_APP_SECRET"] = app_secret
    environ["MKM_ACCESS_TOKEN"] = ""
    environ["MKM_ACCESS_TOKEN_SECRET"] = ""
    return
示例#8
0
 def __init__(self):
     self.mkm = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])
     self.stock_client = StockClient(self.mkm)
     self.stock_client.stock()
     self.marketplace_client = MarketplaceClient(self.mkm)
     self.marketplace_client.articles()
示例#9
0
from mkmsdk.mkm import Mkm
from mkmsdk.api_map import _API_MAP
from util import response_code_valid, pretty


mkm_url = "https://www.cardmarket.com/"

mkm = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])

standard_languages = ("English", "Italian", "Japanese", "Korean", "Russian", "S-Chinese")

condition_to_num = {
    "MT": 6,
    "NM": 5,
    "EX": 4,
    "GD": 3,
    "LP": 2,
    "PL": 1,
    "PO": 0
}


def get_products_from_user_in_range(user, min_limit, max_limit):
    return mkm.market_place.user_articles(
        user=user,
        params={
            "start": min_limit,
            "maxResults": max_limit
        }
    )
示例#10
0
import logging
import sys

parser = argparse.ArgumentParser("CardmarketPriceManager")
parser.add_argument("--configFile", type=open, default="./config.yaml")
args = parser.parse_args()

root = logging.getLogger()
root.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
root.addHandler(handler)

config = yaml.safe_load(args.configFile)
cardMarket = Mkm(_API_MAP["2.0"]["api"], _API_MAP["2.0"]["api_root"])

postData = {"article": []}

categories = []
if "Categories" in config:
    for category in config["Categories"]:
        categories.append(CardCategory(category, cardMarket))

exporters = []
if "Exporters" in config:
    exporters = createExporters(config["Exporters"])

stock_response = cardMarket.stock_management.get_stock()
if stock_response.status_code == 307:
    stock_response = cardMarket.resolver.api.request(cardMarket.api_map["stock_management"]["get_stock"]["url"] + "/1", "get")