Compare commits

...

74 Commits

Author SHA1 Message Date
Tobias Fella
88e0c38e5f Fixes 2025-03-13 21:58:07 +01:00
Joshua Goins
20a6b90904 Add command to forcibly end a call in the room 2025-03-13 21:32:35 +01:00
Joshua Goins
fcd7a320e7 Fix publishing video track 2025-03-13 21:32:35 +01:00
Joshua Goins
2f39e70b67 Update to latest LiveKit, fix up QML 2025-03-13 21:32:35 +01:00
Tobias Fella
ddc16a17d2 Calls! 2025-03-13 21:32:34 +01:00
l10n daemon script
f153e57fdb GIT_SILENT Sync po/docbooks with svn 2025-03-12 01:39:11 +00:00
l10n daemon script
bac93e778e GIT_SILENT Sync po/docbooks with svn 2025-03-11 01:37:29 +00:00
James Graham
2aeed10429 Message attached property
Create Message attached property to propagate parameters like room, timeline, index and maxContentWidth down to the message content avoiding lots of boilerplate
2025-03-10 18:28:42 +00:00
l10n daemon script
ea6ad902a7 GIT_SILENT Sync po/docbooks with svn 2025-03-10 01:41:40 +00:00
James Graham
f9c53ee3b0 ThreePIDModel Updates
There is no need for NeochatConnection to depend on ThreePIdModel and also this means it's not in memory when not needed.

Also a little cleanup to make sure only a single job can run at a time.
2025-03-09 12:31:14 +00:00
l10n daemon script
3f0843647c GIT_SILENT Sync po/docbooks with svn 2025-03-09 01:36:22 +00:00
Albert Astals Cid
a50df870e7 GIT_SILENT Upgrade release service version to 25.07.70. 2025-03-08 19:26:23 +01:00
James Graham
716ae11941 Fix Viewing Encrypted Events
Turns out I forgot that an encrypted event is not a roommessage event so we need to handle this when grabbing the content model for the message.
2025-03-08 14:42:48 +00:00
l10n daemon script
4ff16ff402 GIT_SILENT Sync po/docbooks with svn 2025-03-08 01:43:38 +00:00
l10n daemon script
bd598b9c44 GIT_SILENT Sync po/docbooks with svn 2025-03-07 01:39:06 +00:00
Joshua Goins
f1253e4ede Make joining remote rooms more reliable
When joining remote rooms we have to specify another homeserver (that is in the
room) to help us join. The matrix documentation is a little unclear what to do
in this scenario, so instead of giving up let's at least brute force it with the
server in the alias or room id.

This *does* work and allows my server to join rooms in NeoChat I otherwise
couldn't.

BUG: 487253
CCBUG: 491359
FIXED-IN: 24.12.3
2025-03-06 15:39:32 +00:00
Joshua Goins
79a3da3358 Stop emojis from destroying your message
This is easy to reproduce in the following scenario with a bunch of
half-completed emojis: ":a :a :a :a". Trying to complete anything but the last
one starts replacing parts of the message because it only considers the last
colon to the current completion identifier.

This change fixes that and said scenario can no longer cause a message
massacare. This bug doesn't seem to affect the other completions because their
searching in the string was correct, but I made sure they all share the same
index now.

BUG: 479587
FIXED-IN: 24.12.3
2025-03-06 14:47:27 +00:00
l10n daemon script
5a6bdfbbba GIT_SILENT Sync po/docbooks with svn 2025-03-06 01:39:29 +00:00
Joshua Goins
3d663be506 Move the "Explore rooms" button from the hamburger to the space drawer
I think we should put this feature in a more obvious place (and similar to other
chat applications.) Instead of it being buried underneath a menu, joining
spaces/rooms should have the space promenience as creating them - you're going
to be more likely to access this dialog more anyway.
2025-03-05 22:03:54 +00:00
Joshua Goins
0ada4cdebe Add a dialog explaining what to do next when tapping "Verify this device"
The menu that has this action is now more discoverable, and this menu item is
plagued with a bad UX - when you tap on it nothing obvious happens! To people
not familiar with device verification they will think this is a bug, but in fact
all they need to do is open another verified session on another device.

So now there's a dialog explaining that the next step is to do just that. This
dialog also closes once the verification session starts, but the user has the
option to close it in the meantime.
2025-03-05 22:03:38 +00:00
Balló György
d103de96aa Don't create tray icon if system tray is not supported
This fixes the problem that the tray icon is created in GNOME if it was
enabled in other desktop environment previously.
2025-03-05 20:35:18 +00:00
l10n daemon script
f248b04834 GIT_SILENT Sync po/docbooks with svn 2025-03-05 01:54:04 +00:00
l10n daemon script
9572f20682 GIT_SILENT Sync po/docbooks with svn 2025-03-04 01:37:41 +00:00
Justin Zobel
409cec08fc CI - Flatpak Updates 2025-03-03 02:18:43 +00:00
l10n daemon script
51f330eae9 GIT_SILENT Sync po/docbooks with svn 2025-03-03 01:37:33 +00:00
l10n daemon script
51750267e5 GIT_SILENT Sync po/docbooks with svn 2025-03-02 01:35:42 +00:00
l10n daemon script
99948d5151 GIT_SILENT Sync po/docbooks with svn 2025-03-01 01:48:27 +00:00
l10n daemon script
030726e6fb GIT_SILENT Sync po/docbooks with svn 2025-02-28 01:36:36 +00:00
Heiko Becker
1fad54272f GIT_SILENT Update Appstream for new release
(cherry picked from commit a85af258fe)
2025-02-27 21:59:20 +01:00
James Graham
4af4bfd55f Improve the handling of switching link preivews on and off.
First make sure that the global setting is tied into the room setting, previously it was a bit of a patchwork that worked more by luck than judgement. The two levels of global and room level are properly tied together in a hierarchy.

Add a message in the room when global notifcations re turned off. This has caused confusion in the past when people don't realise there are 2 levels.
2025-02-27 16:37:33 +00:00
l10n daemon script
77cedef5bb GIT_SILENT Sync po/docbooks with svn 2025-02-27 01:35:42 +00:00
Joshua Goins
db36f187dc Don't show the "Settings" button when adding a new account
As much as I like opening Settings while I'm in Settings, this
doesn't make much sense.
2025-02-26 23:59:05 +00:00
Joshua Goins
2861eb9c60 Add new message action to pin and unpin messages in rooms
Self-explanatory, now you can manage pinned messages in NeoChat alone.
2025-02-26 23:53:38 +00:00
l10n daemon script
9811c0d97a GIT_SILENT Sync po/docbooks with svn 2025-02-26 01:37:50 +00:00
l10n daemon script
e9c21373ed GIT_SILENT Sync po/docbooks with svn 2025-02-25 01:35:40 +00:00
l10n daemon script
bda23ec54a GIT_SILENT Sync po/docbooks with svn 2025-02-24 10:28:45 +00:00
l10n daemon script
e23641375b GIT_SILENT Sync po/docbooks with svn 2025-02-24 01:35:59 +00:00
l10n daemon script
024d54345a GIT_SILENT Sync po/docbooks with svn 2025-02-23 01:34:15 +00:00
James Graham
59fd4d3916 Make sure the thread dev setting is actually obeyed 2025-02-22 19:48:56 +00:00
Joshua Goins
88d684b6c1 Don't allow long-pressing on non-touchscreen devices
It isn't the right kind of interaction on a computer with a mouse or
trackpad, it should be relegated to touchscreen only. This should
hopefully cover everything from room list delegates to messages.
2025-02-22 18:50:39 +00:00
Joshua Goins
94fdf777cb Early exit if we're checking mutual rooms with yourself
This is rejected by servers too, so don't even bother doing as it
doesn't make sense.
2025-02-22 13:05:30 -05:00
Joshua Goins
dea70152e4 Improve discoverability of the account menu
I figure that not many users know there's a secret and super useful
account menu. Right-clicking or long-pressing opens this menu.
Additionally, tapping your avatar brings up the "Accounts" settings for
some reason. Worse, there's no indication of any of this functionality
or why we're hiding two separate functions here.

Instead, let's make it a ToolButton but keep the general appearance the
same. That makes it act and feel more like a regular button, and
pressing on it will open the account menu. The shortcut to the accounts
settings is removed, there's plenty of other ways to get there.
2025-02-22 17:31:00 +00:00
Joshua Goins
614caf5ca0 Add ellipses to "Remove" message action
This doesn't apply instantly, it opens a dialog to confirm with you and
optionally add a message. According to the HIG (and just a good idea in
general) it should be marked with ellipses.
2025-02-22 17:30:25 +00:00
Joshua Goins
25dbae37fb Change "Copy Message Link" icon to "link-symbolic"
Instead of sharing the same icon as the "Copy Text" action, this make it
even clearer.
2025-02-22 17:30:12 +00:00
Joshua Goins
e060032e6a Improve the notification setting description
The current text has invited a lot of confusion around how notifications
work in NeoChat, because it mentions "push notifications". Some users
take it to mean that somehow the notifications appear in the background,
but that's only supported if built with KUnifiedPush.

To make it super clear, let's change the description dynamically based
on whether:
1. NeoChat is built with KUnifiedPush support.
2. We were able to connect with the KUnifiedPush daemon and your server
has a push gateway.
2025-02-22 10:33:52 -05:00
l10n daemon script
4725410c0f GIT_SILENT Sync po/docbooks with svn 2025-02-22 01:35:48 +00:00
Scarlett Moore
20488ee400 snapcraft: Move to core24 2025-02-21 04:25:07 -07:00
l10n daemon script
b1c0619af5 GIT_SILENT Sync po/docbooks with svn 2025-02-21 01:35:30 +00:00
l10n daemon script
ade730179a GIT_SILENT Sync po/docbooks with svn 2025-02-20 01:36:40 +00:00
Joshua Goins
9264ad26d6 Make the Notifications window non-modal
Tapping on a notification here doesn't close the window. Additionally,
you need to tap it several times for NeoChat to scroll up in a room.

Considering all of this, it would make more sense for this window to be
non-modal for now so you can have the Notifications window open while
using the main NeoChat window.
2025-02-19 13:21:16 +00:00
Joshua Goins
9020e2c7cb Remove word puzzle in the new invitation page 2025-02-18 20:52:13 -05:00
Joshua Goins
0f51c34b24 Add dedicated invitation subtitle text to rooms
Instead of displaying the message event - or usually nothing at all -
show a label like "user has invited you".
2025-02-19 01:45:02 +00:00
Joshua Goins
f6a427e865 Add user information to the invitation page
Currently the invite page kinda sucks. If someone invites you to a room,
you have no idea who from the UI - which is a safety issue.

Now the invite page shows you who invited you, and it has a slightly
different layout & text for one-on-one chats and room invites.

Also the buttons on this page are improved with fixed capitalization
and icons!
2025-02-19 01:45:02 +00:00
l10n daemon script
9b95930463 GIT_SILENT Sync po/docbooks with svn 2025-02-19 01:37:15 +00:00
l10n daemon script
cb96b4991e GIT_SILENT Sync po/docbooks with svn 2025-02-17 01:34:35 +00:00
l10n daemon script
cde7a51cde GIT_SILENT Sync po/docbooks with svn 2025-02-16 01:38:19 +00:00
l10n daemon script
046d611f56 GIT_SILENT Sync po/docbooks with svn 2025-02-15 01:48:20 +00:00
Albert Astals Cid
d7b3748159 CI: Add linux-qt6-next build 2025-02-13 08:14:42 +00:00
l10n daemon script
188c9fc726 GIT_SILENT Sync po/docbooks with svn 2025-02-13 01:43:18 +00:00
l10n daemon script
dbc735e63b SVN_SILENT made messages (.desktop file) - always resolve ours
In case of conflict in i18n, keep the version of the branch "ours"
To resolve a particular conflict, "git checkout --ours path/to/file.desktop"
2025-02-13 01:33:08 +00:00
James Graham
8750486f7b Move to upstream JoinRuleEvent 2025-02-12 18:04:59 +00:00
l10n daemon script
6dc4baeeb5 GIT_SILENT Sync po/docbooks with svn 2025-02-12 01:34:39 +00:00
l10n daemon script
ff28828a2e GIT_SILENT Sync po/docbooks with svn 2025-02-11 01:38:11 +00:00
l10n daemon script
e28452dfd1 GIT_SILENT Sync po/docbooks with svn 2025-02-10 01:33:12 +00:00
James Graham
5d7cb5c28f Move the reaction delegate into the bubble
Move the reaction delegate into the bubble so it can be instantiated by the Content model. This aims to make sure we only instantiate it when needed rather than for every event. You can now hover the event to show the ReactionComponent with a button to add a reaction if none are currently present

