monitor.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import collections
  2. import math
  3. import json
  4. import logging
  5. import datetime
  6. import requests
  7. import db
  8. import config
  9. import init_localities
  10. import util
  11. _SEARCH_PAGE_SIZE = 50
  12. def get_locality_tree(conn):
  13. parents = {}
  14. for parent, child in conn.select('select parent, child from locality_relationships'):
  15. parents[child] = parent
  16. roots = set()
  17. locality_ancestors = collections.defaultdict(list)
  18. for child, parent in parents.items():
  19. locality_ancestors[child].append(parent)
  20. while parents.get(parent):
  21. locality_ancestors[child].append(parents[parent])
  22. parent = parents[parent]
  23. roots.add(parent)
  24. return roots, parents, locality_ancestors
  25. def process_properties(conn):
  26. count = conn.select('select count(1) from properties where processed=0')[0]
  27. if not count:
  28. return
  29. _, _, locality_ancestors = get_locality_tree(conn)
  30. print('Processing %i properties...' % count)
  31. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
  32. while rows:
  33. stmt = 'replace into properties (id, last_update, raw_json, processed, price, lat, lon, size, ber, address, locality_id, property_type, bathrooms, bedrooms) values'
  34. params = []
  35. property_localities = []
  36. for property_id, last_update, raw_json in rows:
  37. stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
  38. params.extend([
  39. property_id,
  40. last_update,
  41. raw_json,
  42. ])
  43. if raw_json is None:
  44. params.extend([None] * 10)
  45. else:
  46. data = json.loads(raw_json)
  47. size = None
  48. if data.get('SizeStringMeters'):
  49. size = data.get('SizeStringMeters')
  50. elif data.get('SizeStringFeet'):
  51. size = round(data.get('SizeStringFeet') * 0.09290304, 2)
  52. params.extend([
  53. data.get('Price', {}).get('MinPrice'),
  54. data.get('BrochureMap', {}).get('latitude'),
  55. data.get('BrochureMap', {}).get('longitude'),
  56. size,
  57. data.get('BerRating'),
  58. data.get('DisplayAddress', data.get('Address')),
  59. data.get('LocalityId'),
  60. data.get('PropertyType'),
  61. data.get('Bathrooms', data.get('BathString', '').replace(' baths', '') or None),
  62. data.get('BedsString', '').replace(' beds', '') or None,
  63. ])
  64. if data.get('LocalityId'):
  65. property_localities.append((property_id, data.get('LocalityId')))
  66. if params:
  67. conn.execute(stmt[:-1], *params)
  68. stmt = 'replace into property_locality_map (id, property_id, locality_id) values'
  69. params = []
  70. for property_id, locality_id in property_localities:
  71. ancestors = [locality_id] + locality_ancestors.get(locality_id, [])
  72. for ancestor in ancestors:
  73. stmt += ' (?, ?, ?),'
  74. params.extend([
  75. '%i_%i' % (property_id, ancestor),
  76. property_id,
  77. ancestor
  78. ])
  79. if params:
  80. conn.execute(stmt[:-1], *params)
  81. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 10')
  82. def fetch_properties(conn):
  83. unknown_properties = conn.select('''
  84. select distinct sr.property_id
  85. from search_results sr left join properties p on sr.property_id = p.id
  86. where p.id is null
  87. ''')
  88. complete = 0
  89. for batch in util.batches(unknown_properties, 10):
  90. print('Fetching property details (complete: %i/%i)...' % (complete, len(unknown_properties)))
  91. stmt = 'insert into properties (id, last_update, raw_json) values'
  92. params = []
  93. for property_id in batch:
  94. resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.MYHOME_API_KEY))
  95. if resp.json() in ["The property you requested isn't available any more", "The property you requested is inactive and can't be found"]:
  96. stmt += ' (?, ?, ?),'
  97. params.extend([
  98. property_id,
  99. db.now(),
  100. None,
  101. ])
  102. else:
  103. try:
  104. data = resp.json()['Brochure']['Property']
  105. stmt += ' (?, ?, ?),'
  106. params.extend([
  107. property_id,
  108. db.now(),
  109. json.dumps(data)
  110. ])
  111. except Exception as e:
  112. print(str(e))
  113. print(resp.json())
  114. if params:
  115. conn.execute(stmt[:-1], *params)
  116. complete += len(batch)
  117. def search(conn, locality_id):
  118. logging.info('Searching %i...', locality_id)
  119. known_prices = conn.select('select property_id, max(time), price from search_results where search_locality_id=? group by property_id', locality_id)
  120. known_prices = {row[0]: str(row[2]) for row in known_prices}
  121. page = 1
  122. num_pages = None
  123. added = 0
  124. modified = 0
  125. seen_properties = set()
  126. while True:
  127. config.SEARCH_PARAMS['RegionId'] = str(locality_id)
  128. body = {
  129. 'AddedSince': "",
  130. 'ApiKey': config.MYHOME_API_KEY,
  131. 'Page': page,
  132. 'PageSize': _SEARCH_PAGE_SIZE,
  133. 'RequestTypeId': 2,
  134. 'SearchRequest': config.SEARCH_PARAMS,
  135. 'SortColumn': 2,
  136. 'SortDirection': 2,
  137. 'endpoint': {
  138. 'name': "Search",
  139. 'paramsName': "SearchRequest",
  140. },
  141. 'params': {
  142. 'RegionId': locality_id
  143. },
  144. }
  145. headers = {
  146. 'content-type': 'application/json',
  147. 'accept': 'application/json',
  148. }
  149. if num_pages:
  150. print('Fetching page %i/%i...' % (page, num_pages))
  151. else:
  152. print('Fetching page %i...' % page)
  153. resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.MYHOME_API_KEY, json=body, headers=headers)
  154. resp.raise_for_status()
  155. data = resp.json()
  156. if not isinstance(data, dict):
  157. print('Error: %s' % data)
  158. return
  159. stmt = 'insert into search_results (search_locality_id, time, property_id, price, raw_json) VALUES '
  160. params = []
  161. for result in data.get('SearchResults', []):
  162. if not result.get('PriceAsString'):
  163. continue
  164. property_id = result['id']
  165. price = result['PriceAsString'].replace(',', '').replace('\u20ac', '')
  166. seen_properties.add(property_id)
  167. if property_id in known_prices and known_prices[property_id] == price:
  168. continue
  169. stmt += ' (?, ?, ?, ?, ?),'
  170. params.extend([
  171. locality_id,
  172. db.now(),
  173. property_id,
  174. price,
  175. json.dumps(result)
  176. ])
  177. if property_id not in known_prices:
  178. added += 1
  179. else:
  180. modified += 1
  181. if params:
  182. conn.execute(stmt[:-1], *params)
  183. num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
  184. if page >= num_pages:
  185. break
  186. page += 1
  187. gone = {pid for pid, price in known_prices.items() if price != 'GONE'}.difference(seen_properties)
  188. if gone:
  189. stmt = 'insert into search_results (search_locality_id, time, property_id, price) VALUES'
  190. params = []
  191. for property_id in gone:
  192. stmt += ' (?, ?, ?, ?),'
  193. params.extend([
  194. locality_id,
  195. db.now(),
  196. property_id,
  197. 'GONE',
  198. ])
  199. conn.execute(stmt[:-1], *params)
  200. print('Search complete. %i records fetched; %i new records added; %i records modified; %i records marked as gone.' % (len(seen_properties), added, modified, len(gone)))
  201. def run():
  202. with db.connect() as conn:
  203. if config.MONITORED_LOCALITIES:
  204. for locality_id in config.MONITORED_LOCALITIES:
  205. init_localities.init_localities(conn, locality_id=locality_id)
  206. search(conn, locality_id)
  207. else:
  208. print('You must set MONITORED_LOCATIONS. Possible values: ')
  209. init_localities.init_localities(conn)
  210. fetch_properties(conn)
  211. process_properties(conn)
  212. if __name__ == '__main__':
  213. run()