# Copyright (C) 2019 Philipp Hörist # Copyright (C) 2019 Pavel R. # This file is part of Gajim OTR Plugin. # # Gajim OTR Plugin is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation; version 3 only. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You can always obtain full license text at . import sqlite3 from collections import namedtuple class Keystore: SCHEMA = ''' PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS keystore (jid TEXT, privatekey TEXT, fingerprint TEXT, trust INTEGER, timestamp INTEGER, comment TEXT, UNIQUE(privatekey)); CREATE UNIQUE INDEX IF NOT EXISTS jid_fingerprint ON keystore (jid, fingerprint); ''' def __init__(self, db): self._db = sqlite3.connect(db, isolation_level=None) self._db.row_factory = lambda cur,row : namedtuple("Row", [col[0] for col in cur.description])(*row) self._db.executescript(self.SCHEMA) def __del__(self): self._db.close() # fetch all entries with known fingerprints: `load()` or specific entry `load(jid = jid)` def load(self, **args): sql = "SELECT * FROM keystore WHERE %s" % (not args and "fingerprint IS NOT NULL" or " AND ".join(["{0}='{1}'".format(*arg) for arg in args.items()])) return (args) and self._db.execute(sql).fetchone() or self._db.execute(sql).fetchall() # save entry to database: save(jid=jid, fingerprint=fingerprint) def save(self, **args): sql = "REPLACE INTO keystore({0}) VALUES({1})".format(",".join(args.keys()), ",".join(["'%s'"%s for s in args.values()])) self._db.execute(sql) # delete entry from database: `delete(jid=jid) ` def delete(self, **args): sql = "DELETE FROM keystore WHERE %s" % " AND ".join(["{0}='{1}'".format(*a) for a in args.items()]) self._db.execute(sql)