Browse Source

Split app in seperate modules

JoostSijm 5 years ago
parent
commit
37d343578e
5 changed files with 141 additions and 141 deletions
  1. 1 2
      app/__init__.py
  2. 17 20
      app/__main__.py
  3. 100 0
      app/api.py
  4. 0 119
      app/app.py
  5. 23 0
      app/database.py

+ 1 - 2
app/__init__.py

@@ -7,7 +7,7 @@ from sqlalchemy.orm import sessionmaker
 from dotenv import load_dotenv
 from apscheduler.schedulers.background import BackgroundScheduler
 
-from hvs.models import Base, Region, DeepExploration, ResourceTrack, ResourceStat
+from app.models import Base, Region, DeepExploration, ResourceTrack, ResourceStat
 
 
 load_dotenv()
@@ -18,7 +18,6 @@ Session = sessionmaker(bind=engine)
 
 # scheduler
 scheduler = BackgroundScheduler()
-scheduler.add_jobstore('sqlalchemy', url=os.environ["DATABASE_URI"])
 scheduler.start()
 
 # api

+ 17 - 20
app/__main__.py

@@ -4,17 +4,18 @@ from datetime import datetime, timedelta
 import random
 import time
 
-from hvs import scheduler
-from hvs.app import download_resources, need_refill, max_refill_seconds, refill, \
-    save_resources, print_resources
+from app import scheduler
+from app.api import download_resources, refill
+from app.database import save_resources
+from app.app import need_refill, max_refill_seconds, print_resources
 
 
-def job_check_resources(state_id, capital_id, resource_id):
+def job_check_resources(state_id, capital_id, resource_id, do_refill):
     """Check resources and refill if necessary"""
     regions = download_resources(state_id, resource_id)
     save_resources(state_id, regions, resource_id)
     print_resources(regions)
-    if need_refill(regions, 25):
+    if do_refill and need_refill(regions, 25):
         max_seconds = max_refill_seconds(regions, 25, 900)
         random_seconds = random.randint(0, max_seconds)
         random_time_delta = timedelta(seconds=random_seconds)
@@ -39,27 +40,23 @@ def job_refill_resource(state_id, capital_id, resource_id):
     """Execute refill job"""
     refill(state_id, capital_id, resource_id)
 
-if __name__ == '__main__':
-    # jobs
-    # job_refill_resource(2788, 4002, 0)
-    # job_check_resources(2788, 4002, 0)
+def add_check_resources(state_id, capital_id, resource_id, do_refill, minute):
+    """Add check resources job"""
     scheduler.add_job(
         job_check_resources,
         'cron',
-        args=[2788, 4002, 0],
-        id='vn_check_gold',
+        args=[state_id, capital_id, resource_id, do_refill],
+        id='{}_check_{}'.format(state_id, resource_id),
         replace_existing=True,
-        minute='0,15,30,45'
+        minute=minute
     )
 
-    scheduler.add_job(
-        job_check_resources,
-        'cron',
-        args=[2788, 4002, 11],
-        id='vn_check_uranium',
-        replace_existing=True,
-        minute='0'
-    )
+if __name__ == '__main__':
+    # jobs
+    # job_refill_resource(2788, 4002, 0)
+    # job_check_resources(2788, 4002, 0)
+    add_check_resources(2788, 4003, 0, True, '0,15,30,45')
+    add_check_resources(2788, 4003, 6, True, '0')
 
     while True:
         time.sleep(100)

+ 100 - 0
app/api.py

@@ -0,0 +1,100 @@
+"""Main application"""
+
+import re
+
+import requests
+from bs4 import BeautifulSoup
+
+from app import BASE_URL, HEADERS
+
+
+RESOURCES = {
+    0: 'gold',
+    2: 'oil',
+    4: 'ore',
+    11: 'uranium',
+    15: 'diamond',
+}
+
+def download_resources(state_id, resource_id):
+    """Download the resource list"""
+    response = requests.get(
+        '{}listed/stateresources/{}/{}'.format(BASE_URL, state_id, RESOURCES[resource_id]),
+        headers=HEADERS
+    )
+    return parse_resources(response.text)
+
+
+def read_resources():
+    """Read resource file"""
+    with open('resources.html') as file:
+        return parse_resources(file)
+
+
+def parse_resources(html):
+    """Read the resources left"""
+    soup = BeautifulSoup(html, 'html.parser')
+
+    regions_tree = soup.find_all(class_='list_link')
+
+    regions = {}
+    for region_tree in regions_tree:
+        region_id = int(region_tree['user'])
+        columns = region_tree.find_all('td')
+        regions[region_id] = {
+            'name': re.sub('Factories: .*$', '', columns[1].text),
+            'explored': float(columns[2].string),
+            'maximum': int(float(columns[3].string)),
+            'deep_exploration': int(columns[4].string),
+            'limit_left': int(columns[5].string),
+        }
+    return regions
+
+
+def refill(state_id, capital_id, resource_id):
+    """Main function"""
+    # Check location
+    response = requests.get(
+        '{}main/content'.format(BASE_URL),
+        headers=HEADERS
+    )
+    soup = BeautifulSoup(response.text, 'html.parser')
+    state_div = soup.find_all('div', {'class': 'index_case_50'})[1]
+    action = state_div.findChild()['action']
+    current_state_id = int(re.sub('.*/', '', action))
+    print('Current state: {}'.format(current_state_id))
+
+    data = {
+        'tmp_gov': resource_id
+    }
+    params = {}
+    if current_state_id != state_id:
+        params['alt'] = True
+
+    requests.post(
+        '{}parliament/donew/42/{}/0'.format(BASE_URL, resource_id),
+        headers=HEADERS,
+        params=params,
+        data=data
+    )
+
+    response = requests.get(
+        '{}parliament/index/{}'.format(BASE_URL, capital_id),
+        headers=HEADERS
+    )
+    soup = BeautifulSoup(response.text, 'html.parser')
+    active_laws = soup.find('div', {'id': 'parliament_active_laws'})
+    resource_name = RESOURCES[resource_id]
+    exploration_laws = active_laws.findAll(
+        text='Resources exploration: state, {} resources'.format(resource_name)
+    )
+    print('Resources exploration: state, {} resources'.format(resource_name))
+    print(exploration_laws)
+    for exploration_law in exploration_laws:
+        action = exploration_law.parent.parent['action']
+        action = action.replace('law', 'votelaw')
+        result = requests.post(
+            '{}{}/pro'.format(BASE_URL, action),
+            headers=HEADERS
+        )
+        print(result.text)

