Example #1
0
def index(request):
    try:
        if request.session.get('player'):
            print('[view.awards.index] get player id from session')
            tId = request.session["player"].get("tId")
            player = Player.objects.filter(tId=tId).first()
            player.lastActionTS = int(timezone.now().timestamp())
            awardsJson = json.loads(player.awardsJson)
            userInfo = awardsJson.get('userInfo')

            error = False
            tornAwards = Call.objects.first().load()
            userInfo = apiCall('user', '', 'personalstats,crimes,education,battlestats,workstats,perks,networth,merits,profile,medals,honors,icons', player.key)
            if 'apiError' in userInfo:
                error = userInfo
            else:
                print("[view.awards.index] update awards")
                awardsJson["userInfo"] = userInfo
                player.awardsJson = json.dumps(awardsJson)
                updatePlayerAwards(player, tornAwards, userInfo)
                player.save()

            # get graph data
            awards = awardsJson.get('awards')
            graph = []
            for k, h in sorted(tornAwards.get("honors").items(), key=lambda x: x[1]["circulation"], reverse=True):
                # if h.get("rarity") not in ["Unknown Rarity"]:
                if h.get("circulation", 0) > 0:
                    graph.append([h.get("name", "?"), h.get("circulation", 0), int(h.get("achieve", 0)), h.get("img", ""), h.get("rScore", 0), h.get("unreach", 0)])

            graph2 = []
            for k, h in sorted(tornAwards.get("medals").items(), key=lambda x: x[1]["circulation"], reverse=True):
                # if h.get("rarity") not in ["Unknown Rarity"]:
                if h.get("circulation", 0) > 0:
                    graph2.append([h.get("name", "?"), h.get("circulation", 0), int(h.get("achieve", 0)), h.get("img", ""), h.get("rScore", 0), h.get("unreach", 0)])

            context = {"player": player, "graph": graph, "graph2": graph2, "awardscat": True, "view": {"awards": True}}
            for k, v in json.loads(player.awardsJson).items():
                context[k] = v
            if error:
                context.update(error)
            return render(request, "awards.html", context)

        else:
            return returnError(type=403, msg="You might want to log in.")

    except Exception:
        return returnError()
