monitor.py 8.8 KB

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