model.py 6.5 KB

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