Example #2
0
def list(request, type):
    try:
        if request.session.get('player'):
            print('[view.awards.list] get player id from session')
            tId = request.session["player"].get("tId")
            player = Player.objects.filter(tId=tId).first()
            player.lastActionTS = int(timezone.now().timestamp())
            player.save()

            awardsJson = json.loads(player.awardsJson)
            print('[view.awards.list] award type: {}'.format(type))

            tornAwards = Call.objects.first().load()
            userInfo = awardsJson.get('userInfo')
            summaryByType = awardsJson.get('summaryByType')

            if type in AWARDS_CAT:
                awards, awardsSummary = createAwards(tornAwards, userInfo,
                                                     type)
                graph = []
                graph2 = []
                for type, honors in awards.items():
                    for k, h in honors.items():
                        # if h.get("rarity", "Unknown Rarity") not in ["Unknown Rarity"]:
                        if h.get("circulation", 0) > 0:
                            if h.get("awardType") in ["Honor"]:
                                graph.append([
                                    h.get("name", "?"),
                                    h.get("circulation", 0),
                                    int(h.get("achieve", 0)),
                                    h.get("img", ""),
                                    h.get("rScore", 0),
                                    h.get("unreach", 0)
                                ])
                            elif h.get("awardType") in ["Medal"]:
                                graph2.append([
                                    h.get("name", "?"),
                                    h.get("circulation", 0),
                                    int(h.get("achieve", 0)),
                                    h.get("img", ""),
                                    h.get("rScore", 0),
                                    h.get("unreach", 0)
                                ])

                graph = sorted(graph, key=lambda x: -x[1])
                graph2 = sorted(graph2, key=lambda x: -x[1])
                context = {
                    "player": player,
                    "view": {
                        "awards": True
                    },
                    "awardscat": True,
                    "awards": awards,
                    "awardsSummary": awardsSummary,
                    "summaryByType": summaryByType,
                    "graph": graph,
                    "graph2": graph2
                }
                page = 'awards/list.html' if request.method == 'POST' else "awards.html"
                return render(request, page, context)

            elif type == "all":
                awards = awardsJson.get('awards')
                graph = []
                updatePlayerAwards(player, tornAwards, userInfo)
                for k, h in sorted(tornAwards.get("honors").items(),
                                   key=lambda x: x[1]["circulation"],
                                   reverse=True):
                    if h.get("circulation", 0) > 0:
                        graph.append([
                            h.get("name", "?"),
                            h.get("circulation", 0),
                            int(h.get("achieve", 0)),
                            h.get("img", ""),
                            h.get("rScore", 0),
                            h.get("unreach", 0)
                        ])

                graph2 = []
                for k, h in sorted(tornAwards.get("medals").items(),
                                   key=lambda x: x[1]["circulation"],
                                   reverse=True):
                    if h.get("circulation", 0) > 0:
                        graph2.append([
                            h.get("name", "?"),
                            h.get("circulation", 0),
                            int(h.get("achieve", 0)),
                            h.get("img", ""),
                            h.get("rScore", 0),
                            h.get("unreach", 0)
                        ])

                context = {
                    "player": player,
                    "view": {
                        "awards": True
                    },
                    "awardscat": True,
                    "awards": awards,
                    "summaryByType": summaryByType,
                    "graph": graph,
                    "graph2": graph2
                }
                page = 'awards/content-reload.html' if request.method == 'POST' else "awards.html"
                return render(request, page, context)

            elif type == "hof":
                hof = []
                hofGraph = []
                for p in Player.objects.exclude(awardsInfo="N/A").all():
                    try:
                        hof.append({
                            "player":
                            p,
                            "rscore":
                            float(p.awardsInfo),
                            # "nAwarded": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwarded"],
                            # "nAwards": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwards"],
                            "nAwarded":
                            json.loads(p.awardsJson)["summaryByType"]
                            ["AllAwards"]["nAwarded"],
                            "nAwards":
                            json.loads(p.awardsJson)["summaryByType"]
                            ["AllAwards"]["nAwards"],
                        })
                        hofGraph.append(float(p.awardsInfo))
                    except BaseException:
                        print('[view.awards.list] error getting info on {}'.
                              format(p))

                awards = awardsJson.get('awards')
                graph = []
                updatePlayerAwards(player, tornAwards, userInfo)
                for k, h in sorted(tornAwards.get("honors").items(),
                                   key=lambda x: x[1]["circulation"],
                                   reverse=True):
                    if h.get("circulation", 0) > 0:
                        graph.append([
                            h.get("name", "?"),
                            h.get("circulation", 0),
                            int(h.get("achieve", 0)),
                            h.get("img", ""),
                            h.get("rScore", 0),
                            h.get("unreach", 0)
                        ])

                graph2 = []
                for k, h in sorted(tornAwards.get("medals").items(),
                                   key=lambda x: x[1]["circulation"],
                                   reverse=True):
                    if h.get("circulation", 0) > 0:
                        graph2.append([
                            h.get("name", "?"),
                            h.get("circulation", 0),
                            int(h.get("achieve", 0)),
                            h.get("img", ""),
                            h.get("rScore", 0),
                            h.get("unreach", 0)
                        ])

                bins = numpy.logspace(-2, 2, num=101)
                bins[0] = 0
                histo, _ = numpy.histogram(hofGraph, bins=bins)
                cBins = [
                    0.5 * float(a + b) for a, b in zip(bins[:-1], bins[1:])
                ]
                hofGraph = [[
                    x, y, xm, xp, 0
                ] for x, y, xm, xp in zip(cBins, histo, bins[:-1], bins[1:])]
                hofGraph[0][4] = hofGraph[0][1]
                for i in range(len(hofGraph) - 1):
                    hofGraph[i + 1][4] = hofGraph[i + 1][1] + hofGraph[i][4]
                context = {
                    "player": player,
                    "view": {
                        "hof": True
                    },
                    "awardscat": True,
                    "awards": awards,
                    "summaryByType": summaryByType,
                    "graph": graph,
                    "graph2": graph2,
                    "hof": sorted(hof, key=lambda x: -x["rscore"]),
                    "hofGraph": hofGraph
                }
                page = 'awards/content-reload.html' if request.method == 'POST' else "awards.html"
                return render(request, page, context)

        else:
            return returnError(type=403, msg="You might want to log in.")

    except Exception:
        return returnError()
