コード例 #1
0
def store_topic(store, topic_map_identifier, topic):
    store.open()
    if not store.topic_exists(topic_map_identifier, topic.identifier):
        text_occurrence = Occurrence(
            instance_of="text",
            topic_identifier=topic.identifier,
            scope=UNIVERSAL_SCOPE,
            resource_data="Topic automatically created.",
        )
        timestamp = str(datetime.now())
        modification_attribute = Attribute(
            "modification-timestamp",
            timestamp,
            topic.identifier,
            data_type=DataType.TIMESTAMP,
        )
        # Persist objects to the topic store
        store.set_topic(topic_map_identifier, topic)
        # store.set_occurrence(topic_map_identifier, text_occurrence)  # Not sure if these topics should have auto-generated topic text
        store.set_attribute(topic_map_identifier, modification_attribute)
        # Persist tags, if any
        tags_attribute = topic.get_attribute_by_name("tags")
        if tags_attribute:
            for tag in tags_attribute.value.split(","):
                store.set_tag(topic_map_identifier, topic.identifier, tag)
    store.close()
コード例 #2
0
def test_attribute():
    attribute1 = Attribute('name', 'true', 'test-entity1',
                           identifier='test-attribute1',
                           data_type=DataType.BOOLEAN,
                           language=Language.FRA)

    # Instantiate and open topic store.
    store = TopicStore(username, password)
    store.open()

    # Persist attribute to store.
    if not store.attribute_exists(TOPIC_MAP_IDENTIFIER, 'test-entity1', 'name'):
        store.set_attribute(TOPIC_MAP_IDENTIFIER, attribute1)

    # Retrieve attribute from store.
    attribute2 = store.get_attribute(TOPIC_MAP_IDENTIFIER, 'test-attribute1')

    store.close()

    assert attribute2.identifier == 'test-attribute1'
    assert attribute2.name == 'name'
    assert attribute2.value == 'true'
    assert attribute2.entity_identifier == 'test-entity1'
    assert attribute2.scope == '*'  # Universal scope.
    assert attribute2.data_type is DataType.BOOLEAN
    assert attribute2.language is Language.FRA
コード例 #3
0
    def set_character(self, topic_map_identifier, character, scene_identifier):
        topic = Topic(character.identifier, character.instance_of,
                      character.name)
        self.topic_store.set_topic(topic_map_identifier, topic)

        description_attribute = Attribute(
            'description', character.description,
            topic.identifier) if character.description else None
        location_attribute = Attribute('location', character.location,
                                       topic.identifier)
        rotation_attribute = Attribute('rotation', character.rotation,
                                       topic.identifier)
        scale_attribute = Attribute('scale', character.scale, topic.identifier)

        attributes = [
            x for x in [
                description_attribute, location_attribute, rotation_attribute,
                scale_attribute
            ] if x is not None
        ]
        self.topic_store.set_attributes(topic_map_identifier, attributes)

        for asset in character.assets:
            occurrence = Occurrence(instance_of=asset.instance_of,
                                    topic_identifier=topic.identifier,
                                    resource_ref=asset.reference,
                                    resource_data=asset.data)
            self.topic_store.set_occurrence(topic_map_identifier, occurrence)

        scene_association = Association(
            instance_of='character',
            src_topic_ref=topic.identifier,  # The character's reference.
            dest_topic_ref=scene_identifier,
            src_role_spec='included-in',
            dest_role_spec='includes')
        self.topic_store.set_association(topic_map_identifier,
                                         scene_association)

        book_association = Association(
            instance_of='character',
            src_topic_ref=topic.identifier,  # The character's reference.
            dest_topic_ref='genesis',
            src_role_spec='included-in',
            dest_role_spec='includes',
            scope='book')
        self.topic_store.set_association(topic_map_identifier,
                                         book_association)
