예제 #1
0
    def handle(self, **options):
        print(f"[CRON {logdate()}] START loot")
        
        # update NPC status
        for npc in NPC.objects.filter(show=True):
            print(f"[CRON {logdate()}] Update {npc}")
            npc.update()

        if options.get("clear_cache", False):
            r = clear_cf_cache(["https://yata.yt/api/v1/loot/"])
            print("[loot.NPC.update] clear cloudflare cache", r)
    
        print(f"[CRON {logdate()}] END")
예제 #2
0
    def handle(self, **options):
        print(f"[CRON {logdate()}] start loot")

        # update NPC status
        for npc in NPC.objects.filter(show=True):
            print(f"[CRON {logdate()}] update {npc}")
            npc.update()

        if options.get("clear_cache", False):
            r = clear_cf_cache(["https://yata.yt/api/v1/loot/"])
            print(f"[CRON {logdate()}] clear cloudflare cache:")
            for k, v in r.items():
                print(f"[CRON {logdate()}]\t\t{k}: {v}")

        print(f"[CRON {logdate()}] end")
예제 #3
0
    def handle(self, **options):
        print(f"[CRON {logdate()}] start loot")

        # update NPC status
        for npc in NPC.objects.filter(show=True):
            print(f"[CRON {logdate()}] update {npc}")
            npc.update()

        if options.get("clear_cache", False):
            print(f"[CRON {logdate()}] clear loot cache")
            cache.delete("context_processor_loot")
            # cache.delete("api_loot")
            r = clear_cf_cache([
                "https://yata.yt/api/v1/loot/", "https://yata.yt/api/v1/loot"
            ])

        print(f"[CRON {logdate()}] end")
예제 #4
0
    def update(self, key=None):
        if key is None:
            key = randomKey()

        # req = requests.get('https://api.torn.com/user/{}?&selections=profile,timestamp&key={}'.format(self.tId, key)).json()
        req = apiCall("user",
                      self.tId,
                      "profile,timestamp",
                      key=key,
                      verbose=False)

        if 'apiError' in req:
            return req['apiError']
        else:
            old_hospitalTS = self.hospitalTS
            self.name = req.get("name", "?")
            self.updateTS = int(req.get("timestamp", 0))
            states = req.get("states")
            status = req.get("status")

            if states['hospital_timestamp']:
                self.hospitalTS = states['hospital_timestamp']
                self.status = 'hospitalized'
            else:
                self.status = status["details"]

            # print("[loot.NPC.update] {}: {} {} {}".format(self, self.status, self.hospitalTS, self.updateTS))
            self.save()

        # clear context processor caching caching
        # clear cloudfare caching
        if old_hospitalTS != self.hospitalTS:
            print("[loot.NPC.update] clear cache")
            cache.delete("context_processor_loot")
            # cache.delete("api_loot")
            r = clear_cf_cache([
                "https://yata.yt/api/v1/loot/", "https://yata.yt/api/v1/loot"
            ])
예제 #5
0
 def handle(self, **options):
     print(f"[CRON {logdate()}]")
     r = clear_cf_cache(["https://yata.yt/api/v1/travel/export/"])
     print("[api.travel.export] clear cloudflare cache", r)
     print(f"[CRON {logdate()}] END")
