buypeeb/settings.py

79 lines
2.2 KiB
Python

import json, os, pickle
from os import path
from datetime import datetime
import functions
from listing import YahooAuctionsItem, JST
class BuypeebSettings:
def __init__(self, location: str):
self.updateInterval = 10 * 60
self.favouriteUpdateInterval = 5 * 60
self.updateIntervalCritical = 60
self.favouriteUpdateIntervalCritical = 30
self.watchlist = {}
self.jwatchlist = {}
self.location = location
def save(self, backup = False):
for id, item in self.watchlist.items():
self.jwatchlist[id] = {
"name": item.name,
"original_name": item.original_name,
"favourite": False
}
# create a shallow copy to avoid deleting the actual watchlist
out_dict = self.__dict__.copy()
out_dict['watchlist'] = {}
print(out_dict)
filename = "config.json"
if backup:
filename += ".bak"
json.dump(out_dict, open(self.location + filename, 'w'))
self.jwatchlist = {}
def load(self):
if not path.isfile(self.location + "config.json"):
os.makedirs(self.location, 0o755, True)
open(self.location + "config.json", 'x')
open(self.location + "config.json.bak", 'x')
else:
try:
j = json.load(open(self.location + "config.json", 'r'))
for key in j:
setattr(self, key, j[key])
for key in self.jwatchlist:
self.watchlist[key] = YahooAuctionsItem(url = None, from_json = self.jwatchlist[key], id = key)
self.jwatchlist = {}
self.save(backup = True)
except:
raise
print("Couldn't load settings - using defaults")
def watch(self, url: str, name: str = ""):
id = functions.id_from_url(url)
self.watchlist[id] = YahooAuctionsItem(url, id, name)
for item in self.watchlist.values():
print(item.name, item.price)
def outdated_items(self):
out = []
now = datetime.now(tz = JST).timestamp()
for item in self.watchlist.values():
time_difference = now - item.last_checked.timestamp()
ending_soon = False # TODO: this
if (item.favourite and time_difference >= self.favouriteUpdateInterval) or \
(item.favourite and ending_soon and time_difference >= self.favouriteUpdateIntervalCritical) or \
(time_difference >= self.updateInterval) or \
(ending_soon and time_difference >= self.updateIntervalCritical):
out.append(item)
return out