2006-12-11 13:55:01 +01:00
|
|
|
#!/bin/python
|
|
|
|
# Copyright (C) 2006, Red Hat, Inc.
|
|
|
|
#
|
|
|
|
# This program 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; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program 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 should have received a copy of the GNU General Public License
|
|
|
|
# along with this program; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
|
|
|
|
|
|
|
import os
|
|
|
|
import dbus, dbus.glib, gobject
|
|
|
|
import logging
|
2007-03-02 21:17:03 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
from sqlite3 import dbapi2 as sqlite
|
|
|
|
except ImportError:
|
|
|
|
from pysqlite2 import dbapi2 as sqlite
|
|
|
|
|
2006-12-11 13:55:01 +01:00
|
|
|
import dbus_helpers
|
2006-12-20 20:04:52 +01:00
|
|
|
import string
|
2007-03-02 21:17:03 +01:00
|
|
|
import demodata
|
2006-12-11 13:55:01 +01:00
|
|
|
|
|
|
|
have_sugar = False
|
|
|
|
try:
|
|
|
|
from sugar import env
|
|
|
|
have_sugar = True
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2006-12-20 20:04:52 +01:00
|
|
|
def is_hex(s):
|
|
|
|
return s.strip(string.hexdigits) == ''
|
|
|
|
|
|
|
|
ACTIVITY_ID_LEN = 40
|
|
|
|
|
|
|
|
def validate_activity_id(actid):
|
|
|
|
"""Validate an activity ID."""
|
|
|
|
if not isinstance(actid, str) and not isinstance(actid, unicode):
|
|
|
|
return False
|
|
|
|
if len(actid) != ACTIVITY_ID_LEN:
|
|
|
|
return False
|
|
|
|
if not is_hex(actid):
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2006-12-11 13:55:01 +01:00
|
|
|
|
|
|
|
_DS_SERVICE = "org.laptop.sugar.DataStore"
|
|
|
|
_DS_DBUS_INTERFACE = "org.laptop.sugar.DataStore"
|
|
|
|
_DS_OBJECT_PATH = "/org/laptop/sugar/DataStore"
|
|
|
|
|
|
|
|
_DS_OBJECT_DBUS_INTERFACE = "org.laptop.sugar.DataStore.Object"
|
|
|
|
_DS_OBJECT_OBJECT_PATH = "/org/laptop/sugar/DataStore/Object"
|
|
|
|
|
|
|
|
class NotFoundError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _create_op(uid):
|
|
|
|
return "%s/%d" % (_DS_OBJECT_OBJECT_PATH, uid)
|
|
|
|
|
|
|
|
def _get_uid_from_op(op):
|
|
|
|
if not op.startswith(_DS_OBJECT_OBJECT_PATH + "/"):
|
|
|
|
raise ValueError("Invalid object path %s." % op)
|
|
|
|
item = op[len(_DS_OBJECT_OBJECT_PATH + "/"):]
|
|
|
|
return int(item)
|
|
|
|
|
|
|
|
def _get_data_as_string(data):
|
|
|
|
if isinstance(data, list):
|
|
|
|
data_str = ""
|
|
|
|
for item in data:
|
|
|
|
data_str += chr(item)
|
|
|
|
return data_str
|
|
|
|
elif isinstance(data, int):
|
|
|
|
return str(data)
|
2007-03-02 21:17:03 +01:00
|
|
|
elif isinstance(data, float):
|
|
|
|
return str(data)
|
2006-12-11 13:55:01 +01:00
|
|
|
elif isinstance(data, str):
|
|
|
|
return data
|
|
|
|
elif isinstance(data, unicode):
|
|
|
|
return str(data)
|
|
|
|
else:
|
2007-03-02 21:17:03 +01:00
|
|
|
raise ValueError("Unsupported data type: %s" % type(data))
|
2006-12-11 13:55:01 +01:00
|
|
|
|
|
|
|
class DataStoreDBusHelper(dbus.service.Object):
|
|
|
|
def __init__(self, parent, bus_name):
|
|
|
|
self._parent = parent
|
|
|
|
self._bus_name = bus_name
|
|
|
|
dbus.service.Object.__init__(self, bus_name, _DS_OBJECT_PATH)
|
|
|
|
|
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
|
|
|
in_signature="x", out_signature="o")
|
|
|
|
def get(self, uid):
|
2006-12-11 23:25:48 +01:00
|
|
|
return _create_op(self._parent.get(uid))
|
2006-12-11 13:55:01 +01:00
|
|
|
|
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
2006-12-20 20:04:52 +01:00
|
|
|
in_signature="s", out_signature="o")
|
|
|
|
def getActivityObject(self, activity_id):
|
|
|
|
if not validate_activity_id(activity_id):
|
|
|
|
raise ValueError("invalid activity id")
|
|
|
|
return _create_op(self._parent.get_activity_object(activity_id))
|
|
|
|
|
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
2007-03-02 21:17:03 +01:00
|
|
|
in_signature="a{sv}", out_signature="o")
|
|
|
|
def create(self, prop_dict):
|
|
|
|
uid = self._parent.create(prop_dict)
|
2006-12-11 13:55:01 +01:00
|
|
|
return _create_op(uid)
|
|
|
|
|
2007-03-04 11:27:33 +01:00
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
|
|
|
in_signature="ia{sv}", out_signature="o")
|
|
|
|
def update(self, uid, prop_dict):
|
|
|
|
self._parent.update(uid, prop_dict)
|
|
|
|
return _create_op(uid)
|
|
|
|
|
2006-12-11 13:55:01 +01:00
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
|
|
|
in_signature="o", out_signature="i")
|
|
|
|
def delete(self, op):
|
|
|
|
uid = _get_uid_from_op(op)
|
|
|
|
self._parent.delete(uid)
|
|
|
|
return 0
|
|
|
|
|
|
|
|
@dbus.service.method(_DS_DBUS_INTERFACE,
|
2007-03-02 21:17:03 +01:00
|
|
|
in_signature="s", out_signature="ao")
|
|
|
|
def find(self, query):
|
|
|
|
uids = self._parent.find(query)
|
2006-12-11 13:55:01 +01:00
|
|
|
ops = []
|
|
|
|
for uid in uids:
|
|
|
|
ops.append(_create_op(uid))
|
|
|
|
return ops
|
|
|
|
|
|
|
|
class ObjectDBusHelper(dbus_helpers.FallbackObject):
|
|
|
|
def __init__(self, parent, bus_name):
|
|
|
|
self._parent = parent
|
|
|
|
self._bus_name = bus_name
|
|
|
|
dbus_helpers.FallbackObject.__init__(self, bus_name, _DS_OBJECT_OBJECT_PATH)
|
|
|
|
|
|
|
|
@dbus_helpers.method(_DS_OBJECT_DBUS_INTERFACE,
|
2007-03-01 17:53:43 +01:00
|
|
|
in_signature="", out_signature="ay", object_path_keyword="dbus_object_path")
|
|
|
|
def get_data(self, dbus_object_path=None):
|
|
|
|
if not dbus_object_path:
|
|
|
|
raise RuntimeError("Need the dbus object path.")
|
|
|
|
uid = _get_uid_from_op(dbus_object_path)
|
2007-03-01 19:23:29 +01:00
|
|
|
return dbus.ByteArray(self._parent.get_data(uid))
|
2006-12-11 13:55:01 +01:00
|
|
|
|
|
|
|
@dbus_helpers.method(_DS_OBJECT_DBUS_INTERFACE,
|
2007-03-01 17:53:43 +01:00
|
|
|
in_signature="ay", out_signature="i", object_path_keyword="dbus_object_path")
|
|
|
|
def set_data(self, data, dbus_object_path=None):
|
|
|
|
if not dbus_object_path:
|
|
|
|
raise RuntimeError("Need the dbus object path.")
|
|
|
|
uid = _get_uid_from_op(dbus_object_path)
|
2006-12-11 13:55:01 +01:00
|
|
|
self._parent.set_data(uid, data)
|
|
|
|
return 0
|
|
|
|
|
|
|
|
@dbus_helpers.method(_DS_OBJECT_DBUS_INTERFACE,
|
2007-03-01 17:53:43 +01:00
|
|
|
in_signature="as", out_signature="a{sv}", object_path_keyword="dbus_object_path")
|
|
|
|
def get_properties(self, keys, dbus_object_path=None):
|
|
|
|
if not dbus_object_path:
|
|
|
|
raise RuntimeError("Need the dbus object path.")
|
|
|
|
uid = _get_uid_from_op(dbus_object_path)
|
2006-12-11 13:55:01 +01:00
|
|
|
return self._parent.get_properties(uid, keys)
|
|
|
|
|
|
|
|
@dbus_helpers.method(_DS_OBJECT_DBUS_INTERFACE,
|
2007-03-01 17:53:43 +01:00
|
|
|
in_signature="a{sv}", out_signature="i", object_path_keyword="dbus_object_path")
|
|
|
|
def set_properties(self, prop_dict, dbus_object_path=None):
|
|
|
|
if not dbus_object_path:
|
|
|
|
raise RuntimeError("Need the dbus object path.")
|
|
|
|
uid = _get_uid_from_op(dbus_object_path)
|
2006-12-11 13:55:01 +01:00
|
|
|
self._parent.set_properties(uid, prop_dict)
|
|
|
|
return 0
|
|
|
|
|
|
|
|
@dbus_helpers.fallback_signal(_DS_OBJECT_DBUS_INTERFACE,
|
|
|
|
signature="ba{sv}b", ignore_args=["uid"])
|
|
|
|
def Updated(self, data, prop_dict, deleted, uid=None):
|
|
|
|
# Return the object path so the signal decorator knows what
|
|
|
|
# object this signal should be fore
|
|
|
|
if not uid:
|
|
|
|
raise RuntimeError("Need a UID.")
|
|
|
|
op = _create_op(uid)
|
|
|
|
return op
|
|
|
|
|
|
|
|
class DataStore(object):
|
|
|
|
def __init__(self):
|
|
|
|
self._session_bus = dbus.SessionBus()
|
|
|
|
self._bus_name = dbus.service.BusName(_DS_SERVICE, bus=self._session_bus)
|
|
|
|
self._dbus_helper = DataStoreDBusHelper(self, self._bus_name)
|
|
|
|
self._dbus_obj_helper = ObjectDBusHelper(self, self._bus_name)
|
|
|
|
|
|
|
|
ppath = "/tmp"
|
|
|
|
if have_sugar:
|
|
|
|
ppath = env.get_profile_path()
|
|
|
|
self._dbfile = os.path.join(ppath, "ds", "data-store.db")
|
|
|
|
if not os.path.exists(os.path.dirname(self._dbfile)):
|
|
|
|
os.makedirs(os.path.dirname(self._dbfile), 0755)
|
|
|
|
|
2007-03-02 21:17:03 +01:00
|
|
|
self._dbcx = sqlite.connect(self._dbfile, timeout=3)
|
|
|
|
self._dbcx.row_factory = sqlite.Row
|
2006-12-11 13:55:01 +01:00
|
|
|
try:
|
|
|
|
self._ensure_table()
|
|
|
|
except StandardError, e:
|
|
|
|
logging.info("Could not access the data store. Reason: '%s'. Exiting..." % e)
|
|
|
|
os._exit(1)
|
|
|
|
|
|
|
|
def __del__(self):
|
|
|
|
self._dbcx.close()
|
|
|
|
del self._dbcx
|
|
|
|
|
|
|
|
def _ensure_table(self):
|
|
|
|
curs = self._dbcx.cursor()
|
|
|
|
try:
|
|
|
|
curs.execute('SELECT * FROM properties LIMIT 4')
|
|
|
|
self._dbcx.commit()
|
|
|
|
except Exception, e:
|
|
|
|
# If table wasn't created, try to create it
|
|
|
|
self._dbcx.commit()
|
|
|
|
curs.execute('CREATE TABLE objects (' \
|
2007-03-02 21:17:03 +01:00
|
|
|
'uid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT);')
|
2006-12-11 13:55:01 +01:00
|
|
|
curs.execute('CREATE TABLE properties (' \
|
|
|
|
'objid INTEGER NOT NULL, ' \
|
|
|
|
'key VARCHAR(100),' \
|
|
|
|
'value VARCHAR(200)' \
|
|
|
|
');')
|
|
|
|
curs.execute('CREATE INDEX objid_idx ON properties(objid);')
|
|
|
|
self._dbcx.commit()
|
2007-03-02 21:17:03 +01:00
|
|
|
demodata.insert_demo_data(self)
|
2006-12-11 13:55:01 +01:00
|
|
|
del curs
|
|
|
|
|
|
|
|
def get(self, uid):
|
|
|
|
curs = self._dbcx.cursor()
|
2007-03-01 18:42:53 +01:00
|
|
|
curs.execute('SELECT uid FROM objects WHERE uid=?;', (uid,))
|
2006-12-11 13:55:01 +01:00
|
|
|
res = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
del curs
|
|
|
|
if len(res) > 0:
|
|
|
|
return uid
|
|
|
|
raise NotFoundError("Object %d was not found." % uid)
|
|
|
|
|
2006-12-20 20:04:52 +01:00
|
|
|
def get_activity_object(self, activity_id):
|
|
|
|
curs = self._dbcx.cursor()
|
2007-03-01 18:42:53 +01:00
|
|
|
curs.execute("SELECT uid FROM objects WHERE activity_id=?;", (activity_id,))
|
2006-12-20 20:04:52 +01:00
|
|
|
res = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
if len(res) > 0:
|
|
|
|
del curs
|
|
|
|
return res[0][0]
|
|
|
|
del curs
|
|
|
|
raise NotFoundError("Object for activity %s was not found." % activity_id)
|
|
|
|
|
2007-03-02 21:17:03 +01:00
|
|
|
def create(self, prop_dict):
|
2006-12-11 13:55:01 +01:00
|
|
|
curs = self._dbcx.cursor()
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("INSERT INTO objects (uid) VALUES (NULL);")
|
2006-12-11 13:55:01 +01:00
|
|
|
curs.execute("SELECT last_insert_rowid();")
|
|
|
|
rows = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
last_row = rows[0]
|
|
|
|
uid = last_row[0]
|
|
|
|
for (key, value) in prop_dict.items():
|
2007-03-01 18:42:53 +01:00
|
|
|
value = _get_data_as_string(value)
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("INSERT INTO properties (objid, key, value) VALUES (?, ?, ?);", (uid, key, value))
|
2006-12-11 13:55:01 +01:00
|
|
|
self._dbcx.commit()
|
|
|
|
del curs
|
|
|
|
return uid
|
|
|
|
|
|
|
|
def delete(self, uid):
|
|
|
|
curs = self._dbcx.cursor()
|
2007-03-01 18:42:53 +01:00
|
|
|
curs.execute("DELETE FROM objects WHERE (uid=?);", (uid,))
|
|
|
|
curs.execute("DELETE FROM properties WHERE (objid=?);", (uid,))
|
2006-12-11 13:55:01 +01:00
|
|
|
self._dbcx.commit()
|
|
|
|
del curs
|
|
|
|
self._dbus_obj_helper.Updated(False, {}, True, uid=uid)
|
|
|
|
return 0
|
|
|
|
|
2007-03-02 21:17:03 +01:00
|
|
|
def find(self, query):
|
2007-03-05 16:56:39 +01:00
|
|
|
sql_query = "SELECT props1.objid objid," \
|
|
|
|
" props1.value date," \
|
|
|
|
" props2.value object_type," \
|
|
|
|
" props3.value buddies " \
|
|
|
|
"FROM properties props1," \
|
|
|
|
" properties props2," \
|
|
|
|
" properties props3 " \
|
|
|
|
"WHERE props1.objid = props2.objid AND" \
|
|
|
|
" props2.objid = props3.objid AND" \
|
|
|
|
" props1.key = 'date' AND" \
|
|
|
|
" props2.key = 'object-type' AND" \
|
|
|
|
" props3.key = 'buddies' " \
|
|
|
|
"ORDER BY date DESC"
|
2007-03-02 21:17:03 +01:00
|
|
|
if query:
|
|
|
|
# TODO: parse the query for avoiding sql injection attacks.
|
2007-03-05 16:56:39 +01:00
|
|
|
sql_query = "SELECT objid FROM (%s) WHERE (%s)" % (sql_query, query)
|
2007-03-02 21:17:03 +01:00
|
|
|
sql_query += ";"
|
2006-12-11 13:55:01 +01:00
|
|
|
curs = self._dbcx.cursor()
|
2007-03-05 16:56:39 +01:00
|
|
|
logging.debug(sql_query)
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute(sql_query)
|
2006-12-11 13:55:01 +01:00
|
|
|
rows = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
# FIXME: ensure that each properties.objid has a match in objects.uid
|
|
|
|
uids = []
|
|
|
|
for row in rows:
|
|
|
|
uids.append(row['objid'])
|
|
|
|
del curs
|
|
|
|
return uids
|
|
|
|
|
2007-03-04 11:27:33 +01:00
|
|
|
def update(self, uid, prop_dict):
|
2006-12-11 13:55:01 +01:00
|
|
|
curs = self._dbcx.cursor()
|
2007-03-01 18:42:53 +01:00
|
|
|
curs.execute('SELECT uid FROM objects WHERE uid=?;', (uid,))
|
2006-12-11 13:55:01 +01:00
|
|
|
res = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
if len(res) <= 0:
|
|
|
|
del curs
|
|
|
|
raise NotFoundError("Object %d was not found." % uid)
|
|
|
|
|
|
|
|
for (key, value) in prop_dict.items():
|
2006-12-11 23:25:48 +01:00
|
|
|
value = _get_data_as_string(value)
|
2006-12-11 16:59:30 +01:00
|
|
|
if not len(value):
|
|
|
|
# delete the property
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("DELETE FROM properties WHERE (objid=? AND key=?);", (uid, key))
|
2006-12-11 13:55:01 +01:00
|
|
|
else:
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("SELECT objid FROM properties WHERE (objid=? AND key=?);", (uid, key))
|
2006-12-11 16:59:30 +01:00
|
|
|
if len(curs.fetchall()) > 0:
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("UPDATE properties SET value=? WHERE (objid=? AND key=?);", (value, uid, key))
|
2006-12-11 16:59:30 +01:00
|
|
|
else:
|
2007-03-02 21:17:03 +01:00
|
|
|
curs.execute("INSERT INTO properties (objid, key, value) VALUES (?, ?, ?);", (uid, key, value))
|
2006-12-11 13:55:01 +01:00
|
|
|
self._dbcx.commit()
|
|
|
|
del curs
|
|
|
|
self._dbus_obj_helper.Updated(False, {}, False, uid=uid)
|
|
|
|
|
|
|
|
def get_properties(self, uid, keys):
|
2006-12-11 23:25:48 +01:00
|
|
|
query = "SELECT objid, key, value FROM properties WHERE (objid=%d" % uid
|
2006-12-11 13:55:01 +01:00
|
|
|
subquery = ""
|
2006-12-11 23:25:48 +01:00
|
|
|
if len(keys) > 0:
|
|
|
|
for key in keys:
|
2007-03-02 21:17:03 +01:00
|
|
|
if not subquery:
|
|
|
|
subquery += " AND ("
|
|
|
|
else:
|
2006-12-11 23:25:48 +01:00
|
|
|
subquery += " OR "
|
2007-03-02 21:17:03 +01:00
|
|
|
subquery += "key='%s'" % key
|
2006-12-11 23:25:48 +01:00
|
|
|
subquery += ")"
|
|
|
|
query += subquery + ");"
|
2006-12-11 13:55:01 +01:00
|
|
|
curs = self._dbcx.cursor()
|
|
|
|
curs.execute(query)
|
|
|
|
rows = curs.fetchall()
|
|
|
|
self._dbcx.commit()
|
|
|
|
prop_dict = {}
|
|
|
|
for row in rows:
|
|
|
|
conv_key = row['key'].replace("''", "'")
|
2007-03-01 19:23:55 +01:00
|
|
|
prop_dict[conv_key] = row['value']
|
2007-03-02 21:17:03 +01:00
|
|
|
prop_dict['handle'] = str(uid)
|
2006-12-11 13:55:01 +01:00
|
|
|
del curs
|
|
|
|
return prop_dict
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
loop = gobject.MainLoop()
|
|
|
|
ds = DataStore()
|
|
|
|
try:
|
|
|
|
loop.run()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print 'Ctrl+C pressed, exiting...'
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|