Esempio n. 1
0
def obtain(item, body, args):
    if item['shopItemType'] == 'CARD':
        args = dt.updateJson(args, getCard(item['card']['charaNo'],
                                           body['num']))
    elif item['shopItemType'] == 'FORMATION_SHEET':
        args = dt.updateJson(args, getFormation(item['formationSheet']['id']))
    elif item['shopItemType'] == 'GEM':
        args = dt.updateJson(args, getGems(int(item['genericId']),
                                           body['num']))
    elif item['shopItemType'] == 'GIFT':
        amount = 1
        if 'rewardCode' in item:
            amount = int(item['rewardCode'].split('_')[-1])
        newGifts = getGift(item['gift']['id'], body['num'] * amount)
        args['userGiftList'] = args.get('userGiftList',
                                        []) + newGifts['userGiftList']
    elif item['shopItemType'] == 'ITEM':
        amount = 1
        if 'rewardCode' in item:
            amount = int(item['rewardCode'].split('_')[-1])
        newItems = getItem(item['item']['itemCode'], body['num'] * amount,
                           item['item'])
        args['userItemList'] = args.get('userItemList',
                                        []) + newItems['userItemList']
    elif item['shopItemType'] == 'LIVE2D':
        args = dt.updateJson(
            args,
            getLive2d(item['chara']['id'], item['live2d']['live2dId'],
                      item['live2d']))
    elif item['shopItemType'] in ['MAXPIECE', 'PIECE']:
        args = dt.updateJson(
            args,
            getPiece(item['piece'], item['shopItemType'] == 'MAXPIECE',
                     body['num']))
    return args
Esempio n. 2
0
def obtainSet(item, body, args):
    for code in item['rewardCode'].split(','):
        itemType = code.split('_')[0]
        amount = int(code.split('_')[-1])
        if itemType == 'ITEM':
            args = dt.updateJson(
                args,
                getItem('_'.join(code.split('_')[1:-1]), amount * body['num']))
        elif itemType == 'RICHE':
            args = dt.updateJson(args, getCC(amount * body['num']))
        elif itemType == 'GIFT':
            args = dt.updateJson(
                args, getGift(int(code.split('_')[1]), amount * body['num']))
Esempio n. 3
0
def giveDrops(battle):
    resultDict = {}
    # default drop seems to always be CC...
    if 'defaultDropItem' in battle['questBattle']:
        cc = int(battle['questBattle']['defaultDropItem']['rewardCode1'].split(
            '_')[-1])
        if len(getEpisodeUpCards(battle['deckType'])) > 0:
            cc *= 1.05  # CC up memes
        resultDict['gameUser'] = dt.setGameUserValue(
            'riche',
            dt.getGameUserValue('riche') + cc)
        battle['riche'] = cc

    dropRewardCodes = []
    dropCodes = dt.readJson('data/user/promisedDrops.json')
    if dropCodes['questBattleId'] != battle[
            'questBattleId']:  # weird error that should never happen...
        logger.error('questBattleId mismatch when sending drops')
        return resultDict
    for dropCode, amount in dropCodes.items():
        if dropCode == 'questBattleId': continue
        resultDict = dt.updateJson(resultDict, obtainItem(dropCode, amount))
        dropRewardCodes += [dropCode] * amount

    battle['dropRewardCodes'] = ','.join(dropRewardCodes)
    return resultDict
Esempio n. 4
0
def receiveReward(challenge):
    response = {}
    for reward in challenge['challenge']['rewardCodes'].split(','):
        response = dt.updateJson(response, obtainItem(reward))
    challenge['receivedAt'] = nowstr()
    dt.setUserObject('userDailyChallengeList', challenge['challengeId'],
                     challenge)
    return response
Esempio n. 5
0
def receiveAll():
    response = {"resultCode": "success"}
    userChallenges = dt.readJson('data/user/userDailyChallengeList.json')
    finalChallenges = []
    for challenge in userChallenges:
        if challenge['clearedCount'] >= challenge['challenge']['count']:
            response = dt.updateJson(response, receiveReward(challenge))
            finalChallenges.append(challenge)
    response['userDailyChallengeList'] = finalChallenges
    return flask.jsonify(response)
