Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: feat(matrix_state_info): add new module for querying state info #92

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions cliff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# configuration file for git-cliff
# see https://github.com/orhun/git-cliff#configuration-file

[changelog]
# changelog header
header = """
# Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://tera.netlify.app/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
<!-- generated by git-cliff -->
"""

[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
# { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/orhun/git-cliff/issues/${2}))"}, # replace issue numbers
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^update", group = "Component Updates"},
{ message = "^feat", group = "Features"},
{ message = "^fix", group = "Bug Fixes"},
{ message = "^doc", group = "Documentation"},
{ message = "^perf", group = "Performance"},
{ message = "^refactor", group = "Refactor"},
{ message = "^style", group = "Styling"},
{ message = "^test", group = "Testing"},
{ message = "^chore\\(release\\): prepare for", skip = true},
{ message = "^chore", group = "Miscellaneous Tasks"},
{ body = ".*security", group = "Security"},
]
# protect breaking changes from being skipped due to matching a skipping commit_parser
protect_breaking_commits = false
# filter out the commits that are not matched by commit parsers
filter_commits = false
# glob pattern for matching git tags
tag_pattern = "v[0-9]*"
# regex for skipping tags
skip_tags = "v0.1.0-beta.1"
# regex for ignoring tags
ignore_tags = ""
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
# limit the number of commits included in the changelog.
# limit_commits = 42
52 changes: 39 additions & 13 deletions plugins/modules/matrix_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@
- Alias of the room to join/create
required: true
type: str
no_create:
description:
- Prevent creation of room
required: false
default: false
type: bool
no_join:
description:
- Prevent joining of room
required: false
default: false
type: bool
requirements:
- matrix-nio (Python library)
"""
Expand Down Expand Up @@ -100,7 +112,11 @@


async def run_module():
module_args = dict(alias=dict(type="str", required=True))
module_args = dict(
alias=dict(type="str", required=True),
no_create=dict(type="bool", required=False, default=False),
no_join=dict(type="bool", required=False, default=False),
)

result = dict(changed=False, message="")

Expand Down Expand Up @@ -130,6 +146,11 @@ async def run_module():
result = {"msg": "Couldn't get joined rooms."}
elif room_id_resp.room_id in rooms_resp.rooms:
result = {"room_id": room_id_resp.room_id, "changed": False}
elif module.params["no_join"]:
failed = True
result = {
"msg": "Room exists, we aren't a member of it, but joining was explicitly disabled"
}
else:
# Try to join room
join_resp = await client.join(module.params["alias"])
Expand All @@ -141,22 +162,27 @@ async def run_module():
failed = True
result = {"msg": f"Room exists, but couldn't join: {join_resp}"}
else:
# Get local part of alias
local_part_regex = re.search("#([^:]*):(.*)", module.params["alias"])
local_part = local_part_regex.groups()[0]

# Try to create room with alias
create_room_resp = await client.room_create(alias=local_part)

# If successful, exit with changed=true and room_id
if isinstance(create_room_resp, RoomCreateResponse):
result = {"room_id": create_room_resp.room_id, "changed": True}
else:
if module.params["no_create"]:
failed = True
result = {
"msg": f"Room does not exist but couldn't be created either: {create_room_resp}"
"msg": "Room doesn't exist, but room creation was explicitly disabled"
}
else:
# Get local part of alias
local_part_regex = re.search("#([^:]*):(.*)", module.params["alias"])
local_part = local_part_regex.groups()[0]

# Try to create room with alias
create_room_resp = await client.room_create(alias=local_part)

# If successful, exit with changed=true and room_id
if isinstance(create_room_resp, RoomCreateResponse):
result = {"room_id": create_room_resp.room_id, "changed": True}
else:
failed = True
result = {
"msg": f"Room does not exist but couldn't be created either: {create_room_resp}"
}
if failed:
await module.fail_json(**result)
else:
Expand Down
140 changes: 140 additions & 0 deletions plugins/modules/matrix_state_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#!/usr/bin/python
# coding: utf-8

# (c) 2018, Jan Christian Grünhage <[email protected]>
# (c) 2020-2023, Famedly GmbH
# GNU Affero General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/agpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}

DOCUMENTATION = """
---
author: "Jan Christian Grünhage (@jcgruenhage)"
module: matrix_state_info
short_description: Query matrix room state
description:
- This module queries matrix room state
options:
hs_url:
description:
- URL of the homeserver, where the CS-API is reachable
required: true
type: str
user_id:
description:
- The user id of the user
required: false
type: str
password:
description:
- The password to log in with
required: false
type: str
token:
description:
- Authentication token for the API call
required: false
type: str
room_id:
description:
- ID of the room to set the state for
required: true
type: str
requirements:
- matrix-client (Python library)
"""

EXAMPLES = """
- name: Set the server ACL for the admin room
famedly.matrix.matrix_state_info:
room_id: "!LAVFnosfDouvhA9VEhiuSV:matrix.org"
hs_url: "https://matrix.org"
token: "{{ matrix_auth_token }}"
register: current_room_state
"""

# TODO: put actual return value homeserver
RETURN = """
event_id:
description:
- ID of the created event
returned: changed
type: str
sample: $Het2Dv7EEDFNJNgY-ehLSUrdqMo8JOxZDCMnuQPSNfo
"""
import asyncio
import traceback

from ansible.module_utils.basic import missing_required_lib

LIB_IMP_ERR = None
try:
from ansible_collections.famedly.matrix.plugins.module_utils.matrix import (
AnsibleNioModule,
)
from nio import (
JoinedRoomsResponse,
JoinedRoomsError,
RoomGetStateResponse,
)

HAS_LIB = True
except ImportError:
LIB_IMP_ERR = traceback.format_exc()
HAS_LIB = False


async def run_module():
module_args = dict(
room_id=dict(type="str", required=True),
)

result = dict(changed=False, message="")

module = AnsibleNioModule(module_args)
if not HAS_LIB:
await module.fail_json(msg=missing_required_lib("matrix-nio"))
await module.matrix_login()
client = module.client

failed = False

# Check if already in room
rooms_resp = await client.joined_rooms()
if isinstance(rooms_resp, JoinedRoomsError):
failed = True
result = {"msg": "Couldn't get joined rooms."}
elif module.params["room_id"] not in rooms_resp.rooms:
failed = True
result = {"msg": "Not in the room you're trying to query state for."}
else:
# Fetch state from room
state_resp = await client.room_get_state(module.params["room_id"])
# If successful, compare with content from module and content is the same, return with changed=false and the ID of the old event
if isinstance(state_resp, RoomGetStateResponse):
result["events"] = state_resp.events
# Else, try to send a new state event
else:
failed = True
result = {"msg": "Failed to fetch state."}

if failed:
await module.fail_json(**result)
else:
await module.exit_json(**result)


def main():
asyncio.run(run_module())


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions tests/sanity/ignore-2.12.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ plugins/modules/matrix_signing_key.py validate-modules:missing-gplv3-license # i
plugins/modules/synapse_register.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_notification.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state_info.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_room.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_uia_login.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/synapse_ratelimit.py validate-modules:missing-gplv3-license # ignore license check
Expand Down
1 change: 1 addition & 0 deletions tests/sanity/ignore-2.13.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ plugins/modules/matrix_signing_key.py validate-modules:missing-gplv3-license # i
plugins/modules/synapse_register.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_notification.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state_info.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_room.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_uia_login.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/synapse_ratelimit.py validate-modules:missing-gplv3-license # ignore license check
Expand Down
1 change: 1 addition & 0 deletions tests/sanity/ignore-2.14.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ plugins/modules/matrix_signing_key.py validate-modules:missing-gplv3-license # i
plugins/modules/synapse_register.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_notification.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_state_info.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_room.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/matrix_uia_login.py validate-modules:missing-gplv3-license # ignore license check
plugins/modules/synapse_ratelimit.py validate-modules:missing-gplv3-license # ignore license check
Expand Down