Example #3
0
File: models.py Project: kib/yata
    def update_info(self):
        """ update player information

        """
        print("[player.models.update_info] {}".format(self))
        from yata.handy import apiCall
        from awards.functions import updatePlayerAwards
        from chain.models import Faction
        import json

        # API Calls
        user = apiCall(
            'user', '',
            'personalstats,crimes,education,battlestats,workstats,perks,networth,merits,profile,medals,honors,icons',
            self.key)

        # if user.get('apiErrorCode') == 2:
        #    print("delete player")
        #    self.delete()
        #    return 0

        # update basic info (and chain)
        self.name = user.get("name", "?")
        self.factionId = user.get("faction", dict({})).get("faction_id", 0)
        self.factionNa = user.get("faction",
                                  dict({})).get("faction_name", "N/A")

        # update chain info
        if self.factionId:
            faction = Faction.objects.filter(tId=self.factionId).first()
            if faction is None:
                faction = Faction.objects.create(tId=self.factionId)
            faction.name = self.factionNa

            chains = apiCall("faction", "", "chains", self.key)
            if chains.get("chains") is not None:
                self.factionAA = True
                self.chainInfo = "{} [AA]".format(self.factionNa)
                faction.addKey(self.tId, self.key)
            else:
                self.factionAA = False
                self.chainInfo = "{}".format(self.factionNa)
                faction.delKey(self.tId)

            faction.save()

        else:
            self.factionAA = False
            self.chainInfo = "N/A"
        self.chainUpda = int(timezone.now().timestamp())

        # update awards info
        # tornAwards = apiCall('torn', '', 'honors,medals', self.key)
        tornAwards = Call.objects.first().load()
        if 'apiError' in tornAwards:
            self.awardsJson = json.dumps(tornAwards)
            self.awardsInfo = "0"
        else:
            updatePlayerAwards(self, tornAwards, user)
        self.awardsUpda = int(timezone.now().timestamp())

        # clean '' targets
        targetsAttacks = json.loads(self.targetJson)
        if len(targetsAttacks):
            targets = targetsAttacks.get("targets", dict({}))
            for k, v in targets.items():
                if k == '':
                    print(
                        "[player.models.update_info] delete target of player {}: {}"
                        .format(self, v))
            if targets.get('') is not None:
                del targets['']
            targetsAttacks["targets"] = targets
            self.targetJson = json.dumps(targetsAttacks)
            self.targetInfo = len(targets)

        self.lastUpdateTS = int(timezone.now().timestamp())
        self.save()

        print("[player.models.update_info] {} / {}".format(
            self.chainInfo, self.awardsInfo))