Added bonus ReactionModel no longer needs an event pointer, the event ID is enough to get reaction from the room so things are less likely to blow up.
2025-02-09 19:07:53 +00:00
James Graham
08b29f7081 Make sure that a blank entry is never added to the message model store
title
2025-02-09 18:18:15 +00:00
l10n daemon script
c9e034b5b3 SVN_SILENT made messages (.desktop file) - always resolve ours
In case of conflict in i18n, keep the version of the branch "ours"
To resolve a particular conflict, "git checkout --ours path/to/file.desktop"
2025-02-09 01:27:43 +00:00
l10n daemon script
d9f0ff466f GIT_SILENT Sync po/docbooks with svn 2025-02-08 01:33:49 +00:00
Joshua Goins
6b4b895102 Fixup higher power levels not being displayed correctly
This is is a fix or 4d1c82a623, I was
coercing integer values to PowerLevel (the enum.)
2025-02-05 20:36:04 +00:00
l10n daemon script
0c7e02e7c9 GIT_SILENT Sync po/docbooks with svn 2025-02-05 01:36:34 +00:00
Joshua Goins
4d1c82a623 Add power level to the user details dialog
The only way to check a user's power level is to haul yourself over to
the member list, which is cumbersome but also hard to parse - especially
if a room has lots of members.

This adds the user's power level to the existing details dialog. For
example, this makes it easier to identify someone as a moderator if they
sent a message in the room.
2025-02-04 20:14:58 +00:00
Joshua Goins
8d33fe6221 StateKeys: Fix opening a specific state key member 2025-02-04 20:13:09 +00:00
l10n daemon script
9d27651411 GIT_SILENT Sync po/docbooks with svn 2025-02-04 01:34:04 +00:00
Joshua Goins
268975bc3b Fix crash when trying to view Security settings in an invited room
This state event doesn't exist (or is inaccessible) to us, and tries to
access nullptr.
2025-02-04 01:02:25 +00:00
173 changed files with 17831 additions and 11189 deletions

View File

