<commit_before># Copyright (C) 2007, One Laptop Per Child
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import logging
import time
from datetime import datetime
import os

import gobject

from sugar.datastore import dbus_helpers
from sugar.bundle.contentbundle import ContentBundle
from sugar.bundle.activitybundle import ActivityBundle
from sugar import mime

class DSMetadata(gobject.GObject):
    __gsignals__ = {
        'updated': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                    ([]))
    }

    def __init__(self, props=None):
        gobject.GObject.__init__(self)
        if not props:
            self._props = {}
        else:
            self._props = props
        
        default_keys = ['activity', 'activity_id',
                        'mime_type', 'title_set_by_user']
        for key in default_keys:
            if not self._props.has_key(key):
                self._props[key] = ''

    def __getitem__(self, key):
        return self._props[key]

    def __setitem__(self, key, value):
        if not self._props.has_key(key) or self._props[key] != value:
            self._props[key] = value
            self.emit('updated')

    def __delitem__(self, key):
        del self._props[key]

    def __contains__(self, key):
        return self._props.__contains__(key)
    
    def has_key(self, key):
        return self._props.has_key(key)

    def keys(self):
        return self._props.keys()
    
    def get_dictionary(self):
        return self._props

    def copy(self):
        return DSMetadata(self._props.copy())

    def get(self, key, default=None):
        if self._props.has_key(key):
            return self._props[key]
        else:
            return default

class DSObject(object):
    def __init__(self, object_id, metadata=None, file_path=None):
        self.object_id = object_id
        self._metadata = metadata
        self._file_path = file_path
        self._destroyed = False
        self._owns_file = False

    def get_metadata(self):
        if self._metadata is None and not self.object_id is None:
            metadata = DSMetadata(dbus_helpers.get_properties(self.object_id))
            self._metadata = metadata
        return self._metadata
    
    def set_metadata(self, metadata):
        if self._metadata != metadata:
            self._metadata = metadata

    metadata = property(get_metadata, set_metadata)

    def get_file_path(self, fetch=True):
        if fetch and self._file_path is None and not self.object_id is None:
            self.set_file_path(dbus_helpers.get_filename(self.object_id))
            self._owns_file = True
        return self._file_path
    
    def set_file_path(self, file_path):
        if self._file_path != file_path:
            if self._file_path and self._owns_file:
                if os.path.isfile(self._file_path):
                    os.remove(self._file_path)
                self._owns_file = False
            self._file_path = file_path

    file_path = property(get_file_path, set_file_path)

    def is_activity_bundle(self):
        return self.metadata['mime_type'] in \
               [ActivityBundle.MIME_TYPE, ActivityBundle.DEPRECATED_MIME_TYPE]

    def is_content_bundle(self):
        return self.metadata['mime_type'] == ContentBundle.MIME_TYPE

    def is_bundle(self):
        return self.is_activity_bundle() or self.is_content_bundle()

    def destroy(self):
        if self._destroyed:
            logging.warning('This DSObject has already been destroyed!.')
            return
        self._destroyed = True
        if self._file_path and self._owns_file:
            if os.path.isfile(self._file_path):
                os.remove(self._file_path)
            self._owns_file = False
        self._file_path = None

    def __del__(self):
        if not self._destroyed:
            logging.warning('DSObject was deleted without cleaning up first. ' \
                            'Call DSObject.destroy() before disposing it.')
            self.destroy()

    def copy(self):
        return DSObject(None, self._metadata.copy(), self._file_path)

def get(object_id):
    logging.debug('datastore.get')
    metadata = dbus_helpers.get_properties(object_id)

    ds_object = DSObject(object_id, DSMetadata(metadata), None)
    # TODO: register the object for updates<commit_msg>Revert "Move DSObject.resume() from sugar-toolkit to the shell"<commit_after># Copyright (C) 2007, One Laptop Per Child
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import logging
import time
from datetime import datetime
import os

import gobject

from sugar.datastore import dbus_helpers
from sugar import activity
from sugar.activity.activityhandle import ActivityHandle
from sugar.bundle.contentbundle import ContentBundle
from sugar.bundle.activitybundle import ActivityBundle
from sugar import mime

class DSMetadata(gobject.GObject):
    __gsignals__ = {
        'updated': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                    ([]))
    }

    def __init__(self, props=None):
        gobject.GObject.__init__(self)
        if not props:
            self._props = {}
        else:
            self._props = props
        
        default_keys = ['activity', 'activity_id',
                        'mime_type', 'title_set_by_user']
        for key in default_keys:
            if not self._props.has_key(key):
                self._props[key] = ''

    def __getitem__(self, key):
        return self._props[key]

    def __setitem__(self, key, value):
        if not self._props.has_key(key) or self._props[key] != value:
            self._props[key] = value
            self.emit('updated')

    def __delitem__(self, key):
        del self._props[key]

    def __contains__(self, key):
        return self._props.__contains__(key)
    
    def has_key(self, key):
        return self._props.has_key(key)

    def keys(self):
        return self._props.keys()
    
    def get_dictionary(self):
        return self._props

    def copy(self):
        return DSMetadata(self._props.copy())

    def get(self, key, default=None):
        if self._props.has_key(key):
            return self._props[key]
        else:
            return default

