Martin 8 лет назад
Родитель
Сommit
ebbf9561f4
5 измененных файлов с 113 добавлено и 35 удалено
  1. 1 1
      .gitignore
  2. 2 0
      config.py
  3. 26 12
      db.py
  4. 2 0
      init_localities.py
  5. 82 22
      monitor.py

+ 1 - 1
.gitignore

@@ -62,4 +62,4 @@ docs/_build/
 # PyBuilder
 target/
 
-data.db
+data.db*

+ 2 - 0
config.py

@@ -1,6 +1,8 @@
 API_KEY = '5f4bc74f-8d9a-41cb-ab85-a1b7cfc86622'
 BASE = 'https://api.myhome.ie'
 
+DB_PATH = 'data.db'
+
 MONITORED_LOCALITIES = [
     1265, # Dublin
 ]

+ 26 - 12
db.py

@@ -1,11 +1,13 @@
 import logging
 import sqlite3
 
+import config
+
 class connect:
     conn = None
 
     def __enter__(self):
-        self.conn = sqlite3.connect('data.db')
+        self.conn = sqlite3.connect(config.DB_PATH)
         self.cursor = self.conn.cursor()
         return self
 
@@ -30,28 +32,40 @@ class connect:
         return res
 
 def init():
-    with connect() as conn:
-        conn.execute('''
-        create table if not exists regions (
-            id int not null primary key,
-            name varchar(255) not null
-        );
-        ''')
+    logging.info('Initializing database at %s...', config.DB_PATH)
 
+    with connect() as conn:
         # conn.execute('drop table if exists localities;')
         conn.execute('''
         create table if not exists localities (
-            id int not null primary key,
+            id integer not null primary key,
             name varchar(255) not null
         );
         ''')
 
-        conn.execute('drop table if exists locality_relationships;')
+        # conn.execute('drop table if exists locality_relationships;')
         conn.execute('''
         create table if not exists locality_relationships (
             id varchar(255) not null primary key,
-            parent int not null,
-            child int not null
+            parent integer not null,
+            child integer not null
+        )
+        ''')
+
+        conn.execute('''
+        create table if not exists search_results (
+            id integer not null primary key,
+            time datetime not null,
+            property_id integer not null,
+            raw_json text not null
+        )
+        ''')
+
+        conn.execute('''
+        create table if not exists properties (
+            id integer not null primary key,
+            last_update datetime not null,
+            raw_json text not null
         )
         ''')
 

+ 2 - 0
init_localities.py

@@ -1,3 +1,4 @@
+import logging
 import requests
 import config
 
@@ -25,6 +26,7 @@ def _init_relationships(conn, locality_id):
 
 
 def init_localities(conn, locality_id=None):
+    logging.info('Loading known localities...')
     known = set(conn.select('select id from localities'))
 
     to_insert = []

+ 82 - 22
monitor.py

@@ -1,34 +1,94 @@
+import json
+import logging
+import datetime
+
 import requests
+
 import db
 import config
 
 import init_localities
 
-def search(locality_id):
-    request = {
-        'AddedSince': "",
-        'ApiKey': config.API_KEY,
-        'Page': 1,
-        'PageSize': 20,
-        'RequestTypeId': 2,
-        'SearchRequest': config.SEARCH_PARAMS,
-        'SortColumn': 2,
-        'SortDirection': 2,
-        'endpoint': {
-            'name': "Search",
-            'paramsName': "SearchRequest",
-        },
-        'params': {
-            'RegionId': locality_id
-        },
-    }
+def _now():
+    return datetime.datetime.now().strftime(r'%Y-%m-%d %M:%H:%S')
+
+def get_property(conn, property_id):
+    resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.API_KEY))
+
+    print(json.dumps(resp.json()))
+
+    data = resp.json()['Brochure']['Property']
 
+    stmt = 'insert into properties (id, last_update, raw_json) values (?,?,?)'
+    params = [data['PropertyId'], _now(), json.dumps(data)]
+
+    conn.execute(stmt, *params)
+
+def search(conn, locality_id):
+    logging.info('Searching %i...', locality_id)
     
-    resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.API_KEY, body=request)
+    page = 1
+    found_properties = set()
+
+    while True:
+        body = {
+            'AddedSince': "",
+            'ApiKey': config.API_KEY,
+            'Page': page,
+            'PageSize': 50,
+            'RequestTypeId': 2,
+            'SearchRequest': config.SEARCH_PARAMS,
+            'SortColumn': 2,
+            'SortDirection': 2,
+            'endpoint': {
+                'name': "Search",
+                'paramsName': "SearchRequest",
+            },
+            'params': {
+                'RegionId': locality_id
+            },
+        }
+
+        headers = {
+            'content-type': 'application/json',
+            'accept': 'application/json',
+
+        }
+
+        print('Fetching page %i...' % page)
+
+        resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.API_KEY, json=body, headers=headers)
+
+        resp.raise_for_status()
+
+        data = resp.json()
+
+        if not isinstance(data, dict):
+            print('Error: %s' % data)
+            return
+
+        stmt = 'insert into search_results (time, property_id, raw_json) VALUES '
+        params = []
+
+        for result in data.get('SearchResults', []):
+            found_properties.add(result['id'])
+            stmt += '(?, ?, ?),' 
+            params.extend([_now(), result['id'], json.dumps(result)])
+
+        conn.execute(stmt[:-1], *params)
+
+        if page*500 > data['ResultCount']:
+            break
+        
+        page += 1
+            
+    known_properties = set(conn.select('select id from properties'))
+
+    to_get = found_properties.difference(known_properties)
 
-    # resp.raise_for_status()
+    get_property(conn, list(to_get)[0])
 
-    print(resp.content)
+    print('Getting %i properties...' % len(to_get))
 
 def run():
     with db.connect() as conn:
@@ -39,7 +99,7 @@ def run():
             print('You must set MONITORED_LOCATIONS. Possible values: ')
             init_localities.init_localities(conn)
 
-    search(1265)
+        search(conn, 1265)
 
 if __name__ == '__main__':
     run()