-
Notifications
You must be signed in to change notification settings - Fork 0
/
bgg.py
executable file
·173 lines (150 loc) · 8.09 KB
/
bgg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import argparse
import json
import webbrowser
from sys import platform
from simple_term_menu import TerminalMenu
import link
from utils import *
selected = None
class Reversor:
def __init__(self, value): self.value =value
def __eq__(self, oth): return oth.value == self.value
def __lt__(self, oth): return oth.value < self.value
def choose_title():
if platform == 'ios':
import dialogs
sections = [
{"title":"Game: ", "type": "text", "key":"game"},
{"title":"Plays: ", "type":"number", "key":"plays", "value": "1"}
]
choices = dialogs.form_dialog("Game Played", fields=sections) or {}
try:
plays = int(choices.get('plays', 0))
game = choices.get('game')
if game and plays > 0:
game_options = link.get_games(game)
if game_options:
selected = dialogs.list_dialog("Choose Title", [f'{g["name"]} ({g["year"]}) - {g["idx"]}' for g in game_options])
if selected:
idx = selected.split('-')[-1]
link.log_play(idx, plays)
dialogs.alert("Add Success", f"Added {str(plays) + ' plays' if plays != 1 else str(plays) + ' play'} to {game}", "Close", hide_cancel_button=True)
else:
dialogs.alert(f"No entries found for {game} on BoardGameGeek!")
except ValueError:
dialogs.alert("Play count must be a number!")
else:
raise ImportError("Cannot run choose_title on a non-iOS device!")
if __name__ == '__main__':
try:
if platform != 'ios':
try:
with open(cache_path, 'r') as cf:
cache = json.load(cf)
except FileNotFoundError:
cache = {}
parser = argparse.ArgumentParser(
prog='bgg',
description="Various utilities for BoardGameGeek logging",
allow_abbrev=True,
)
mutex = parser.add_mutually_exclusive_group()
mutex.add_argument('-a', '--add', nargs='+', metavar=('title', '?plays'), help="add plays by title")
mutex.add_argument('-s', '--summary', nargs='*', metavar=('?days', '?filter'), const=None, help='get game summary for last # of days (or full history if omitted)')
mutex.add_argument('-l', '--login', action='store_true', help="login to a BoardGameGeek account")
mutex.add_argument('-o', '--open', action='store_true', help='open logged in BoardGameGeek account')
mutex.add_argument('-r', '--reset-cache', action='store_true', help="reset stored search cache information")
parser.add_argument('-n', '--nocache', action='store_true', help='ignore cache')
parser.add_argument('-m', '--sortmode', default='plays', const='plays', nargs='?', choices=['title', 'plays'], help='mode to sort summary by')
parser.add_argument('-c', '--comment', nargs='?', help='play comment')
args = vars(parser.parse_args())
add, summary = args.get('add'), args.get('summary')
no_args = True
if args.get('reset_cache'):
no_args = False
try:
print("Clearing stored play cache!")
os.remove(cache_path)
except OSError as e:
pass
if args.get('login'):
link.login()
elif add is not None:
plays = 1
if len(add) == 2:
try:
plays = int(add[1])
if plays < 1: raise ValueError
except ValueError:
parser.error("Play argument must be a positive number (preferably an integer)!")
use_cache = not args.get('nocache')
title = add[0].lower()
game_options = link.get_games(title)
if use_cache and title in cache and cache[title]['count'] >= 3:
selected = cache[title]
else:
if not game_options:
print("No items found!")
else:
game_items = [f'{game["name"]} ({game["year"]}) - ID: {game["idx"]}' for game in game_options]
sidx = TerminalMenu(game_items, menu_highlight_style=("bg_cyan", "fg_black")).show()
selected = game_options[sidx] if isinstance(sidx, int) else None
if selected is not None:
print(f"Adding {CYAN}{plays} {'plays' if plays > 1 else 'play'}{DEFAULT} to {YELLOW}{selected['name']} ({selected['year']}){DEFAULT}...")
try:
res = link.log_play(selected['idx'], plays=plays, comment=args.get('comment'))
if res == 200:
print(f"{GREEN}{'Plays added!' if plays > 1 else 'Play added!'}{DEFAULT}")
else:
if res == 401:
print(f"{RED}Incorrect credentials for currently logged in account{DEFAULT}. Try logging in with {YELLOW}bgg -l{DEFAULT}!")
else:
print(f"{RED}Play adding failed for unknown reasons!{DEFAULT}")
exit(1)
if not title in cache or cache[title]['idx'] != selected['idx']:
cache[title] = {'count': 1, 'idx': selected['idx'], 'name': selected['name'],
'year': selected['year']}
else:
cache[title]['count'] += 1
with open(cache_path, 'w+') as cf:
json.dump(cache, cf)
except Exception as e:
print(e)
print(f"{RED}Play adding failed!{DEFAULT}")
elif summary is not None:
days = 0
filter_on = "".join(summary[1:]) if len(summary) > 1 else ""
if len(summary) > 0 and summary[0] != '.':
try:
days = int(summary[0])
except ValueError:
print("Summary must have a number or . as its first argument!")
exit(1)
play_data = link.get_plays(None if days < 1 else days)
if play_data:
game_data = {}
for play in play_data:
if play['name'] in game_data: game_data[play['name']] += play['plays']
else: game_data[play['name']] = play['plays']
game_sorter = lambda gd: gd
if args.get('sortmode') == 'plays':
game_sorter = lambda gd: (Reversor(gd[1]), gd[0] if not gd[0].lower().startswith("the ") else gd[0][4:])
elif args.get('sortmode') == 'title':
game_sorter = lambda gd: (gd[0] if not gd[0].lower().startswith("the ") else gd[0][4:])
summary_set = [gd for gd in sorted(game_data.items(), key=game_sorter) if filter_on.lower() in gd[0].lower()]
if not summary_set:
print(f"{RED}No games found matching filter condition '{filter_on}'!{DEFAULT}")
else:
for game, plays in summary_set:
print(f"- {YELLOW}{game}{DEFAULT}: {CYAN}{plays}{DEFAULT}")
else:
print(f"{RED}No plays logged{' in that timespan' if summary < 1 else ''}!{DEFAULT}")
elif args.get('open'):
user = link.get_user()
webbrowser.open(f'https://boardgamegeek.com/collection/user/{user.get("username")}')
elif no_args:
parser.print_help()
else:
choose_title()
except KeyboardInterrupt:
pass