|
1 | 1 | import random |
2 | 2 | import argparse |
| 3 | +import json |
| 4 | +import sys |
| 5 | +import traceback |
| 6 | +from pathlib import Path |
| 7 | +from datetime import datetime, timezone, timedelta |
3 | 8 |
|
4 | 9 | def main(): |
5 | 10 | parser = argparse.ArgumentParser() |
@@ -74,10 +79,39 @@ def run(sources, posters): |
74 | 79 |
|
75 | 80 |
|
76 | 81 | def pick_pet(pets): |
77 | | - eligible = [pet for pet in pets if pet.image_url and pet.adoption_url] |
78 | | - if not eligible: |
79 | | - return None |
80 | | - return random.choice(eligible) |
| 82 | + Path("database.json").touch(exist_ok=True) |
| 83 | + # Open file |
| 84 | + with open("database.json", "r+") as f: |
| 85 | + # Load json |
| 86 | + try: |
| 87 | + data = json.load(f) |
| 88 | + except (json.JSONDecodeError, ValueError) as e: |
| 89 | + print(f"{type(e).__name__}:{e}", file=sys.stderr) |
| 90 | + traceback.print_exc() |
| 91 | + data = {} |
| 92 | + |
| 93 | + if "posted_pets" in data: |
| 94 | + posted_pet_ids = {pet.pet_id for pet in data["posted_pets"]} |
| 95 | + else: |
| 96 | + pet_ids = {} |
| 97 | + data["posted_pets"] = [] |
| 98 | + # Check pet has an image, adoption url, and has not been posted |
| 99 | + eligible = [pet for pet in pets if pet.image_url and pet.adoption_url and pet.pet_id not in posted_pet_ids] |
| 100 | + if not eligible: |
| 101 | + return None |
| 102 | + |
| 103 | + selected_pet = random.choice(eligible) |
| 104 | + # Add pet ID to list of posted pets |
| 105 | + data["posted_pets"].append({"name": selected_pet.name, "pet_id": selected_pet.pet_id, "time": datetime.now(timezone.utc).isoformat()}) |
| 106 | + # Remove old pets |
| 107 | + cutoff = datetime.now() - timedelta(weeks=12) |
| 108 | + new_pets = [item for item in data["posted_pets"] if datetime.fromisoformat(item['time']) > cutoff] |
| 109 | + data["posted_pets"] = new_pets |
| 110 | + # Export json |
| 111 | + f.seek(0) |
| 112 | + json.dump(data, f) |
| 113 | + f.truncate() |
| 114 | + return selected_pet |
81 | 115 |
|
82 | 116 |
|
83 | 117 | if __name__ == "__main__": |
|
0 commit comments