コード例 #4
0
ファイル: bootstrap.py プロジェクト: dwtcourses/topic-db
def create_tree():
    script_dir = os.path.dirname(__file__)
    data_file = "topics.dat"
    abs_file_path = os.path.join(script_dir, data_file)
    topics_file = open(abs_file_path, "r")
    stack = {}
    for line in topics_file:
        normalized_tags = None
        index = int(line.count(SPACE) / SPACES_PER_TAB)
        topic_data = line.strip().split(";")
        if len(topic_data) < 1 or len(topic_data) > 4:
            raise TopicImportError("Invalid topic data")
        topic_identifier = slugify(str(topic_data[IDENTIFIER]))
        topic_instance_of = "topic"
        if len(topic_data) == 1:  # Only identifier provided
            topic_name = normalize_topic_name(topic_identifier)
        elif len(topic_data) == 2:  # Both identifier and name is provided
            topic_name = topic_data[NAME] if topic_data[
                NAME] else normalize_topic_name(topic_identifier)
        elif len(topic_data
                 ) == 3:  # Identifier, name and type (instance of) is provided
            topic_name = topic_data[NAME] if topic_data[
                NAME] else normalize_topic_name(topic_identifier)
            topic_instance_of = slugify(
                str(topic_data[INSTANCE_OF]
                    )) if topic_data[INSTANCE_OF] else "topic"
        # All parameters have been provided: identifier, name, type and one or more (comma-separated) tags
        else:
            topic_name = topic_data[NAME] if topic_data[
                NAME] else normalize_topic_name(topic_identifier)
            topic_instance_of = slugify(
                str(topic_data[INSTANCE_OF]
                    )) if topic_data[INSTANCE_OF] else "topic"
            normalized_tags = ",".join(
                [slugify(str(tag)) for tag in topic_data[TAGS].split(",")])
        topic = Topic(topic_identifier, topic_instance_of, topic_name)
        if normalized_tags:
            tags_attribute = Attribute("tags",
                                       normalized_tags,
                                       topic.identifier,
                                       data_type=DataType.STRING)
            topic.add_attribute(tags_attribute)
        stack[index] = topic_identifier
        if index == 0:  # Root node
            tree.add_node(
                topic_identifier,
                node_type="identifier",
                edge_type="relationship",
                payload=topic,
            )
        else:
            tree.add_node(
                topic_identifier,
                parent_pointer=stack[index - 1],
                node_type="identifier",
                edge_type="relationship",
                payload=topic,
            )
コード例 #5
0
ファイル: test_models.py プロジェクト: mbrukman/topic-db
def test_init_attribute1():
    attribute1 = Attribute("name", "value", "test-entity1")

    assert attribute1.name == "name"
    assert attribute1.value == "value"
    assert attribute1.entity_identifier == "test-entity1"
    assert attribute1.scope == "*"  # Universal scope.
    assert attribute1.data_type is DataType.STRING
    assert attribute1.language is Language.ENG
コード例 #6
0
ファイル: test_models.py プロジェクト: fractos/topic_db
def test_init_attribute1():
    attribute1 = Attribute('name', 'value', 'test-entity1')

    assert attribute1.name == 'name'
    assert attribute1.value == 'value'
    assert attribute1.entity_identifier == 'test-entity1'
    assert attribute1.scope == '*'  # Universal scope.
    assert attribute1.data_type is DataType.STRING
    assert attribute1.language is Language.ENG
コード例 #7
0
 def set_place(self,
               map_identifier: int,
               place: Place,
               event_identifier: str = None) -> None:
     place.add_attribute(
         Attribute(
             "auto-rotate",
             place.auto_rotate,
             place.identifier,
             data_type=DataType.BOOLEAN,
         ))
     place.add_attribute(
         Attribute(
             "view-labels",
             place.view_labels,
             place.identifier,
             data_type=DataType.BOOLEAN,
         ))
     self.set_entity(map_identifier, place, event_identifier)
