monitor.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import math
  2. import json
  3. import logging
  4. import datetime
  5. import requests
  6. import db
  7. import config
  8. import init_localities
  9. import util
  10. _SEARCH_PAGE_SIZE = 50
  11. _DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
  12. def _now():
  13. return datetime.datetime.now().strftime(_DATETIME_FORMAT)
  14. def process_properties(conn):
  15. count = conn.select('select count(1) from properties where processed=0')[0]
  16. if not count:
  17. return
  18. print('Processing %i properties...' % count)
  19. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
  20. while rows:
  21. stmt = 'replace into properties (id, last_update, raw_json, processed, price, lat, lon, size, ber, address, locality_id, property_type, bathrooms, bedrooms) values'
  22. params = []
  23. for property_id, last_update, raw_json in rows:
  24. stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
  25. params.extend([
  26. property_id,
  27. last_update,
  28. raw_json,
  29. ])
  30. if raw_json is None:
  31. params.extend([None] * 10)
  32. else:
  33. data = json.loads(raw_json)
  34. size = None
  35. if data.get('SizeStringMeters'):
  36. size = data.get('SizeStringMeters')
  37. elif data.get('SizeStringFeet'):
  38. size = round(data.get('SizeStringFeet') * 0.09290304, 2)
  39. params.extend([
  40. data.get('Price', {}).get('MinPrice'),
  41. data.get('BrochureMap', {}).get('latitude'),
  42. data.get('BrochureMap', {}).get('longitude'),
  43. size,
  44. data.get('BerRating'),
  45. data.get('DisplayAddress', data.get('Address')),
  46. data.get('LocalityId'),
  47. data.get('PropertyType'),
  48. data.get('Bathrooms', data.get('BathString', '').replace(' baths', '') or None),
  49. data.get('BedsString', '').replace(' beds', '') or None,
  50. ])
  51. if params:
  52. conn.execute(stmt[:-1], *params)
  53. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 10')
  54. def fetch_properties(conn):
  55. unknown_properties = conn.select('''
  56. select distinct sr.property_id
  57. from search_results sr left join properties p on sr.property_id = p.id
  58. where p.id is null
  59. ''')
  60. complete = 0
  61. for batch in util.batches(unknown_properties, 10):
  62. print('Fetching property details (complete: %i/%i)...' % (complete, len(unknown_properties)))
  63. stmt = 'insert into properties (id, last_update, raw_json) values'
  64. params = []
  65. for property_id in batch:
  66. resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.API_KEY))
  67. if resp.json() in ["The property you requested isn't available any more", "The property you requested is inactive and can't be found"]:
  68. stmt += ' (?, ?, ?),'
  69. params.extend([
  70. property_id,
  71. _now(),
  72. None,
  73. ])
  74. else:
  75. try:
  76. data = resp.json()['Brochure']['Property']
  77. stmt += ' (?, ?, ?),'
  78. params.extend([
  79. property_id,
  80. _now(),
  81. json.dumps(data)
  82. ])
  83. except Exception as e:
  84. print(str(e))
  85. print(resp.json())
  86. if params:
  87. conn.execute(stmt[:-1], *params)
  88. complete += len(batch)
  89. def search(conn, locality_id):
  90. logging.info('Searching %i...', locality_id)
  91. cutoff = (datetime.datetime.now() - datetime.timedelta(hours=20)).strftime(_DATETIME_FORMAT)
  92. recent_properties = set(conn.select('''select property_id from (select property_id, max(time) m
  93. from search_results group by property_id) where m > ?''', cutoff))
  94. page = 1
  95. num_pages = None
  96. inserted = 0
  97. while True:
  98. body = {
  99. 'AddedSince': "",
  100. 'ApiKey': config.API_KEY,
  101. 'Page': page,
  102. 'PageSize': _SEARCH_PAGE_SIZE,
  103. 'RequestTypeId': 2,
  104. 'SearchRequest': config.SEARCH_PARAMS,
  105. 'SortColumn': 2,
  106. 'SortDirection': 2,
  107. 'endpoint': {
  108. 'name': "Search",
  109. 'paramsName': "SearchRequest",
  110. },
  111. 'params': {
  112. 'RegionId': locality_id
  113. },
  114. }
  115. headers = {
  116. 'content-type': 'application/json',
  117. 'accept': 'application/json',
  118. }
  119. if num_pages:
  120. print('Fetching page %i/%i...' % (page, num_pages))
  121. else:
  122. print('Fetching page %i...' % page)
  123. resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.API_KEY, json=body, headers=headers)
  124. resp.raise_for_status()
  125. data = resp.json()
  126. if not isinstance(data, dict):
  127. print('Error: %s' % data)
  128. return
  129. stmt = 'insert into search_results (time, property_id, price, raw_json) VALUES '
  130. params = []
  131. for result in data.get('SearchResults', []):
  132. if not result.get('PriceAsString'):
  133. continue
  134. if result['id'] in recent_properties:
  135. continue
  136. stmt += '(?, ?, ?, ?),'
  137. params.extend([
  138. _now(),
  139. result['id'],
  140. result['PriceAsString'].replace(',', '').replace('\u20ac', ''),
  141. json.dumps(result)
  142. ])
  143. inserted += 1
  144. if params:
  145. conn.execute(stmt[:-1], *params)
  146. num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
  147. if page >= num_pages:
  148. break
  149. page += 1
  150. print('Search complete. %i records inserted.' % inserted)
  151. def run():
  152. with db.connect() as conn:
  153. if config.MONITORED_LOCALITIES:
  154. for locality_id in config.MONITORED_LOCALITIES:
  155. # init_localities.init_localities(conn, locality_id=locality_id)
  156. # search(conn, 1265)
  157. pass
  158. else:
  159. print('You must set MONITORED_LOCATIONS. Possible values: ')
  160. init_localities.init_localities(conn)
  161. fetch_properties(conn)
  162. process_properties(conn)
  163. if __name__ == '__main__':
  164. run()