@@ -25,13 +25,23 @@
"modules": [
{
"name": "kirigamiaddons",
"config-opts": [ "-DBUILD_TESTING=OFF" ],
"config-opts": [
"-DBUILD_TESTING=OFF"
],
"buildsystem": "cmake-ninja",
"sources": [ { "type": "git", "url": "https://invent.kde.org/libraries/kirigami-addons.git", "commit": "34d311219e8b7209746a98b3a29b91ded05ff936" } ]
"sources": [
{
"type": "git",
"url": "https://invent.kde.org/libraries/kirigami-addons.git"
}
]
},
{
"name": "kquickimageeditor",
"config-opts": [ "-DBUILD_WITH_QT6=ON" ],
"config-opts": [
"-DBUILD_WITH_QT6=ON",
"-DBUILD_TESTING=OFF"
],
"buildsystem": "cmake-ninja",
"sources": [
{
@@ -43,17 +53,19 @@
{
"name": "olm",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DOLM_TESTS=OFF" ],
"config-opts": [
"-DOLM_TESTS=OFF"
],
"sources": [
{
"type": "git",
"url": "https://gitlab.matrix.org/matrix-org/olm.git",
"tag": "3.2.10",
"tag": "3.2.16",
"x-checker-data": {
"type": "git",
"tag-pattern": "^([\\d.]+)$"
},
"commit": "9908862979147a71dc6abaecd521be526ae77be1"
"commit": "7e0c8277032e40308987257b711b38af8d77cc69"
}
]
},
@@ -65,13 +77,13 @@
"-Dvapi=false",
"-Dgtk_doc=false",
"-Dintrospection=false",
"-Dgcrypt=false"
"-Dcrypto=disabled"
],
"sources": [
{
"type": "archive",
"url": "https://download.gnome.org/sources/libsecret/0.20/libsecret-0.20.5.tar.xz",
"sha256": "3fb3ce340fcd7db54d87c893e69bfc2b1f6e4d4b279065ffe66dac9f0fd12b4d",
"url": "https://download.gnome.org/sources/libsecret/0.21/libsecret-0.21.6.tar.xz",
"sha256": "747b8c175be108c880d3adfb9c3537ea66e520e4ad2dccf5dce58003aeeca090",
"x-checker-data": {
"type": "gnome",
"name": "libsecret",
@@ -86,13 +98,13 @@
"sources": [
{
"type": "archive",
"url": "https://github.com/frankosterfeld/qtkeychain/archive/0.14.2.tar.gz",
"sha256": "cf2e972b783ba66334a79a30f6b3a1ea794a1dc574d6c3bebae5ffd2f0399571",
"url": "https://github.com/frankosterfeld/qtkeychain/archive/refs/tags/0.15.0.tar.gz",
"sha256": "f4254dc8f0933b06d90672d683eab08ef770acd8336e44dfa030ce041dc2ca22",
"x-checker-data": {
"type": "anitya",
"project-id": 4138,
"stable-only": true,
"url-template": "https://github.com/frankosterfeld/qtkeychain/archive/v$version.tar.gz"
"url-template": "https://github.com/frankosterfeld/qtkeychain/archive/refs/tags/$version.tar.gz"
}
}
],
@@ -100,7 +112,8 @@
"-DBUILD_WITH_QT6=ON",
"-DCMAKE_INSTALL_LIBDIR=/app/lib",
"-DLIB_INSTALL_DIR=/app/lib",
"-DBUILD_TRANSLATIONS=NO"
"-DBUILD_TRANSLATIONS=NO",
"-DBUILD_TESTING=OFF"
]
},
{
@@ -123,29 +136,31 @@
{
"name": "cmark",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DCMARK_TESTS=OFF" ],
"config-opts": [
"-DCMARK_TESTS=OFF",
"-DCMAKE_BUILD_TYPE=Release",
"-DCMAKE_INSTALL_PREFIX=/app"
],
"sources": [
{
"type": "git",
"url": "https://github.com/commonmark/cmark.git"
}
],
"config-opts": [
"-DCMARK_TESTS=OFF",
"-DCMAKE_BUILD_TYPE=Release",
"-DCMAKE_INSTALL_PREFIX=/app"
],
"builddir": true
},
{
"name": "qcoro",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DQCORO_BUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF" ],
"config-opts": [
"-DQCORO_BUILD_EXAMPLES=OFF",
"-DBUILD_TESTING=OFF"
],
"sources": [
{
"type": "archive",
"url": "https://github.com/danvratil/qcoro/archive/refs/tags/v0.7.0.tar.gz",
"sha256": "23ef0217926e67c8d2eb861cf91617da2f7d8d5a9ae6c62321b21448b1669210",
"url": "https://github.com/danvratil/qcoro/archive/refs/tags/v0.11.0.tar.gz",
"sha256": "9942c5b4c533192f6c5954dc6d10178b3829075e6a621b67df73f0a4b74d8297",
"x-checker-data": {
"type": "anitya",
"project-id": 236236,
@@ -158,14 +173,15 @@
{
"name": "neochat",
"buildsystem": "cmake-ninja",
"config-opts": [
"-DBUILD_TESTING=OFF",
"-DNEOCHAT_FLATPAK=ON"
],
"sources": [
{
"type": "dir",
"path": "."
}
],
"config-opts": [
"-DNEOCHAT_FLATPAK=ON"
]
}
]

View File

@@ -10,6 +10,7 @@ include:
- /gitlab-templates/yaml-lint.yml
- /gitlab-templates/android-qt6.yml
- /gitlab-templates/linux-qt6.yml
- /gitlab-templates/linux-qt6-next.yml
- /gitlab-templates/windows-qt6.yml
# - /gitlab-templates/freebsd-qt6.yml
- /gitlab-templates/flatpak.yml

View File

@@ -8,7 +8,7 @@ cmake_minimum_required(VERSION 3.16)
# KDE Applications version, managed by release script.
set(RELEASE_SERVICE_VERSION_MAJOR "25")
set(RELEASE_SERVICE_VERSION_MINOR "03")
set(RELEASE_SERVICE_VERSION_MINOR "07")
set(RELEASE_SERVICE_VERSION_MICRO "70")
set(RELEASE_SERVICE_VERSION "${RELEASE_SERVICE_VERSION_MAJOR}.${RELEASE_SERVICE_VERSION_MINOR}.${RELEASE_SERVICE_VERSION_MICRO}")
@@ -56,7 +56,7 @@ ecm_setup_version(${PROJECT_VERSION}
VERSION_HEADER ${CMAKE_CURRENT_BINARY_DIR}/neochat-version.h
)
find_package(Qt6 ${QT_MIN_VERSION} NO_MODULE COMPONENTS Core Quick Gui QuickControls2 Multimedia Svg WebView)
find_package(Qt6 ${QT_MIN_VERSION} NO_MODULE COMPONENTS Core Quick Gui QuickControls2 Multimedia Svg Protobuf WebView)
set_package_properties(Qt6 PROPERTIES
TYPE REQUIRED
PURPOSE "Basic application components"
@@ -115,6 +115,8 @@ set_package_properties(QuotientQt6 PROPERTIES
PURPOSE "Talk with matrix server"
)
find_package(LiveKit REQUIRED)
find_package(cmark)
set_package_properties(cmark PROPERTIES
TYPE REQUIRED

View File

@@ -51,6 +51,10 @@ is primarily aimed at Linux development.
For Windows and Android [Craft](https://invent.kde.org/packaging/craft) is the primary choice. There are guides for setting up
development environments for [Windows](https://community.kde.org/Get_Involved/development/Windows) and [Android](https://develop.kde.org/docs/packaging/android/building_applications/).
### Building with support for voice / video calls
[LiveKit](https://livekit.io) is needed for call support. Build the [Rust SDK](https://github.com/livekit/rust-sdks) and copy `liblivekit_ffi.so` to your usual library folder. Copy `livekit_ffi.h` to somewhere under your usual include folder. NeoChat should then automatically pick it up.
## Running
Just start the executable in your preferred way - either from the build directory or from the installed location.

View File

@@ -12,6 +12,7 @@
#include "models/messagecontentmodel.h"
#include "neochatconnection.h"
#include "testutils.h"
using namespace Quotient;
@@ -32,7 +33,7 @@ private Q_SLOTS:
void MessageContentModelTest::initTestCase()
{
connection = Connection::makeMockConnection(u"@bob:kde.org"_s);
connection = new NeoChatConnection;
}
void MessageContentModelTest::missingEvent()

View File

@@ -20,11 +20,11 @@ class ReactionModelTest : public QObject
private:
Connection *connection = nullptr;
TestUtils::TestRoom *room = nullptr;
MessageContentModel *parentModel;
private Q_SLOTS:
void initTestCase();
void nullModel();
void basicReaction();
void newReaction();
};
@@ -33,20 +33,13 @@ void ReactionModelTest::initTestCase()
{
connection = Connection::makeMockConnection(u"@bob:kde.org"_s);
room = new TestUtils::TestRoom(connection, u"#myroom:kde.org"_s, u"test-reactionmodel-sync.json"_s);
}
void ReactionModelTest::nullModel()
{
auto model = ReactionModel(nullptr, nullptr);
QCOMPARE(model.rowCount(), 0);
QCOMPARE(model.data(model.index(0), ReactionModel::TextContentRole), QVariant());
parentModel = new MessageContentModel(room, "123456"_L1);
}
void ReactionModelTest::basicReaction()
{
auto event = eventCast<const RoomMessageEvent>(room->messageEvents().at(0).get());
auto model = ReactionModel(event, room);
auto model = ReactionModel(parentModel, event->id(), room);
QCOMPARE(model.rowCount(), 1);
QCOMPARE(model.data(model.index(0), ReactionModel::TextContentRole), u"<span style=\"font-family: 'emoji';\">👍</span>"_s);
@@ -58,7 +51,7 @@ void ReactionModelTest::basicReaction()
void ReactionModelTest::newReaction()
{
auto event = eventCast<const RoomMessageEvent>(room->messageEvents().at(0).get());
auto model = new ReactionModel(event, room);
auto model = new ReactionModel(parentModel, event->id(), room);
QCOMPARE(model->rowCount(), 1);
QCOMPARE(model->data(model->index(0), ReactionModel::ToolTipRole), u"Alice Margatroid reacted with <span style=\"font-family: 'emoji';\">👍</span>"_s);

10
cmake/FindLiveKit.cmake Normal file
View File

@@ -0,0 +1,10 @@
# SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
find_library(LIVEKIT_LIB NAMES livekit_ffi)
find_path(LIVEKIT_INCLUDE_DIR NAMES livekit_ffi.h)
add_library(LiveKit UNKNOWN IMPORTED)
set_target_properties(LiveKit PROPERTIES IMPORTED_LOCATION ${LIVEKIT_LIB})
set_target_properties(LiveKit PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${LIVEKIT_INCLUDE_DIR})
set(LiveKit_FOUND True)

View File

@@ -473,6 +473,7 @@
<content_attribute id="social-chat">intense</content_attribute>
</content_rating>
<releases>
<release version="24.12.3" date="2025-03-06"/>
<release version="24.12.2" date="2025-02-06"/>
<release version="24.12.1" date="2025-01-09"/>
<release version="24.12.0" date="2024-12-12"/>

View File

@@ -112,6 +112,7 @@ Comment[ka]=ჩატი Matrix-ზე
Comment[lv]=Tērzējiet „Matrix“ tīklā
Comment[nl]=Chat op Matrix
Comment[pl]=Rozmawiaj na Matriksie
Comment[pt_BR]=Bate papo na Matrix
Comment[sa]=Matrix इत्यत्र गपशपं कुर्वन्तु
Comment[sl]=Klepet na Matrixu
Comment[sv]=Chatta på Matrix

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
# SPDX-License-Identifier: CC0-1.0
---
name: neochat
base: core22
base: core24
adopt-info: neochat
grade: stable
confinement: strict
@@ -106,8 +106,6 @@ parts:
build-snaps:
- cmake
build-packages:
- gcc-13
- g++-13
- libssl-dev
cmake-parameters:
- -DCMAKE_INSTALL_PREFIX=/usr
@@ -115,11 +113,6 @@ parts:
- -DBUILD_TESTING=OFF
- -DQuotient_ENABLE_E2EE=ON
- -DBUILD_WITH_QT6=ON
override-build: |
"update-alternatives --install /usr/bin/gcc gcc\
/usr/bin/gcc-13 100 --slave /usr/bin/g++ g++ \
/usr/bin/g++-13 --slave /usr/bin/gcov gcov /usr/bin/gcov-13"
craftctl default
prime:
- -usr/include
- -usr/lib/*/pkgconfig
@@ -132,6 +125,8 @@ parts:
plugin: cmake
build-environment:
- PATH: /snap/bin:${PATH}
- PYTHONPATH: ${CRAFT_STAGE}/lib/python3.12/site-packages:${CRAFT_STAGE}/usr/lib/python3/dist-packages
- LD_LIBRARY_PATH: "/snap/mesa-2404/current/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR:$CRAFT_STAGE/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR:/snap/kde-qt6-core24-sdk/current/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/libproxy:$LD_LIBRARY_PATH"
cmake-parameters:
- -DCMAKE_INSTALL_PREFIX=/usr
- -DCMAKE_BUILD_TYPE=Release
@@ -153,6 +148,8 @@ parts:
plugin: cmake
build-environment:
- PATH: /snap/bin:${PATH}
- PYTHONPATH: ${CRAFT_STAGE}/lib/python3.12/site-packages:${CRAFT_STAGE}/usr/lib/python3/dist-packages
- LD_LIBRARY_PATH: "/snap/mesa-2404/current/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR:$CRAFT_STAGE/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR:/snap/kde-qt6-core24-sdk/current/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/libproxy:$LD_LIBRARY_PATH"
build-packages:
- cmark
- libcmark-dev
@@ -175,3 +172,13 @@ parts:
- libcmark0.30.2
prime:
- usr/lib/*/libcmark.so*
gpu-2404:
after: [neochat]
source: https://github.com/canonical/gpu-snap.git
plugin: dump
override-prime: |
craftctl default
${CRAFT_PART_SRC}/bin/gpu-2404-cleanup mesa-2404
prime:
- bin/gpu-2404-wrapper

View File

@@ -107,8 +107,6 @@ add_library(neochat STATIC
models/imagepacksmodel.h
events/imagepackevent.cpp
events/imagepackevent.h
events/joinrulesevent.cpp
events/joinrulesevent.h
models/reactionmodel.cpp
models/reactionmodel.h
delegatesizehelper.cpp
@@ -198,6 +196,15 @@ add_library(neochat STATIC
models/pinnedmessagemodel.h
models/commonroomsmodel.cpp
models/commonroomsmodel.h
events/callencryptionkeysevent.h
events/callmemberevent.h
events/callnotifyevent.h
calls/callcontroller.cpp
calls/callcontroller.h
livekitlogmodel.cpp
livekitlogmodel.h
events/callmemberevent.cpp
events/callmemberevent.h
)
set_source_files_properties(qml/OsmLocationPlugin.qml PROPERTIES
@@ -298,6 +305,12 @@ ecm_add_qml_module(neochat URI org.kde.neochat GENERATE_PLUGIN_SOURCE
qml/HoverLinkIndicator.qml
qml/AvatarNotification.qml
qml/ReasonDialog.qml
qml/LivekitLogViewer.qml
qml/CallPage.qml
qml/IncomingCallDialog.qml
SOURCES
messageattached.cpp
messageattached.h
DEPENDENCIES
QtCore
QtQuick
@@ -406,7 +419,22 @@ else()
target_compile_definitions(neochat PUBLIC -DHAVE_X11=0)
endif()
target_include_directories(neochat PRIVATE ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/models ${CMAKE_CURRENT_SOURCE_DIR}/enums)
qt_add_protobuf(neochat
GENERATE_PACKAGE_SUBFOLDERS
PROTO_FILES
protocols/ffi.proto
protocols/room.proto
protocols/e2ee.proto
protocols/audio_frame.proto
protocols/video_frame.proto
protocols/handle.proto
protocols/participant.proto
protocols/stats.proto
protocols/track.proto
protocols/rpc.proto
)
target_include_directories(neochat PRIVATE ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/models ${CMAKE_CURRENT_SOURCE_DIR}/enums ${CMAKE_CURRENT_SOURCE_DIR}/calls)
target_link_libraries(neochat PRIVATE settingsplugin timelineplugin devtoolsplugin loginplugin chatbarplugin)
target_link_libraries(neochat PUBLIC
Qt::Core
@@ -416,6 +444,7 @@ target_link_libraries(neochat PUBLIC
Qt::Multimedia
Qt::Network
Qt::QuickControls2
Qt::Protobuf
KF6::I18n
KF6::Kirigami
KF6::Notifications
@@ -430,6 +459,7 @@ target_link_libraries(neochat PUBLIC
cmark::cmark
QCoro::Core
QCoro::Network
LiveKit
)
if (TARGET KF6::Crash)

0
src/calls/call.cpp Normal file
View File

74
src/calls/call.h Normal file
View File

@@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include <QAbstractListModel>
#include <QObject>
#include <QQmlEngine>
#include "neochatroom.h"
class Participant : public QObject
{
Q_OBJECT
void setVolume(float volume);
void muteLocally();
void unmuteLocally();
void ring(); // See MSC4075
// TODO: if these are possible; check livekit api
void muteGlobally();
void forceDisableCamera();
void forceDisableScreenShare();
void setPermissions();
void kick();
void ban();
Q_SIGNALS:
void muted();
void unmuted();
void cameraEnabled();
void cameraDisabled();
void screenShareEnabled();
void screenShareDisabled();
};
class Call : public QObject
{
Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("")
Q_PROPERTY(bool cameraEnabled READ cameraEnabled WRITE setCameraEnabled NOTIFY cameraEnabledChanged)
Q_PROPERTY(bool microphoneMuted READ microphoneMuted WRITE setMicrophoneMuted NOTIFY microphoneMutedChanged)
Q_PROPERTY(bool screenshareEnabled READ screenshareEnabled NOTIFY screenshareEnabledChanged)
Q_PROPERTY(NeoChatRoom *room READ room CONSTANT)
public:
explicit Call(NeoChatRoom *room, QObject *parent = nullptr);
Q_SIGNALS:
void participantJoined(const Participant &participant);
void participantLeft(const Participant &participant);
private:
QList<Participant *> m_participants;
};
class CallParticipantsModel : public QAbstractListModel
{
Q_OBJECT
public:
enum Roles {
NameRoleRole,
HasCameraRole,
HasScreenShareRole,
IsMutedRole,
};
Q_ENUM(Roles)
};

View File

@@ -0,0 +1,447 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "callcontroller.h"
#include <QAudioSink>
#include <QMediaDevices>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QProtobufSerializer>
#include <QVideoFrame>
#include <QVideoFrameFormat>
#include <QVideoSink>
#include <livekit_ffi.h>
#include <Quotient/csapi/openid.h>
#include "audio_frame.qpb.h"
#include "ffi.qpb.h"
#include "livekitlogmodel.h"
#include "neochatroom.h"
#include "track.qpb.h"
#include "video_frame.qpb.h"
using namespace livekit::proto;
using namespace Quotient;
extern "C" {
void livekit_ffi_initialize(void(ffiCallbackFn(const uint8_t *, size_t)), bool capture_logs, const char *, const char *);
}
void callback(const uint8_t *data, size_t length)
{
auto byteArrayData = QByteArray::fromRawData((const char *)data, length);
QProtobufSerializer serializer;
FfiEvent event;
event.deserialize(&serializer, byteArrayData);
CallController::instance().handleEvent(std::move(event));
}
CallController::CallController()
: QObject()
{
init();
}
void CallController::init()
{
// qRegisterProtobufTypes();
livekit_ffi_initialize(callback, true, "test", "1.0");
}
static void handleLog(const LogRecordRepeated &&logs)
{
for (const auto &log : logs) {
if (log.level() <= LogLevelGadget::LogLevel::LOG_WARN) {
qWarning() << log.message();
}
}
LivekitLogModel::instance().addMessages(logs);
}
void CallController::handleConnect(ConnectCallback &&callback)
{
qWarning() << "Connecting to" << callback.result().room().info().name() << "with id" << callback.asyncId();
if (!m_connectingRooms.contains(callback.asyncId()) || !m_connectingRooms[callback.asyncId()]
|| m_connectingRooms[callback.asyncId()]->id() != callback.result().room().info().name()) {
qWarning() << "Connecting to unexpected room";
return;
}
m_connectingRooms.remove(callback.asyncId());
m_rooms[callback.asyncId()] = callback.result().room();
localParticipant = callback.result().localParticipant().handle().id_proto();
Q_EMIT connected();
}
void CallController::handleDispose(DisposeCallback &&callback)
{
qWarning() << "Disposing" << callback.asyncId();
if (m_rooms.contains(callback.asyncId())) {
qWarning() << " room" << m_rooms[callback.asyncId()].info().name();
m_rooms.erase(callback.asyncId());
} else {
qWarning() << " unknown object";
}
}
void CallController::handleRoomEvent(livekit::proto::RoomEvent &&event)
{
if (event.hasParticipantConnected()) {
qWarning() << "Participant connected" << event.participantConnected().info().info().identity();
} else if (event.hasParticipantDisconnected()) {
qWarning() << "Participant connected" << event.participantDisconnected().participantIdentity();
} else if (event.hasLocalTrackPublished()) {
qWarning() << "Local track published";
m_localVideoTrackSid = event.localTrackPublished().trackSid();
} else if (event.hasLocalTrackUnpublished()) {
qWarning() << "Local track unpublished";
} else if (event.hasTrackPublished()) {
qWarning() << "Track published";
} else if (event.hasTrackUnpublished()) {
qWarning() << "Track unpublished";
} else if (event.hasTrackSubscribed()) {
qWarning() << "Track subscribed";
auto track = event.trackSubscribed().track();
if (track.info().kind() == TrackKindGadget::TrackKind::KIND_AUDIO) {
NewAudioStreamRequest audioStreamRequest;
audioStreamRequest.setTrackHandle(track.handle().id_proto());
FfiRequest request;
request.setNewAudioStream(audioStreamRequest);
QProtobufSerializer serializer;
auto data = request.serialize(&serializer);
const uint8_t *ret_data;
size_t size;
livekit_ffi_request((const uint8_t *)data.data(), data.length(), &ret_data, &size);
FfiResponse newResponse;
newResponse.deserialize(&serializer, QByteArray::fromRawData((const char *)ret_data, size));
} else if (track.info().kind() == TrackKindGadget::TrackKind::KIND_VIDEO) {
NewVideoStreamRequest videoStreamRequest;
videoStreamRequest.setTrackHandle((track.handle().id_proto()));
FfiRequest request;
request.setNewVideoStream(videoStreamRequest);
QProtobufSerializer serializer;
auto data = request.serialize(&serializer);
const uint8_t *ret_data;
size_t size;
livekit_ffi_request((const uint8_t *)data.data(), data.length(), &ret_data, &size);
FfiResponse newResponse;
newResponse.deserialize(&serializer, QByteArray::fromRawData((const char *)ret_data, size));
}
} else if (event.hasTrackUnsubscribed()) {
qWarning() << "Track unsubscribed";
} else if (event.hasTrackSubscriptionFailed()) {
qWarning() << "Track subscription failed";
} else if (event.hasTrackMuted()) {
qWarning() << "Track muted";
} else if (event.hasTrackUnmuted()) {
qWarning() << "Track unmuted";
} else if (event.hasActiveSpeakersChanged()) {
qWarning() << "Active speakers changed";
} else if (event.hasRoomMetadataChanged()) {
qWarning() << "room metadata changed";
} else if (event.hasParticipantMetadataChanged()) {
qWarning() << "participant metadata changed";
} else if (event.hasParticipantNameChanged()) {
qWarning() << "participant name changed";
} else if (event.hasConnectionQualityChanged()) {
qWarning() << "connection quality changed to" << event.connectionQualityChanged().quality();
} else if (event.hasDataPacketReceived()) {
qWarning() << "data received";
} else if (event.hasConnectionStateChanged()) {
qWarning() << "connection state changed";
} else if (event.hasDisconnected()) {
qWarning() << "disconnected";
} else if (event.hasReconnecting()) {
qWarning() << "reconnecting";
} else if (event.hasReconnected()) {
qWarning() << "Reconnected";
} else if (event.hasE2eeStateChanged()) {
qWarning() << "e2eeStateChanged";
} else if (event.hasEos()) {
qWarning() << "eos";
} else {
qWarning() << "Unknown room event";
}
}
void saveByteArray(const QByteArray &data, const QString &name)
{
QFile file(u"/home/tobias/"_s + name);
file.open(QFile::WriteOnly);
file.write(data);
file.close();
}
void CallController::handleEvent(FfiEvent &&event)
{
if (event.hasLogs()) {
handleLog(std::move(event.logs().records()));
} else if (event.hasRoomEvent()) {
handleRoomEvent(std::move(event.roomEvent()));
} else if (event.hasTrackEvent()) {
qWarning() << "track event";
} else if (event.hasVideoStreamEvent()) {
qWarning() << "video stream event";
auto video = event.videoStreamEvent();
auto info = video.frameReceived().buffer().info();
QByteArray data((const char *)info.dataPtr(), info.width() * info.height() * 1.5);
auto frame = QVideoFrame(QVideoFrameFormat(QSize(info.width(), info.height()), QVideoFrameFormat::Format_YUV420P));
frame.map(QVideoFrame::WriteOnly);
memcpy(frame.bits(0), data.constData(), data.size() / 3 * 2);
memcpy(frame.bits(1), data.constData() + data.size() / 3 * 2, data.size() / 6);
memcpy(frame.bits(2), data.constData() + data.size() / 3 * 2 + data.size() / 6, data.size() / 6);
qWarning() << frame.size() << data.toBase64();
frame.unmap();
m_sink->setVideoFrame(frame);
delete (char *)info.dataPtr();
} else if (event.hasAudioStreamEvent()) {
return; //TODO remove
static bool initialized = false;
if (!initialized) {
initialized = true;
QAudioFormat format;
format.setSampleRate(48000);
format.setChannelCount(2);
format.setSampleFormat(QAudioFormat::Int16);
QAudioDevice info(QMediaDevices::defaultAudioOutput());
if (!info.isFormatSupported(format)) {
qWarning() << "Audio format not supported";
Q_ASSERT(false);
return;
}
sink = new QAudioSink(format);
audioData = sink->start();
QProtobufSerializer serializer;
NewAudioResamplerRequest narr;
FfiRequest request;
request.setNewAudioResampler(narr);
auto data = request.serialize(&serializer);
const uint8_t *ret_data;
size_t size;
livekit_ffi_request((const uint8_t *)data.data(), data.length(), &ret_data, &size);
FfiResponse newResponse;
newResponse.deserialize(&serializer, QByteArray::fromRawData((const char *)ret_data, size));
resampler = newResponse.newAudioResampler().resampler().handle().id_proto();
}
if (event.audioStreamEvent().hasFrameReceived()) {
FfiRequest request;
RemixAndResampleRequest rarr;
rarr.setBuffer(event.audioStreamEvent().frameReceived().frame().info());
rarr.setNumChannels(2);
rarr.setSampleRate(48000);
rarr.setResamplerHandle(resampler);
request = FfiRequest();
request.setRemixAndResample(rarr);
static QProtobufSerializer serializer;
auto data = request.serialize(&serializer);
const uint8_t *ret_data;
size_t size;
livekit_ffi_request((const uint8_t *)data.data(), data.length(), &ret_data, &size);
FfiResponse response;
response.deserialize(&serializer, QByteArray::fromRawData((const char *)ret_data, size));
Q_ASSERT(response.hasRemixAndResample());
auto info = response.remixAndResample().buffer().info();
auto bytes = info.numChannels() * info.samplesPerChannel() * 2;
data = QByteArray::fromRawData((const char *)info.dataPtr(), bytes);
audioData->write(data);
}
} else if (event.hasConnect()) {
handleConnect(std::move(event.connect()));
} else if (event.hasDisconnect()) {
qWarning() << "disconnect";
} else if (event.hasDispose()) {
handleDispose(std::move(event.dispose()));
} else if (event.hasPublishTrack()) {
qWarning() << "publish track";
} else if (event.hasUnpublishTrack()) {
qWarning() << "unpublish track";
} else if (event.hasPublishData()) {
qWarning() << "publish data";
} else if (event.hasCaptureAudioFrame()) {
qWarning() << "audio frame";
} else if (event.hasGetStats()) {
qWarning() << "get stats";
} else if (event.hasGetSessionStats()) {
qWarning() << "get session stats";
} else if (event.hasPanic()) {
qWarning() << "panic";
} else {
qWarning() << event.messageField();
}
}
void CallController::handleCallMemberEvent(const Quotient::CallMemberEvent *event, NeoChatRoom *room)
{
qWarning() << event->fullJson();
Q_EMIT callStarted();
const auto connection = room->connection();
auto job = connection->callApi<RequestOpenIdTokenJob>(connection->userId());
connect(job, &BaseJob::finished, this, [this, room, job, connection, event]() {
auto nam = new QNetworkAccessManager;
auto json = QJsonDocument(QJsonObject{
{"room"_L1, room->id()},
{"openid_token"_L1,
QJsonObject{{"access_token"_L1, job->tokenData().accessToken},
{"token_type"_L1, job->tokenData().tokenType},
{"matrix_server_name"_L1, job->tokenData().matrixServerName}}},
{"device_id"_L1, connection->deviceId()},
})
.toJson();
// This is an old event!
if (!event->contentJson().contains("foci_preferred"_L1)) {
return;
}
QNetworkRequest request(QUrl((event->contentJson()["foci_preferred"_L1].toArray()[0]["livekit_service_url"_L1].toString() + "/sfu/get"_L1)));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"_L1);
auto reply = nam->post(request, json);
connect(reply, &QNetworkReply::finished, this, [reply, this, room]() {
auto json = QJsonDocument::fromJson(reply->readAll()).object();
FfiRequest message;
ConnectRequest connectRequest;
connectRequest.setUrl(json["url"_L1].toString());
connectRequest.setToken(json["jwt"_L1].toString());
message.setConnect(connectRequest);
QProtobufSerializer serializer;
auto data = message.serialize(&serializer);
size_t size;
const uint8_t *ret_data;
livekit_ffi_request((const uint8_t *)data.data(), data.length(), &ret_data, &size);
FfiResponse connectResponse;
connectResponse.deserialize(&serializer, QByteArray::fromRawData((const char *)ret_data, size));
if (!connectResponse.hasConnect()) {
qWarning() << "connectResponse has unexpected content" << connectResponse.messageField();
return;
}
m_connectingRooms[connectResponse.connect().asyncId()] = room;
});
});
}
FfiResponse request(FfiRequest &&request)
{
static QProtobufSerializer serializer;
auto data = request.serialize(&serializer);
size_t responseLength;
const char *responseData;
livekit_ffi_request((const uint8_t *)data.constData(), data.size(), (const uint8_t **)&responseData, &responseLength);
auto response = QByteArray::fromRawData(responseData, responseLength);
FfiResponse ffiResponse;
ffiResponse.deserialize(&serializer, response);
return ffiResponse;
}
void CallController::setCameraVideoSink(QVideoSink *videoSink)
{
m_cameraVideoSink = videoSink;
connect(videoSink, &QVideoSink::videoFrameChanged, this, [videoSink, this]() {
static bool initialized = false;
if (localParticipant == 100000) {
return; // TODO make less shitty
}
static QtProtobuf::uint64 handle;
if (!initialized) {
initialized = true;
NewVideoSourceRequest newVideoSourceRequest;
VideoSourceResolution resolution;
resolution.setHeight(videoSink->videoSize().height());
resolution.setWidth(videoSink->videoSize().width());
newVideoSourceRequest.setResolution(resolution);
newVideoSourceRequest.setType(VideoSourceTypeGadget::VideoSourceType::VIDEO_SOURCE_NATIVE);
FfiRequest ffiRequest;
ffiRequest.setNewVideoSource(newVideoSourceRequest);
auto response = request(std::move(ffiRequest));
handle = response.newVideoSource().source().handle().id_proto();
m_localVideoTrackHandle = handle;
CreateVideoTrackRequest createVideoTrackRequest;
createVideoTrackRequest.setName("Camera"_L1);
createVideoTrackRequest.setSourceHandle(handle);
FfiRequest request;
request.setCreateVideoTrack(createVideoTrackRequest);
auto createResponse = ::request(std::move(request));
m_localVideoTrackId = createResponse.createVideoTrack().track().handle().id_proto();
publishTrack(m_localVideoTrackId);
}
auto image = videoSink->videoFrame().toImage();
image.convertTo(QImage::Format_RGB888);
CaptureVideoFrameRequest request;
VideoBufferInfo buffer;
buffer.setType(VideoBufferTypeGadget::VideoBufferType::RGB24);
buffer.setWidth(image.width());
buffer.setHeight(image.height());
buffer.setDataPtr((QtProtobuf::uint64)image.bits());
buffer.setStride(image.bytesPerLine());
QList<VideoBufferInfo_QtProtobufNested::ComponentInfo> components;
VideoBufferInfo_QtProtobufNested::ComponentInfo componentInfo;
componentInfo.setStride(image.bytesPerLine());
componentInfo.setDataPtr((QtProtobuf::uint64)image.bits());
componentInfo.setSize(image.sizeInBytes());
components += componentInfo;
buffer.setComponents(components);
request.setBuffer(buffer);
request.setSourceHandle(handle);
request.setTimestampUs(QDateTime::currentMSecsSinceEpoch() * 1000);
request.setRotation(VideoRotationGadget::VideoRotation::VIDEO_ROTATION_0);
FfiRequest ffiRequest;
ffiRequest.setCaptureVideoFrame(request);
auto response = ::request(std::move(ffiRequest));
});
}
void CallController::setVideoSink(QObject *sink)
{
m_sink = dynamic_cast<QVideoSink *>(sink);
}
void LivekitVideoSink::setVideoSink(QVideoSink *videoSink)
{
m_videoSink = videoSink;
CallController::instance().setVideoSink(videoSink);
Q_EMIT videoSinkChanged();
}
QVideoSink *LivekitVideoSink::videoSink() const
{
return m_videoSink;
}
void CallController::toggleCamera()
{
if (m_localVideoTrackSid.isEmpty()) {
publishTrack(m_localVideoTrackId);
} else {
FfiRequest request;
UnpublishTrackRequest unpublishRequest;
unpublishRequest.setLocalParticipantHandle(localParticipant);
unpublishRequest.setTrackSid(m_localVideoTrackSid);
request.setUnpublishTrack(unpublishRequest);
auto response = ::request(std::move(request));
m_localVideoTrackSid = QString();
}
}
void CallController::publishTrack(uint64_t id)
{
PublishTrackRequest publishTrackRequest;
publishTrackRequest.setTrackHandle(id);
publishTrackRequest.setLocalParticipantHandle(localParticipant);
TrackPublishOptions options;
options.setSource(TrackSourceGadget::TrackSource::SOURCE_CAMERA);
options.setVideoCodec(VideoCodecGadget::VideoCodec::VP8);
publishTrackRequest.setOptions(options);
auto request = FfiRequest();
request.setPublishTrack(publishTrackRequest);
auto publishResponse = ::request(std::move(request));
}

View File

@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QObject>
#include <QQmlEngine>
#include <QVideoSink>
#include "events/callmemberevent.h"
#include "room.qpb.h"
namespace livekit::proto
{
class FfiEvent;
class ConnectCallback;
class DisposeCallback;
class RoomEvent;
}
class LivekitMediaPlayer;
class NeoChatRoom;
class QAudioSink;
class CallController : public QObject
{
Q_OBJECT
QML_ELEMENT
QML_SINGLETON
public:
static CallController &instance()
{
static CallController _instance;
return _instance;
}
static CallController *create(QQmlEngine *, QJSEngine *)
{
QQmlEngine::setObjectOwnership(&instance(), QQmlEngine::CppOwnership);
return &instance();
}
void handleCallMemberEvent(const Quotient::CallMemberEvent *event, NeoChatRoom *room);
// Internal. Do not use.
void handleEvent(livekit::proto::FfiEvent &&event);
Q_INVOKABLE void setVideoSink(QObject *sink);
Q_INVOKABLE void setCameraVideoSink(QVideoSink *videoSink);
Q_INVOKABLE void toggleCamera();
Q_SIGNALS:
void callStarted();
void connected();
private:
CallController();
void init();
QMap<uint64_t, QPointer<NeoChatRoom>> m_connectingRooms;
std::map<uint64_t, livekit::proto::OwnedRoom> m_rooms;
void handleConnect(livekit::proto::ConnectCallback &&callback);
void handleDispose(livekit::proto::DisposeCallback &&callback);
void handleRoomEvent(livekit::proto::RoomEvent &&event);
void publishTrack(uint64_t id);
QIODevice *audioData = nullptr;
QAudioSink *sink;
QVideoSink *m_sink;
uint64_t resampler;
QVideoSink *m_cameraVideoSink = nullptr;
uint64_t localParticipant = 100000;
QString m_localVideoTrackSid;
uint64_t m_localVideoTrackId;
uint64_t m_localVideoTrackHandle;
};
class LivekitVideoSink : public QObject
{
Q_OBJECT
QML_ELEMENT
public:
Q_PROPERTY(QVideoSink *videoSink READ videoSink WRITE setVideoSink NOTIFY videoSinkChanged REQUIRED)
using QObject::QObject;
void setVideoSink(QVideoSink *videoSink);
QVideoSink *videoSink() const;
Q_SIGNALS:
void videoSinkChanged();
private:
QVideoSink *m_videoSink = nullptr;
};

View File

View File

View File

0
src/calls/participant.h Normal file
View File

View File

@@ -349,7 +349,7 @@ QQC2.Control {
replyEventId: _private.chatBarCache.replyId
replyAuthor: _private.chatBarCache.relationAuthor
replyContentModel: _private.chatBarCache.relationEventContentModel
maxContentWidth: paneLoader.item.width
Message.maxContentWidth: paneLoader.item.width
}
QQC2.Button {
id: cancelButton

View File

@@ -222,11 +222,14 @@ void ChatDocumentHandler::complete(int index)
return;
}
// Ensure we only search for the beginning of the current completion identifier
const auto fromIndex = qMax(completionStartIndex(), 0);
if (m_completionModel->autoCompletionType() == CompletionModel::User) {
auto name = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::DisplayNameRole).toString();
auto id = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::SubtitleRole).toString();
auto text = getText();
auto at = text.lastIndexOf(QLatin1Char('@'), cursorPosition() - 1);
auto at = text.indexOf(QLatin1Char('@'), fromIndex);
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
@@ -239,7 +242,7 @@ void ChatDocumentHandler::complete(int index)
} else if (m_completionModel->autoCompletionType() == CompletionModel::Command) {
auto command = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::ReplacedTextRole).toString();
auto text = getText();
auto at = text.lastIndexOf(QLatin1Char('/'));
auto at = text.indexOf(QLatin1Char('/'), fromIndex);
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
@@ -247,7 +250,7 @@ void ChatDocumentHandler::complete(int index)
} else if (m_completionModel->autoCompletionType() == CompletionModel::Room) {
auto alias = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::SubtitleRole).toString();
auto text = getText();
auto at = text.lastIndexOf(QLatin1Char('#'), cursorPosition() - 1);
auto at = text.indexOf(QLatin1Char('#'), fromIndex);
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
@@ -260,7 +263,7 @@ void ChatDocumentHandler::complete(int index)
} else if (m_completionModel->autoCompletionType() == CompletionModel::Emoji) {
auto shortcode = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::ReplacedTextRole).toString();
auto text = getText();
auto at = text.lastIndexOf(QLatin1Char(':'));
auto at = text.indexOf(QLatin1Char(':'), fromIndex);
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);

View File

@@ -45,6 +45,8 @@ bool testMode = false;
using namespace Quotient;
Controller::Controller(QObject *parent)
: QObject(parent)
{
@@ -132,6 +134,7 @@ Controller::Controller(QObject *parent)
m_endpoint = connector->endpoint();
#endif
}
Controller &Controller::instance()
@@ -294,7 +297,7 @@ bool Controller::supportSystemTray() const
void Controller::setQuitOnLastWindowClosed()
{
#ifndef Q_OS_ANDROID
if (NeoChatConfig::self()->systemTray()) {
if (supportSystemTray() && NeoChatConfig::self()->systemTray()) {
m_trayIcon = new TrayIcon(this);
m_trayIcon->show();
} else {

View File

@@ -3,6 +3,7 @@
import QtQuick
import QtQuick.Layouts
import QtQuick.Window
import org.kde.kirigami as Kirigami
import org.kde.kirigamiaddons.formcard as FormCard
@@ -37,7 +38,7 @@ FormCard.FormCardPage {
}
function openEventSource(stateKey: string): void {
pageStack.pushDialogLayer(Qt.createComponent('org.kde.neochat', 'MessageSourceSheet'), {
root.Window.window.pageStack.pushDialogLayer(Qt.createComponent('org.kde.neochat', 'MessageSourceSheet'), {
model: stateKeysModel,
allowEdit: true,
room: root.room,

View File

@@ -7,5 +7,5 @@
using namespace Qt::StringLiterals;
QMultiHash<QString, QVariant> EmojiTones::_tones = {
#include "emojitones_data.h"
//#include "emojitones_data.h"
};

View File

@@ -50,6 +50,7 @@ public:
LiveLocation, /**< The initial event of a shared live location (i.e., the place where this is supposed to be shown in the timeline). */
Encrypted, /**< An encrypted message that cannot be decrypted. */
Reply, /**< A component to show a replied-to message. */
Reaction, /**< A component to show the reactions to this message. */
LinkPreview, /**< A preview of a URL in the message. */
LinkPreviewLoad, /**< A loading dialog for a link preview. */
ChatBar, /**< A text edit for editing a message. */

View File

@@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.1-or-later
#pragma once
#include <Quotient/events/roomevent.h>
namespace Quotient
{
class CallEncryptionKeysEvent : public RoomEvent
{
public:
QUO_EVENT(CallEncryptionKeysEvent, "io.element.call.encryption_keys");
explicit CallEncryptionKeysEvent(const QJsonObject &obj)
: RoomEvent(obj)
{
}
};
}

View File

@@ -0,0 +1,38 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "callmemberevent.h"
#include <QString>
using namespace Quotient;
using namespace Qt::Literals::StringLiterals;
CallMemberEventContent::CallMemberEventContent(const QJsonObject &json)
{
for (const auto &membership : json["memberships"_L1].toArray()) {
QList<Focus> foci;
for (const auto &focus : membership["foci_active"_L1].toArray()) {
foci.append(Focus{
.livekitAlias = focus["livekit_alias"_L1].toString(),
.livekitServiceUrl = focus["livekit_service_url"_L1].toString(),
.type = focus["livekit"_L1].toString(),
});
}
memberships.append(CallMembership{
.application = membership["application"_L1].toString(),
.callId = membership["call_id"_L1].toString(),
.deviceId = membership["device_id"_L1].toString(),
.expires = membership["expires"_L1].toInt(),
.expiresTs = membership["expires"_L1].toVariant().value<uint64_t>(),
.fociActive = foci,
.membershipId = membership["membershipID"_L1].toString(),
.scope = membership["scope"_L1].toString(),
});
}
}
QJsonObject CallMemberEventContent::toJson() const
{
return {};
}

View File

@@ -0,0 +1,59 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.1-or-later
#pragma once
#include <Quotient/events/stateevent.h>
namespace Quotient
{
struct Focus {
QString livekitAlias;
QString livekitServiceUrl;
QString type;
};
struct CallMembership {
QString application;
QString callId;
QString deviceId;
int expires;
uint64_t expiresTs;
QList<Focus> fociActive;
QString membershipId;
QString scope;
};
class CallMemberEventContent
{
public:
explicit CallMemberEventContent(const QJsonObject &json);
QJsonObject toJson() const;
QList<CallMembership> memberships;
};
/**
* @class CallMemberEvent
*
* Class to define a call member event.
*
* @sa Quotient::StateEvent
*/
class CallMemberEvent : public KeyedStateEventBase<CallMemberEvent, CallMemberEventContent>
{
public:
QUO_EVENT(CallMemberEvent, "org.matrix.msc3401.call.member")
explicit CallMemberEvent(const QJsonObject &obj)
: KeyedStateEventBase(obj)
{
}
QJsonArray memberships() const
{
return contentJson()[u"memberships"_s].toArray();
}
};
}

View File

@@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.1-or-later
#pragma once
#include <Quotient/events/roomevent.h>
namespace Quotient
{
class CallNotifyEvent : public RoomEvent
{
public:
QUO_EVENT(CallNotifyEvent, "org.matrix.msc4075.call.notify");
explicit CallNotifyEvent(const QJsonObject &obj);
};

View File

@@ -1,16 +0,0 @@
// SPDX-FileCopyrightText: 2019 Kitsune Ral <Kitsune-Ral@users.sf.net>
// SPDX-License-Identifier: LGPL-2.1-or-later
#include "joinrulesevent.h"
using namespace Quotient;
QString JoinRulesEvent::joinRule() const
{
return fromJson<QString>(contentJson()["join_rule"_L1]);
}
QJsonArray JoinRulesEvent::allow() const
{
return contentJson()["allow"_L1].toArray();
}

View File

@@ -1,43 +0,0 @@
// SPDX-FileCopyrightText: 2021 Carl Schwan <carl@carlschwan.eu>
// SPDX-License-Identifier: LGPL-2.1-or-later
#pragma once
#include <Quotient/events/stateevent.h>
namespace Quotient
{
/**
* @class JoinRulesEvent
*
* Class to define a join rule state event.
*
* @sa Quotient::StateEvent
*/
class JoinRulesEvent : public StateEvent
{
public:
QUO_EVENT(JoinRulesEvent, "m.room.join_rules")
explicit JoinRulesEvent(const QJsonObject &obj)
: StateEvent(obj)
{
}
/**
* @brief The join rule for the room.
*
* see https://spec.matrix.org/latest/client-server-api/#mroomjoin_rules for
* the available join rules for a room.
*/
QString joinRule() const;
/**
* @brief The allow rule for restricted rooms.
*
* see https://spec.matrix.org/latest/client-server-api/#mroomjoin_rules for
* full details on allow rules.
*/
QJsonArray allow() const;
};
}

View File

@@ -9,7 +9,6 @@
#include <Quotient/events/roommessageevent.h>
#include "neochatconfig.h"
#include "utils.h"
using namespace Quotient;
@@ -22,7 +21,6 @@ LinkPreviewer::LinkPreviewer(const QUrl &url, QObject *parent)
Q_ASSERT(dynamic_cast<Connection *>(this->parent()));
connect(this, &LinkPreviewer::urlChanged, this, &LinkPreviewer::emptyChanged);
connect(NeoChatConfig::self(), &NeoChatConfig::ShowLinkPreviewChanged, this, &LinkPreviewer::loadUrlPreview);
loadUrlPreview();
}

39
src/livekitlogmodel.cpp Normal file
View File

@@ -0,0 +1,39 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "livekitlogmodel.h"
using namespace livekit::proto;
QVariant LivekitLogModel::data(const QModelIndex &index, int role) const
{
const auto &message = m_messages[index.row()];
if (role == MessageRole) {
return message.message();
}
return {};
}
int LivekitLogModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_messages.size();
}
QHash<int, QByteArray> LivekitLogModel::roleNames() const
{
return {
{MessageRole, "message"},
};
}
void LivekitLogModel::addMessages(livekit::proto::LogRecordRepeated messages)
{
for (const auto &message : messages) {
// if (message.level() < 3) {
beginInsertRows({}, m_messages.size(), m_messages.size() + 1);
m_messages += message;
endInsertRows();
// }
}
}

61
src/livekitlogmodel.h Normal file
View File

@@ -0,0 +1,61 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QAbstractListModel>
#include <QQmlEngine>
#include <QList>
#include "ffi.qpb.h"
class LivekitLogModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
QML_SINGLETON
public:
static LivekitLogModel &instance() {
static LivekitLogModel _instance;
return _instance;
}
static LivekitLogModel *create(QQmlEngine *, QJSEngine *) {
QQmlEngine::setObjectOwnership(&instance(), QQmlEngine::CppOwnership);
return &instance();
}
/**
* @brief Defines the model roles.
*/
enum Roles {
MessageRole = Qt::DisplayRole,
};
/**
* @brief Get the given role value at the given index.
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role) const override;
/**
* @brief Number of rows in the model.
*
* @sa QAbstractItemModel::rowCount
*/
[[nodiscard]] int rowCount(const QModelIndex &parent = QModelIndex()) const override;
/**
* @brief Returns a mapping from Role enum values to role names.
*
* @sa Roles, QAbstractItemModel::roleNames()
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
void addMessages(livekit::proto::LogRecordRepeated messages);
private:
livekit::proto::LogRecordRepeated m_messages;
LivekitLogModel() = default;
};

View File

@@ -17,6 +17,7 @@ Kirigami.Page {
property bool showExisting: false
property bool _showExisting: showExisting && root.currentStepString === root.initialStep
property bool showSettings: true
property alias currentStep: module.item
property string currentStepString: initialStep
property string initialStep: "LoginRegister"
@@ -265,6 +266,7 @@ Kirigami.Page {
FormCard.FormCard {
Layout.topMargin: Kirigami.Units.largeSpacing * 2
maximumWidth: Kirigami.Units.gridUnit * 20
visible: root.showSettings
FormCard.FormButtonDelegate {
text: i18nc("@action:button", "Settings")
icon.name: "settings-configure"

View File

@@ -239,6 +239,7 @@ int main(int argc, char *argv[])
Q_IMPORT_QML_PLUGIN(org_kde_neochat_chatbarPlugin)
qml_register_types_org_kde_neochat();
qmlRegisterUncreatableMetaObject(Quotient::staticMetaObject, "Quotient", 1, 0, "JoinRule", u"Access to JoinRule enum only"_s);
QQmlApplicationEngine engine;

View File

@@ -1,11 +1,141 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "mediamanager.h"
#include <QDirIterator>
#include <QMimeDatabase>
#include <Quotient/qt_connection_util.h>
#include "events/callmemberevent.h"
#include "neochatroom.h"
using namespace Qt::Literals::StringLiterals;
using namespace Quotient;
void MediaManager::startPlayback()
{
Q_EMIT playbackStarted();
}
#include "moc_mediamanager.cpp"
void MediaManager::ring(const QJsonObject &json, NeoChatRoom *room)
{
qWarning() << "start check ring";
// todo: check sender != us
if (json["content"_L1]["application"_L1].toString() != "m.call"_L1) {
qWarning() << "not m.call";
return;
}
qWarning() << json;
if (!json["content"_L1]["m.mentions"_L1]["room"_L1].toBool() || json[u"sender"_s].toString() == room->connection()->userId()) {
bool mentioned = false;
for (const auto &user : json["content"_L1]["m.mentions"_L1]["user_ids"_L1].toArray()) {
if (user.toString() == room->connection()->userId()) {
mentioned = true;
break;
}
}
if (!mentioned) {
qWarning() << "not mentioned";
return;
}
}
if (json["content"_L1]["notify_type"_L1].toString() != "ring"_L1) {
qWarning() << "not ring";
return;
}
if (room->pushNotificationState() == PushNotificationState::Mute) {
qWarning() << "mute";
return;
}
if (isRinging()) {
qWarning() << "already ringing";
return;
}
if (const auto &event = room->currentState().get<CallMemberEvent>(room->connection()->userId())) {
if (event) {
auto memberships = event->contentJson()["memberships"_L1].toArray();
for (const auto &m : memberships) {
const auto &membership = m.toObject();
if (membership["application"_L1] == "m.call"_L1 && membership["call_id"_L1].toString().isEmpty()) {
qWarning() << "already in a call";
return;
}
}
}
}
connectUntil(room, &NeoChatRoom::changed, this, [this, room]() {
if (const auto &event = room->currentState().get<CallMemberEvent>(room->connection()->userId())) {
if (event) {
auto memberships = event->contentJson()["memberships"_L1].toArray();
for (const auto &m : memberships) {
const auto &membership = m.toObject();
if (membership["application"_L1] == "m.call"_L1 && membership["call_id"_L1].toString().isEmpty()) {
qWarning() << "stopping";
stopRinging();
return true;
}
}
}
}
return false;
});
if (json["unsigned"_L1]["age"_L1].toInt() > 10000) {
qWarning() << "too old";
return;
}
ringUnchecked();
}
void MediaManager::ringUnchecked()
{
qWarning() << "ring";
static QString path;
if (path.isEmpty()) {
for (const auto &dir : QString::fromUtf8(qgetenv("XDG_DATA_DIRS")).split(u':')) {
if (QFileInfo(dir + QStringLiteral("/sounds/freedesktop/stereo/phone-incoming-call.oga")).exists()) {
path = dir + QStringLiteral("/sounds/freedesktop/stereo/phone-incoming-call.oga");
break;
}
}
}
if (path.isEmpty()) {
return;
}
m_player->setSource(QUrl::fromLocalFile(path));
m_player->play();
Q_EMIT showIncomingCallDialog();
}
MediaManager::MediaManager(QObject *parent)
: QObject(parent)
, m_player(new QMediaPlayer())
, m_output(new QAudioOutput())
, m_timer(new QTimer())
{
m_player->setAudioOutput(m_output);
m_timer->setInterval(1000);
m_timer->setSingleShot(true);
connect(m_timer, &QTimer::timeout, this, [this]() {
m_player->play();
});
connect(m_player, &QMediaPlayer::playbackStateChanged, this, [this]() {
if (m_player->playbackState() == QMediaPlayer::StoppedState) {
m_timer->start();
}
});
}
bool MediaManager::isRinging() const
{
return m_ringing;
}
void MediaManager::stopRinging()
{
m_ringing = false;
m_player->pause();
m_timer->stop();
//Q_EMIT stopRinging();
}

View File

@@ -3,8 +3,13 @@
#pragma once
#include <QAudioOutput>
#include <QMediaPlayer>
#include <QObject>
#include <QQmlEngine>
#include <QTimer>
class NeoChatRoom;
/**
* @class MediaManager
@@ -34,9 +39,29 @@ public:
*/
Q_INVOKABLE void startPlayback();
/**
* Starts ringing if the criteria (see MSC / spec) are met.
*/
void ring(const QJsonObject &json, NeoChatRoom *room);
bool isRinging() const;
Q_SIGNALS:
/**
* @brief Emitted when any media player starts playing. Other objects should stop / pause playback.
*/
void playbackStarted();
void showIncomingCallDialog();
void closeIncomingCallDialog();
private:
void ringUnchecked();
void stopRinging();
QMediaPlayer *m_player;
QAudioOutput *m_output;
QTimer *m_timer;
bool m_ringing = false;
explicit MediaManager(QObject *parent = nullptr);
};

126
src/messageattached.cpp Normal file
View File

@@ -0,0 +1,126 @@
// SPDX-FileCopyrightText: 2025 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#include "messageattached.h"
MessageAttached::MessageAttached(QObject *parent)
: QQuickAttachedPropertyPropagator(parent)
{
if (parent == nullptr) {
qWarning() << "Message must be attached to an Item" << parent;
return;
}
initialize();
}
MessageAttached *MessageAttached::qmlAttachedProperties(QObject *object)
{
return new MessageAttached(object);
}
NeoChatRoom *MessageAttached::room() const
{
return m_room;
}
void MessageAttached::setRoom(NeoChatRoom *room)
{
m_explicitRoom = true;
if (m_room == room) {
return;
}
m_room = room;
propagateMessage(this);
Q_EMIT roomChanged();
}
QQuickItem *MessageAttached::timeline() const
{
return m_timeline;
}
void MessageAttached::setTimeline(QQuickItem *timeline)
{
m_explicitTimeline = true;
if (m_timeline == timeline) {
return;
}
m_timeline = timeline;
propagateMessage(this);
Q_EMIT timelineChanged();
}
int MessageAttached::index() const
{
return m_index;
}
void MessageAttached::setIndex(int index)
{
m_explicitIndex = true;
if (m_index == index) {
return;
}
m_index = index;
propagateMessage(this);
Q_EMIT indexChanged();
}
qreal MessageAttached::maxContentWidth() const
{
return m_maxContentWidth;
}
void MessageAttached::setMaxContentWidth(qreal maxContentWidth)
{
m_explicitMaxContentWidth = true;
if (m_maxContentWidth == maxContentWidth) {
return;
}
m_maxContentWidth = maxContentWidth;
propagateMessage(this);
Q_EMIT maxContentWidthChanged();
}
void MessageAttached::propagateMessage(MessageAttached *message)
{
if (m_explicitRoom || m_room != message->room()) {
m_room = message->room();
Q_EMIT roomChanged();
}
if (m_explicitTimeline || m_timeline != message->timeline()) {
m_timeline = message->timeline();
Q_EMIT timelineChanged();
}
if (m_explicitIndex || m_index != message->index()) {
m_index = message->index();
Q_EMIT indexChanged();
}
if (m_explicitMaxContentWidth || m_maxContentWidth != message->maxContentWidth()) {
m_maxContentWidth = message->maxContentWidth();
Q_EMIT maxContentWidthChanged();
}
const auto styles = attachedChildren();
for (auto *child : attachedChildren()) {
MessageAttached *message = qobject_cast<MessageAttached *>(child);
if (message != nullptr) {
message->propagateMessage(this);
}
}
}
void MessageAttached::attachedParentChange(QQuickAttachedPropertyPropagator *newParent, QQuickAttachedPropertyPropagator *oldParent)
{
Q_UNUSED(oldParent);
MessageAttached *attachedParent = qobject_cast<MessageAttached *>(newParent);
if (attachedParent) {
propagateMessage(attachedParent);
}
}
#include "moc_messageattached.cpp"

78
src/messageattached.h Normal file
View File

@@ -0,0 +1,78 @@
// SPDX-FileCopyrightText: 2025 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <QQmlEngine>
#include <QQuickAttachedPropertyPropagator>
#include <QQuickItem>
#include "neochatroom.h"
class MessageAttached : public QQuickAttachedPropertyPropagator
{
Q_OBJECT
QML_NAMED_ELEMENT(Message)
QML_ATTACHED(MessageAttached)
QML_UNCREATABLE("")
/**
* @brief The room that the message comes from.
*/
Q_PROPERTY(NeoChatRoom *room READ room WRITE setRoom NOTIFY roomChanged FINAL)
/**
* @brief The timeline for the current message.
*/
Q_PROPERTY(QQuickItem *timeline READ timeline WRITE setTimeline NOTIFY timelineChanged FINAL)
/**
* @brief The index of the message in the timeline
*/
Q_PROPERTY(int index READ index WRITE setIndex NOTIFY indexChanged FINAL)
/**
* @brief The width available to the message content.
*/
Q_PROPERTY(qreal maxContentWidth READ maxContentWidth WRITE setMaxContentWidth NOTIFY maxContentWidthChanged FINAL)
public:
explicit MessageAttached(QObject *parent = nullptr);
static MessageAttached *qmlAttachedProperties(QObject *object);
NeoChatRoom *room() const;
void setRoom(NeoChatRoom *room);
QQuickItem *timeline() const;
void setTimeline(QQuickItem *timeline);
int index() const;
void setIndex(int index);
qreal maxContentWidth() const;
void setMaxContentWidth(qreal maxContentWidth);
Q_SIGNALS:
void roomChanged();
void timelineChanged();
void indexChanged();
void maxContentWidthChanged();
protected:
void propagateMessage(MessageAttached *message);
void attachedParentChange(QQuickAttachedPropertyPropagator *newParent, QQuickAttachedPropertyPropagator *oldParent) override;
private:
QPointer<NeoChatRoom> m_room;
bool m_explicitRoom = false;
QPointer<QQuickItem> m_timeline;
bool m_explicitTimeline = false;
int m_index;
bool m_explicitIndex = false;
qreal m_maxContentWidth = -1;
bool m_explicitMaxContentWidth = false;
};

View File

@@ -505,6 +505,19 @@ QList<ActionsModel::Action> actions{
kli18n("<user id> [<reason>]"),
kli18n("Removes the user from the room"),
},
Action{
QStringLiteral("endcall"),
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
auto events = room->currentState().eventsOfType(QStringLiteral("org.matrix.msc3401.call.member"));
for (auto event : events) {
room->setRoomState(QStringLiteral("org.matrix.msc3401.call.member"), event->stateKey(), {});
}
return QString();
},
std::nullopt,
kli18n(""),
kli18n("Forcibly end the call in this room"),
},
};
int ActionsModel::rowCount(const QModelIndex &parent) const

View File

@@ -60,6 +60,11 @@ void CommonRoomsModel::reload()
return;
}
// Checking if you have mutual rooms with yourself doesn't make sense and servers reject it too
if (m_connection->userId() == m_userId) {
return;
}
m_connection->callApi<NeochatGetCommonRoomsJob>(m_userId).then([this](const auto job) {
const auto &replyData = job->jsonData();
beginResetModel();

View File

@@ -20,7 +20,7 @@ EmojiModel::EmojiModel(QObject *parent)
, m_configGroup(KConfigGroup(m_config, u"Editor"_s))
{
if (_emojis.isEmpty()) {
#include "emojis.h"
//#include "emojis.h"
}
}

View File

@@ -3,6 +3,7 @@
#include "messagecontentmodel.h"
#include "eventhandler.h"
#include "messagecomponenttype.h"
#include "neochatconfig.h"
#include <QImageReader>
@@ -27,6 +28,7 @@
#include "chatbarcache.h"
#include "filetype.h"
#include "linkpreviewer.h"
#include "models/reactionmodel.h"
#include "neochatconnection.h"
#include "neochatroom.h"
#include "texthandler.h"
@@ -130,9 +132,6 @@ void MessageContentModel::initializeModel()
connect(m_room, &NeoChatRoom::urlPreviewEnabledChanged, this, [this]() {
resetContent();
});
connect(NeoChatConfig::self(), &NeoChatConfig::ShowLinkPreviewChanged, this, [this]() {
resetContent();
});
connect(m_room, &Room::memberNameUpdated, this, [this](RoomMember member) {
if (m_room != nullptr) {
if (senderId().isEmpty() || senderId() == member.id()) {
@@ -152,12 +151,18 @@ void MessageContentModel::initializeModel()
updateReplyModel();
resetModel();
});
connect(m_room, &Room::updatedEvent, this, [this](const QString &eventId) {
if (eventId == m_eventId) {
updateReactionModel();
}
});
initializeEvent();
if (m_currentState == Available || m_currentState == Pending) {
updateReplyModel();
}
resetModel();
updateReactionModel();
}
void MessageContentModel::initializeEvent()
@@ -340,6 +345,10 @@ QVariant MessageContentModel::data(const QModelIndex &index, int role) const
if (role == ReplyContentModelRole) {
return QVariant::fromValue<MessageContentModel *>(m_replyModel);
}
if (role == ReactionModelRole) {
return QVariant::fromValue<ReactionModel *>(m_reactionModel);
;
}
if (role == ThreadRootRole) {
auto roomMessageEvent = eventCast<const RoomMessageEvent>(event.first);
#if Quotient_VERSION_MINOR > 9 || (Quotient_VERSION_MINOR == 9 && Quotient_VERSION_PATCH > 1)
@@ -400,6 +409,7 @@ QHash<int, QByteArray> MessageContentModel::roleNamesStatic()
roles[MessageContentModel::ReplyEventIdRole] = "replyEventId";
roles[MessageContentModel::ReplyAuthorRole] = "replyAuthor";
roles[MessageContentModel::ReplyContentModelRole] = "replyContentModel";
roles[MessageContentModel::ReactionModelRole] = "reactionModel";
roles[MessageContentModel::ThreadRootRole] = "threadRoot";
roles[MessageContentModel::LinkPreviewerRole] = "linkPreviewer";
roles[MessageContentModel::ChatBarCacheRole] = "chatBarCache";
@@ -480,11 +490,16 @@ QList<MessageComponent> MessageContentModel::messageContentComponents(bool isEdi
newComponents = addLinkPreviews(newComponents);
}
if ((m_reactionModel && m_reactionModel->rowCount() > 0)) {
newComponents += MessageComponent{MessageComponentType::Reaction, QString(), {}};
}
#if Quotient_VERSION_MINOR > 9 || (Quotient_VERSION_MINOR == 9 && Quotient_VERSION_PATCH > 1)
if (roomMessageEvent && (roomMessageEvent->isThreaded() || m_room->threads().contains(roomMessageEvent->id()))
if (NeoChatConfig::self()->threads() && roomMessageEvent && (roomMessageEvent->isThreaded() || m_room->threads().contains(roomMessageEvent->id()))
&& roomMessageEvent->id() == roomMessageEvent->threadRootEventId()) {
#else
if (isThreading && roomMessageEvent && roomMessageEvent->isThreaded() && roomMessageEvent->id() == roomMessageEvent->threadRootEventId()) {
if (NeoChatConfig::self()->threads() && roomMessageEvent && roomMessageEvent->isThreaded()
&& roomMessageEvent->id() == roomMessageEvent->threadRootEventId()) {
#endif
newComponents += MessageComponent{MessageComponentType::Separator, {}, {}};
newComponents += MessageComponent{MessageComponentType::ThreadBody, u"Thread Body"_s, {}};
@@ -513,7 +528,7 @@ void MessageContentModel::updateReplyModel()
if (roomMessageEvent == nullptr) {
return;
}
if (!roomMessageEvent->isReply() || (roomMessageEvent->isThreaded() && NeoChatConfig::self()->threads())) {
if (!roomMessageEvent->isReply(!NeoChatConfig::self()->threads()) || (roomMessageEvent->isThreaded() && NeoChatConfig::self()->threads())) {
if (m_replyModel) {
delete m_replyModel;
}
@@ -524,7 +539,7 @@ void MessageContentModel::updateReplyModel()
return;
}
m_replyModel = new MessageContentModel(m_room, roomMessageEvent->replyEventId(), true, false, this);
m_replyModel = new MessageContentModel(m_room, roomMessageEvent->replyEventId(!NeoChatConfig::self()->threads()), true, false, this);
connect(m_replyModel, &MessageContentModel::eventUpdated, this, [this]() {
Q_EMIT dataChanged(index(0), index(0), {ReplyAuthorRole});
@@ -731,4 +746,25 @@ void MessageContentModel::updateItineraryModel()
}
}
void MessageContentModel::updateReactionModel()
{
if (m_reactionModel != nullptr && m_reactionModel->rowCount() > 0) {
return;
}
if (m_reactionModel == nullptr) {
m_reactionModel = new ReactionModel(this, m_eventId, m_room);
connect(m_reactionModel, &ReactionModel::reactionsUpdated, this, &MessageContentModel::updateReactionModel);
}
if (m_reactionModel->rowCount() <= 0) {
m_reactionModel->disconnect(this);
delete m_reactionModel;
m_reactionModel = nullptr;
return;
}
resetContent();
}
#include "moc_messagecontentmodel.cpp"

View File

@@ -7,11 +7,11 @@
#include <QQmlEngine>
#include <Quotient/events/roomevent.h>
#include <Quotient/room.h>
#include "enums/messagecomponenttype.h"
#include "itinerarymodel.h"
#include "messagecomponent.h"
#include "models/reactionmodel.h"
#include "neochatroommember.h"
/**
@@ -57,6 +57,8 @@ public:
ReplyAuthorRole, /**< The author of the event that was replied to. */
ReplyContentModelRole, /**< The MessageContentModel for the reply event. */
ReactionModelRole, /**< Reaction model for this event. */
ThreadRootRole, /**< The thread root event ID for the event. */
LinkPreviewerRole, /**< The link preview details. */
@@ -125,6 +127,7 @@ private:
QPointer<MessageContentModel> m_replyModel;
void updateReplyModel();
ReactionModel *m_reactionModel = nullptr;
ItineraryModel *m_itineraryModel = nullptr;
QList<MessageComponent> componentsForType(MessageComponentType::Type type);
@@ -135,4 +138,6 @@ private:
void updateItineraryModel();
bool m_emptyItinerary = false;
void updateReactionModel();
};

View File

@@ -5,6 +5,7 @@
#include "neochatconfig.h"
#include <Quotient/events/encryptedevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/stickerevent.h>
#if Quotient_VERSION_MINOR > 9 || (Quotient_VERSION_MINOR == 9 && Quotient_VERSION_PATCH > 1)
@@ -120,8 +121,12 @@ QVariant MessageModel::data(const QModelIndex &idx, int role) const
}
if (role == ContentModelRole) {
if (event->get().is<EncryptedEvent>()) {
return QVariant::fromValue<MessageContentModel *>(m_room->contentModelForEvent(event->get().id()));
}
auto roomMessageEvent = eventCast<const RoomMessageEvent>(&event.value().get());
if (roomMessageEvent && roomMessageEvent->isThreaded()) {
if (NeoChatConfig::self()->threads() && roomMessageEvent && roomMessageEvent->isThreaded()) {
return QVariant::fromValue<MessageContentModel *>(m_room->contentModelForEvent(roomMessageEvent->threadRootEventId()));
}
return QVariant::fromValue<MessageContentModel *>(m_room->contentModelForEvent(&event->get()));
@@ -216,6 +221,9 @@ QVariant MessageModel::data(const QModelIndex &idx, int role) const
}
if (role == IsThreadedRole) {
if (!NeoChatConfig::self()->threads()) {
return false;
}
if (auto roomMessageEvent = eventCast<const RoomMessageEvent>(&event.value().get())) {
return roomMessageEvent->isThreaded();
}
@@ -258,18 +266,6 @@ QVariant MessageModel::data(const QModelIndex &idx, int role) const
return m_readMarkerModels.contains(event.value().get().id());
}
if (role == ReactionRole) {
if (m_reactionModels.contains(event.value().get().id())) {
return QVariant::fromValue<ReactionModel *>(m_reactionModels[event.value().get().id()].data());
} else {
return QVariantList();
}
}
if (role == ShowReactionsRole) {
return m_reactionModels.contains(event.value().get().id());
}
if (role == VerifiedRole) {
if (event.value().get().originalEvent()) {
auto encrypted = dynamic_cast<const EncryptedEvent *>(event.value().get().originalEvent());
@@ -323,8 +319,6 @@ QHash<int, QByteArray> MessageModel::roleNames() const
roles[ShowSectionRole] = "showSection";
roles[ReadMarkersRole] = "readMarkers";
roles[ShowReadMarkersRole] = "showReadMarkers";
roles[ReactionRole] = "reaction";
roles[ShowReactionsRole] = "showReactions";
roles[VerifiedRole] = "verified";
roles[AuthorDisplayNameRole] = "authorDisplayName";
roles[IsRedactedRole] = "isRedacted";
@@ -454,31 +448,6 @@ void MessageModel::createEventObjects(const Quotient::RoomEvent *event, bool isP
}
}
}
if (const auto roomEvent = eventCast<const RoomMessageEvent>(event)) {
// ReactionModel handles updates to add and remove reactions, we only need to
// handle adding and removing whole models here.
if (m_reactionModels.contains(eventId)) {
// If a model already exists but now has no reactions remove it
if (m_reactionModels[eventId]->rowCount() <= 0) {
m_reactionModels.remove(eventId);
if (!resetting) {
refreshEventRoles(eventId, {ReactionRole, ShowReactionsRole});
}
}
} else {
if (m_room->relatedEvents(*event, Quotient::EventRelation::AnnotationType).count() > 0) {
// If a model doesn't exist and there are reactions add it.
auto reactionModel = QSharedPointer<ReactionModel>(new ReactionModel(roomEvent, m_room));
if (reactionModel->rowCount() > 0) {
m_reactionModels[eventId] = reactionModel;
if (!resetting) {
refreshEventRoles(eventId, {ReactionRole, ShowReactionsRole});
}
}
}
}
}
}
void MessageModel::clearModel()
@@ -504,7 +473,6 @@ void MessageModel::clearModel()
void MessageModel::clearEventObjects()
{
m_reactionModels.clear();
m_readMarkerModels.clear();
}

View File

@@ -77,8 +77,6 @@ public:
ReadMarkersRole, /**< The first 5 other users at the event for read marker tracking. */
ShowReadMarkersRole, /**< Whether there are any other user read markers to be shown. */
ReactionRole, /**< List model for this event. */
ShowReactionsRole, /**< Whether there are any reactions to be shown. */
VerifiedRole, /**< Whether an encrypted message is sent in a verified session. */
AuthorDisplayNameRole, /**< The displayname for the event's sender; for name change events, the old displayname. */
@@ -155,7 +153,6 @@ private:
bool movingEvent = false;
QMap<QString, QSharedPointer<ReadMarkerModel>> m_readMarkerModels;
QMap<QString, QSharedPointer<ReactionModel>> m_reactionModels;
void createEventObjects(const Quotient::RoomEvent *event, bool isPending = false);
};

View File

@@ -9,22 +9,27 @@
#include <KLocalizedString>
#include "neochatroom.h"
using namespace Qt::StringLiterals;
ReactionModel::ReactionModel(const Quotient::RoomMessageEvent *event, NeoChatRoom *room)
: QAbstractListModel(nullptr)
ReactionModel::ReactionModel(MessageContentModel *parent, const QString &eventId, NeoChatRoom *room)
: QAbstractListModel(parent)
, m_room(room)
, m_event(event)
, m_eventId(eventId)
{
if (m_event != nullptr && m_room != nullptr) {
connect(m_room, &NeoChatRoom::updatedEvent, this, [this](const QString &eventId) {
if (m_event && m_event->id() == eventId) {
updateReactions();
}
});
Q_ASSERT(parent);
Q_ASSERT(parent != nullptr);
Q_ASSERT(!eventId.isEmpty());
Q_ASSERT(room != nullptr);
updateReactions();
}
connect(m_room, &NeoChatRoom::updatedEvent, this, [this](const QString &eventId) {
if (m_eventId == eventId) {
updateReactions();
}
});
updateReactions();
}
QVariant ReactionModel::data(const QModelIndex &index, int role) const
@@ -99,12 +104,16 @@ int ReactionModel::rowCount(const QModelIndex &parent) const
void ReactionModel::updateReactions()
{
if (m_room == nullptr) {
return;
}
beginResetModel();
m_reactions.clear();
m_shortcodes.clear();
const auto &annotations = m_room->relatedEvents(*m_event, Quotient::EventRelation::AnnotationType);
const auto &annotations = m_room->relatedEvents(m_eventId, Quotient::EventRelation::AnnotationType);
if (annotations.isEmpty()) {
endResetModel();
return;

View File

@@ -3,11 +3,20 @@
#pragma once
#include "neochatroom.h"
#include <QAbstractListModel>
#include <QQmlEngine>
#include <Quotient/events/reactionevent.h>
#include <Quotient/roommember.h>
namespace Quotient
{
class RoomMessageEvent;
}
class MessageContentModel;
class NeoChatRoom;
/**
* @class ReactionModel
*
@@ -38,7 +47,7 @@ public:
HasLocalMember, /**< Whether the local member is in the list of authors. */
};
explicit ReactionModel(const Quotient::RoomMessageEvent *event, NeoChatRoom *room);
explicit ReactionModel(MessageContentModel *parent, const QString &eventId, NeoChatRoom *room);
/**
* @brief Get the given role value at the given index.
@@ -61,9 +70,15 @@ public:
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
Q_SIGNALS:
/**
* @brief The reactions in the model have been updated.
*/
void reactionsUpdated();
private:
QPointer<NeoChatRoom> m_room;
const Quotient::RoomMessageEvent *m_event;
QString m_eventId;
QList<Reaction> m_reactions;
QMap<QString, QString> m_shortcodes;

View File

@@ -348,6 +348,12 @@ QVariant RoomTreeModel::data(const QModelIndex &index, int role) const
return QVariant::fromValue(room);
}
if (role == SubtitleTextRole) {
if (room->isInvite()) {
if (room->isDirectChat()) {
return i18nc("@info:label", "Invited you to chat");
}
return i18nc("@info:label", "%1 invited you", room->member(room->invitingUserId()).displayName());
}
if (room->lastEvent() == nullptr || room->lastEventIsSpoiler()) {
return QString();
}

View File

@@ -19,7 +19,6 @@
#include "messagecontentmodel.h"
class NeoChatRoom;
class ReactionModel;
/**
* @class ThreadFetchModel
@@ -172,8 +171,6 @@ private:
ThreadFetchModel *m_threadFetchModel;
ThreadChatBarModel *m_threadChatBarModel;
QMap<QString, QSharedPointer<ReactionModel>> m_reactionModels;
QPointer<Quotient::GetRelatingEventsWithRelTypeJob> m_currentJob = nullptr;
std::optional<QString> m_nextBatch = QString();
bool m_addingPending = false;

View File

@@ -13,13 +13,35 @@
using namespace Qt::StringLiterals;
ThreePIdModel::ThreePIdModel(NeoChatConnection *connection)
: QAbstractListModel(connection)
ThreePIdModel::ThreePIdModel(QObject *parent)
: QAbstractListModel(parent)
{
Q_ASSERT(connection);
connect(connection, &NeoChatConnection::stateChanged, this, [this]() {
}
NeoChatConnection *ThreePIdModel::connection() const
{
return m_connection;
}
void ThreePIdModel::setConnection(NeoChatConnection *connection)
{
if (m_connection == connection) {
return;
}
if (m_connection != nullptr) {
m_connection->disconnect(this);
}
m_connection = connection;
if (m_connection) {
connect(m_connection, &NeoChatConnection::stateChanged, this, [this]() {
refreshModel();
});
refreshModel();
});
}
Q_EMIT connectionChanged();
}
QVariant ThreePIdModel::data(const QModelIndex &index, int role) const
@@ -62,12 +84,14 @@ QHash<int, QByteArray> ThreePIdModel::roleNames() const
void ThreePIdModel::refreshModel()
{
const auto connection = dynamic_cast<NeoChatConnection *>(this->parent());
if (connection != nullptr && connection->isLoggedIn()) {
const auto threePIdJob = connection->callApi<Quotient::GetAccount3PIDsJob>();
connect(threePIdJob, &Quotient::BaseJob::success, this, [this, threePIdJob]() {
if (m_connection != nullptr && m_connection->isLoggedIn()) {
if (m_job.isRunning()) {
m_job.cancel();
}
m_job = m_connection->callApi<Quotient::GetAccount3PIDsJob>();
connect(m_job, &Quotient::BaseJob::success, this, [this]() {
beginResetModel();
m_threePIds = threePIdJob->threepids();
m_threePIds = m_job->threepids();
endResetModel();
refreshBindStatus();
@@ -77,25 +101,24 @@ void ThreePIdModel::refreshModel()
void ThreePIdModel::refreshBindStatus()
{
const auto connection = dynamic_cast<NeoChatConnection *>(this->parent());
if (connection == nullptr || !connection->hasIdentityServer()) {
if (m_connection == nullptr || !m_connection->hasIdentityServer()) {
return;
}
const auto openIdJob = connection->callApi<Quotient::RequestOpenIdTokenJob>(connection->userId());
connect(openIdJob, &Quotient::BaseJob::success, this, [this, connection, openIdJob]() {
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/account/register"_s);
const auto openIdJob = m_connection->callApi<Quotient::RequestOpenIdTokenJob>(m_connection->userId());
connect(openIdJob, &Quotient::BaseJob::success, this, [this, openIdJob]() {
const auto requestUrl = QUrl(m_connection->identityServer().toString() + u"/_matrix/identity/v2/account/register"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
QNetworkRequest request(requestUrl);
auto newRequest = Quotient::NetworkAccessManager::instance()->post(request, QJsonDocument(openIdJob->jsonData()).toJson());
connect(newRequest, &QNetworkReply::finished, this, [this, connection, newRequest]() {
connect(newRequest, &QNetworkReply::finished, this, [this, newRequest]() {
QJsonObject replyJson = QJsonDocument::fromJson(newRequest->readAll()).object();
const auto identityServerToken = replyJson["token"_L1].toString();
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/hash_details"_s);
const auto requestUrl = QUrl(m_connection->identityServer().toString() + u"/_matrix/identity/v2/hash_details"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
@@ -104,11 +127,11 @@ void ThreePIdModel::refreshBindStatus()
hashRequest.setRawHeader("Authorization", "Bearer " + identityServerToken.toLatin1());
auto hashReply = Quotient::NetworkAccessManager::instance()->get(hashRequest);
connect(hashReply, &QNetworkReply::finished, this, [this, connection, identityServerToken, hashReply]() {
connect(hashReply, &QNetworkReply::finished, this, [this, identityServerToken, hashReply]() {
QJsonObject replyJson = QJsonDocument::fromJson(hashReply->readAll()).object();
const auto lookupPepper = replyJson["lookup_pepper"_L1].toString();
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/lookup"_s);
const auto requestUrl = QUrl(m_connection->identityServer().toString() + u"/_matrix/identity/v2/lookup"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
@@ -127,13 +150,13 @@ void ThreePIdModel::refreshBindStatus()
requestData["addresses"_L1] = idLookups;
auto lookupReply = Quotient::NetworkAccessManager::instance()->post(lookupRequest, QJsonDocument(requestData).toJson(QJsonDocument::Compact));
connect(lookupReply, &QNetworkReply::finished, this, [this, connection, lookupReply]() {
connect(lookupReply, &QNetworkReply::finished, this, [this, lookupReply]() {
beginResetModel();
m_bindings.clear();
QJsonObject mappings = QJsonDocument::fromJson(lookupReply->readAll()).object()["mappings"_L1].toObject();
for (const auto &id : mappings.keys()) {
if (mappings[id] == connection->userId()) {
if (mappings[id] == m_connection->userId()) {
m_bindings += id.section(u' ', 0, 0);
}
}

View File

@@ -7,6 +7,7 @@
#include <QQmlEngine>
#include <Quotient/csapi/administrative_contact.h>
#include <Quotient/jobs/jobhandle.h>
class NeoChatConnection;
@@ -19,19 +20,27 @@ class ThreePIdModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("")
/**
* @brief The current connection for the model to use.
*/
Q_PROPERTY(NeoChatConnection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
public:
/**
* @brief Defines the model roles.
*/
enum EventRoles {
enum Roles {
AddressRole = Qt::DisplayRole, /**< The third-party identifier address. */
MediumRole, /**< The medium of the third-party identifier. One of: [email, msisdn]. */
IsBoundRole, /**< Whether the 3PID is bound to the current identity server. */
};
Q_ENUM(Roles)
explicit ThreePIdModel(NeoChatConnection *parent);
explicit ThreePIdModel(QObject *parent = nullptr);
[[nodiscard]] NeoChatConnection *connection() const;
void setConnection(NeoChatConnection *connection);
/**
* @brief Get the given role value at the given index.
@@ -56,9 +65,15 @@ public:
Q_INVOKABLE void refreshModel();
Q_SIGNALS:
void connectionChanged();
private:
QPointer<NeoChatConnection> m_connection;
QVector<Quotient::GetAccount3PIDsJob::ThirdPartyIdentifier> m_threePIds;
Quotient::JobHandle<Quotient::GetAccount3PIDsJob> m_job;
QList<QString> m_bindings;
void refreshBindStatus();

View File

@@ -32,42 +32,6 @@ class TimelineMessageModel : public MessageModel
QML_ELEMENT
public:
/**
* @brief Defines the model roles.
*/
enum EventRoles {
DelegateTypeRole = Qt::UserRole + 1, /**< The delegate type of the message. */
EventIdRole, /**< The matrix event ID of the event. */
TimeRole, /**< The timestamp for when the event was sent (as a QDateTime). */
SectionRole, /**< The date of the event as a string. */
AuthorRole, /**< The author of the event. */
HighlightRole, /**< Whether the event should be highlighted. */
SpecialMarksRole, /**< Whether the event is hidden or not. */
ProgressInfoRole, /**< Progress info when downloading files. */
GenericDisplayRole, /**< A generic string based upon the message type. */
MediaInfoRole, /**< The media info for the event. */
ContentModelRole, /**< The MessageContentModel for the event. */
IsThreadedRole, /**< Whether the message is in a thread. */
ThreadRootRole, /**< The Matrix ID of the thread root message, if any . */
ShowSectionRole, /**< Whether the section header should be shown. */
ReadMarkersRole, /**< The first 5 other users at the event for read marker tracking. */
ShowReadMarkersRole, /**< Whether there are any other user read markers to be shown. */
ReactionRole, /**< List model for this event. */
ShowReactionsRole, /**< Whether there are any reactions to be shown. */
VerifiedRole, /**< Whether an encrypted message is sent in a verified session. */
AuthorDisplayNameRole, /**< The displayname for the event's sender; for name change events, the old displayname. */
IsRedactedRole, /**< Whether an event has been deleted. */
IsPendingRole, /**< Whether an event is waiting to be accepted by the server. */
IsEditableRole, /**< Whether the event can be edited by the user. */
LastRole, // Keep this last
};
Q_ENUM(EventRoles)
explicit TimelineMessageModel(QObject *parent = nullptr);
/**

View File

@@ -303,6 +303,7 @@ Name[ta]=பகிர்
Name[tr]=Paylaş
Name[uk]=Оприлюднення
Name[x-test]=xxSharexx
Name[zh_CN]=分享
Name[zh_TW]=分享
Comment=The result of sharing a piece of content
Comment[ar]=نتيجة مشاركة محتوى
@@ -336,5 +337,6 @@ Comment[ta]=எதையோ பகிர்ந்த‍தன் விளைவ
Comment[tr]=Bir parça içerik paylaşımının sonucu
Comment[uk]=Результат оприлюднення даних
Comment[x-test]=xxThe result of sharing a piece of contentxx
Comment[zh_CN]=分享一个内容得到的结果
Comment[zh_TW]=分享一份內容之後的結果
Action=Popup

View File

@@ -104,6 +104,7 @@
</entry>
<entry name="ShowLinkPreview" type="bool">
<label>Show preview of the links in the chat messages</label>
<default>true</default>
</entry>
<entry name="SystemTray" type="bool">
<label>Close NeoChat to system tray</label>

Some files were not shown because too many files have changed in this diff Show More