Esempio n. 6
0
def makeCampaignLoginBonus(lastLoginBonusDate, response):
    campaignList = dt.readJson('data/loginBonusCampaignList.json')
    campaignList = homu.filterCurrValid(campaignList, lambda x: x['campaign']['startAt'], lambda x: x['campaign']['endAt'])
    if len(campaignList) == 0:
        return

    # only works when there's only one campaign at a time
    campaign = campaignList[0]

    for rewardCode in campaign['rewardCodes'].split(','):
        loginItems = obtainItem(rewardCode)
        response = dt.updateJson(response, loginItems)

    response['loginBonusCampaignList'] = campaignList
    response['loginBonusCampaign'] = campaign
    response['campaignList'] = dt.readJson('data/campaignList.json')
Esempio n. 7
0
def addArgs(response, args, isLogin):
    user = dt.readJson('data/user/user.json')

    # checking if midnight passed; logins have to happen then too
    if isLogin or datetime.now().date() > datetime.strptime(user['todayFirstAccessDate'], homu.DATE_FORMAT).date():
        response = dt.updateJson(response, login())

    for arg in args:
        if arg in ['user', 'gameUser',
        'userLive2dList', 'userCardList', 'userCharaList', 'userDeckList', 'userFormationSheetList',
        'userPieceList', 'userPieceSetList', 'userItemList', 'userSectionList', 'userGiftList',
        'userQuestAdventureList', 'userQuestBattleList', 'userChapterList', 'userDoppelList',
        'userDailyChallengeList', 'userLimitedChallengeList', 'userTotalChallengeList',]:
            logger.info('loading ' + arg + ' from json')
            fpath = 'data/user/'+arg+'.json'
            if os.path.exists(fpath):
                response[arg] = dt.readJson(fpath)
                if arg == 'userPieceList':
                    response[arg] = [userPiece for userPiece in response[arg] if not userPiece['archive']]
                if arg == 'userSectionList':
                    response[arg], _ = homu.pruneLabyrinths(userSectionList=response[arg])
                if arg == 'userQuestBattleList':
                    _, response[arg] = homu.pruneLabyrinths(userQuestBattleList=response[arg])
            else:
                logger.warning(f'{fpath} not found')
        elif arg == 'userStatusList':
            response[arg] = homu.getAllStatuses()
        elif arg in ['itemList', 'giftList', 'pieceList']:
            logger.info('loading ' + arg + ' from json')
            fpath = 'data/'+arg+'.json'
            if os.path.exists(fpath):
                response[arg] = dt.readJson(fpath)
            else:
                logger.warning(f'{fpath} not found')
        elif arg.endswith('BattleResultList'):
            logger.info('loading ' + arg[:-4] + ' from json')
            fpath = 'data/user/'+arg[:-4]+'.json'
            if os.path.exists(fpath):
                response[arg] = dt.readJson(fpath)
        elif arg.lower().endswith('list'):
            response[arg] = []
Esempio n. 8
0
def makeLoginBonus(lastLoginBonusDate, response):
    loginBonusCount = (dt.getGameUserValue('loginBonusCount') % 7) + 1
    if datetime.now().date().weekday() == 0:
        loginBonusCount = 1

    lastMonday, nextMonday = homu.thisWeek()
    if homu.strToDateTime(lastLoginBonusDate).date() < lastMonday:
        loginBonusCount = 1

    dt.setGameUserValue('loginBonusGetAt', homu.nowstr())
    dt.setGameUserValue('loginBonusPattern', 'S1') # no clue how to get the other patterns, even from JP, or if this even matters...
    dt.setGameUserValue('loginBonusCount', loginBonusCount)

    bonuses = dt.readJson('data/loginBonusList.json')
    currBonus = bonuses[loginBonusCount-1]
    for rewardCode in currBonus['rewardCodes'].split(','):
        loginItems = obtainItem(rewardCode)
        response = dt.updateJson(response, loginItems)
    response['loginBonusList'] = bonuses

    response['loginBonusPeriod'] = lastMonday.strftime('%m/%d') + '〜' + nextMonday.strftime('%m/%d')