class DSObject(object):
    def __init__(self, object_id, metadata=None, file_path=None):
        self.object_id = object_id
        self._metadata = metadata
        self._file_path = file_path
        self._destroyed = False
        self._owns_file = False

    def get_metadata(self):
        if self._metadata is None and not self.object_id is None:
            metadata = DSMetadata(dbus_helpers.get_properties(self.object_id))
            self._metadata = metadata
        return self._metadata
    
    def set_metadata(self, metadata):
        if self._metadata != metadata:
            self._metadata = metadata

    metadata = property(get_metadata, set_metadata)

    def get_file_path(self, fetch=True):
        if fetch and self._file_path is None and not self.object_id is None:
            self.set_file_path(dbus_helpers.get_filename(self.object_id))
            self._owns_file = True
        return self._file_path
    
    def set_file_path(self, file_path):
        if self._file_path != file_path:
            if self._file_path and self._owns_file:
                if os.path.isfile(self._file_path):
                    os.remove(self._file_path)
                self._owns_file = False
            self._file_path = file_path

    file_path = property(get_file_path, set_file_path)

    def _get_activities_for_mime(self, mime_type):
        registry = activity.get_registry()
        result = registry.get_activities_for_type(mime_type)
        if not result:
            for parent_mime in mime.get_mime_parents(mime_type):
                result.extend(registry.get_activities_for_type(parent_mime))
        return result

    def get_activities(self):
        activities = []

        bundle_id = self.metadata.get('activity', '')
        if bundle_id:
            activity_info = activity.get_registry().get_activity(bundle_id)
            if activity_info:
                activities.append(activity_info)

        mime_type = self.metadata.get('mime_type', '')
        if mime_type:
            activities_info = self._get_activities_for_mime(mime_type)
            for activity_info in activities_info:
                if activity_info.bundle_id != bundle_id:
                    activities.append(activity_info)

        return activities

    def is_activity_bundle(self):
        return self.metadata['mime_type'] in \
               [ActivityBundle.MIME_TYPE, ActivityBundle.DEPRECATED_MIME_TYPE]

    def is_content_bundle(self):
        return self.metadata['mime_type'] == ContentBundle.MIME_TYPE

    def is_bundle(self):
        return self.is_activity_bundle() or self.is_content_bundle()

    def resume(self, bundle_id=None):
        from sugar.activity import activityfactory

        if self.is_activity_bundle() and not bundle_id:

            logging.debug('Creating activity bundle')
            bundle = ActivityBundle(self.file_path)
            if not bundle.is_installed():
                logging.debug('Installing activity bundle')
                bundle.install()
            elif bundle.need_upgrade():
                logging.debug('Upgrading activity bundle')
                bundle.upgrade()

            logging.debug('activityfactory.creating bundle with id %r',
                          bundle.get_bundle_id())
            activityfactory.create(bundle.get_bundle_id())

        elif self.is_content_bundle() and not bundle_id:

            logging.debug('Creating content bundle')
            bundle = ContentBundle(self.file_path)
            if not bundle.is_installed():
                logging.debug('Installing content bundle')
                bundle.install()

            activities = self._get_activities_for_mime('text/html')
            if len(activities) == 0:
                logging.warning('No activity can open HTML content bundles')
                return

            uri = bundle.get_start_uri()
            logging.debug('activityfactory.creating with uri %s', uri)
            activityfactory.create_with_uri(activities[0].bundle_id,
                                            bundle.get_start_uri())
        else:
            if not self.get_activities() and bundle_id is None:
                logging.warning('No activity can open this object, %s.' %
                        self.metadata.get('mime_type', None))
                return
            if bundle_id is None:
                bundle_id = self.get_activities()[0].bundle_id

            activity_id = self.metadata['activity_id']
            object_id = self.object_id

            if activity_id:
                handle = ActivityHandle(object_id=object_id,
                                        activity_id=activity_id)
                activityfactory.create(bundle_id, handle)
            else:
                activityfactory.create_with_object_id(bundle_id, object_id)

    def destroy(self):
        if self._destroyed:
            logging.warning('This DSObject has already been destroyed!.')
            return
        self._destroyed = True
        if self._file_path and self._owns_file:
            if os.path.isfile(self._file_path):
                os.remove(self._file_path)
            self._owns_file = False
        self._file_path = None

    def __del__(self):
        if not self._destroyed:
            logging.warning('DSObject was deleted without cleaning up first. ' \
                            'Call DSObject.destroy() before disposing it.')
            self.destroy()

    def copy(self):
        return DSObject(None, self._metadata.copy(), self._file_path)

def get(object_id):
    logging.debug('datastore.get')
    metadata = dbus_helpers.get_properties(object_id)

    ds_object = DSObject(object_id, DSMetadata(metadata), None)
    # TODO: register the object for updates
{'fraction_non_alphanumeric': 0.08244401022095295, 'fraction_numerical': 0.0030813166992334287, 'mean_word_length': 2.3409490333919156, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6624590', 'n_tokens_mistral': 3744, 'n_tokens_neox': 3613, 'n_words': 979}