コード例 #8
0
    def set_scene(self, topic_map_identifier, scene):
        topic = Topic(scene.identifier, scene.instance_of, scene.name)
        self.topic_store.set_topic(topic_map_identifier, topic)

        description_attribute = Attribute(
            'description', scene.description,
            topic.identifier) if scene.description else None
        location_attribute = Attribute('location', scene.location,
                                       topic.identifier)
        rotation_attribute = Attribute('rotation', scene.rotation,
                                       topic.identifier)
        scale_attribute = Attribute('scale', scene.scale, topic.identifier)
        ordinal_attribute = Attribute(
            'ordinal', scene.ordinal,
            topic.identifier) if scene.ordinal else None

        attributes = [
            x for x in [
                description_attribute, location_attribute, rotation_attribute,
                scale_attribute, ordinal_attribute
            ] if x is not None
        ]
        self.topic_store.set_attributes(topic_map_identifier, attributes)

        for asset in scene.assets:
            occurrence = Occurrence(instance_of=asset.instance_of,
                                    topic_identifier=topic.identifier,
                                    resource_ref=asset.reference,
                                    resource_data=asset.data)
            self.topic_store.set_occurrence(topic_map_identifier, occurrence)

        book_association = Association(
            instance_of='scene',
            src_topic_ref=topic.identifier,  # The scene's reference.
            dest_topic_ref='genesis',
            src_role_spec='included-in',
            dest_role_spec='includes',
            scope='book')
        self.topic_store.set_association(topic_map_identifier,
                                         book_association)
コード例 #9
0
ファイル: test_models.py プロジェクト: fractos/topic_db
def test_init_attribute2():
    attribute2 = Attribute('name',
                           'true',
                           'test-entity1',
                           scope='test-scope',
                           data_type=DataType.BOOLEAN,
                           language=Language.FRA)

    assert attribute2.name == 'name'
    assert attribute2.value == 'true'
    assert attribute2.entity_identifier == 'test-entity1'
    assert attribute2.scope == 'test-scope'
    assert attribute2.data_type is DataType.BOOLEAN
    assert attribute2.language is Language.FRA
コード例 #10
0
ファイル: test_models.py プロジェクト: mbrukman/topic-db
def test_init_attribute2():
    attribute2 = Attribute(
        "name",
        "true",
        "test-entity1",
        scope="test-scope",
        data_type=DataType.BOOLEAN,
        language=Language.FRA,
    )

    assert attribute2.name == "name"
    assert attribute2.value == "true"
    assert attribute2.entity_identifier == "test-entity1"
    assert attribute2.scope == "test-scope"
    assert attribute2.data_type is DataType.BOOLEAN
    assert attribute2.language is Language.FRA
コード例 #11
0
 def set_spatial_connection(
     self,
     map_identifier: int,
     source_identifier: str,
     destination_identifier: str,
     navigation_identifier: str,
 ) -> None:
     association = Association(
         instance_of="spatial-navigation",
         src_topic_ref=source_identifier,
         dest_topic_ref=destination_identifier,
         src_role_spec="from",
         dest_role_spec="to",
     )
     attribute = Attribute(
         "navigation-identifier",
         navigation_identifier,
         association.identifier,
         data_type=DataType.STRING,
     )
     self.topic_store.set_association(map_identifier, association)
     self.topic_store.set_attribute(map_identifier, attribute)
コード例 #12
0
ファイル: video.py プロジェクト: plucena24/contextualise
def add(map_identifier, topic_identifier):
    topic_store = get_topic_store()
    topic_map = topic_store.get_topic_map(map_identifier)

    if topic_map is None:
        abort(404)

    if current_user.id != topic_map.user_identifier:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    form_video_title = ""
    form_video_url = ""
    form_video_scope = session["current_scope"]

    error = 0

    if request.method == "POST":
        form_video_title = request.form["video-title"].strip()
        form_video_url = request.form["video-url"].strip()
        form_video_scope = request.form["video-scope"].strip()

        # If no values have been provided set their default values
        if not form_video_scope:
            form_video_scope = UNIVERSAL_SCOPE

        # Validate form inputs
        if not form_video_title:
            error = error | 1
        if not form_video_url:
            error = error | 2
        if not topic_store.topic_exists(topic_map.identifier,
                                        form_video_scope):
            error = error | 4

        if error != 0:
            flash(
                "An error occurred when submitting the form. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            video_occurrence = Occurrence(
                instance_of="video",
                topic_identifier=topic.identifier,
                scope=form_video_scope,
                resource_ref=form_video_url,
            )
            title_attribute = Attribute(
                "title",
                form_video_title,
                video_occurrence.identifier,
                data_type=DataType.STRING,
            )

            # Persist objects to the topic store
            topic_store.set_occurrence(topic_map.identifier, video_occurrence)
            topic_store.set_attribute(topic_map.identifier, title_attribute)

            flash("Video link successfully added.", "success")
            return redirect(
                url_for(
                    "video.index",
                    map_identifier=topic_map.identifier,
                    topic_identifier=topic.identifier,
                ))

    return render_template(
        "video/add.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        video_title=form_video_title,
        video_url=form_video_url,
        video_scope=form_video_scope,
    )