Esempio n. 9
0
def send():
    body = flask.request.json
    battle = dt.readJson('data/user/userQuestBattleResult.json')

    if (battle['battleType'] == "ARENA"):
        return sendArena(
            body, {
                'userQuestBattleResultList': [battle],
                'gameUser': dt.readJson('data/user/gameUser.json')
            })

    if not battle['id'] == body['userQuestBattleResultId']:
        flask.abort(
            400,
            description=
            '{"errorTxt": "You didn\'t really start this quest, or something...","resultCode": "error","title": "Error"}'
        )

    # really gross, but cbf'd rn to refactor
    storyResponse = None
    dropResponse = None
    rewardResponse = None
    resultUserCardList = None
    resultUserCharaList = None
    resultUserSectionList = None
    gameUser = dt.readJson('data/user/gameUser.json')
    newStatus = []

    # change userQuestBattleResult status
    if body['result'] == 'FAILED':
        battle['questBattleStatus'] = 'FAILED'
        resultUserQuestBattle = dt.getUserObject('userQuestBattleList',
                                                 battle['questBattleId'])
        if resultUserQuestBattle is None:  # not sure why this would happen, but?? make it just in case
            resultUserQuestBattle = newtil.createUserQuestBattle(
                battle['questBattleId'])
            dt.setUserObject('userQuestBattleList', battle['questBattleId'],
                             resultUserQuestBattle)
    else:
        battle['questBattleStatus'] = 'SUCCESSFUL'
        resultUserQuestBattle = dt.getUserObject('userQuestBattleList',
                                                 battle['questBattleId'])
        # add exp to user and level up, maybe
        gameUser, newStatus = giveUserExp(battle)
        # level up/episode up megucas
        resultUserCardList, resultUserCharaList, resultUserSectionList = giveMegucaExp(
            battle)
        cleared = 'cleared' in resultUserQuestBattle and resultUserQuestBattle[
            'cleared']
        # add drops -- required before clearing
        dropResponse = giveDrops(battle)
        # clear
        if not cleared:
            resultUserQuestBattle = storyUtil.clearBattle(battle)
            storyResponse = storyUtil.progressStory(battle)
        else:
            resultUserQuestBattle['lastClearedAt'] = homu.nowstr()
            resultUserQuestBattle['clearCount'] = resultUserQuestBattle.get(
                'clearCount', 0) + 1
        # missions
        battle, resultUserQuestBattle, rewardResponse = clearMissions(
            body, battle)

    # make response
    response = {
        "resultCode": "success",
        'gameUser': gameUser,
        'userCardList': resultUserCardList,
        'userCharaList': resultUserCharaList,
        'userQuestBattleResultList': [battle],
        'userQuestBattleList': [resultUserQuestBattle]
    }

    # a bunch of stuff that may or may not be necessary depending on which story and who's participating
    for partResponse in [storyResponse, dropResponse, rewardResponse]:
        if partResponse is not None:
            response = dt.updateJson(response, partResponse)

    userCards, userCharas = getBattleCards(battle)
    if resultUserCardList is not None:
        response['userCardList'] = resultUserCardList
    else:
        response['userCardList'] = userCards
    if resultUserCharaList is not None:
        response['userCharaList'] = resultUserCharaList
    else:
        response['userCharaList'] = userCharas
    if resultUserSectionList is not None and len(resultUserSectionList) != 0:
        response['userSectionList'] = resultUserSectionList

    if newStatus != []:
        response['userStatusList'] = newStatus

    return flask.jsonify(response)
Esempio n. 10
0
def buy():
    body = flask.request.json
    shopList = dt.readJson('data/shopList.json')

    currShop = {}
    for shop in shopList:
        if shop['shopId'] == body['shopId']:
            currShop = shop
            break
    if currShop == {}:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Trying to buy from a nonexistent shop","resultCode": "error","title": "Error"}'
        )

    item = {}
    for shopItem in shop['shopItemList']:
        if shopItem['id'] == body['shopItemId']:
            item = shopItem
            break
    if item == {}:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Trying to buy something not in this shop","resultCode": "error","title": "Error"}'
        )

    # get the thing
    args = {}
    if item['shopItemType'] == 'SET':
        obtainSet(item, body, args)
    else:
        obtain(item, body, args)

    # spend items
    if item['consumeType'] == 'ITEM':
        spendArgs = getItem(item['needItemId'],
                            -1 * item['needNumber'] * body['num'])
        if 'userItemList' in args:
            args['userItemList'] += spendArgs['userItemList']
        else:
            args = dt.updateJson(args, spendArgs)
    elif item['consumeType'] == 'MONEY':
        itemList = gacha.spend('MONEY', item['needNumber'] * body['num'])
        if 'userItemList' in args:
            args['userItemList'] += itemList
        else:
            args['userItemList'] = itemList

    userShopItem = {
        "createdAt": nowstr(),
        "num": body['num'],
        "shopItemId": body['shopItemId'],
        "userId": dt.userId
    }
    args['userShopItemList'] = [userShopItem]
    path = 'data/user/userShopItemList.json'
    dt.saveJson(path, dt.readJson(path) + [userShopItem])

    return flask.jsonify(args)