model.py 7.0 KB

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