Example #4
0
    def update_info(self, i=None, n=None):
        """ update player information

        """

        progress = "{:04}/{:04}: ".format(i, n) if i is not None else ""

        # API Calls
        user = apiCall(
            'user',
            '',
            'personalstats,crimes,education,battlestats,workstats,perks,networth,merits,profile,medals,honors,icons,bars,discord',
            self.key,
            verbose=False)

        # set active
        self.active = int(
            timezone.now().timestamp()) - self.lastActionTS < 60 * 60 * 24 * 31

        # change to false if error code 2
        self.validKey = False if user.get('apiErrorCode',
                                          0) == 2 else self.validKey

        # change to true if fetch result
        self.validKey = True if user.get('name', False) else self.validKey

        # discrod id
        dId = user.get('discord', {'discordID': ''})['discordID']
        self.dId = 0 if dId in [''] else dId

        # skip if not yata active and no valid key
        if not self.active and not self.validKey:
            print(
                "[player.models.update_info] {}{} action: {:010} active: {:1} api: {:1} -> delete user"
                .format(progress, self, self.lastActionTS, self.active,
                        self.validKey))
            # self.delete()
            self.save()
            return 0

        # skip if api error (not invalid key)
        elif 'apiError' in user:
            print(
                "[player.models.update_info] {}{} action: {:010} active: {:1} api: {:1} -> api error {}"
                .format(progress, self, self.lastActionTS, self.active,
                        self.validKey, user["apiError"]))
            self.save()
            return 0

        # skip if not active in torn since last update
        elif self.lastUpdateTS > int(user.get("last_action")["timestamp"]):
            print(
                "[player.models.update_info] {}{} skip since not active since last update"
                .format(progress, self))
            return 0

        # do update
        else:
            print(
                "[player.models.update_info] {}{} action: {:010} active: {:1} api: {:1}"
                .format(progress, self, self.lastActionTS, self.active,
                        self.validKey))

        # update basic info (and chain)
        self.name = user.get("name", "?")
        self.factionId = user.get("faction", dict({})).get("faction_id", 0)
        self.factionNa = user.get("faction",
                                  dict({})).get("faction_name", "N/A")

        # update chain info
        if self.factionId:
            faction = Faction.objects.filter(tId=self.factionId).first()
            if faction is None:
                faction = Faction.objects.create(tId=self.factionId)
            faction.name = self.factionNa

            chains = apiCall("faction", "", "chains", self.key, verbose=False)
            if chains.get("chains") is not None:
                self.factionAA = True
                self.chainInfo = "{} [AA]".format(self.factionNa)
                faction.addKey(self.tId, self.key)
            else:
                self.factionAA = False
                self.chainInfo = "{}".format(self.factionNa)
                faction.delKey(self.tId)

            faction.save()

        else:
            self.factionAA = False
            self.chainInfo = "N/A"
        self.chainUpda = int(timezone.now().timestamp())

        # update awards info
        # tornAwards = apiCall('torn', '', 'honors,medals', self.key)
        tornAwards = AwardsData.objects.first().loadAPICall()
        if 'apiError' in tornAwards:
            self.awardsJson = json.dumps(tornAwards)
            self.awardsInfo = "0"
        else:
            updatePlayerAwards(self, tornAwards, user)
        self.awardsUpda = int(timezone.now().timestamp())

        # clean '' targets
        targetsAttacks = json.loads(self.targetJson)
        if len(targetsAttacks):
            targets = targetsAttacks.get("targets", dict({}))
            for k, v in targets.items():
                if k == '':
                    print(
                        "[player.models.update_info] delete target of player {}: {}"
                        .format(self, v))
            if targets.get('') is not None:
                del targets['']
            targetsAttacks["targets"] = targets
            self.targetJson = json.dumps(targetsAttacks)
            self.targetInfo = len(targets)

        self.lastUpdateTS = int(timezone.now().timestamp())
        self.save()