コード例 #13
0
def upload(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    map_notes_count = topic_store.get_topic_occurrences_statistics(map_identifier, "notes")["note"]
    error = 0

    if request.method == "POST":
        form_image_title = request.form["image-title"].strip()
        form_image_scope = request.form["image-scope"].strip()
        form_upload_file = request.files["image-file"] if "image-file" in request.files else None

        # If no values have been provided set their default values
        if not form_image_scope:
            form_image_scope = session["current_scope"]

        # Validate form inputs
        if not form_image_title:
            error = error | 1
        if not form_upload_file:
            error = error | 2
        else:
            if form_upload_file.filename == "":
                error = error | 4
            elif not allowed_file(form_upload_file.filename):
                error = error | 8
        if not topic_store.topic_exists(topic_map.identifier, form_image_scope):
            error = error | 16

        if error != 0:
            flash(
                "An error occurred when uploading the image. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            image_file_name = f"{str(uuid.uuid4())}.{get_file_extension(form_upload_file.filename)}"

            # Create the image directory for this topic map if it doesn't already exist
            image_directory = os.path.join(current_app.static_folder, RESOURCES_DIRECTORY, str(map_identifier))
            if not os.path.isdir(image_directory):
                os.makedirs(image_directory)

            file_path = os.path.join(image_directory, image_file_name)
            form_upload_file.save(file_path)

            image_occurrence = Occurrence(
                instance_of="image",
                topic_identifier=topic.identifier,
                scope=form_image_scope,
                resource_ref=image_file_name,
            )
            title_attribute = Attribute(
                "title",
                form_image_title,
                image_occurrence.identifier,
                data_type=DataType.STRING,
            )

            # Persist objects to the topic store
            topic_store.create_occurrence(topic_map.identifier, image_occurrence)
            topic_store.create_attribute(topic_map.identifier, title_attribute)

            flash("Image successfully uploaded.", "success")
            return redirect(
                url_for(
                    "image.index",
                    map_identifier=topic_map.identifier,
                    topic_identifier=topic.identifier,
                )
            )

        return render_template(
            "image/upload.html",
            error=error,
            topic_map=topic_map,
            topic=topic,
            image_title=form_image_title,
            image_scope=form_image_scope,
            map_notes_count=map_notes_count,
        )

    return render_template(
        "image/upload.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        map_notes_count=map_notes_count,
    )
コード例 #14
0
def create(map_identifier, topic_identifier):
    topic_store = get_topic_store()
    topic_map = topic_store.get_topic_map(map_identifier)

    if topic_map is None:
        abort(404)

    if current_user.id != topic_map.user_identifier:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    form_topic_name = ""
    form_topic_identifier = ""
    form_topic_text = ""
    form_topic_instance_of = "topic"
    form_topic_text_scope = session["current_scope"]

    error = 0

    if request.method == "POST":
        form_topic_identifier = request.form["topic-identifier"].strip()
        form_topic_name = request.form["topic-name"].strip()
        form_topic_text = request.form["topic-text"].strip()
        form_topic_instance_of = request.form["topic-instance-of"].strip()
        form_topic_text_scope = request.form["topic-text-scope"].strip()

        # If no values have been provided set their default values
        if not form_topic_instance_of:
            form_topic_instance_of = "topic"

        # Validate form inputs
        if not form_topic_name:
            error = error | 1
        if topic_store.topic_exists(topic_map.identifier,
                                    form_topic_identifier):
            error = error | 2
        if not form_topic_identifier:
            error = error | 4
        if not topic_store.topic_exists(topic_map.identifier,
                                        form_topic_instance_of):
            error = error | 8
        if not topic_store.topic_exists(topic_map.identifier,
                                        form_topic_text_scope):
            error = error | 16

        if error != 0:
            flash(
                "An error occurred when submitting the form. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            new_topic = Topic(form_topic_identifier, form_topic_instance_of,
                              form_topic_name)
            text_occurrence = Occurrence(
                instance_of="text",
                topic_identifier=new_topic.identifier,
                scope=form_topic_text_scope,
                resource_data=form_topic_text,
            )
            timestamp = str(datetime.now())
            modification_attribute = Attribute(
                "modification-timestamp",
                timestamp,
                new_topic.identifier,
                data_type=DataType.TIMESTAMP,
            )

            query_attribute = Attribute(
                "knowledge-graph-query",
                form_topic_name.lower(),
                new_topic.identifier,
                data_type=DataType.STRING,
            )

            # Persist objects to the topic store
            topic_store.set_topic(topic_map.identifier, new_topic)
            topic_store.set_occurrence(topic_map.identifier, text_occurrence)
            topic_store.set_attribute(topic_map.identifier,
                                      modification_attribute)
            topic_store.set_attribute(topic_map.identifier, query_attribute)

            flash("Topic successfully created.", "success")
            return redirect(
                url_for(
                    "topic.view",
                    map_identifier=topic_map.identifier,
                    topic_identifier=new_topic.identifier,
                ))

    return render_template(
        "topic/create.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        topic_name=form_topic_name,
        topic_identifier=form_topic_identifier,
        topic_text=form_topic_text,
        topic_instance_of=form_topic_instance_of,
        topic_text_scope=form_topic_text_scope,
    )
コード例 #15
0
def entity_add(map_identifier, topic_identifier, entity_identifier, entity_type):
    topic_store = get_topic_store()

    if "admin" not in current_user.roles:
        abort(403)
    topic_map = topic_store.get_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    entity = topic_store.get_occurrence(
        map_identifier,
        entity_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if entity is None:
        abort(404)

    post_url = "attribute.entity_add"
    cancel_url = "attribute.entity_index"

    map_notes_count = topic_store.get_topic_occurrences_statistics(map_identifier, "notes")["note"]
    error = 0

    if request.method == "POST":
        form_attribute_name = request.form["attribute-name"].strip()
        form_attribute_value = request.form["attribute-value"].strip()
        form_attribute_type = request.form["attribute-type"]
        form_attribute_scope = request.form["attribute-scope"].strip()

        # If no values have been provided set their default values
        if not form_attribute_scope:
            form_attribute_scope = session["current_scope"]

        # Validate form inputs
        if not form_attribute_name:
            error = error | 1
        if not form_attribute_value:
            error = error | 2
        if not topic_store.topic_exists(topic_map.identifier, form_attribute_scope):
            error = error | 4
        if entity.get_attribute_by_name(form_attribute_name):
            error = error | 8

        if error != 0:
            flash(
                "An error occurred when submitting the form. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            attribute = Attribute(
                form_attribute_name,
                form_attribute_value,
                entity.identifier,
                data_type=DataType[form_attribute_type],
                scope=form_attribute_scope,
            )

            # Persist objects to the topic store
            topic_store.create_attribute(topic_map.identifier, attribute)

            flash("Attribute successfully added.", "success")
            return redirect(
                url_for(
                    "attribute.entity_index",
                    map_identifier=topic_map.identifier,
                    topic_identifier=topic.identifier,
                    entity_identifier=entity.identifier,
                    entity_type=entity_type,
                )
            )

        return render_template(
            "attribute/add.html",
            error=error,
            topic_map=topic_map,
            topic=topic,
            entity=entity,
            entity_type=entity_type,
            post_url=post_url,
            cancel_url=cancel_url,
            attribute_name=form_attribute_name,
            attribute_value=form_attribute_value,
            attribute_type=form_attribute_type,
            attribute_scope=form_attribute_scope,
            map_notes_count=map_notes_count,
        )

    return render_template(
        "attribute/add.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        entity=entity,
        entity_type=entity_type,
        post_url=post_url,
        cancel_url=cancel_url,
        map_notes_count=map_notes_count,
    )
コード例 #16
0
ファイル: demo3.py プロジェクト: jonike/story_engine
TOPIC_MAP_IDENTIFIER = 3
SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), '../settings.ini')

config = configparser.ConfigParser()
config.read(SETTINGS_FILE_PATH)

username = config['DATABASE']['Username']
password = config['DATABASE']['Password']

# Instantiate and open the scene store.
scene_store = SceneStore(username, password)
scene_store.open()

# Genesis topic.
attribute01 = Attribute('entry-scene', 'environment', 'genesis')
scene_store.set_attribute(TOPIC_MAP_IDENTIFIER, attribute01)

story_text = """A test story.
"""
story_text_occurrence = Occurrence(topic_identifier='genesis',
                                   instance_of='text',
                                   resource_data=bytes(story_text, 'utf-8'))
scene_store.set_occurrence(TOPIC_MAP_IDENTIFIER, story_text_occurrence)

story_image_occurrence = Occurrence(topic_identifier='genesis',
                                    instance_of='image',
                                    resource_ref='locomotive.png')
scene_store.set_occurrence(TOPIC_MAP_IDENTIFIER, story_image_occurrence)

# Test scene.
コード例 #17
0
ファイル: demo2.py プロジェクト: jonike/story_engine
TOPIC_MAP_IDENTIFIER = 2
SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), '../settings.ini')

