-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
506 lines (421 loc) · 19 KB
/
main.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import os
import requests
import concurrent.futures
import logging
import json
from functools import partial
from lxml import etree
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from pathlib import Path
from android.permissions import request_permissions, Permission
from kivy.utils import platform
from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.core.window import Window
from kivy.properties import StringProperty, ObjectProperty, NumericProperty, DictProperty, ListProperty
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition, SlideTransition
from kivy.metrics import sp
from Py.connectivity import connectivity_status
from Py.standings import fetch_standings
from Py.stats import update_dict, access_per_game_stats
from Py.webview import WebViewInModal
from Widgets.popups import MessagePopup, DisplayStats, NotesPopup
from Widgets.rv_stats import RV
__version__ = '23.12.3'
class StatsByGame(Screen):
player_name = StringProperty('')
player_tree = DictProperty({})
recycle_view_mod = ObjectProperty(None)
data = ListProperty([])
opponents = ObjectProperty(None)
message = ObjectProperty(None)
notification = StringProperty('')
def extract_player_games(self):
self.opponents = self.player_tree.xpath('//div[@class="stats-table_table__dpgY7"]')
if len(self.opponents) != 0:
data = access_per_game_stats(self.player_tree, self.player_name)
self.data = data
else:
text = 'No games played by ' + self.player_name + ' yet!'
self.notification = text
def on_data(self, *args):
self.recycle_view_mod.perf_data = self.data
def on_notification(self, *args):
if self.notification != '':
self.message = MessagePopup(on_open=self.dismiss_text)
self.message.notification.text = self.notification
self.message.open()
def dismiss_text(self, *args):
Clock.schedule_once(self.message.dismiss, 1.5)
Clock.schedule_once(self.reset_text, 1.6)
def reset_text(self, *args):
self.notification = ''
@staticmethod
def call_teams_screen(*args):
del App.get_running_app().root.screens_visited[1:]
App.get_running_app().root.transition = FadeTransition(duration=.5)
App.get_running_app().root.current = 'teams'
class Stats(Screen):
player_tree = DictProperty({})
player_name = StringProperty('')
player_url = StringProperty()
player_photo = StringProperty('Images/NoImage.jpg')
text_1 = StringProperty('')
text_2 = StringProperty('')
stats = ListProperty([])
rv = ObjectProperty(None)
show_stats = ObjectProperty(None)
message = ObjectProperty(None)
notification = StringProperty('')
def extract_players_data(self):
pos = self.player_tree.xpath(
'//div[@class="player-hero_inner__rwwR_ side-gaps_sectionSideGaps__v5CKj"]'
'//div[@class="hero-info_position__GDXbP"]/text()')
info_1 = self.player_tree.xpath(
'//div[@class="player-hero_inner__rwwR_ side-gaps_sectionSideGaps__v5CKj"]'
'//ul[@class="hero-info_dataList__kKi0z"]//li[@class="hero-info_dataItem__UbJZU"]'
'//span[@class="hero-info_key__Pcrzp"]/text()')
info_2 = self.player_tree.xpath(
'//div[@class="player-hero_inner__rwwR_ side-gaps_sectionSideGaps__v5CKj"]'
'//ul[@class="hero-info_dataList__kKi0z"]//li[@class="hero-info_dataItem__UbJZU"]'
'//b[@class="hero-info_value__XFJeE"]/text()')
info = list()
for i, j, in zip(info_1, info_2):
s = i + ': ' + j
info.append(s)
try:
'''Check if photo already exists.'''
if self.player_photo.strip('.png') == self.player_name:
pass
elif len(self.player_url) != 0:
try:
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get(self.player_url)
player_photo = self.player_name + '.png'
with open(player_photo, 'wb') as f:
f.write(response.content)
self.player_photo = self.player_name + '.png'
except requests.exceptions.ConnectTimeout as conn_timeout:
logging.warning('Connection timed-out: {}'.format(conn_timeout))
except Exception as e:
logging.warning(e)
else:
self.player_photo = 'Images/NoImage.jpg'
except requests.exceptions.RequestException as request_exceptions:
logging.warning('Requests exceptions occurred: {}'.format(request_exceptions))
try:
self.text_1 = pos[0]
self.text_2 = '\n' + info[0] + '\n\n' + info[1] + '\n\n' + info[2]
except IndexError as index_error:
logging.warning('Index error occurred: {}'.format(index_error))
def select_stats(self, instance, *args):
if instance.text == 'Average Stats':
average_stats = self.player_tree.xpath(
'//div[@class="tab-season_seasonTableWrap__I0CUd"]//div[@class="stats-table_table__dpgY7"]'
'//div[@class="stats-table_row__ttfiG"][3]//div[@class="stats-table_cell__hdmqc"]/text()')
if len(average_stats) != 0:
self.show_stats = DisplayStats()
self.show_stats.title = 'Average Stats for ' + self.player_name
self.rv = RV(update_dict(average_stats))
else:
text = 'No games played by ' + self.player_name + ' yet!'
self.notification = text
elif instance.text == 'Total Stats':
total_stats = self.player_tree.xpath(
'//div[@class="tab-season_seasonTableWrap__I0CUd"]//div[@class="stats-table_table__dpgY7"]'
'//div[@class="stats-table_row__ttfiG"][2]//div[@class="stats-table_cell__hdmqc"]/text()')
if len(total_stats) != 0:
self.show_stats = DisplayStats()
self.show_stats.title = 'Total Stats for ' + self.player_name
self.rv = RV(update_dict(total_stats))
else:
text = 'No games played by ' + self.player_name + ' yet!'
self.notification = text
def on_rv(self, *args):
self.show_stats.content = self.rv
self.show_stats.open()
def on_notification(self, *args):
if self.notification != '':
self.message = MessagePopup(on_open=self.dismiss_text)
self.message.notification.text = self.notification
self.message.open()
def dismiss_text(self, *args):
Clock.schedule_once(self.message.dismiss, 1.5)
Clock.schedule_once(self.reset_text, 1.6)
def reset_text(self, *args):
self.notification = ''
def stats_animate_on_push(self, instance):
anim = Animation(size_hint_x=.68, duration=.2)
anim &= Animation(height=sp(70), duration=.2)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.stats_reverse_animate, instance), .2))
def stats_reverse_animate(self, instance, *args):
anim = Animation(size_hint_x=.7, duration=.1)
anim &= Animation(height=sp(80), duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.select_stats, instance), .2))
@staticmethod
def call_teams_screen(*args):
del App.get_running_app().root.screens_visited[1:]
App.get_running_app().root.transition = FadeTransition(duration=.5)
App.get_running_app().root.current = 'teams'
class Roster(Screen):
grid_roster = ObjectProperty(None)
trees = DictProperty({})
player_name = StringProperty()
repeated_selection_flag = NumericProperty(0)
canvas_opacity = NumericProperty(0)
def assert_tree(self, *args):
for name, t in self.trees.items():
if name == self.player_name:
Stats.player_tree = self.trees[name][0]
Stats.player_url = self.trees[name][1]
StatsByGame.player_tree = self.trees[name][0]
StatsByGame.player_name = name
@staticmethod
def fetch_tree(url):
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get(url)
t = etree.HTML(response.content)
return t
def fetch_trees(self, *args):
temp_dict = dict()
roster_keys = self.grid_roster.roster.keys()
roster_values = self.grid_roster.roster.values()
names = list(roster_keys)
roster_values = list(roster_values)
players_urls = list()
photo_urls = list()
for _tuple in roster_values:
players_urls.append(_tuple[0])
photo_urls.append(_tuple[1])
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
trees = executor.map(self.fetch_tree, players_urls)
except TimeoutError as timeout_error:
logging.warning('Timeout error occurred: {}'.format(timeout_error))
for name, tree, url in zip(names, trees, photo_urls):
if name in temp_dict:
temp_dict[name] = name
else:
temp_dict[name] = tree, url
self.trees = temp_dict
self.grid_roster.roster = dict()
def call_stats(self):
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'stats'
self.grid_roster.stats_option = False
def call_stats_by_game(self):
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'stats_by_game'
self.grid_roster.stats_by_game_option = False
@staticmethod
def call_teams_screen(*args):
del App.get_running_app().root.screens_visited[1:]
App.get_running_app().root.transition = FadeTransition(duration=.5)
App.get_running_app().root.current = 'teams'
class Teams(Screen):
idx = NumericProperty()
grid_teams = ObjectProperty(None)
def call_roster_screen(self, *args):
conn = connectivity_status()
if conn is True:
if len(self.grid_teams.selected_roster) != 0:
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'roster'
else:
message = MessagePopup()
message.notification.text = 'Roster\'s announcement is pending!'
message.open()
Clock.schedule_once(message.dismiss, 2)
else:
App.get_running_app().root.show_popup(conn)
Clock.schedule_once(App.get_running_app().stop, 5)
class Standings(Screen):
standings = DictProperty({})
recycle_view = ObjectProperty(None)
class Menu(Screen):
current = ObjectProperty(None)
standings = ObjectProperty(None)
about = ObjectProperty(None)
def stats_animate_on_push(self, instance):
anim = Animation(size_hint=[.86, .06], duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.stats_reverse_animate, instance), .1))
def stats_reverse_animate(self, instance, *args):
anim = Animation(size_hint=[.88, .08], duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.selection, instance), .1))
def about_animate_on_push(self, instance):
anim = Animation(size_hint=[.38, .04], duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.about_reverse_animate, instance), .1))
def about_reverse_animate(self, instance, *args):
anim = Animation(size_hint=[.4, .06], duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.selection, instance), .1))
def selection(self, instance, *args):
if instance is self.current:
self.call_teams_screen()
elif instance is self.standings:
self.call_standings_screen()
elif instance is self.about:
self.call_changelog_screen()
@staticmethod
def call_teams_screen(*args):
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'teams'
@staticmethod
def call_standings_screen(*args):
conn = connectivity_status()
if conn is True:
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'standings'
else:
App.get_running_app().root.show_popup(conn)
Clock.schedule_once(App.get_running_app().stop, 3)
@staticmethod
def call_changelog_screen(*args):
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'changelog'
class Changelog(Screen):
notes = ObjectProperty(None)
privacy_policy = ObjectProperty(None)
def stats_animate_on_push(self, instance):
anim = Animation(size_hint=[.86, .06], duration=.2)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.stats_reverse_animate, instance), .2))
def stats_reverse_animate(self, instance, *args):
anim = Animation(size_hint=[.88, .08], duration=.1)
anim.start(instance)
anim.on_complete(Clock.schedule_once(partial(self.selection, instance), .2))
def selection(self, instance, *args):
if instance is self.notes:
self.view_notes()
elif instance is self.privacy_policy:
self.view_privacy_policy()
@staticmethod
def view_notes():
notes = NotesPopup()
notes.open()
@staticmethod
def view_privacy_policy(*args):
view = WebViewInModal()
view.open_web_view()
class Home(Screen):
welcome = ObjectProperty(None)
rosters_reg = DictProperty({})
standings = DictProperty({})
def allow_image_display(self, *args):
Clock.schedule_once(self.download_global_values_file, .1)
def create_dict_with_rosters(self, *args):
with open('roster.json') as json_file:
data = json.load(json_file)
self.rosters_reg = data
def download_global_values_file(self, *args):
conn = connectivity_status()
if conn is True:
global_url = 'https://drive.google.com/uc?export=download&id=1_hiu_G8jm7LABNZevYMzJef4UfFM5H0L'
response = requests.get(global_url, params={"downloadformat": "txt"})
if response.status_code == 200:
with open('global_values.txt', mode='wb') as file:
file.write(response.content)
path = Path('global_values.txt')
path.rename(path.with_suffix('.py'))
try:
import global_values
except ModuleNotFoundError as error:
logging.warning('globals.py is missing: {}'.format(error))
else:
pass
try:
json_url = global_values.JSON_URL
response = requests.get(json_url)
if response.status_code == 200:
with open('roster.json', mode='wb') as file:
file.write(response.content)
self.create_dict_with_rosters()
except ValueError as value_error:
logging.warning('Value error occurred: {}'.format(value_error))
Clock.schedule_once(partial(self.time_out_popup, conn='Error while downloading data.'), 1)
else:
Clock.schedule_once(partial(self.time_out_popup, conn), 1)
@staticmethod
def time_out_popup(conn, *args):
App.get_running_app().root.show_popup(conn)
Clock.schedule_once(App.get_running_app().stop, 4)
def on_rosters_reg(self, *args):
self.standings = fetch_standings()
def on_standings(self, *args):
self.call_menu_screen()
@staticmethod
def call_menu_screen():
App.get_running_app().root.transition = SlideTransition(direction='left')
App.get_running_app().root.current = 'menu'
class ELSScreenManager(ScreenManager):
home_screen = ObjectProperty(None)
teams_screen = ObjectProperty(None)
roster_screen = ObjectProperty(None)
standing_screen = ObjectProperty(None)
stats_screen = ObjectProperty(None)
screens_visited = ListProperty([])
def __init__(self):
super().__init__()
Window.bind(on_keyboard=self.android_back_click)
def android_back_click(self, window, key, *largs):
screens_resolution_order = (('teams', 'menu'), ('standings', 'menu'), ('changelog', 'menu'),
('roster', 'teams'), ('stats', 'roster'), ('stats_by_game', 'roster'))
if key in (27, 1001):
if self.screens_visited[-1] not in 'menu':
for scr_name, instance in screens_resolution_order:
if self.screens_visited[-1] == scr_name:
App.get_running_app().root.current = instance
del self.screens_visited[-1]
return True
else:
Clock.schedule_once(self.exit_app, .5)
return True
def check_in_names(self, screen_name):
if screen_name in self.screens_visited:
pass
else:
self.screens_visited.append(screen_name)
@staticmethod
def show_popup(text_to_display):
message = MessagePopup()
message.notification.text = text_to_display
message.open()
@staticmethod
def exit_app(*args):
App.get_running_app().stop()
class EuroLeagueStatsApp(App):
def build(self):
return ELSScreenManager()
def on_stop(self):
suffixes = ('.png', 'json')
for file_name in os.listdir(os.getcwd()):
if file_name.endswith(suffixes) and file_name not in ('Court.jpg', 'NoImage.jpg'):
try:
os.remove(file_name)
os.remove('global_values.py')
except OSError as os_error:
logging.warning('OS error occurred: {}'.format(os_error))
if __name__ == '__main__':
if platform == "android":
request_permissions(
[Permission.READ_EXTERNAL_STORAGE, Permission.INTERNET, Permission.ACCESS_NETWORK_STATE])
LabelBase.register(name='MyriadPro', fn_regular='Fonts/MyriadPro-Regular.ttf',
fn_bold='Fonts/MyriadPro-BoldCondensedItalic.ttf',
fn_italic='Fonts/MyriadPro-BlackCondensedItalic.ttf')
EuroLeagueStatsApp().run()