Example #5
0
def list(request, type):
    try:
        if request.session.get('player'):
            print('[view.awards.list] get player id from session')
            tId = request.session["player"].get("tId")
        else:
            print('[view.awards.index] anon session')
            tId = -1

        player = Player.objects.filter(tId=tId).first()
        player.lastActionTS = int(timezone.now().timestamp())
        player.save()

        awardsJson = json.loads(player.awardsJson)
        print('[view.awards.list] award type: {}'.format(type))

        tornAwards = AwardsData.objects.first().loadAPICall()
        userInfo = awardsJson.get('userInfo')
        summaryByType = awardsJson.get('summaryByType')

        if type in AWARDS_CAT:
            awards, awardsSummary = createAwards(tornAwards, userInfo, type)
            graph = []
            graph2 = []
            for type, honors in awards.items():
                for k, h in honors.items():
                    # if h.get("rarity", "Unknown Rarity") not in ["Unknown Rarity"]:
                    if h.get("circulation", 0) > 0:
                        if h.get("awardType") in ["Honor"]:
                            graph.append([
                                h.get("name", "?"),
                                h.get("circulation", 0),
                                int(h.get("achieve", 0)),
                                h.get("img", ""),
                                h.get("rScore", 0),
                                h.get("unreach", 0)
                            ])
                        elif h.get("awardType") in ["Medal"]:
                            graph2.append([
                                h.get("name", "?"),
                                h.get("circulation", 0),
                                int(h.get("achieve", 0)),
                                h.get("img", ""),
                                h.get("rScore", 0),
                                h.get("unreach", 0)
                            ])

            graph = sorted(graph, key=lambda x: -x[1])
            graph2 = sorted(graph2, key=lambda x: -x[1])
            context = {
                "player": player,
                "view": {
                    "awards": True
                },
                "awardscat": True,
                "awards": awards,
                "awardsSummary": awardsSummary,
                "summaryByType": summaryByType,
                "graph": graph,
                "graph2": graph2
            }
            page = 'awards/list.html' if request.method == 'POST' else "awards.html"
            return render(request, page, context)

        elif type == "all":
            awards = awardsJson.get('awards')
            graph = []
            updatePlayerAwards(player, tornAwards, userInfo)
            for k, h in sorted(tornAwards.get("honors").items(),
                               key=lambda x: x[1]["circulation"],
                               reverse=True):
                if h.get("circulation", 0) > 0:
                    graph.append([
                        h.get("name", "?"),
                        h.get("circulation", 0),
                        int(h.get("achieve", 0)),
                        h.get("img", ""),
                        h.get("rScore", 0),
                        h.get("unreach", 0)
                    ])

            graph2 = []
            for k, h in sorted(tornAwards.get("medals").items(),
                               key=lambda x: x[1]["circulation"],
                               reverse=True):
                if h.get("circulation", 0) > 0:
                    graph2.append([
                        h.get("name", "?"),
                        h.get("circulation", 0),
                        int(h.get("achieve", 0)),
                        h.get("img", ""),
                        h.get("rScore", 0),
                        h.get("unreach", 0)
                    ])

            context = {
                "player": player,
                "view": {
                    "awards": True
                },
                "awardscat": True,
                "awards": awards,
                "summaryByType": summaryByType,
                "graph": graph,
                "graph2": graph2
            }
            page = 'awards/content-reload.html' if request.method == 'POST' else "awards.html"
            return render(request, page, context)

        elif type == "hof":
            hof = []
            playerInHOF = False
            for p in Player.objects.filter(
                    awardsRank__lt=(HOF_SIZE + 1)).order_by('awardsRank'):
                try:
                    playerInHOF = True if tId == p.tId else playerInHOF
                    hof.append({
                        "player":
                        p,
                        "rscore":
                        float(p.awardsScor / 10000.0),
                        # "nAwarded": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwarded"],
                        # "nAwards": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwards"],
                        "nAwarded":
                        json.loads(p.awardsJson)["summaryByType"]["AllAwards"]
                        ["nAwarded"],
                        "nAwards":
                        json.loads(p.awardsJson)["summaryByType"]["AllAwards"]
                        ["nAwards"],
                    })
                except BaseException:
                    print('[view.awards.list] error getting info on {}'.format(
                        p))

            if not playerInHOF and player.tId > 0:
                hof.append({
                    "player":
                    player,
                    "rscore":
                    float(player.awardsScor / 10000.0),
                    # "nAwarded": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwarded"],
                    # "nAwards": json.loads(p.awardsJson)["summaryByType"]["AllHonors"]["nAwards"],
                    "nAwarded":
                    json.loads(player.awardsJson)["summaryByType"]["AllAwards"]
                    ["nAwarded"],
                    "nAwards":
                    json.loads(player.awardsJson)["summaryByType"]["AllAwards"]
                    ["nAwards"],
                })

            awards = awardsJson.get('awards')
            graph = []
            updatePlayerAwards(player, tornAwards, userInfo)
            for k, h in sorted(tornAwards.get("honors").items(),
                               key=lambda x: x[1]["circulation"],
                               reverse=True):
                if h.get("circulation", 0) > 0:
                    graph.append([
                        h.get("name", "?"),
                        h.get("circulation", 0),
                        int(h.get("achieve", 0)),
                        h.get("img", ""),
                        h.get("rScore", 0),
                        h.get("unreach", 0)
                    ])

            graph2 = []
            for k, h in sorted(tornAwards.get("medals").items(),
                               key=lambda x: x[1]["circulation"],
                               reverse=True):
                if h.get("circulation", 0) > 0:
                    graph2.append([
                        h.get("name", "?"),
                        h.get("circulation", 0),
                        int(h.get("achieve", 0)),
                        h.get("img", ""),
                        h.get("rScore", 0),
                        h.get("unreach", 0)
                    ])

            context = {
                "player": player,
                "view": {
                    "hof": True
                },
                "awardscat": True,
                "awards": awards,
                "summaryByType": summaryByType,
                "graph": graph,
                "graph2": graph2,
                "hof": sorted(hof, key=lambda x: -x["rscore"]),
                "hofGraph": json.loads(AwardsData.objects.first().hofHistogram)
            }
            page = 'awards/content-reload.html' if request.method == 'POST' else "awards.html"
            return render(request, page, context)

        # else:
        #     return returnError(type=403, msg="You might want to log in.")

    except Exception:
        return returnError()