config = configparser.ConfigParser()
config.read(SETTINGS_FILE_PATH)

username = config['DATABASE']['Username']
password = config['DATABASE']['Password']

# Instantiate and open the scene store.
scene_store = SceneStore(username, password)
scene_store.open()

# Genesis topic.
attribute01 = Attribute('entry-scene', 'cafeteria', 'genesis')
scene_store.set_attribute(TOPIC_MAP_IDENTIFIER, attribute01)

story_text = """An unexpected or casual meeting with someone or something. She felt totally unnerved by the encounter. I told them of my encounter with the __cardinal__. What do we know about the people we encounter in our daily lives?

Unexpectedly be faced with or experience (something hostile or difficult). The guides will help if you encounter any problems.
"""
story_text_occurrence = Occurrence(topic_identifier='genesis',
                                   instance_of='text',
                                   resource_data=bytes(story_text, 'utf-8'))
scene_store.set_occurrence(TOPIC_MAP_IDENTIFIER, story_text_occurrence)

story_image_occurrence = Occurrence(topic_identifier='genesis',
                                    instance_of='image',
                                    resource_ref='town.png')
scene_store.set_occurrence(TOPIC_MAP_IDENTIFIER, story_image_occurrence)
コード例 #18
0
def edit(map_identifier, topic_identifier, attribute_identifier):
    topic_store = get_topic_store()

    if "admin" not in current_user.roles:
        abort(403)
    topic_map = topic_store.get_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    attribute = topic.get_attribute(attribute_identifier)
    if attribute is None:
        abort(404)

    form_attribute_name = attribute.name
    form_attribute_value = attribute.value
    form_attribute_type = str(attribute.data_type).capitalize()
    form_attribute_scope = attribute.scope

    map_notes_count = topic_store.get_topic_occurrences_statistics(map_identifier, "notes")["note"]
    error = 0

    if request.method == "POST":
        form_attribute_name = request.form["attribute-name"].strip()
        form_attribute_value = request.form["attribute-value"].strip()
        form_attribute_type = request.form["attribute-type"]
        form_attribute_scope = request.form["attribute-scope"].strip()

        # If no values have been provided set their default values
        if not form_attribute_scope:
            form_attribute_scope = session["current_scope"]

        # Validate form inputs
        if not form_attribute_name:
            error = error | 1
        if not form_attribute_value:
            error = error | 2
        if not topic_store.topic_exists(topic_map.identifier, form_attribute_scope):
            error = error | 4

        if error != 0:
            flash(
                "An error occurred when submitting the form. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            # Update the attribute by deleting the existing attribute and
            # adding a new one
            topic_store.delete_attribute(map_identifier, attribute.identifier)
            updated_attribute = Attribute(
                form_attribute_name,
                form_attribute_value,
                topic.identifier,
                data_type=DataType[form_attribute_type],
                scope=form_attribute_scope,
            )
            topic_store.create_attribute(topic_map.identifier, updated_attribute)

            flash("Attribute successfully updated.", "success")
            return redirect(
                url_for(
                    "attribute.index",
                    map_identifier=topic_map.identifier,
                    topic_identifier=topic.identifier,
                )
            )

    entity_type = "topic"
    data_types = [
        ("STRING", "String"),
        ("NUMBER", "Number"),
        ("TIMESTAMP", "Timestamp"),
        ("BOOLEAN", "Boolean"),
    ]
    post_url = "attribute.edit"
    cancel_url = "attribute.index"

    return render_template(
        "attribute/edit.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        attribute=attribute,
        entity_type=entity_type,
        data_types=data_types,
        post_url=post_url,
        cancel_url=cancel_url,
        attribute_name=form_attribute_name,
        attribute_value=form_attribute_value,
        attribute_type=form_attribute_type,
        attribute_scope=form_attribute_scope,
        map_notes_count=map_notes_count,
    )
コード例 #19
0
ファイル: topic.py プロジェクト: brettkromkamp/contextualise
def create(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_map(map_identifier, current_user.id)
    if topic_map is None:
        current_app.logger.warning(
            f"Topic map not found: user identifier: [{current_user.id}], topic map identifier: [{map_identifier}]"
        )
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier,
        topic_identifier,
        resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        current_app.logger.warning(
            f"Topic not found: user identifier: [{current_user.id}], topic map identifier: [{map_identifier}], topic identifier: [{topic_identifier}]"
        )
        abort(404)

    map_notes_count = topic_store.get_topic_occurrences_statistics(
        map_identifier, "notes")["note"]
    error = 0

    if request.method == "POST":
        form_topic_identifier = request.form["topic-identifier"].strip()
        form_topic_name = request.form["topic-name"].strip()
        form_topic_text = request.form["topic-text"].strip()
        form_topic_instance_of = request.form["topic-instance-of"].strip()
        form_topic_text_scope = request.form["topic-text-scope"].strip()

        # If no values have been provided set their default values
        if not form_topic_instance_of:
            form_topic_instance_of = "topic"
        if not form_topic_text_scope:
            form_topic_text_scope = session["current_scope"]

        # Validate form inputs
        if not form_topic_name:
            error = error | 1
        if topic_store.topic_exists(topic_map.identifier,
                                    form_topic_identifier):
            error = error | 2
        if not form_topic_identifier:
            error = error | 4
        if not topic_store.topic_exists(topic_map.identifier,
                                        form_topic_instance_of):
            error = error | 8
        if not topic_store.topic_exists(topic_map.identifier,
                                        form_topic_text_scope):
            error = error | 16

        if error != 0:
            flash(
                "An error occurred when submitting the form. Please review the warnings and fix accordingly.",
                "warning",
            )
        else:
            new_topic = Topic(form_topic_identifier, form_topic_instance_of,
                              form_topic_name)
            text_occurrence = Occurrence(
                instance_of="text",
                topic_identifier=new_topic.identifier,
                scope=form_topic_text_scope,
                resource_data=form_topic_text,
            )

            new_topic.first_base_name.scope = session["current_scope"]

            timestamp = str(datetime.now())
            modification_attribute = Attribute(
                "modification-timestamp",
                timestamp,
                new_topic.identifier,
                data_type=DataType.TIMESTAMP,
            )

            # Persist objects to the topic store
            topic_store.create_topic(topic_map.identifier, new_topic)
            topic_store.create_occurrence(topic_map.identifier,
                                          text_occurrence)
            topic_store.create_attribute(topic_map.identifier,
                                         modification_attribute)

            flash("Topic successfully created.", "success")
            return redirect(
                url_for(
                    "topic.view",
                    map_identifier=topic_map.identifier,
                    topic_identifier=new_topic.identifier,
                ))

        return render_template(
            "topic/create.html",
            error=error,
            topic_map=topic_map,
            topic=topic,
            topic_name=form_topic_name,
            topic_identifier=form_topic_identifier,
            topic_text=form_topic_text,
            topic_instance_of=form_topic_instance_of,
            topic_text_scope=form_topic_text_scope,
            map_notes_count=map_notes_count,
        )

    return render_template(
        "topic/create.html",
        error=error,
        topic_map=topic_map,
        topic=topic,
        map_notes_count=map_notes_count,
    )