示例#1
0
 def append_default_holder(uuid):
     user_node = CaliopeUser.index.get(
         username=LoginManager().get_user())
     super(TaskServices, cls) \
         .update_relationship(uuid, "holders", user_node.uuid,
                              new_properties={"category": "ToDo"})
     return {user_node.uuid: {"category": "ToDo"}}
示例#2
0
            def wrapped_f(*args, **kwargs):
                ac = AccessControlManager.get_acl()
                versioned_node_class = getattr(f, "func_globals")[
                    "VersionedNode"]
                class_type = versioned_node_class.pull(args[uuid_pos],
                                                       only_class=True)

                if ac.is_access_granted(LoginManager.get_user(), action,
                                        class_type):
                    return f(*args, **kwargs)
                else:
                    raise RuntimeError("No available {}".format(f.__name__))
示例#3
0
            def wrapped_f(*args, **kwargs):
                ac = AccessControlManager.get_acl()
                versioned_node_class = getattr(f,
                                               "func_globals")["VersionedNode"]
                class_type = versioned_node_class.pull(args[uuid_pos],
                                                       only_class=True)

                if ac.is_access_granted(LoginManager.get_user(), action,
                                        class_type):
                    return f(*args, **kwargs)
                else:
                    raise RuntimeError("No available {}".format(f.__name__))
示例#4
0
    def get_all(cls, context=None, recursive=False):
        user_node = CaliopeUser.index.get(username=LoginManager().get_user())

        if context:
            node_context = VersionedNode.pull(context).__node__.id
        else:
            node_context = '*'

        results, metadata = user_node.cypher("""
            START n=node(*)
            MATCH path=(n)-[:TARGET]-(task)-[:__CONTEXT__]-(context), p_none=(task)<-[?:PARENT*]-()
            WHERE has(n.uuid) and p_none=null
            RETURN n
             """.format(context=node_context))

        rv = list()
        instances = list()
        entities = list()
        models = list()
        for row in results:
            form = dict()
            uuid = row[0]['uuid']
            entity_name = VersionedNode.pull(uuid).__class__.__name__

            #TODO: fix workaround
            if entity_name not in current_app.caliope_forms:
                continue

            if entity_name not in entities:
                entities.append(entity_name)

            data = super(FormManager, cls).get_data(uuid=uuid)

            form['uuid'] = uuid
            form['classname'] = entity_name
            form['data'] = data
            form['browsable'] = current_app.caliope_forms[entity_name]['browsable']

            if (recursive):
                cls.get_related_data(instances, data)

            instances.append(form)

        rv.append({'instances': instances})

        for entity_name in entities:
            models.append(cls.get_empty_model(entity_name, thumbnails=True))

        rv.append({'models': models})

        return rv
示例#5
0
    def get_all_with_thumbnails(cls, context=None, thumbnails=False):
        rv = cls.get_all(context=context, recursive=False)

        #TODO: move to DocumentServices
        user_node = CaliopeUser.index.get(username=LoginManager().get_user())

        storage_setup = current_app.config['storage']
        if 'local' in storage_setup and 'absolut_path' in storage_setup['local']:
            STORAGE = storage_setup['local']['absolut_path']

        for form in rv[0]['instances']:
            #TODO: optimize
            results, metadata = user_node.cypher("""
                START form=node:CaliopeStorage(uuid='{uuid}')
                MATCH  pa=(form)-[*1..2]-(file)<-[CALIOPE_DOCUMENT]-(),p_none=(file)<-[?:PARENT*]-()
                WHERE p_none = null and has(file.url)
                return distinct file
                 """.format(uuid=form['uuid']))

            #TODO: use cache to thumbnails
            attachments = list()
            for row in results:
                attachment = row[0]
                file_uuid = attachment['uuid']
                node = CaliopeDocument.pull(file_uuid)
                if thumbnails:
                    filename = os.path.join(STORAGE, file_uuid)
                    size = os.stat(filename).st_size
                    data = {
                        'uuid': file_uuid,
                        'name': node.filename,
                        'size': human_readable_size(size),
                        'thumbnail': get_thumbnail(filename, field_name='data', mimetype=node.mimetype)
                    }
                else:
                    data = {
                        'uuid': file_uuid,
                        'name': node.filename
                    }
                attachments.append(data)
            form['attachments'] = attachments

        return rv
