0ptr/nullptr/store.py

104 lines
2.6 KiB
Python
Raw Normal View History

from nullptr.models.base import Base
from nullptr.models.waypoint import Waypoint
from nullptr.models.sector import Sector
from nullptr.models.system import System
from nullptr.models.agent import Agent
from nullptr.models.marketplace import Marketplace
from nullptr.models.jumpgate import Jumpgate
2023-06-09 20:20:46 +00:00
from os.path import isfile, dirname, isdir
import os
import json
from .util import *
from time import time
2023-06-09 11:19:47 +00:00
class Store:
2023-06-09 20:20:46 +00:00
def __init__(self, data_dir):
self.init_models()
2023-06-09 20:20:46 +00:00
self.data_dir = data_dir
self.data = {}
self.dirty_objects = set()
def init_models(self):
self.models = Base.__subclasses__()
self.extensions = {c.ext(): c for c in self.models}
def dirty(self, obj):
self.dirty_objects.add(obj)
2023-06-09 20:20:46 +00:00
def path(self, obj):
return os.path.join(self.data_dir, obj.path())
def load(self, obj):
path = self.path(obj)
if not isfile(path):
return obj
with open(path) as f:
data = json.load(f)
data['store'] = self
obj.__dict__ = data
2023-06-12 11:56:56 +00:00
def get_file(self, typ, path):
if not isfile(path):
print(path)
2023-06-12 11:56:56 +00:00
return None
with open(path) as f:
data = json.load(f)
symbol = mg(data, 'symbol')
oid = f'{symbol}.{typ.ext()}'
if oid in self.data:
return self.data[oid]
obj = typ(symbol, self)
self.load(obj)
self.data[oid] = obj
return obj
2023-06-09 20:20:46 +00:00
def store(self, obj):
path = self.path(obj)
path_dir = dirname(path)
data = obj.dict()
if not isdir(path_dir):
os.makedirs(path_dir, exist_ok=True)
with open(path, 'w') as f:
json.dump(data, f, indent=2)
def get(self, typ, symbol):
oid = f'{symbol}.{typ.ext()}'
if oid in self.data:
return self.data[oid]
2023-06-09 20:20:46 +00:00
obj = typ(symbol, self)
self.load(obj)
self.data[oid] = obj
2023-06-09 20:20:46 +00:00
return obj
2023-06-10 18:49:50 +00:00
def update(self, typ, symbol, data):
obj = self.get(typ, symbol)
obj.update(data)
return obj
def update_list(self, typ, lst):
return [self.update(typ, mg(d, 'symbol'), d) for d in lst]
def all(self, path, typ, recursive=False):
2023-06-10 17:39:32 +00:00
if hasattr(path, 'path'):
path = path.path()
path = os.path.join(self.data_dir, path)
if not isdir(path):
return
ext = '.' + typ.ext()
for fil in list_files(path, recursive):
2023-06-10 17:39:32 +00:00
if not fil.endswith(ext):
continue
2023-06-12 11:56:56 +00:00
yield self.get_file(typ, fil)
2023-06-10 17:39:32 +00:00
2023-06-09 20:20:46 +00:00
def flush(self):
it = 0
start_time = time()
for obj in self.dirty_objects:
it += 1
self.store(obj)
self.dirty_objects = set()
dur = time() - start_time
2023-06-12 11:56:56 +00:00
# print(f'flush done {it} items {dur:.2f}')