+ 0 - 119
app/app.py

@@ -1,56 +1,5 @@
 """Main application"""
 
-import re
-
-import requests
-from bs4 import BeautifulSoup
-
-from hvs import BASE_URL, HEADERS, Session
-from hvs.models import ResourceTrack, ResourceStat
-
-
-RESOURCES = {
-    0: 'gold',
-    2: 'oil',
-    4: 'ore',
-    11: 'uranium',
-    15: 'diamond',
-}
-
-def download_resources(state_id, resource_id):
-    """Download the resource list"""
-    response = requests.get(
-        '{}listed/stateresources/{}/{}'.format(BASE_URL, state_id, RESOURCES[resource_id]),
-        headers=HEADERS
-    )
-    return parse_resources(response.text)
-
-
-def read_resources():
-    """Read resource file"""
-    with open('resources.html') as file:
-        return parse_resources(file)
-
-
-def parse_resources(html):
-    """Read the resources left"""
-    soup = BeautifulSoup(html, 'html.parser')
-
-    regions_tree = soup.find_all(class_='list_link')
-
-    regions = {}
-    for region_tree in regions_tree:
-        region_id = int(region_tree['user'])
-        columns = region_tree.find_all('td')
-        regions[region_id] = {
-            'name': re.sub('Factories: .*$', '', columns[1].text),
-            'explored': float(columns[2].string),
-            'maximum': int(float(columns[3].string)),
-            'deep_exploration': int(columns[4].string),
-            'limit_left': int(columns[5].string),
-        }
-    return regions
-
 def print_resources(regions):
     """print resources"""
     print('region                        expl max   D left    c %    t %')
@@ -87,71 +36,3 @@ def max_refill_seconds(regions, limit, max_time):
         if percentage < lowest_percentage:
             lowest_percentage = percentage
     return int(max_time / limit * lowest_percentage)
-
-
-def refill(state_id, capital_id, resource_id):
-    """Main function"""
-    # Check location
-    response = requests.get(
-        '{}main/content'.format(BASE_URL),
-        headers=HEADERS
-    )
-    soup = BeautifulSoup(response.text, 'html.parser')
-    state_div = soup.find_all('div', {'class': 'index_case_50'})[1]
-    action = state_div.findChild()['action']
-    current_state_id = int(re.sub('.*/', '', action))
-    print('Current state: {}'.format(current_state_id))
-
-    data = {
-        'tmp_gov': resource_id
-    }
-    params = {}
-    if current_state_id != state_id:
-        params['alt'] = True
-
-    requests.post(
-        '{}parliament/donew/42/{}/0'.format(BASE_URL, resource_id),
-        headers=HEADERS,
-        params=params,
-        data=data
-    )
-
-    response = requests.get(
-        '{}parliament/index/{}'.format(BASE_URL, capital_id),
-        headers=HEADERS
-    )
-    soup = BeautifulSoup(response.text, 'html.parser')
-    active_laws = soup.find('div', {'id': 'parliament_active_laws'})
-    resource_name = RESOURCES[resource_id]
-    exploration_laws = active_laws.findAll(
-        text='Resources exploration: state, {} resources'.format(resource_name)
-    )
-    print('Resources exploration: state, {} resources'.format(resource_name))
-    print(exploration_laws)
-    for exploration_law in exploration_laws:
-        action = exploration_law.parent.parent['action']
-        action = action.replace('law', 'votelaw')
-        result = requests.post(
-            '{}{}/pro'.format(BASE_URL, action),
-            headers=HEADERS
-        )
-        print(result.text)
-
-
-def save_resources(state_id, regions, resource_id):
-    """Save resources to database"""
-    session = Session()
-    resource_track = ResourceTrack()
-    resource_track.state_id = state_id
-    resource_track.resource_id = resource_id
-    session.add(resource_track)
-    session.commit()
-
-    for region_id, region in regions.items():
-        resource_stat = ResourceStat()
-        resource_stat.region_id = region_id
-        resource_stat.explored = region['explored']
-        resource_stat.deep_exploration = region['deep_exploration']
-        resource_stat.limit_left = region['limit_left']
-        session.add(resource_stat)
-    session.commit()

+ 23 - 0
app/database.py

@@ -0,0 +1,23 @@
+"""Main application"""
+
+from app import Session
+from app.models import ResourceTrack, ResourceStat
+
+
+def save_resources(state_id, regions, resource_id):
+    """Save resources to database"""
+    session = Session()
+    resource_track = ResourceTrack()
+    resource_track.state_id = state_id
+    resource_track.resource_id = resource_id
+    session.add(resource_track)
+    session.commit()
+
+    for region_id, region in regions.items():
+        resource_stat = ResourceStat()
+        resource_stat.region_id = region_id
+        resource_stat.explored = region['explored']
+        resource_stat.deep_exploration = region['deep_exploration']
+        resource_stat.limit_left = region['limit_left']
+        session.add(resource_stat)
+    session.commit()