| 21 | |
| 22 | @PluginManager.acceptPlugins |
| 23 | class SiteStorage(object): |
| 24 | def __init__(self, site, allow_create=True): |
| 25 | self.site = site |
| 26 | self.directory = "%s/%s" % (config.data_dir, self.site.address) # Site data diretory |
| 27 | self.allowed_dir = os.path.abspath(self.directory) # Only serve file within this dir |
| 28 | self.log = site.log |
| 29 | self.db = None # Db class |
| 30 | self.db_checked = False # Checked db tables since startup |
| 31 | self.event_db_busy = None # Gevent AsyncResult if db is working on rebuild |
| 32 | self.has_db = self.isFile("dbschema.json") # The site has schema |
| 33 | |
| 34 | if not os.path.isdir(self.directory): |
| 35 | if allow_create: |
| 36 | os.mkdir(self.directory) # Create directory if not found |
| 37 | else: |
| 38 | raise Exception("Directory not exists: %s" % self.directory) |
| 39 | |
| 40 | def getDbFile(self): |
| 41 | if self.isFile("dbschema.json"): |
| 42 | schema = self.loadJson("dbschema.json") |
| 43 | return schema["db_file"] |
| 44 | else: |
| 45 | return False |
| 46 | |
| 47 | # Create new databaseobject with the site's schema |
| 48 | def openDb(self, close_idle=False): |
| 49 | schema = self.getDbSchema() |
| 50 | db_path = self.getPath(schema["db_file"]) |
| 51 | return Db(schema, db_path, close_idle=close_idle) |
| 52 | |
| 53 | def closeDb(self): |
| 54 | if self.db: |
| 55 | self.db.close() |
| 56 | self.event_db_busy = None |
| 57 | self.db = None |
| 58 | |
| 59 | def getDbSchema(self): |
| 60 | try: |
| 61 | schema = self.loadJson("dbschema.json") |
| 62 | except Exception as err: |
| 63 | raise Exception("dbschema.json is not a valid JSON: %s" % err) |
| 64 | return schema |
| 65 | |
| 66 | # Return db class |
| 67 | def getDb(self): |
| 68 | if not self.db: |
| 69 | self.log.debug("No database, waiting for dbschema.json...") |
| 70 | self.site.needFile("dbschema.json", priority=3) |
| 71 | self.has_db = self.isFile("dbschema.json") # Recheck if dbschema exist |
| 72 | if self.has_db: |
| 73 | schema = self.getDbSchema() |
| 74 | db_path = self.getPath(schema["db_file"]) |
| 75 | if not os.path.isfile(db_path) or os.path.getsize(db_path) == 0: |
| 76 | try: |
| 77 | self.rebuildDb() |
| 78 | except Exception as err: |
| 79 | self.log.error(err) |
| 80 | pass |