示例#6
0
    def _get_project_list(cls):
        user_node = CaliopeUser.index.get(username=LoginManager().get_user())
        #: default context "personal is related to current user
        rv = [{
            'uuid': {
                'value': user_node.uuid
            },
            'name': {
                'value': 'Personal'
            }
        }]

        results, metadata = user_node.cypher("""
             START project=node(*)
             MATCH pa=(p)<-[?:PARENT*]-(project)-[:PROJECT]-(category), p_none= (project)<-[?:PARENT*]-()
             WHERE ANY(project in TAIL(pa) WHERE has(project.uuid)) and p_none = null
             RETURN distinct project.uuid, project.name
             """)
        for row in results:
            rv.append({'uuid': {'value': row[0]}, 'name': {'value': row[1]}})
        return rv
示例#7
0
    def commit(cls, uuid, loopback_notification=False):
        """
        Push the changes that are in the draft (Redis) to the neo4j database

        Also creates a node containg the changes doing within the commit for
        the conservation of the history of transactions in the system.
        """
        #: TODO: Ensure all updates runs within the same transaction or batch.

        #: check for changes of any kind
        if cls._has_draft_props(uuid) or cls._has_draft_rels(uuid):
            versioned_node = cls.service_class.pull(uuid)
            #: if first time save create a node with given uuid.
            if versioned_node is None:
                node_class = cls._get_draft_class(uuid)
                versioned_node = node_class(uuid=uuid)
                #: apply first the properties changes
            if cls._has_draft_props(uuid):
                changes = cls._get_draft_props(uuid)
                for delta_k, delta_v in changes.items():
                    try:
                        delta_v = json.loads(
                            delta_v,
                            object_hook=DatetimeDecoder.json_date_parser)
                    except BaseException as be:
                        delta_v = DatetimeDecoder._parser(delta_v)
                        #: do the changes
                    versioned_node.update_field(delta_k, delta_v)
                    #: clean stage area
                #: push all changes to database
                versioned_node.update_field(
                    'change_info',
                    LoginManager().get_current_user_uuid(),
                    special=True)
                versioned_node.save()

            cls._remove_draft_props(uuid)
            if cls._has_draft_rels(uuid):
                changes = cls._get_draft_rels(uuid)
                for delta_k, delta_v in changes.items():
                    delta_v = json.loads(
                        delta_v, object_hook=DatetimeDecoder.json_date_parser)
                    #: do the deletes first.
                    order_list = []
                    for target, props in delta_v.items():
                        if "__delete__" in props and props["__delete__"]:
                            order_list.insert(0, target)
                        elif "__changed__" in props and props["__changed__"]:
                            order_list.append(target)
                    #: do the changes for each target, in order first delete rels.
                    for i in xrange(len(order_list)):
                        target = order_list[i]
                        props = delta_v[target]
                        if "__delete__" in props and props["__delete__"]:
                            versioned_node.delete_relationship(delta_k, target)
                        elif "__changed__" in props and props["__changed__"]:
                            del props["__changed__"]
                            versioned_node.add_or_update_relationship_target(
                                delta_k, target, new_properties=props)
                            #: clean stage area
                cls._remove_draft_rels(uuid)
            return {'uuid': uuid, 'value': versioned_node.uuid == uuid}
        else:
            return {'uuid': uuid, 'value': False}