예제 #6
0
파일: travel.py 프로젝트: selits/yata
def importStocks(request):
    try:
        if request.method != 'POST':
            return JsonResponse(
                {"error": {
                    "code": 2,
                    "error": "POST request needed"
                }},
                status=400)

        payload = json.loads(request.body)

        # check mandatory keys
        for key in ["country", "items"]:
            if key not in payload:
                return JsonResponse(
                    {
                        "error": {
                            "code": 2,
                            "error": f'Missing \'{key}\' key in payload"'
                        }
                    },
                    status=400)

        # check items length
        if not len(payload["items"]):
            return JsonResponse(
                {"error": {
                    "code": 2,
                    "error": "Empty items list"
                }},
                status=400)

        # check country:
        country_key = str(payload["country"]).lower().strip()[:3]
        if country_key not in countries:
            return JsonResponse(
                {
                    "error": {
                        "code": 2,
                        "error": f'Unknown country key \'{country_key}\''
                    }
                },
                status=400)

        country = countries[country_key]["name"]
        items = payload["items"]
        # uid = int(payload.get("uid", 0)) if str(payload.get("uid", 0)).isdigit() else 0
        client_name = payload.get("client", "unknown").strip()
        client_version = payload.get("version", "0.0")
        timestamp = tsnow()

        # convert list to dict and check keys
        # for all keys to be int
        if isinstance(items, list):
            items_list = items
            items = dict({})
            for item in items_list:
                for key in ["id", "quantity", "cost"]:
                    if not str(item.get(key)).isdigit():
                        return JsonResponse(
                            {
                                "error": {
                                    "code":
                                    2,
                                    "error":
                                    f'Wrong {key} for item object: {item.get(key)}'
                                }
                            },
                            status=400)

                items[int(item["id"])] = {
                    "cost": int(item["cost"]),
                    "quantity": int(item["quantity"])
                }

        elif isinstance(items, dict):
            # cast to int the keys
            cast_to_int = []
            for item_id, item in items.items():
                if not str(item_id).isdigit():
                    return JsonResponse(
                        {
                            "error": {
                                "code": 2,
                                "error": f'Wrong item id {item_id}'
                            }
                        },
                        status=400)

                for key in ["quantity", "cost"]:
                    if not str(item.get(key)).isdigit():
                        return JsonResponse(
                            {
                                "error": {
                                    "code": 2,
                                    "error":
                                    f'Wrong item {key} for item {item_id}'
                                }
                            },
                            status=400)

                item = {
                    "cost": int(item["cost"]),
                    "quantity": int(item["quantity"])
                }
                if not isinstance(item_id, int):
                    cast_to_int.append(item_id)

            # cast to int the keys
            for k in cast_to_int:
                items[int(k)] = items[k]
                del items[k]

        else:
            return JsonResponse(
                {"error": {
                    "code": 2,
                    "error": "Expecting a POST request"
                }},
                status=400)

        # get all unique items from this country
        distinct_items = [
            k['item_id'] for k in AbroadStocks.objects.filter(
                country_key=country_key).values('item_id').distinct()
        ]

        # add items not in db
        # for all keys and values to be int
        for k in items:
            if k not in distinct_items:
                distinct_items.append(k)

        stocks = dict({})
        for item_id in distinct_items:
            item = items.get(item_id, False)
            cost = 0
            quantity = 0
            if item:
                cost = item["cost"]
                quantity = item["quantity"]
            else:
                lastItem = AbroadStocks.objects.filter(
                    item_id=item_id,
                    country_key=country_key).order_by("-timestamp").first()
                cost = 0 if lastItem is None else lastItem.cost
                quantity = 0

            stocks[item_id] = {
                "country": country,
                "country_key": country_key,
                "client": "{} [{}]".format(client_name, client_version),
                "timestamp": timestamp,
                "cost": cost,
                "quantity": quantity
            }

        client, _ = VerifiedClient.objects.get_or_create(
            name=client_name, version=client_version)
        client.update_author(payload)
        if client.verified:
            for k, v in stocks.items():
                item = Item.objects.filter(tId=k).first()
                if item is None:
                    return JsonResponse(
                        {
                            "error": {
                                "code": 2,
                                "error": f"Item {k} not found in database"
                            }
                        },
                        status=400)

                AbroadStocks.objects.filter(item=item,
                                            country_key=v["country_key"],
                                            last=True).update(last=False)
                v["last"] = True
                item.abroadstocks_set.create(**v)

            # clear cloudflare cache
            r = clear_cf_cache(["https://yata.yt/api/v1/travel/export/"])
            print("[api.travel.import] clear cloudflare cache", r)

            return JsonResponse(
                {"message": f"The stocks have been updated with {client}"},
                status=200)

        else:
            msg = f'Your client \'{client_name} [{client_name}]\' made a successful request but has not been added to the official API list. If you feel confident it\'s working correctly contact Kivou [2000607] to start updating the database.'
            return JsonResponse({"message": msg, "stocks": stocks}, status=200)

    except BaseException as e:
        return JsonResponse({"error": {
            "code": 1,
            "error": str(e)
        }},
                            status=500)