model.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import re
  2. import _html
  3. import _bs
  4. import pytz
  5. import datetime
  6. # import time
  7. import psycopg2.extras
  8. from pprint import pprint
  9. import arrow
  10. import view
  11. import warnings
  12. try:
  13. warnings.simplefilter("ignore", arrow.factory.ArrowParseWarning)
  14. except AttributeError:
  15. pass
  16. """
  17. Modules _html and _bs4 contain specialized methods.
  18. """
  19. local_timezones = {
  20. "NSW": "Australia/Sydney",
  21. "VIC": "Australia/Melbourne",
  22. "QLD": "Australia/Brisbane",
  23. "WA": "Australia/Perth",
  24. "SA": "Australia/Adelaide",
  25. "TAS": "Australia/Hobart",
  26. "ACT": "Australia/Sydney",
  27. "NT": "Australia/Darwin"}
  28. def scrape_racingaustralia_main_page(row):
  29. this_url = """https://racingaustralia.horse/Home.aspx"""
  30. this_data = _html.get_page(this_url)
  31. venues_all = _bs.get_today_row(this_data, row)
  32. return venues_all
  33. def scrape_racenet_main_page():
  34. this_url = """https://www.racenet.com.au/updates/scratchings"""
  35. this_data = _html.get_page(this_url)
  36. # print(this_data[:50])
  37. json = _bs.get_racenet_json(this_data)
  38. return json
  39. def get_raw_scratchings(this_venue):
  40. this_raw_data = _html.get_page(this_venue.scratchings_url)
  41. return this_raw_data
  42. def process_raw_data(this_raw_data, this_venue):
  43. """
  44. Processes the raw data from the Scratchings page to obtain meta data.
  45. this_venue is passed to _bs.process_scratchings() to create the inherited namedTuple
  46. :param this_raw_data:
  47. :param this_venue:
  48. :return:
  49. """
  50. race_day_info = _bs.get_meta_data(this_raw_data, this_venue)
  51. return race_day_info
  52. def get_scratching_details(this_raw_data, this_venue):
  53. # this_data = _html.get_page(this_venue.scratchings_url)
  54. scratchings_info = _bs.process_scratchings(this_raw_data, this_venue)
  55. return scratchings_info
  56. def convert_to_unixtime(dt_object):
  57. """
  58. Simple utility function that returns the unixtime from a timezone aware dateTime object
  59. :param dt_object:
  60. :return:
  61. """
  62. utc = pytz.UTC
  63. d = dt_object.astimezone(utc)
  64. epoch = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
  65. ts = int((d - epoch).total_seconds())
  66. return ts
  67. def convert_to_date(weird_string):
  68. """
  69. Converts a string like 'MONDAY 15 JUL' to a python datetime object
  70. :param weird_string:
  71. :return datetime object:
  72. """
  73. weird_string = re.sub(r' (\d) ', ' 0\1 ', weird_string)
  74. local_timezone = pytz.timezone('Australia/Sydney')
  75. now = datetime.datetime.now(local_timezone)
  76. calculated_date = datetime.datetime.strptime(str(now.year) + ' ' + weird_string, "%Y %A %d %b").date()
  77. # print(calculated_date)
  78. return calculated_date
  79. def send_messages(scratches, source):
  80. long_message = ''
  81. message_string = '{} {}venue = {} {} {}-{} | race = {} starts at {} | {} UTC | horse = {}'
  82. for m in scratches:
  83. flag = ''
  84. if m.torn:
  85. flag = 'FLAGGED!! '
  86. pprint(m)
  87. message = message_string.format(source,
  88. flag,
  89. m.date.strftime('%a'),
  90. m.date,
  91. m.state,
  92. m.venue,
  93. m.race,
  94. m.time,
  95. m.utc,
  96. '{} {}'.format(m.horse_no, m.horse_display_name))
  97. print('this_message: {}'.format(message))
  98. # Append message if possible
  99. if len(long_message) + len(message) < 5997:
  100. if len(long_message) == 0:
  101. long_message = message
  102. else:
  103. long_message += '\n' + message
  104. else:
  105. # Send long message (max 6k characters)
  106. print('Sending very long message > {}'.format(len(long_message)))
  107. view.broadcast(long_message)
  108. # Best would be to now store horses that were just broadcast
  109. long_message = m
  110. # Send all messages
  111. if len(long_message) > 0:
  112. print('Sending long_message > {}'.format(len(long_message)))
  113. view.broadcast(long_message)
  114. def store_scratched_horses(db, full_scratches):
  115. query = """INSERT INTO horses(venue, race_date, race, horse_no, horse_display_name)
  116. VALUES(%s, %s, %s, %s, %s)
  117. ON CONFLICT(venue, race_date, race, horse_no) DO NOTHING;"""
  118. scratches_to_return = []
  119. regex = r'^INSERT \d+ (\d+)$'
  120. cur3 = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  121. for this_scratching in full_scratches:
  122. database_entry = (this_scratching.venue, this_scratching.date,
  123. this_scratching.race, this_scratching.horse_no,
  124. this_scratching.horse_display_name)
  125. cur3.execute(query, database_entry)
  126. match = re.match(regex, cur3.statusmessage)
  127. status = 0
  128. if match:
  129. status = int(match.group(1))
  130. if status > 0:
  131. print('Stored: {}'.format(database_entry))
  132. print(cur3.statusmessage)
  133. scratches_to_return.append(this_scratching)
  134. cur3.close()
  135. db.commit()
  136. return scratches_to_return
  137. def get_race_from_races(this_haystack, needle_date, needle_venue, needle_race):
  138. """
  139. From the previous acquired database data this will return 'start_time',
  140. 'utctime' and torn (boolean) where the date, venue and race are given.
  141. :param this_haystack:
  142. :param needle_date:
  143. :param needle_venue:
  144. :param needle_race:
  145. :return:
  146. """
  147. return_values = ()
  148. # needle_date = arrow.get(needle_date).date()
  149. print('{} -> {}'.format(needle_date, needle_date.strftime('%Y-%m-%d')))
  150. for race in this_haystack:
  151. # pprint(race)
  152. # print(race.race_date == needle_date)
  153. # print('race.race_date == needle_date: {} == {}'.format(race.race_date, needle_date))
  154. # print('type(race.race_date) == type(needle_date): {} == {}'.format(type(race.race_date), type(needle_date)))
  155. # print(race.venue == needle_venue)
  156. # print(race.race == needle_race)
  157. if ((race.race_date == needle_date) and (race.venue == needle_venue) and (
  158. race.race == needle_race)):
  159. return_values = (race.start_time, race.utctime, race.torn)
  160. break
  161. return return_values
  162. def get_relevant_races_from_database(db):
  163. query = """
  164. SELECT venue, start_time, race_date, utctime, race, torn FROM race_program
  165. WHERE race_date >= %s;
  166. """
  167. # Run this query once and use resulting NamedTuple for data
  168. cur_races = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  169. today = arrow.utcnow().date()
  170. # print('today: {}'.format(today))
  171. cur_races.execute(query, (today,))
  172. races = cur_races.fetchall()
  173. # print('len(races): {}'.format(len(races)))
  174. # pprint(races)
  175. cur_races.close()
  176. return races