model.py 6.4 KB

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