示例#8
0
def uploader():
    if request.method == 'POST':
        #print request.form['id']
        #print str(request.form.viewitems())
        attachment_params = {
            k: v[0]
            for k, v in [x for x in request.form.viewitems()]
        }
        if 'session_uuid' in request.form:
            if LoginManager().check_with_uuid(request.form['session_uuid']):
                print "OK"
            else:
                return "unrecheable"
        else:
            return "unrecheable"

        app = current_app
        storage_setup = app.config['storage']

        if 'local' in storage_setup and 'absolut_path' in storage_setup[
                'local']:
            UPLOAD_FOLDER = storage_setup['local']['absolut_path']

        if 'local' in storage_setup and 'allowed_extensions' in storage_setup[
                'local']:
            ALLOWED_EXTENSIONS = storage_setup['local']['allowed_extensions']

        rv = []
        for uploaded_file in request.files.getlist('files[]'):
            filename = secure_filename(uploaded_file.filename)
            if uploaded_file and allowed_file(uploaded_file.filename,
                                              ALLOWED_EXTENSIONS):
                model = FormManager().get_empty_model('CaliopeDocument',
                                                      data=True)
                idfile = model['data']['uuid']['value']
                uploaded_file.save(os.path.join(UPLOAD_FOLDER, idfile))

                mimetype = mimetypes.guess_type(filename)[0]
                if mimetype is None:
                    mimetype = 'application/octet-stream'

                CaliopeServices().update_field(idfile, 'mimetype', mimetype)
                CaliopeServices().update_field(idfile, 'filename', filename)
                CaliopeServices().update_field(
                    idfile, 'url', local_document_url('', idfile, ''))
                #DocumentProcess().enqueue(doc)

                result = {
                    'result':
                    'ok',
                    'name':
                    filename,
                    'size':
                    human_readable_size(uploaded_file.tell()),
                    'id':
                    idfile,
                    'thumbnail':
                    get_thumbnail(os.path.join(UPLOAD_FOLDER, idfile),
                                  mimetype=mimetype,
                                  field_name='data')
                }
                CaliopeServices().update_relationship(
                    attachment_params['uuid'], attachment_params['field'],
                    idfile)
            else:
                result = {'result': 'error', 'name': filename}
            rv.append(result)

        return json.dumps(rv)
    return "unrecheable"
示例#9
0
    def get_current_user_kanban(cls, category=None, context=None):

        user_node = CaliopeUser.index.get(username=LoginManager().get_user())

        #: Starting from current user, match all nodes which are connected througth a HOLDER
        #: relationship and that node is connected with a  CURRENT relationship to a task.
        #: From the task find the FIRST node
        if context:
            node_context = VersionedNode.pull(context).__node__.id
        else:
            node_context = '*'

        if category is None:
            results, metadata = user_node.cypher("""
            START user=node({{self}}), context_node=node({context})
            MATCH (user)-[r:HOLDER]-(t)-[TASK]-(), (t)-[:__CONTEXT__]-(context)
            WHERE has(r.category) and (r.category='ToDo' or
                                        r.category='Doing' or
                                        r.category='Done') and
                   id(context_node)=id(context)
            RETURN distinct t, r.category
             """.format(context=node_context))
        else:
            results, metadata = user_node.cypher("""
            START user=node({{self}}), context_arg=node({context})
            MATCH (user)-[r:HOLDER]-(t)-[TASK]-(), (t)-[:__CONTEXT__]-(context)
            WHERE has(r.category) and (r.category='{category}')
            RETURN distinct t, r.category
             """.format(category=category, context=node_context))

        tasks_list = {
            'ToDo': {
                'pos': 0,
                'category': {
                    'value': 'ToDo'
                },
                'tasks': []
            },
            'Doing': {
                'pos': 1,
                'category': {
                    'value': 'Doing'
                },
                'tasks': []
            },
            'Done': {
                'pos': 2,
                'category': {
                    'value': 'Done'
                },
                'tasks': []
            }
        }

        for row in results:
            tl = tasks_list[row[1]]['tasks']
            task = cls.get_data(row[0]._properties['uuid'])
            tl.append(task)

        return [
            list
            for list in sorted(tasks_list.values(), key=lambda pos: pos['pos'])
        ]
示例#10
0
 def append_default_context(uuid):
     user_node = CaliopeUser.index.get(
         username=LoginManager().get_user())
     super(TaskServices, cls) \
         .update_relationship(uuid, "contexts", user_node.uuid)
     return {user_node.uuid: {}}