From 8d49d83b3b45ab22d7b9d945c4b32296b07cb49e Mon Sep 17 00:00:00 2001 From: fiaxh Date: Fri, 14 Aug 2026 11:45:08 +0200 Subject: Add initial support for multi-file transfers --- libdino/src/service/content_item_store.vala | 34 +++++ libdino/src/service/database.vala | 30 +++- libdino/src/service/file_manager.vala | 44 ++---- libdino/src/service/file_transfer_storage.vala | 57 +++++++- libdino/src/service/stateless_file_sharing.vala | 177 +++++++++++++----------- 5 files changed, 226 insertions(+), 116 deletions(-) (limited to 'libdino/src/service') diff --git a/libdino/src/service/content_item_store.vala b/libdino/src/service/content_item_store.vala index d74f9b05..cf4c6975 100644 --- a/libdino/src/service/content_item_store.vala +++ b/libdino/src/service/content_item_store.vala @@ -26,6 +26,8 @@ public class ContentItemStore : StreamInteractionModule, Object { this.db = db; stream_interactor.get_module(FileManager.IDENTITY).received_file.connect(insert_file_transfer); + stream_interactor.get_module(FileManager2.IDENTITY).received_file.connect(insert_file_transfer); + stream_interactor.get_module(FileManager2.IDENTITY).received_file_group.connect(insert_file_group); stream_interactor.get_module(MessageProcessor.IDENTITY).message_received.connect(announce_message); stream_interactor.get_module(MessageProcessor.IDENTITY).message_sent.connect(announce_message); stream_interactor.get_module(Calls.IDENTITY).call_incoming.connect(insert_call); @@ -88,6 +90,13 @@ public class ContentItemStore : StreamInteractionModule, Object { return call_item; } break; + case 4: + FileTransferGroup? file_group = stream_interactor.get_module(FileTransferStorage.IDENTITY).get_file_group_by_id(foreign_id, conversation); + if (file_group != null) { + var file_group_item = new FileGroupItem(file_group, conversation, id); + return file_group_item; + } + break; default: warning("Unknown content item type: %i", content_type); break; @@ -300,6 +309,16 @@ public class ContentItemStore : StreamInteractionModule, Object { new_item(item, conversation); } + private void insert_file_group(FileTransferGroup file_group, Conversation conversation) { + FileGroupItem item = new FileGroupItem(file_group, conversation, file_group.id); + // TODO fix local time + item.id = db.add_content_item(conversation, item.time, item.time, 4, file_group.id, false); + if (collection_conversations.has_key(conversation)) { + collection_conversations.get(conversation).insert_item(item); + } + new_item(item, conversation); + } + private void insert_call(Call call, CallState call_state, Conversation conversation) { CallItem item = new CallItem(call, conversation, -1); item.id = db.add_content_item(conversation, call.time, call.local_time, 3, call.id, false); @@ -415,6 +434,21 @@ public class FileItem : ContentItem { } } +public class FileGroupItem : ContentItem { + public const string TYPE = "file_group"; + + public FileTransferGroup file_group; + public Conversation conversation; + + public FileGroupItem(FileTransferGroup file_group, Conversation conversation, int id) { + var file_transfer = file_group.file_transfers.get(0); + base(id, TYPE, file_transfer.from, file_transfer.time, file_transfer.encryption, Message.Marked.NONE); + + this.file_group = file_group; + this.conversation = conversation; + } +} + public class CallItem : ContentItem { public const string TYPE = "call"; diff --git a/libdino/src/service/database.vala b/libdino/src/service/database.vala index b38ccfca..8432ff40 100644 --- a/libdino/src/service/database.vala +++ b/libdino/src/service/database.vala @@ -7,7 +7,7 @@ using Dino.Entities; namespace Dino { public class Database : Qlite.Database { - private const int VERSION = 33; + private const int VERSION = 34; public class AccountTable : Table { public Column id = new Column.Integer("id") { primary_key = true, auto_increment = true }; @@ -225,6 +225,28 @@ public class Database : Qlite.Database { } } + public class FileTransferGroupTable : Table { + public Column id = new Column.Integer("id") { primary_key = true, auto_increment = true }; + public Column message_id = new Column.Integer("message_id"); + + internal FileTransferGroupTable(Database db) { + base(db, "file_transfer_group"); + init({id, message_id}); + index("file_transfer_group_message_id_idx", {message_id}); + } + } + + public class FileTransferGroupFileTransferTable : Table { + public Column file_transfer_group_id = new Column.Integer("file_transfer_group_id"); + public Column file_transfer_id = new Column.Integer("file_transfer_id"); + + internal FileTransferGroupFileTransferTable(Database db) { + base(db, "file_transfer_group_file_transfer"); + init({file_transfer_group_id, file_transfer_id}); + index("file_transfer_group_file_transfer_id_idx", {file_transfer_group_id}); + } + } + public class FileHashesTable : Table { public Column id = new Column.Integer("id"); public Column algo = new Column.Text("algo") { not_null = true }; @@ -489,6 +511,8 @@ public class Database : Qlite.Database { public RealJidTable real_jid { get; private set; } public OccupantIdTable occupantid { get; private set; } public FileTransferTable file_transfer { get; private set; } + public FileTransferGroupTable file_transfer_group { get; private set; } + public FileTransferGroupFileTransferTable file_transfer_group_file_transfer { get; private set; } public FileHashesTable file_hashes { get; private set; } public FileThumbnailsTable file_thumbnails { get; private set; } public SourcesTable sfs_sources { get; private set; } @@ -525,6 +549,8 @@ public class Database : Qlite.Database { occupantid = new OccupantIdTable(this); real_jid = new RealJidTable(this); file_transfer = new FileTransferTable(this); + file_transfer_group = new FileTransferGroupTable(this); + file_transfer_group_file_transfer = new FileTransferGroupFileTransferTable(this); file_hashes = new FileHashesTable(this); file_thumbnails = new FileThumbnailsTable(this); sfs_sources = new SourcesTable(this); @@ -542,7 +568,7 @@ public class Database : Qlite.Database { settings = new SettingsTable(this); account_settings = new AccountSettingsTable(this); conversation_settings = new ConversationSettingsTable(this); - init({ account, jid, entity, content_item, message, message_occupant_id, body_meta, message_correction, reply, real_jid, occupantid, file_transfer, file_hashes, file_thumbnails, sfs_sources, call, call_counterpart, conversation, avatar, entity_identity, entity_feature, roster, mam_catchup, reaction, muc_affiliation, muc_affiliation_version, settings, account_settings, conversation_settings }); + init({ account, jid, entity, content_item, message, message_occupant_id, body_meta, message_correction, reply, real_jid, occupantid, file_transfer, file_transfer_group, file_transfer_group_file_transfer, file_hashes, file_thumbnails, sfs_sources, call, call_counterpart, conversation, avatar, entity_identity, entity_feature, roster, mam_catchup, reaction, muc_affiliation, muc_affiliation_version, settings, account_settings, conversation_settings }); try { exec("PRAGMA journal_mode = WAL"); diff --git a/libdino/src/service/file_manager.vala b/libdino/src/service/file_manager.vala index 964278a5..60b7fafa 100644 --- a/libdino/src/service/file_manager.vala +++ b/libdino/src/service/file_manager.vala @@ -16,17 +16,22 @@ public class FileManager : StreamInteractionModule, Object { private StreamInteractor stream_interactor; private Database db; - private Gee.List file_senders = new ArrayList(); + public Gee.List file_senders = new ArrayList(); private Gee.List file_encryptors = new ArrayList(); - private Gee.List file_decryptors = new ArrayList(); + public Gee.List file_decryptors = new ArrayList(); private Gee.List file_providers = new ArrayList(); - private Gee.List file_metadata_providers = new ArrayList(); + public Gee.List file_metadata_providers = new ArrayList(); public StatelessFileSharing sfs { owned get { return stream_interactor.get_module(StatelessFileSharing.IDENTITY); } private set { } } + public FileManager2 fm2 { + owned get { return stream_interactor.get_module(FileManager2.IDENTITY); } + private set { } + } + public static void start(StreamInteractor stream_interactor, Database db) { FileManager m = new FileManager(stream_interactor, db); stream_interactor.add_module(m); @@ -97,7 +102,7 @@ public class FileManager : StreamInteractionModule, Object { try { file_transfer.input_stream = yield file.read_async(); - yield save_file(file_transfer); + yield fm2.save_file(file_transfer); stream_interactor.get_module(FileTransferStorage.IDENTITY).add_file(file_transfer); conversation.last_active = file_transfer.time; @@ -151,7 +156,7 @@ public class FileManager : StreamInteractionModule, Object { file_transfer.state = FileTransfer.State.IN_PROGRESS; - // Update current download progress in the FileTransfer + // Update current upload progress in the FileTransfer LimitInputStream? limit_stream = file_transfer.input_stream as LimitInputStream; if (limit_stream == null) { limit_stream = new LimitInputStream(file_transfer.input_stream, file_meta.size); @@ -216,19 +221,6 @@ public class FileManager : StreamInteractionModule, Object { file_metadata_providers.add(file_metadata_provider); } - public bool is_sender_trustworthy(FileTransfer file_transfer, Conversation conversation) { - if (file_transfer.direction == FileTransfer.DIRECTION_SENT) return true; - - Jid relevant_jid = conversation.counterpart; - if (conversation.type_ == Conversation.Type.GROUPCHAT) { - relevant_jid = stream_interactor.get_module(MucManager.IDENTITY).get_real_jid(file_transfer.from, conversation.account); - } - if (relevant_jid == null) return false; - - bool in_roster = stream_interactor.get_module(RosterManager.IDENTITY).get_roster_item(conversation.account, relevant_jid) != null; - return in_roster; - } - private async FileMeta get_file_meta(FileProvider file_provider, FileTransfer file_transfer, Conversation conversation, FileReceiveData receive_data_) throws FileReceiveError { FileReceiveData receive_data = receive_data_; FileMeta file_meta = file_provider.get_file_meta(file_transfer); @@ -390,7 +382,7 @@ public class FileManager : StreamInteractionModule, Object { FileTransfer file_transfer = create_file_transfer_from_provider_incoming(file_provider, info, from, time, local_time, conversation, receive_data, file_meta); stream_interactor.get_module(FileTransferStorage.IDENTITY).add_file(file_transfer); - if (is_sender_trustworthy(file_transfer, conversation)) { + if (fm2.is_sender_trustworthy(file_transfer, conversation)) { try { yield get_file_meta(file_provider, file_transfer, conversation, receive_data); } catch (Error e) { @@ -408,20 +400,6 @@ public class FileManager : StreamInteractionModule, Object { received_file(file_transfer, conversation); } - private async void save_file(FileTransfer file_transfer) throws FileSendError { - try { - string filename = Random.next_int().to_string("%x") + "_" + file_transfer.file_name; - File file = File.new_for_path(Path.build_filename(get_storage_dir(), filename)); - OutputStream os = file.create(FileCreateFlags.REPLACE_DESTINATION); - yield os.splice_async(file_transfer.input_stream, OutputStreamSpliceFlags.CLOSE_SOURCE | OutputStreamSpliceFlags.CLOSE_TARGET); - file_transfer.state = FileTransfer.State.COMPLETE; - file_transfer.path = filename; - file_transfer.input_stream = new LimitInputStream(yield file.read_async(), file_transfer.size); - } catch (Error e) { - throw new FileSendError.SAVE_FAILED("Saving file error: %s".printf(e.message)); - } - } - public Message? get_message_for_file_transfer(FileTransfer file_transfer, Conversation conversation) { if ((file_transfer.provider == 0 || file_transfer.provider == 2) && file_transfer.info != null) { return stream_interactor.get_module(MessageStorage.IDENTITY).get_message_by_id(int.parse(file_transfer.info), conversation); diff --git a/libdino/src/service/file_transfer_storage.vala b/libdino/src/service/file_transfer_storage.vala index 64bb6b81..b4a4db3e 100644 --- a/libdino/src/service/file_transfer_storage.vala +++ b/libdino/src/service/file_transfer_storage.vala @@ -15,6 +15,8 @@ namespace Dino { private WeakMap files_by_db_id = new WeakMap(); private WeakMap files_by_message_id = new WeakMap(); + private WeakMap file_group_by_db_id = new WeakMap(); + private WeakMap file_group_by_message_id = new WeakMap(); private WeakMap files_by_message_and_file_id = new WeakMap(); public static void start(StreamInteractor stream_interactor, Database db) { @@ -32,7 +34,13 @@ namespace Dino { cache_file(file_transfer); } - public FileTransfer? get_file_by_id(int id, Conversation conversation) { + public void add_file_group(FileTransferGroup file_group) { + file_group.persist(db); + cache_file_group(file_group); + } + + // `conversation` should be provided, otherwise the FileTransfer.ourpart might be wrong + public FileTransfer? get_file_by_id(int id, Conversation? conversation) { FileTransfer? file_transfer = files_by_db_id[id]; if (file_transfer != null) { return file_transfer; @@ -58,6 +66,29 @@ namespace Dino { return create_file_from_row_opt(row_option, conversation); } + public FileTransferGroup? get_file_group_by_id(int id, Conversation conversation) { + FileTransferGroup? file_group = file_group_by_db_id[id]; + if (file_group != null) { + return file_group; + } + + RowOption row_option = db.file_transfer_group.select().with(db.file_transfer_group.id, "=", id).row(); + return row_option.is_present() ? create_file_group_from_row(row_option.inner, conversation) : null; + } + + public FileTransferGroup get_file_group_by_message_id(int id, Conversation conversation) { + FileTransferGroup? file_group = file_group_by_message_id[id]; + if (file_group != null) { + return file_group; + } + + foreach (Row row in db.file_transfer_group.select().with(db.file_transfer_group.message_id, "=", id)) { + return create_file_group_from_row(row, conversation); + } + + return null; + } + public FileTransfer get_files_by_message_and_file_id(int message_id, string file_sharing_id, Conversation conversation) { string combined_identifier = message_id.to_string() + file_sharing_id; FileTransfer? file_transfer = files_by_message_and_file_id[combined_identifier]; @@ -79,13 +110,13 @@ namespace Dino { return null; } - private FileTransfer? create_file_from_row_opt(RowOption row_opt, Conversation conversation) { + private FileTransfer? create_file_from_row_opt(RowOption row_opt, Conversation? conversation) { if (!row_opt.is_present()) return null; try { FileTransfer file_transfer = new FileTransfer.from_row(db, row_opt.inner, FileManager.get_storage_dir()); - if (conversation.type_.is_muc_semantic()) { + if (conversation != null && conversation.type_.is_muc_semantic()) { file_transfer.ourpart = conversation.counterpart.with_resource(file_transfer.ourpart.resourcepart); } @@ -97,6 +128,21 @@ namespace Dino { return null; } + private FileTransferGroup? create_file_group_from_row(Row file_transfer_group_row, Conversation conversation) { + QueryBuilder query = db.file_transfer_group_file_transfer.select() + .with(db.file_transfer_group_file_transfer.file_transfer_group_id, "=", file_transfer_group_row[db.file_transfer_group.id]); + var file_transfers = new ArrayList(); + foreach (Qlite.Row row in query) { + FileTransfer file_transfer = get_file_by_id(row[db.file_transfer_group_file_transfer.file_transfer_id], conversation); + file_transfers.add(file_transfer); + } + if (file_transfers.size == 0) return null; + + FileTransferGroup file_group = new FileTransferGroup.from_row(db, file_transfer_group_row, file_transfers); + cache_file_group(file_group); + return file_group; + } + private void cache_file(FileTransfer file_transfer) { files_by_db_id[file_transfer.id] = file_transfer; @@ -109,5 +155,10 @@ namespace Dino { } } } + + private void cache_file_group(FileTransferGroup file_group) { + file_group_by_db_id[file_group.id] = file_group; +// file_group_by_message_id[file_group.message_id] = file_group; + } } } \ No newline at end of file diff --git a/libdino/src/service/stateless_file_sharing.vala b/libdino/src/service/stateless_file_sharing.vala index 15e1ddfe..6e97a5ce 100644 --- a/libdino/src/service/stateless_file_sharing.vala +++ b/libdino/src/service/stateless_file_sharing.vala @@ -16,11 +16,16 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { private set { } } - public FileManager file_manager { + public FileManager fm { owned get { return stream_interactor.get_module(FileManager.IDENTITY); } private set { } } + public FileManager2 fm2 { + owned get { return stream_interactor.get_module(FileManager2.IDENTITY); } + private set { } + } + public Database db { owned get { return Application.get_default().db; } private set { } @@ -30,7 +35,7 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { this.stream_interactor = stream_interactor; this.db = db; - stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(new ReceivedMessageListener(this)); + stream_interactor.get_module(MessageProcessor.IDENTITY).build_message_stanza.connect(check_add_sfs_element); } public static void start(StreamInteractor stream_interactor, Database db) { @@ -38,7 +43,81 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { stream_interactor.add_module(m); } - public async void create_file_transfer(Conversation conversation, Message message, string? file_sharing_id, Xep.FileMetadataElement.FileMetadata metadata, Gee.List? sources) { + public async Entities.Message announce_files(FileTransferGroup file_group, Conversation conversation) { + Entities.Message file_share_message = stream_interactor.get_module(MessageProcessor.IDENTITY).create_out_message(null, conversation); + stream_interactor.get_module(MessageStorage.IDENTITY).add_message(file_share_message, conversation); + file_group.message_id = file_share_message.id; + + foreach (var file_transfer in file_group.file_transfers) { + file_transfer.provider = SFS_PROVIDER_ID; + file_transfer.info = file_share_message.id.to_string(); + file_transfer.file_sharing_id = Xmpp.random_uuid(); + } + + stream_interactor.get_module(MessageProcessor.IDENTITY).send_xmpp_message(file_share_message, conversation); + + return file_share_message; + } + + public async void attach_source(FileTransfer file_transfer, Conversation conversation, string http_url, string to_sfs_id) { + MessageStanza stanza = new MessageStanza() { to = conversation.counterpart, type_ = conversation.type_ == GROUPCHAT ? MessageStanza.TYPE_GROUPCHAT : MessageStanza.TYPE_CHAT }; + stanza.body = http_url; + Xep.OutOfBandData.add_url_to_message(stanza, http_url); + var sources = new ArrayList(); + sources.add(new Xep.StatelessFileSharing.HttpSource() { url = http_url }); + Xep.StatelessFileSharing.set_sfs_attachment(stanza, to_sfs_id, file_transfer.file_sharing_id, sources); + + var stream = stream_interactor.get_stream(conversation.account); + if (stream == null) throw new FileSendError.UPLOAD_FAILED("No stream"); + + stream.get_module(MessageModule.IDENTITY).send_message.begin(stream, stanza); + } + + public async bool try_process_sfs(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { + Gee.List file_shares = Xep.StatelessFileSharing.get_file_shares(stanza); + if (file_shares != null) { + // For now, only accept file shares that have at least one supported hash + foreach (Xep.StatelessFileSharing.FileShare file_share in file_shares) { + if (!Xep.CryptographicHashes.has_supported_hashes(file_share.metadata.hashes)) { + return false; + } + } + + if (file_shares.size > 0) { + var file_transfers = new ArrayList(); + foreach (Xep.StatelessFileSharing.FileShare file_share in file_shares) { + var file_transfer = yield create_incoming_file_transfer(conversation, message, file_share.id, file_share.metadata, file_share.sources); + file_transfers.add(file_transfer); + stream_interactor.get_module(FileTransferStorage.IDENTITY).add_file(file_transfer); + } + var file_group = new FileTransferGroup() { + message_id = message.id, + file_transfers = file_transfers + }; + stream_interactor.get_module(FileTransferStorage.IDENTITY).add_file_group(file_group); + + fm2.received_file_group(file_group, conversation); + } + return true; + } + + var source_attachments = Xep.StatelessFileSharing.get_source_attachments(stanza); + if (source_attachments != null) { + foreach (var source_attachment in source_attachments) { + on_received_sources(stanza.from, conversation, source_attachment.to_message_id, source_attachment.to_file_transfer_id, source_attachment.sources); + return true; + } + } + + // Don't process messages that are fallback for legacy clients + if (Xep.StatelessFileSharing.is_sfs_fallback_message(stanza)) { + return true; + } + + return false; + } + + public async FileTransfer create_incoming_file_transfer(Conversation conversation, Message message, string? file_sharing_id, Xep.FileMetadataElement.FileMetadata metadata, Gee.List? sources) { FileTransfer file_transfer = new FileTransfer(); file_transfer.file_sharing_id = file_sharing_id; file_transfer.account = message.account; @@ -57,7 +136,8 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { stream_interactor.get_module(FileTransferStorage.IDENTITY).add_file(file_transfer); conversation.last_active = file_transfer.time; - file_manager.received_file(file_transfer, conversation); + + return file_transfer; } public void on_received_sources(Jid from, Conversation conversation, string attach_to_message_id, string? attach_to_file_id, Gee.List sources) { @@ -74,9 +154,9 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { // "If no is provided or the elements provided use unsupported algorithms, receiving clients MUST ignore // any attached sources from other senders and only obtain the file from the sources announced by the original sender." - // For now we only allow the original sender - if (from.equals(file_transfer.from) && Xep.CryptographicHashes.get_supported_hashes(file_transfer.hashes).is_empty) { - warning("Ignoring sfs source: Not from original sender or no known file hashes"); + // For now we don't allow source attachments for file shares without hashes. TODO extend this + if (Xep.CryptographicHashes.get_supported_hashes(file_transfer.hashes).is_empty) { + warning("Ignoring sfs source: No known file hashes"); return; } @@ -84,85 +164,26 @@ public class Dino.StatelessFileSharing : StreamInteractionModule, Object { file_transfer.add_sfs_source(source); } - if (file_manager.is_sender_trustworthy(file_transfer, conversation) && file_transfer.state == FileTransfer.State.NOT_STARTED && file_transfer.size >= 0 && file_transfer.size < 5000000) { - file_manager.download_file(file_transfer); + if (fm2.is_sender_trustworthy(file_transfer, conversation) && file_transfer.state == FileTransfer.State.NOT_STARTED && file_transfer.size >= 0 && file_transfer.size < 5000000) { + fm.download_file(file_transfer); } } - /* - public async void create_sfs_for_legacy_transfer(FileProvider file_provider, string info, Jid from, DateTime time, DateTime local_time, Conversation conversation, FileReceiveData receive_data, FileMeta file_meta) { - FileTransfer file_transfer = file_manager.create_file_transfer_from_provider_incoming(file_provider, info, from, time, local_time, conversation, receive_data, file_meta); - - HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData; - if (http_receive_data == null) return; + private void check_add_sfs_element(Entities.Message message, Xmpp.MessageStanza message_stanza, Conversation conversation) { + if (message.encryption != Encryption.NONE) return; - var sources = new ArrayList(); - Xep.StatelessFileSharing.HttpSource source = new Xep.StatelessFileSharing.HttpSource(); - source.url = http_receive_data.url; - sources.add(source); - - if (file_manager.is_jid_trustworthy(from, conversation)) { - try { - file_meta = yield file_provider.get_meta_info(file_transfer, http_receive_data, file_meta); - } catch (Error e) { - warning("Http meta request failed: %s", e.message); + // Check if it's a FileTransferGroup + FileTransferGroup? file_group = stream_interactor.get_module(FileTransferStorage.IDENTITY).get_file_group_by_message_id(message.id, conversation); + if (file_group != null) { + print("check added file group\n"); + foreach (FileTransfer file_transfer in file_group.file_transfers) { + Xep.StatelessFileSharing.set_sfs_element(message_stanza, file_transfer.file_sharing_id, file_transfer.file_metadata, file_transfer.sfs_sources); } - } - - var metadata = new Xep.FileMetadataElement.FileMetadata(); - metadata.size = file_meta.size; - metadata.name = file_meta.file_name; - metadata.mime_type = file_meta.mime_type; - file_transfer.provider = SFS_PROVIDER_ID; - file_transfer.file_metadata = metadata; - file_transfer.sfs_sources = sources; - } - */ - - private class ReceivedMessageListener : MessageListener { + Xep.MessageProcessingHints.set_message_hint(message_stanza, Xep.MessageProcessingHints.HINT_STORE); - public string[] after_actions_const = new string[]{ "STORE" }; - public override string action_group { get { return "MESSAGE_REINTERPRETING"; } } - public override string[] after_actions { get { return after_actions_const; } } - - private StatelessFileSharing outer; - private StreamInteractor stream_interactor; - - public ReceivedMessageListener(StatelessFileSharing outer) { - this.outer = outer; - this.stream_interactor = outer.stream_interactor; + return; } - public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { - Gee.List file_shares = Xep.StatelessFileSharing.get_file_shares(stanza); - if (file_shares != null) { - // For now, only accept file shares that have at least one supported hash - foreach (Xep.StatelessFileSharing.FileShare file_share in file_shares) { - if (!Xep.CryptographicHashes.has_supported_hashes(file_share.metadata.hashes)) { - return false; - } - } - foreach (Xep.StatelessFileSharing.FileShare file_share in file_shares) { - outer.create_file_transfer(conversation, message, file_share.id, file_share.metadata, file_share.sources); - } - return true; - } - - var source_attachments = Xep.StatelessFileSharing.get_source_attachments(stanza); - if (source_attachments != null) { - foreach (var source_attachment in source_attachments) { - outer.on_received_sources(stanza.from, conversation, source_attachment.to_message_id, source_attachment.to_file_transfer_id, source_attachment.sources); - return true; - } - } - - // Don't process messages that are fallback for legacy clients - if (Xep.StatelessFileSharing.is_sfs_fallback_message(stanza)) { - return true; - } - - return false; - } } } \ No newline at end of file -- cgit v1.3 From deea3cae8e848388ee962a92de58dc42b77915d1 Mon Sep 17 00:00:00 2001 From: fiaxh Date: Sat, 22 Aug 2026 21:02:05 +0200 Subject: Store MUC features only in EntityInfo (not in MucFlag), update on change --- libdino/meson.build | 1 - .../src/service/entity_capabilities_storage.vala | 71 ---------------------- libdino/src/service/entity_info.vala | 31 +++++++--- libdino/src/service/message_processor.vala | 8 +-- libdino/src/service/module_manager.vala | 1 + libdino/src/service/muc_manager.vala | 49 +++++++-------- xmpp-vala/src/module/xep/0045_muc/flag.vala | 17 ------ xmpp-vala/src/module/xep/0045_muc/module.vala | 71 +++------------------- .../src/module/xep/0115_entity_capabilities.vala | 5 -- 9 files changed, 57 insertions(+), 197 deletions(-) delete mode 100644 libdino/src/service/entity_capabilities_storage.vala (limited to 'libdino/src/service') diff --git a/libdino/meson.build b/libdino/meson.build index bf29dbf9..12665b18 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -55,7 +55,6 @@ sources = files( 'src/service/conversation_manager.vala', 'src/service/counterpart_interaction_manager.vala', 'src/service/database.vala', - 'src/service/entity_capabilities_storage.vala', 'src/service/entity_info.vala', 'src/service/fallback_body.vala', 'src/service/file_manager.vala', diff --git a/libdino/src/service/entity_capabilities_storage.vala b/libdino/src/service/entity_capabilities_storage.vala deleted file mode 100644 index c6d0bbbd..00000000 --- a/libdino/src/service/entity_capabilities_storage.vala +++ /dev/null @@ -1,71 +0,0 @@ -using Gee; -using Qlite; -using Xmpp; -using Xmpp.Xep.ServiceDiscovery; - -namespace Dino { - -public class EntityCapabilitiesStorage : Xep.EntityCapabilities.Storage, Object { - - private Database db; - private HashMap> features_cache = new HashMap>(); - private HashMap identity_cache = new HashMap(); - - public EntityCapabilitiesStorage(Database db) { - this.db = db; - } - - public void store_features(string entity, Gee.List features) { - if (features_cache.has_key(entity)) return; - - foreach (string feature in features) { - db.entity_feature.insert() - .value(db.entity_feature.entity, entity) - .value(db.entity_feature.feature, feature) - .perform(); - } - } - - public void store_identities(string entity, Gee.Set identities) { - foreach (Identity identity in identities) { - if (identity.category == Identity.CATEGORY_CLIENT) { - db.entity_identity.insert() - .value(db.entity_identity.entity, entity) - .value(db.entity_identity.category, identity.category) - .value(db.entity_identity.type, identity.type_) - .value(db.entity_identity.entity_name, identity.name) - .perform(); - return; - } - } - } - - public Gee.List get_features(string entity) { - Gee.List? features = features_cache[entity]; - if (features != null) { - return features; - } - - features = new ArrayList(); - foreach (Row row in db.entity_feature.select({db.entity_feature.feature}).with(db.entity_feature.entity, "=", entity)) { - features.add(row[db.entity_feature.feature]); - } - features_cache[entity] = features; - return features; - } - - public Identity? get_identities(string entity) { - Identity? identity = identity_cache[entity]; - if (identity != null) { - return identity; - } - - RowOption row = db.entity_identity.select().with(db.entity_identity.entity, "=", entity).single().row(); - if (row.is_present()) { - identity = new Identity(row[db.entity_identity.category], row[db.entity_identity.type], row[db.entity_identity.entity_name]); - } - identity_cache[entity] = identity; - return identity; - } -} -} diff --git a/libdino/src/service/entity_info.vala b/libdino/src/service/entity_info.vala index 53d14b15..03828d1d 100644 --- a/libdino/src/service/entity_info.vala +++ b/libdino/src/service/entity_info.vala @@ -12,7 +12,6 @@ public class EntityInfo : StreamInteractionModule, Object { private StreamInteractor stream_interactor; private Database db; - private EntityCapabilitiesStorage entity_capabilities_storage; private Dino.Entities.Settings settings; private HashMap entity_caps_hashes = new HashMap(Jid.hash_func, Jid.equals_func); @@ -40,7 +39,6 @@ public class EntityInfo : StreamInteractionModule, Object { private EntityInfo(StreamInteractor stream_interactor, Database db, Dino.Entities.Settings settings) { this.stream_interactor = stream_interactor; this.db = db; - this.entity_capabilities_storage = new EntityCapabilitiesStorage(db); this.settings = settings; stream_interactor.account_added.connect(on_account_added); @@ -58,18 +56,32 @@ public class EntityInfo : StreamInteractionModule, Object { Timeout.add_seconds(60 * 60, () => { remove_old_entities(); return true; }); } - public async Gee.Set? get_identities(Account account, Jid jid) { + public Gee.Set? get_identities_offline(Account account, Jid jid) { if (jid_identity.has_key(jid)) { return jid_identity[jid]; } - string? hash = entity_caps_hashes[jid]; - if (hash != null) { - Gee.Set? identities = get_stored_identities(hash); - if (identities != null) return identities; + var qry = db.entity.select() + .with(db.entity.account_id, "=", account.id) + .with(db.entity.jid_id, "=", db.get_jid_id(jid)) + .with(db.entity.resource, "=", jid.resourcepart ?? "") + .join_with(db.entity_identity, db.entity.caps_hash, db.entity_identity.entity); + + HashSet identities = new HashSet(Identity.hash_func, Identity.equals_func); + + foreach (Row row in qry) { + var identity = new Identity(row[db.entity_identity.category], row[db.entity_identity.type], row[db.entity_identity.entity_name]); + identities.add(identity); } - ServiceDiscovery.InfoResult? info_result = yield get_info_result(account, jid, hash); + return identities; + } + + public async Gee.Set? get_identities(Account account, Jid jid) { + var identities = get_identities_offline(account, jid); + if (identities != null) return identities; + + ServiceDiscovery.InfoResult? info_result = yield get_info_result(account, jid, entity_caps_hashes[jid]); if (info_result != null) { return info_result.identities; } @@ -261,7 +273,7 @@ public class EntityInfo : StreamInteractionModule, Object { return identities; } - private async ServiceDiscovery.InfoResult? get_info_result(Account account, Jid jid, string? hash = null) { + public async ServiceDiscovery.InfoResult? get_info_result(Account account, Jid jid, string? hash = null) { XmppStream? stream = stream_interactor.get_stream(account); if (stream == null) return null; @@ -298,7 +310,6 @@ public class EntityInfo : StreamInteractionModule, Object { } private void initialize_modules(Account account, ArrayList modules) { - modules.add(new Xep.EntityCapabilities.Module(entity_capabilities_storage)); var entity_time_module = modules.first_match((it) => it is EntityTime.Module) as EntityTime.Module; if (entity_time_module != null) { settings.bind_property("share-time", entity_time_module, "enabled", BindingFlags.SYNC_CREATE); diff --git a/libdino/src/service/message_processor.vala b/libdino/src/service/message_processor.vala index b9c23240..9190cd9d 100644 --- a/libdino/src/service/message_processor.vala +++ b/libdino/src/service/message_processor.vala @@ -472,12 +472,8 @@ public class MessageProcessor : StreamInteractionModule, Object { // Set an origin ID if a MUC doen't guarantee to keep IDs if (conversation.type_ == Conversation.Type.GROUPCHAT) { - Xep.Muc.Flag? flag = stream.get_flag(Xep.Muc.Flag.IDENTITY); - if (flag == null) { - message.marked = Entities.Message.Marked.UNSENT; - return; - } - if(!flag.has_room_feature(conversation.counterpart, Xep.Muc.Feature.STABLE_ID)) { + var supports_stable_ids = stream_interactor.get_module(EntityInfo.IDENTITY).has_feature_cached(conversation.account, conversation.counterpart, Xep.Muc.FEATURE_STABLE_ID); + if(!supports_stable_ids) { UniqueStableStanzaIDs.set_origin_id(new_message, message.stanza_id); } } diff --git a/libdino/src/service/module_manager.vala b/libdino/src/service/module_manager.vala index 5ba4fe80..f7cad0fe 100644 --- a/libdino/src/service/module_manager.vala +++ b/libdino/src/service/module_manager.vala @@ -69,6 +69,7 @@ public class ModuleManager { module_map[account].add(new Presence.Module()); module_map[account].add(new Xmpp.MessageModule()); module_map[account].add(new Xmpp.MessageArchiveManagement.Module()); + module_map[account].add(new Xep.EntityCapabilities.Module()); module_map[account].add(new Xep.MessageCarbons.Module()); module_map[account].add(new Xep.BitsOfBinary.Module()); module_map[account].add(new Xep.Muc.Module()); diff --git a/libdino/src/service/muc_manager.vala b/libdino/src/service/muc_manager.vala index b47a52bf..4959074b 100644 --- a/libdino/src/service/muc_manager.vala +++ b/libdino/src/service/muc_manager.vala @@ -108,19 +108,11 @@ public class MucManager : StreamInteractionModule, Object { joined_conversation.nickname = nick; stream_interactor.get_module(ConversationManager.IDENTITY).start_conversation(joined_conversation); - bool can_do_affiliation_versioning = yield entity_info.has_feature(account, jid, Xmpp.Xep.MucAffiliationsVersioning.NS_URI); - if (!can_do_affiliation_versioning) { - stream.get_module(Xep.Muc.Module.IDENTITY).fetch_affiliations.begin(stream, jid.bare_jid, () => { - muc_affiliations.clear_affiliations(account, jid); - persist_muc_affiliations(account, jid.bare_jid); - }); - } - if (can_do_mam) { var history_sync = stream_interactor.get_module(MessageProcessor.IDENTITY).history_sync; if (conversation == null) { // We never joined the conversation before, just fetch the latest MAM page - yield history_sync.fetch_latest_page(account, jid.bare_jid, null, new DateTime.from_unix_utc(0), cancellable); + history_sync.fetch_latest_page.begin(account, jid.bare_jid, null, new DateTime.from_unix_utc(0), cancellable); } else { // Fetch everything up to the last time the user actively joined if (!mucs_sync_cancellables.has_key(account)) { @@ -137,6 +129,17 @@ public class MucManager : StreamInteractionModule, Object { } } } + + bool can_do_affiliation_versioning = yield entity_info.has_feature(account, jid, Xmpp.Xep.MucAffiliationsVersioning.NS_URI); + if (!can_do_affiliation_versioning) { + stream.get_module(Xep.Muc.Module.IDENTITY).fetch_affiliations.begin(stream, jid.bare_jid, () => { + muc_affiliations.clear_affiliations(account, jid); + persist_muc_affiliations(account, jid.bare_jid); + }); + } + + room_info_updated(account, jid); // EntityInfo.has_feature trigged a disco query + } else if (res.muc_error != null) { // Join failed enter_errors[jid] = res.muc_error; @@ -254,19 +257,11 @@ public class MucManager : StreamInteractionModule, Object { //the term `private room` is a short hand for members-only+non-anonymous rooms public bool is_private_room(Account account, Jid jid) { var entity_info = stream_interactor.get_module(EntityInfo.IDENTITY); - return entity_info.has_feature_offline(account, jid, "muc_membersonly") && entity_info.has_feature_offline(account, jid, "muc_nonanonymous"); + return entity_info.has_feature_offline(account, jid, Xep.Muc.FEATURE_MEMBERS_ONLY) && entity_info.has_feature_offline(account, jid, Xep.Muc.FEATURE_NON_ANONYMOUS); } public bool is_moderated_room(Account account, Jid jid) { - XmppStream? stream = stream_interactor.get_stream(account); - if (stream == null) { - return false; - } - Xep.Muc.Flag? flag = stream.get_flag(Xep.Muc.Flag.IDENTITY); - if (flag == null) { - return false; - } - return flag.has_room_feature(jid, Xep.Muc.Feature.MODERATED); + return stream_interactor.get_module(EntityInfo.IDENTITY).has_feature_cached(account, jid, Xep.Muc.FEATURE_MODERATED); } public bool is_public_room(Account account, Jid jid) { @@ -332,9 +327,13 @@ public class MucManager : StreamInteractionModule, Object { } public string? get_room_name(Account account, Jid jid) { - Xep.Muc.Flag? flag = get_muc_flag(account); - if (flag != null) { - return flag.get_room_name(jid); + var identities = stream_interactor.get_module(EntityInfo.IDENTITY).get_identities_offline(account, jid); + if (identities == null) return null; + + foreach (var identity in identities) { + if (identity.category == "conference") { + return identity.name; + } } return null; } @@ -471,8 +470,10 @@ public class MucManager : StreamInteractionModule, Object { private_room_occupants_updated(account, muc_jid); } }); - stream_interactor.module_manager.get_module(account, Xep.Muc.Module.IDENTITY).room_info_updated.connect( (stream, muc_jid) => { - room_info_updated(account, muc_jid); + stream_interactor.module_manager.get_module(account, Xep.Muc.Module.IDENTITY).room_info_changed.connect( (stream, muc_jid) => { + stream_interactor.get_module(EntityInfo.IDENTITY).get_info_result.begin(account, muc_jid, null, () => { + room_info_updated(account, muc_jid); + }); }); stream_interactor.module_manager.get_module(account, Xep.OccupantIds.Module.IDENTITY).received_own_occupant_id.connect( (stream, jid, occupant_id) => { if (!own_occupant_ids.has_key(account)) { diff --git a/xmpp-vala/src/module/xep/0045_muc/flag.vala b/xmpp-vala/src/module/xep/0045_muc/flag.vala index d0d2c359..a72965b3 100644 --- a/xmpp-vala/src/module/xep/0045_muc/flag.vala +++ b/xmpp-vala/src/module/xep/0045_muc/flag.vala @@ -5,9 +5,6 @@ namespace Xmpp.Xep.Muc { public class Flag : XmppStreamFlag { public static FlagIdentity IDENTITY = new FlagIdentity(NS_URI, "muc"); - private HashMap> room_features = new HashMap>(Jid.hash_bare_func, Jid.equals_bare_func); - private HashMap room_names = new HashMap(Jid.hash_bare_func, Jid.equals_bare_func); - private HashMap enter_ids = new HashMap(Jid.hash_bare_func, Jid.equals_bare_func); public HashMap> enter_futures = new HashMap>(Jid.hash_func, Jid.equals_func); private HashMap own_nicks = new HashMap(Jid.hash_bare_func, Jid.equals_bare_func); @@ -18,12 +15,6 @@ public class Flag : XmppStreamFlag { private HashMap> affiliations = new HashMap>(Jid.hash_bare_func, Jid.equals_bare_func); private HashMap occupant_role = new HashMap(Jid.hash_func, Jid.equals_func); - public string? get_room_name(Jid muc_jid) { return room_names.has_key(muc_jid.bare_jid) ? room_names[muc_jid.bare_jid] : null; } - - public bool has_room_feature(Jid muc_jid, Feature feature) { - return room_features.has_key(muc_jid.bare_jid) && room_features[muc_jid.bare_jid].contains(feature); - } - public Jid? get_real_jid(Jid full_jid) { return occupant_real_jids[full_jid]; } public Jid? get_occupant_jid(Jid real_jid, Jid room) { @@ -77,14 +68,6 @@ public class Flag : XmppStreamFlag { public string? get_muc_subject(Jid muc_jid) { return subjects[muc_jid.bare_jid]; } - internal void set_room_name(Jid muc_jid, string name) { - room_names[muc_jid.bare_jid] = name; - } - - internal void set_room_features(Jid muc_jid, Gee.List features) { - room_features[muc_jid.bare_jid] = features; - } - internal void set_real_jid(Jid full_jid, Jid real_jid) { occupant_real_jids[full_jid] = real_jid; } internal void set_offline_member(Jid muc_jid, Jid real_jid, Affiliation affiliation) { diff --git a/xmpp-vala/src/module/xep/0045_muc/module.vala b/xmpp-vala/src/module/xep/0045_muc/module.vala index ad929b00..76045172 100644 --- a/xmpp-vala/src/module/xep/0045_muc/module.vala +++ b/xmpp-vala/src/module/xep/0045_muc/module.vala @@ -8,6 +8,12 @@ private const string NS_URI_OWNER = NS_URI + "#owner"; public const string NS_URI_USER = NS_URI + "#user"; private const string NS_URI_REQUEST = NS_URI + "#request"; +public const string FEATURE_STABLE_ID = "http://jabber.org/protocol/muc#stable_id"; +public const string FEATURE_MEMBERS_ONLY = "muc_membersonly"; +public const string FEATURE_MODERATED = "muc_moderated"; +public const string FEATURE_NON_ANONYMOUS = "muc_nonanonymous"; +public const string FEATURE_PASSWORD_PROTECTED = "muc_passwordprotected"; + public enum MucEnterError { PASSWORD_REQUIRED, BANNED, @@ -34,26 +40,6 @@ public enum Role { VISITOR } -public enum Feature { - REGISTER, - ROOMCONFIG, - ROOMINFO, - HIDDEN, - MEMBERS_ONLY, - MODERATED, - NON_ANONYMOUS, - OPEN, - PASSWORD_PROTECTED, - PERSISTENT, - PUBLIC, - ROOMS, - SEMI_ANONYMOUS, - STABLE_ID, - TEMPORARY, - UNMODERATED, - UNSECURED -} - public static void add_muc_pm_message_stanza_x_node(MessageStanza message_stanza) { StanzaNode x_node = new StanzaNode.build("x", "http://jabber.org/protocol/muc#user").add_self_xmlns(); message_stanza.stanza.put_node(x_node); @@ -74,6 +60,7 @@ public class Module : XmppStreamModule { public signal void subject_set(XmppStream stream, string? subject, Jid jid); public signal void invite_received(XmppStream stream, Jid room_jid, Jid from_jid, string? password, string? reason); public signal void voice_request_received(XmppStream stream, Jid room_jid, Jid from_jid, string nick); + public signal void room_info_changed(XmppStream stream, Jid muc_jid); public signal void room_info_updated(XmppStream stream, Jid muc_jid); public signal void self_removed_from_room(XmppStream stream, Jid jid, StatusCode code); @@ -299,7 +286,7 @@ public class Module : XmppStreamModule { if (status_codes.contains(StatusCode.CONFIG_CHANGE_NON_PRIVACY) || status_codes.contains(StatusCode.NON_ANONYMOUS) || status_codes.contains(StatusCode.SEMI_ANONYMOUS)) { - query_room_info.begin(stream, message.from.bare_jid); + room_info_changed(stream, message.from.bare_jid); } } } @@ -358,9 +345,6 @@ public class Module : XmppStreamModule { if (status_codes.contains(StatusCode.SELF_PRESENCE)) { Jid bare_jid = presence.from.bare_jid; if (flag.get_enter_id(bare_jid) != null) { - - query_room_info.begin(stream, bare_jid); - flag.finish_muc_enter(bare_jid); var join_result = new JoinResult() { nick=presence.from.resourcepart, newly_created=status_codes.contains(StatusCode.NEW_ROOM_CREATED) }; flag.enter_futures[bare_jid].set_value(join_result); @@ -430,45 +414,6 @@ public class Module : XmppStreamModule { } } - private async void query_room_info(XmppStream stream, Jid jid) { - ServiceDiscovery.InfoResult? info_result = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).request_info(stream, jid); - if (info_result == null) return; - - Gee.List features = new ArrayList(); - - foreach (ServiceDiscovery.Identity identity in info_result.identities) { - if (identity.category == "conference" && identity.name != null) { - stream.get_flag(Flag.IDENTITY).set_room_name(jid, identity.name); - } - } - - foreach (string feature in info_result.features) { - Feature? parsed = null; - switch (feature) { - case "http://jabber.org/protocol/muc#register": parsed = Feature.REGISTER; break; - case "http://jabber.org/protocol/muc#roomconfig": parsed = Feature.ROOMCONFIG; break; - case "http://jabber.org/protocol/muc#roominfo": parsed = Feature.ROOMINFO; break; - case "http://jabber.org/protocol/muc#stable_id": parsed = Feature.STABLE_ID; break; - case "muc_hidden": parsed = Feature.HIDDEN; break; - case "muc_membersonly": parsed = Feature.MEMBERS_ONLY; break; - case "muc_moderated": parsed = Feature.MODERATED; break; - case "muc_nonanonymous": parsed = Feature.NON_ANONYMOUS; break; - case "muc_open": parsed = Feature.OPEN; break; - case "muc_passwordprotected": parsed = Feature.PASSWORD_PROTECTED; break; - case "muc_persistent": parsed = Feature.PERSISTENT; break; - case "muc_public": parsed = Feature.PUBLIC; break; - case "muc_rooms": parsed = Feature.ROOMS; break; - case "muc_semianonymous": parsed = Feature.SEMI_ANONYMOUS; break; - case "muc_temporary": parsed = Feature.TEMPORARY; break; - case "muc_unmoderated": parsed = Feature.UNMODERATED; break; - case "muc_unsecured": parsed = Feature.UNSECURED; break; - } - if (parsed != null) features.add(parsed); - } - stream.get_flag(Flag.IDENTITY).set_room_features(jid, features); - room_info_updated(stream, jid); - } - public async void fetch_affiliations(XmppStream stream, Jid muc_jid) { query_affiliation.begin(stream, muc_jid, "member"); query_affiliation.begin(stream, muc_jid, "admin"); diff --git a/xmpp-vala/src/module/xep/0115_entity_capabilities.vala b/xmpp-vala/src/module/xep/0115_entity_capabilities.vala index 8e15e0c2..e39dcbbd 100644 --- a/xmpp-vala/src/module/xep/0115_entity_capabilities.vala +++ b/xmpp-vala/src/module/xep/0115_entity_capabilities.vala @@ -35,11 +35,6 @@ namespace Xmpp.Xep.EntityCapabilities { public static ModuleIdentity IDENTITY = new ModuleIdentity(NS_URI, "0115_entity_capabilities"); private string own_ver_hash; - private Storage storage; - - public Module(Storage storage) { - this.storage = storage; - } private string get_own_hash(XmppStream stream) { if (own_ver_hash == null) { -- cgit v1.3 From 98ef191bfb3cc5694b9d1001e46a9b00abbd7195 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sun, 23 Aug 2026 19:32:25 +0200 Subject: Move qlite into libdino --- libdino/dino.deps | 2 +- libdino/meson.build | 12 +- libdino/src/qlite/column.vala | 190 ++++++++++++++++ libdino/src/qlite/database.vala | 163 ++++++++++++++ libdino/src/qlite/delete_builder.vala | 62 ++++++ libdino/src/qlite/insert_builder.vala | 84 ++++++++ libdino/src/qlite/query_builder.vala | 238 +++++++++++++++++++++ libdino/src/qlite/row.vala | 147 +++++++++++++ libdino/src/qlite/statement_builder.vala | 58 +++++ libdino/src/qlite/table.vala | 218 +++++++++++++++++++ libdino/src/qlite/update_builder.vala | 103 +++++++++ libdino/src/qlite/upsert_builder.vala | 93 ++++++++ libdino/src/service/avatar_manager.vala | 4 +- libdino/src/service/call_store.vala | 2 +- libdino/src/service/contact_model.vala | 1 - libdino/src/service/content_item_store.vala | 2 +- libdino/src/service/database.vala | 2 +- libdino/src/service/entity_info.vala | 2 +- libdino/src/service/fallback_body.vala | 1 - libdino/src/service/file_transfer_storage.vala | 2 +- libdino/src/service/history_sync.vala | 2 +- libdino/src/service/message_correction.vala | 2 +- libdino/src/service/message_deletion.vala | 1 - libdino/src/service/message_processor.vala | 2 +- libdino/src/service/message_storage.vala | 2 +- libdino/src/service/occupant_id_store.vala | 2 +- libdino/src/service/reactions.vala | 4 +- libdino/src/service/replies.vala | 2 +- libdino/src/service/search_processor.vala | 4 +- libdino/src/service/util.vala | 1 - main/meson.build | 1 - meson.build | 1 - plugins/ice/meson.build | 1 - plugins/notification-sound/meson.build | 1 - plugins/omemo/meson.build | 1 - plugins/omemo/src/logic/database.vala | 2 +- plugins/omemo/src/logic/decrypt.vala | 5 +- plugins/omemo/src/logic/manager.vala | 5 +- plugins/omemo/src/logic/pre_key_store.vala | 2 +- plugins/omemo/src/logic/session_store.vala | 2 +- plugins/omemo/src/logic/signed_pre_key_store.vala | 2 +- plugins/omemo/src/logic/trust_manager.vala | 7 +- plugins/omemo/src/ui/bad_messages_populator.vala | 2 +- plugins/omemo/src/ui/call_encryption_entry.vala | 5 +- plugins/omemo/src/ui/contact_details_provider.vala | 1 - plugins/omemo/src/ui/encryption_list_entry.vala | 5 +- .../omemo/src/ui/encryption_preferences_entry.vala | 9 +- plugins/omemo/src/ui/manage_key_dialog.vala | 3 +- plugins/openpgp/meson.build | 1 - plugins/openpgp/src/database.vala | 3 +- plugins/rtp/meson.build | 1 - qlite/meson.build | 27 --- qlite/qlite.deps | 3 - qlite/src/column.vala | 190 ---------------- qlite/src/database.vala | 163 -------------- qlite/src/delete_builder.vala | 62 ------ qlite/src/insert_builder.vala | 84 -------- qlite/src/query_builder.vala | 238 --------------------- qlite/src/row.vala | 147 ------------- qlite/src/statement_builder.vala | 58 ----- qlite/src/table.vala | 218 ------------------- qlite/src/update_builder.vala | 103 --------- qlite/src/upsert_builder.vala | 93 -------- 63 files changed, 1414 insertions(+), 1440 deletions(-) create mode 100644 libdino/src/qlite/column.vala create mode 100644 libdino/src/qlite/database.vala create mode 100644 libdino/src/qlite/delete_builder.vala create mode 100644 libdino/src/qlite/insert_builder.vala create mode 100644 libdino/src/qlite/query_builder.vala create mode 100644 libdino/src/qlite/row.vala create mode 100644 libdino/src/qlite/statement_builder.vala create mode 100644 libdino/src/qlite/table.vala create mode 100644 libdino/src/qlite/update_builder.vala create mode 100644 libdino/src/qlite/upsert_builder.vala delete mode 100644 qlite/meson.build delete mode 100644 qlite/qlite.deps delete mode 100644 qlite/src/column.vala delete mode 100644 qlite/src/database.vala delete mode 100644 qlite/src/delete_builder.vala delete mode 100644 qlite/src/insert_builder.vala delete mode 100644 qlite/src/query_builder.vala delete mode 100644 qlite/src/row.vala delete mode 100644 qlite/src/statement_builder.vala delete mode 100644 qlite/src/table.vala delete mode 100644 qlite/src/update_builder.vala delete mode 100644 qlite/src/upsert_builder.vala (limited to 'libdino/src/service') diff --git a/libdino/dino.deps b/libdino/dino.deps index bef3fb2a..b14c7d54 100644 --- a/libdino/dino.deps +++ b/libdino/dino.deps @@ -2,5 +2,5 @@ gee-0.8 gio-2.0 glib-2.0 gmodule-2.0 -qlite +sqlite3 xmpp-vala diff --git a/libdino/meson.build b/libdino/meson.build index dbaddf56..5c7c20c4 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -9,7 +9,7 @@ dependencies = [ dep_gmodule, dep_libsoup, dep_libsrtp2, - dep_qlite, + dep_sqlite3, dep_xmpp_vala ] sources = files( @@ -34,6 +34,16 @@ sources = files( 'src/plugin/interfaces.vala', 'src/plugin/loader.vala', 'src/plugin/registry.vala', + 'src/qlite/column.vala', + 'src/qlite/database.vala', + 'src/qlite/delete_builder.vala', + 'src/qlite/insert_builder.vala', + 'src/qlite/query_builder.vala', + 'src/qlite/row.vala', + 'src/qlite/statement_builder.vala', + 'src/qlite/table.vala', + 'src/qlite/update_builder.vala', + 'src/qlite/upsert_builder.vala', 'src/service/avatar_manager.vala', 'src/service/blocking_manager.vala', 'src/service/call_store.vala', diff --git a/libdino/src/qlite/column.vala b/libdino/src/qlite/column.vala new file mode 100644 index 00000000..8f45307f --- /dev/null +++ b/libdino/src/qlite/column.vala @@ -0,0 +1,190 @@ +using Sqlite; + +namespace Dino.Qlite { + +public abstract class Column { + public const string DEFAULT_TABLE_NAME = ""; + + public string name { get; private set; } + public string? default { get; set; } + public int sqlite_type { get; private set; } + public bool primary_key { get; set; } + public bool auto_increment { get; set; } + public bool unique { get; set; } + public virtual bool not_null { get; set; } + public long min_version { get; set; default = -1; } + public long max_version { get; set; default = long.MAX; } + internal Table table { get; set; } + + public abstract T get(Row row, string? table_name = DEFAULT_TABLE_NAME); + + public virtual bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return false; + } + + internal abstract void bind(Statement stmt, int index, T value); + + public string to_string() { + return table == null ? name : (table.name + "." + name); + } + + public string to_column_definition() { + string res = name; + switch (sqlite_type) { + case INTEGER: + res += " INTEGER"; + break; + case FLOAT: + res += " REAL"; + break; + case TEXT: + res += " TEXT"; + break; + default: + res += " UNKNOWN"; + break; + } + if (primary_key) { + res += " PRIMARY KEY"; + if (auto_increment) res += " AUTOINCREMENT"; + } + if (not_null) res += " NOT NULL"; + if (unique) res += " UNIQUE"; + if (default != null) res += @" DEFAULT $((!) default)"; + + return res; + } + + Column(string name, int type) { + this.name = name; + this.sqlite_type = type; + } + + public class Integer : Column { + public Integer(string name) { + base(name, INTEGER); + } + + public override int get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (int) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, int value) { + stmt.bind_int(index, value); + } + } + + public class Long : Column { + public Long(string name) { + base(name, INTEGER); + } + + public override long get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (long) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, long value) { + stmt.bind_int64(index, value); + } + } + + public class NullableReal : Column { + public NullableReal(string name) { + base(name, FLOAT); + } + + public override bool not_null { get { return false; } set {} } + + public override double? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, double? value) { + stmt.bind_double(index, value); + } + } + + public class Text : Column { + public Text(string name) { + base(name, TEXT); + } + + public override string? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return get(row, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == null; + } + + internal override void bind(Statement stmt, int index, string? value) { + if (value != null) { + stmt.bind_text(index, (!) value); + } else { + stmt.bind_null(index); + } + } + } + + public class NonNullText : Column { + public NonNullText(string name) { + base(name, TEXT); + } + + public override bool not_null { get { return true; } set {} } + + public override string get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (!)row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return false; + } + + internal override void bind(Statement stmt, int index, string value) { + stmt.bind_text(index, (!) value); + } + } + + public class BoolText : Column { + public BoolText(string name) { + base(name, TEXT); + } + + public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == "1"; + } + + internal override void bind(Statement stmt, int index, bool value) { + stmt.bind_text(index, value ? "1" : "0"); + } + } + + public class BoolInt : Column { + public BoolInt(string name) { + base(name, INTEGER); + } + + public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == 1; + } + + internal override void bind(Statement stmt, int index, bool value) { + stmt.bind_int(index, value ? 1 : 0); + } + } +} + +} diff --git a/libdino/src/qlite/database.vala b/libdino/src/qlite/database.vala new file mode 100644 index 00000000..e55d5b59 --- /dev/null +++ b/libdino/src/qlite/database.vala @@ -0,0 +1,163 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class Database { + private string file_name; + private Sqlite.Database db; + private long expected_version; + private Table[]? tables; + + private Column meta_name = new Column.Text("name") { primary_key = true }; + private Column meta_int_val = new Column.Long("int_val"); + private Column meta_text_val = new Column.Text("text_val"); + private Table meta_table; + + public bool debug = false; + + public Database(string file_name, long expected_version) { + this.file_name = file_name; + this.expected_version = expected_version; + meta_table = new Table(this, "_meta"); + meta_table.init({meta_name, meta_int_val, meta_text_val}); + } + + public void init(Table[] tables) { + Sqlite.config(Config.SERIALIZED); + int ec = Sqlite.Database.open_v2(file_name, out db, OPEN_READWRITE | OPEN_CREATE | 0x00010000); + if (ec != Sqlite.OK) { + error(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + this.tables = tables; + if (debug) db.trace((message) => print(@"Qlite trace: $message\n")); + start_migration(); + } + + public void ensure_init() { + if (tables == null) error(@"Database $file_name was not initialized, call init()"); + } + + private void start_migration() { + try { + exec("BEGIN TRANSACTION"); + } catch (Error e) { + error("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + meta_table.create_table_at_version(expected_version); + long old_version = 0; + old_version = meta_table.row_with(meta_name, "version")[meta_int_val, -1]; + if (old_version == -1) { + foreach (Table t in tables) { + t.create_table_at_version(expected_version); + } + meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); + } else if (expected_version != old_version) { + foreach (Table t in tables) { + t.create_table_at_version(old_version); + } + foreach (Table t in tables) { + t.add_columns_for_version(old_version, expected_version); + } + migrate(old_version); + foreach (Table t in tables) { + t.delete_columns_for_version(old_version, expected_version); + } + if (old_version == -1) { + meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); + } else { + meta_table.update().with(meta_name, "=", "version").set(meta_int_val, expected_version).perform(); + } + } + foreach (Table t in tables) { + t.post(); + } + try { + exec("END TRANSACTION"); + } catch (Error e) { + error("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + + internal int errcode() { + return db.errcode(); + } + + internal string errmsg() { + return db.errmsg(); + } + + internal int64 last_insert_rowid() { + return db.last_insert_rowid(); + } + + // To be implemented by actual implementation if required + // new table columns are added, outdated columns are still present and will be removed afterwards + public virtual void migrate(long old_version) { + } + + public QueryBuilder select(Column[]? columns = null) { + ensure_init(); + return new QueryBuilder(this).select(columns); + } + + internal MatchQueryBuilder match_query(Table table) { + ensure_init(); + return new MatchQueryBuilder(this, table); + } + + public InsertBuilder insert() { + ensure_init(); + return new InsertBuilder(this); + } + + public UpdateBuilder update(Table table) { + ensure_init(); + return new UpdateBuilder(this, table); + } + + public UpsertBuilder upsert(Table table) { + ensure_init(); + return new UpsertBuilder(this, table); + } + + public UpdateBuilder update_named(string table) { + ensure_init(); + return new UpdateBuilder.for_name(this, table); + } + + public DeleteBuilder delete() { + ensure_init(); + return new DeleteBuilder(this); + } + + public RowIterator query_sql(string sql, string[]? args = null) { + ensure_init(); + return new RowIterator(this, sql, args); + } + + internal Statement prepare(string sql) { + ensure_init(); + Sqlite.Statement statement; + if (db.prepare_v2(sql, sql.length, out statement) != OK) { + error("SQLite error: %d - %s: %s", db.errcode(), db.errmsg(), sql); + } + return statement; + } + + public void exec(string sql) throws Error { + ensure_init(); + if (db.exec(sql) != OK) { + throw new Error(-1, 0, "SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + + public bool is_known_column(string table, string field) { + ensure_init(); + foreach (Table t in tables) { + if (t.is_known_column(field)) return true; + } + return false; + } +} + +} diff --git a/libdino/src/qlite/delete_builder.vala b/libdino/src/qlite/delete_builder.vala new file mode 100644 index 00000000..df63bba6 --- /dev/null +++ b/libdino/src/qlite/delete_builder.vala @@ -0,0 +1,62 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class DeleteBuilder : StatementBuilder { + + // DELETE FROM [...] + private Table? table; + private string table_name; + + // WHERE [...] + private string selection = "1"; + private StatementBuilder.AbstractField[] selection_args = {}; + + internal DeleteBuilder(Database db) { + base(db); + } + + public DeleteBuilder from(Table table) { + if (this.table != null) error("Qlite Error: ILLEGAL QUERY: cannot use from() multiple times."); + this.table = table; + this.table_name = table.name; + return this; + } + + public DeleteBuilder from_name(string table) { + this.table_name = table; + return this; + } + + public DeleteBuilder where(string selection, string[]? selection_args = null) { + if (this.selection != "1") error("selection was already done, but where() was called."); + this.selection = selection; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public DeleteBuilder with(Column column, string comp, T value) { + selection_args += new Field(column, value); + selection = @"($selection) AND $(column.name) $comp ?"; + return this; + } + + internal override Statement prepare() { + Statement stmt = db.prepare(@"DELETE FROM $table_name WHERE $selection"); + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i+1); + } + return stmt; + } + + public void perform() { + if (prepare().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + +} + +} diff --git a/libdino/src/qlite/insert_builder.vala b/libdino/src/qlite/insert_builder.vala new file mode 100644 index 00000000..3383f0e2 --- /dev/null +++ b/libdino/src/qlite/insert_builder.vala @@ -0,0 +1,84 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class InsertBuilder : StatementBuilder { + + // INSERT [OR ...] + private bool replace_val; + private string? or_val; + + // INTO [...] + private Table table; + private string table_name; + + // VALUES [...] + private StatementBuilder.AbstractField[] fields = {}; + + internal InsertBuilder(Database db) { + base(db); + } + + public InsertBuilder replace() { + this.replace_val = true; + return this; + } + + public InsertBuilder or(string or) { + this.or_val = or; + return this; + } + + public InsertBuilder into(Table table) { + this.table = table; + this.table_name = table.name; + return this; + } + + public InsertBuilder into_name(string table) { + this.table_name = table; + return this; + } + + public InsertBuilder value(Column column, T value) { + fields += new Field(column, value); + return this; + } + + public InsertBuilder value_null(Column column) { + if (column.not_null) error("Qlite Error: ILLEGAL QUERY: Can't set non-null column %s to null", column.name); + fields += new NullField(column); + return this; + } + + internal override Statement prepare() { + string fields_text = ""; + string value_qs = ""; + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + value_qs += ", "; + fields_text += ", "; + } + fields_text += ((!)fields[i].column).name; + value_qs += "?"; + } + string sql = replace_val ? "REPLACE" : "INSERT"; + if (!replace_val && or_val != null) sql += @" OR $((!)or_val)"; + sql += @" INTO $table_name ( $fields_text ) VALUES ($value_qs)"; + Statement stmt = db.prepare(sql); + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i+1); + } + return stmt; + } + + public int64 perform() { + if (prepare().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + return db.last_insert_rowid(); + } + +} + +} diff --git a/libdino/src/qlite/query_builder.vala b/libdino/src/qlite/query_builder.vala new file mode 100644 index 00000000..40514fd5 --- /dev/null +++ b/libdino/src/qlite/query_builder.vala @@ -0,0 +1,238 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class QueryBuilder : StatementBuilder { + private bool single_result; + + // SELECT [...] + private string column_selector = "*"; + private Column[] columns = {}; + + // FROM [...] + protected Table? table; + protected string? table_name; + + // JOIN [...] + private string joins = ""; + + // WHERE [...] + protected string selection = "1"; + internal StatementBuilder.AbstractField[] selection_args = {}; + + // ORDER BY [...] + private OrderingTerm[]? order_by_terms = {}; + + // GROUP BY [...] + private string? group_by_term; + + // LIMIT [...] OFFSET [...] + private int limit_val; + private int offset_val; + + internal QueryBuilder(Database db) { + base(db); + } + + public QueryBuilder select(Column[] columns = {}) { + this.columns = columns; + if (columns.length != 0) { + for (int i = 0; i < columns.length; i++) { + if (column_selector == "*") { + column_selector = columns[i].to_string(); + } else { + column_selector += ", " + columns[i].to_string(); + } + } + } else { + column_selector = "*"; + } + return this; + } + + public QueryBuilder select_string(string column_selector) { + this.columns = {}; + this.column_selector = column_selector; + return this; + } + + public virtual QueryBuilder from(Table table) { + if (this.table_name != null) error("cannot use from() multiple times."); + this.table = table; + this.table_name = table.name; + return this; + } + + public virtual QueryBuilder from_name(string table) { + this.table_name = table; + return this; + } + + public QueryBuilder outer_join_with(Table table, Column lhs, Column rhs, string? as = null) { + return outer_join_on(table, @"$lhs = $rhs", as); + } + + public QueryBuilder outer_join_on(Table table, string on, string? as = null) { + if (as == null) as = table.name; + joins += @" LEFT OUTER JOIN $(table.name) AS $as ON $on"; + return this; + } + + public QueryBuilder join_with(Table table, Column lhs, Column rhs, string? as = null) { + return join_on(table, @"$lhs = $rhs", as); + } + + public QueryBuilder join_on(Table table, string on, string? as = null) { + if (as == null) as = table.name; + joins += @" JOIN $(table.name) AS $as ON $on"; + return this; + } + + internal QueryBuilder join_name(string table_name, string on) { + joins += @" JOIN $table_name ON $on"; + return this; + } + + public QueryBuilder where(string selection, string[] selection_args = {}) { + this.selection = @"($(this.selection)) AND ($selection)"; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public QueryBuilder with(Column column, string comp, T value) { + if ((column.unique || column.primary_key) && comp == "=") single_result = true; + selection_args += new Field(column, value); + selection = @"($selection) AND $column $comp ?"; + return this; + } + + public QueryBuilder with_null(Column column) { + selection = @"($selection) AND $column ISNULL"; + return this; + } + + public QueryBuilder without_null(Column column) { + selection = @"($selection) AND $column NOT NULL"; + return this; + } + + public QueryBuilder order_by(Column column, string dir = "ASC") { + order_by_terms += new OrderingTerm(column, dir); + return this; + } + + public QueryBuilder order_by_name(string name, string dir) { + order_by_terms += new OrderingTerm.by_name(name, dir); + return this; + } + + public QueryBuilder group_by(Column[] columns) { + foreach(Column col in columns) { + if (group_by_term == null) { + group_by_term = col.to_string(); + } else { + group_by_term += @", $col"; + } + } + return this; + } + + public QueryBuilder limit(int limit) { + if (this.limit_val != 0 && limit > this.limit_val) error("tried to increase an existing limit"); + this.limit_val = limit; + return this; + } + + public QueryBuilder offset(int offset) { + if (this.limit_val == 0) error("limit required before offset"); + this.offset_val = offset; + return this; + } + + public QueryBuilder single() { + this.single_result = true; + return limit(1); + } + + public int64 count() { + this.column_selector = @"COUNT($column_selector) AS count"; + this.single_result = true; + return row().get_integer("count"); + } + + private Row? row_() { + if (!single_result) error("query is not suited to return a single row, but row() was called."); + return iterator().get_next(); + } + + public RowOption row() { + return new RowOption(row_()); + } + + public T get(Column field, T def = null) { + return row().get(field, def); + } + + internal override Statement prepare() { + Statement stmt = db.prepare(@"SELECT $column_selector $(table_name == null ? "" : @"FROM $((!) table_name)") $joins WHERE $selection $(group_by_term == null ? "" : @"GROUP BY $group_by_term") $(OrderingTerm.all_to_string(order_by_terms)) $(limit_val > 0 ? @" LIMIT $limit_val OFFSET $offset_val" : "")"); + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i+1); + } + return stmt; + } + + public RowIterator iterator() { + return new RowIterator.from_query_builder(db, this); + } + + class OrderingTerm { + Column? column; + string column_name; + string dir; + + public OrderingTerm(Column column, string dir) { + this.column = column; + this.column_name = column.to_string(); + this.dir = dir; + } + + public OrderingTerm.by_name(string column_name, string dir) { + this.column_name = column_name; + this.dir = dir; + } + + public string to_string() { + return @"$column_name $dir"; + } + + public static string all_to_string(OrderingTerm[]? terms) { + if (terms == null || terms.length == 0) return ""; + string res = "ORDER BY "+terms[0].to_string(); + for (int i = 1; i < terms.length; i++) { + res += @", $(terms[i])"; + } + return res; + } + } +} + +public class MatchQueryBuilder : QueryBuilder { + internal MatchQueryBuilder(Database db, Table table) { + base(db); + if (table.fts_columns == null) error("MATCH query on non FTS table"); + from(table); + join_name(@"_fts_$table_name", @"_fts_$table_name.docid = $table_name.rowid"); + } + + public MatchQueryBuilder match(Column column, string match) { + if (table == null) error("MATCH must occur after FROM statement"); + if (!(column in table.fts_columns)) error("MATCH selection on non FTS column"); + selection_args += new StatementBuilder.StringField(match); + selection = @"($selection) AND _fts_$table_name.$(column.name) MATCH ?"; + return this; + } +} + +} diff --git a/libdino/src/qlite/row.vala b/libdino/src/qlite/row.vala new file mode 100644 index 00000000..65c80f02 --- /dev/null +++ b/libdino/src/qlite/row.vala @@ -0,0 +1,147 @@ +using Gee; +using Sqlite; + +namespace Dino.Qlite { + +public class Row { + private Map text_map = new HashMap(); + private Map int_map = new HashMap(); + private Map real_map = new HashMap(); + + internal Row(Statement stmt) { + for (int i = 0; i < stmt.column_count(); i++) { + string column_name; + if (stmt.column_origin_name(i) != null) { + column_name = @"$(stmt.column_table_name(i)).$(stmt.column_origin_name(i))"; + } else { + column_name = stmt.column_name(i); + } + switch(stmt.column_type(i)) { + case TEXT: + text_map[column_name] = stmt.column_text(i); + break; + case INTEGER: + int_map[column_name] = (long) stmt.column_int64(i); + break; + case FLOAT: + real_map[column_name] = stmt.column_double(i); + break; + } + } + } + + public T get(Column field) { + return field[this]; + } + + private string field_name(string field, string? table) { + if (table != null) { + return @"$table.$field"; + } else { + return field; + } + } + + public string? get_text(string field, string? table = null) { + if (text_map.has_key(field_name(field, table))) { + return text_map[field_name(field, table)]; + } + return null; + } + + public long get_integer(string field, string? table = null) { + return int_map[field_name(field, table)]; + } + + public bool has_integer(string field, string? table = null) { + return int_map.has_key(field_name(field, table)); + } + + public double get_real(string field, string? table = null, double def = 0) { + return real_map[field_name(field, table)] ?? def; + } + + public bool has_real(string field, string? table = null) { + return real_map.has_key(field_name(field, table)) && real_map[field_name(field, table)] != null; + } + + public string to_string() { + string ret = "{"; + + foreach (string key in text_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: \"$(text_map[key])\""; + } + foreach (string key in int_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: $(int_map[key])"; + } + foreach (string key in real_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: $(real_map[key])"; + } + + return ret + "}"; + } +} + +public class RowIterator { + private Database db; + private Statement stmt; + + public RowIterator.from_query_builder(Database db, QueryBuilder query) { + this.db = db; + this.stmt = query.prepare(); + } + + public RowIterator(Database db, string sql, string[]? args = null) { + this.db = db; + this.stmt = db.prepare(sql); + if (args != null) { + for (int i = 0; i < args.length; i++) { + stmt.bind_text(i, sql, sql.length); + } + } + } + + public bool next() { + int r = stmt.step(); + if (r == Sqlite.ROW) return true; + if (r == Sqlite.DONE) return false; + warning(@"SQLite error: $(db.errcode()) - $(db.errmsg())"); + return false; + } + + public Row get() { + return new Row(stmt); + } + + public Row? get_next() { + if (next()) return get(); + return null; + } +} + +public class RowOption { + public Row? inner { get; private set; } + + public RowOption(Row? row) { + this.inner = row; + } + + public bool is_present() { + return inner != null; + } + + public T get(Column field, T def = null) { + if (inner == null || field.is_null((!)inner)) return def; + return field[(!)inner]; + } + + internal long get_integer(string field, long def = 0) { + if (inner == null || !((!)inner).has_integer(field)) return def; + return ((!)inner).get_integer(field); + } +} + +} diff --git a/libdino/src/qlite/statement_builder.vala b/libdino/src/qlite/statement_builder.vala new file mode 100644 index 00000000..5c756ab3 --- /dev/null +++ b/libdino/src/qlite/statement_builder.vala @@ -0,0 +1,58 @@ +using Sqlite; + +namespace Dino.Qlite { + +public abstract class StatementBuilder { + protected Database db; + + internal StatementBuilder(Database db) { + this.db = db; + } + + internal abstract Statement prepare(); + + internal abstract class AbstractField { + public T value; + public Column? column; + + AbstractField(T value) { + this.value = value; + } + + internal abstract void bind(Statement stmt, int index); + } + + internal class Field : AbstractField { + public Field(Column column, T value) { + base(value); + this.column = column; + } + + internal override void bind(Statement stmt, int index) { + ((!)column).bind(stmt, index, value); + } + } + + internal class NullField : AbstractField { + public NullField(Column column) { + base(null); + this.column = column; + } + + internal override void bind(Statement stmt, int index) { + stmt.bind_null(index); + } + } + + internal class StringField : AbstractField { + public StringField(string value) { + base(value); + } + + internal override void bind(Statement stmt, int index) { + stmt.bind_text(index, value); + } + } +} + +} diff --git a/libdino/src/qlite/table.vala b/libdino/src/qlite/table.vala new file mode 100644 index 00000000..3b75e22e --- /dev/null +++ b/libdino/src/qlite/table.vala @@ -0,0 +1,218 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class Table { + protected Database db; + public string name { get; private set; } + protected Column[]? columns; + private string constraints = ""; + private string[] post_statements = {}; + private string[] create_statements = {}; + internal Column[]? fts_columns; + + public Table(Database db, string name) { + this.db = db; + this.name = name; + } + + public void init(Column[] columns, string constraints = "") { + this.columns = columns; + this.constraints = constraints; + + foreach(Column c in columns) { + c.table = this; + } + } + + public void fts(Column[] columns) { + if (fts_columns != null) error("Only one FTS index may be used per table."); + fts_columns = columns; + string cs = ""; + string cnames = ""; + string cnews = ""; + foreach (Column c in columns) { + cs += @", $(c.to_column_definition())"; + cnames += @", $(c.name)"; + cnews += @", new.$(c.name)"; + } + add_create_statement(@"CREATE VIRTUAL TABLE IF NOT EXISTS _fts_$name USING fts4(tokenize=unicode61, content=\"$name\"$cs)"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bu_$(name) BEFORE UPDATE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bd_$(name) BEFORE DELETE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_au_$(name) AFTER UPDATE ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_ai_$(name) AFTER INSERT ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); + } + + public void fts_rebuild() { + if (fts_columns == null) error("FTS not available on this table."); + try { + db.exec(@"INSERT INTO _fts_$name(_fts_$name) VALUES('rebuild');"); + } catch (Error e) { + critical(@"Qlite Error: Rebuilding FTS index: $(e.message)"); + } + } + + public void unique(Column[] columns, string? on_conflict = null) { + constraints += ", UNIQUE ("; + bool first = true; + foreach (Column c in columns) { + if (!first) constraints += ", "; + constraints += c.name; + first = false; + } + constraints += ")"; + if (on_conflict != null) { + constraints += " ON CONFLICT " + (!)on_conflict; + } + } + + public void add_post_statement(string stmt) { + post_statements += stmt; + } + + public void add_create_statement(string stmt) { + create_statements += stmt; + } + + public void index(string index_name, Column[] columns, bool unique = false) { + string stmt = @"CREATE $(unique ? "UNIQUE" : "") INDEX IF NOT EXISTS $index_name ON $name ("; + bool first = true; + foreach (Column c in columns) { + if (!first) stmt += ", "; + stmt += c.name; + first = false; + } + stmt += ")"; + add_post_statement(stmt); + } + + private void ensure_init() { + if (columns == null) error("Table %s was not initialized, call init()", name); + } + + public QueryBuilder select(Column[]? columns = null) { + ensure_init(); + return db.select(columns).from(this); + } + + private MatchQueryBuilder match_query() { + ensure_init(); + return db.match_query(this); + } + + public MatchQueryBuilder match(Column column, string query) { + return match_query().match(column, query); + } + + public InsertBuilder insert() { + ensure_init(); + return db.insert().into(this); + } + + public UpdateBuilder update() { + ensure_init(); + return db.update(this); + } + + public UpsertBuilder upsert() { + ensure_init(); + return db.upsert(this); + } + + public DeleteBuilder delete() { + ensure_init(); + return db.delete().from(this); + } + + public RowOption row_with(Column column, T value) { + ensure_init(); + if (!column.unique && !column.primary_key) error("%s is not suited to identify a row, but used with row_with()", column.name); + return select().with(column, "=", value).row(); + } + + public bool is_known_column(string column) { + ensure_init(); + foreach (Column c in columns) { + if (c.name == column) return true; + } + return false; + } + + public void create_table_at_version(long version) { + ensure_init(); + string sql = @"CREATE TABLE IF NOT EXISTS $name ("; + bool first = true; + for (int i = 0; i < columns.length; i++) { + Column c = columns[i]; + if (c.min_version <= version && c.max_version >= version) { + sql += @"$(!first ? "," : "") $(c.to_column_definition())"; + first = false; + } + } + sql += @"$constraints)"; + try { + db.exec(sql); + } catch (Error e) { + error(@"Qlite Error: Create table at version: $(e.message)"); + } + foreach (string stmt in create_statements) { + try { + db.exec(stmt); + } catch (Error e) { + error(@"Qlite Error: Create table at version: $(e.message)"); + } + } + } + + public void add_columns_for_version(long old_version, long new_version) { + ensure_init(); + foreach (Column c in columns) { + if (c.min_version <= new_version && c.max_version >= new_version && c.min_version > old_version) { + try { + db.exec(@"ALTER TABLE $name ADD COLUMN $(c.to_column_definition())"); + } catch (Error e) { + critical(@"Qlite Error: Add columns for version: $(e.message)"); + } + } + } + } + + public void delete_columns_for_version(long old_version, long new_version) { + bool column_deletion_required = false; + string column_list = ""; + foreach (Column c in columns) { + if (c.min_version <= new_version && c.max_version >= new_version) { + if (column_list == "") { + column_list = c.name; + } else { + column_list += ", " + c.name; + } + } + if (!(c.min_version <= new_version && c.max_version >= new_version) && c.min_version <= old_version && c.max_version >= old_version) { + column_deletion_required = true; + } + } + if (column_deletion_required) { + try { + db.exec(@"ALTER TABLE $name RENAME TO _$(name)_$old_version"); + create_table_at_version(new_version); + db.exec(@"INSERT INTO $name ($column_list) SELECT $column_list FROM _$(name)_$old_version"); + db.exec(@"DROP TABLE _$(name)_$old_version"); + } catch (Error e) { + error(@"Qlite Error: Delete columns for version change: $(e.message)"); + } + } + } + + internal void post() { + foreach (string stmt in post_statements) { + try { + db.exec(stmt); + } catch (Error e) { + error(@"Qlite Error: Post: $(e.message)"); + } + } + } +} + +} diff --git a/libdino/src/qlite/update_builder.vala b/libdino/src/qlite/update_builder.vala new file mode 100644 index 00000000..d371a93a --- /dev/null +++ b/libdino/src/qlite/update_builder.vala @@ -0,0 +1,103 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class UpdateBuilder : StatementBuilder { + + // UPDATE [OR ...] + private string? or_val; + + // [...] + private Table? table; + private string table_name; + + // SET [...] + private StatementBuilder.AbstractField[] fields = {}; + + // WHERE [...] + private string selection = "1"; + private StatementBuilder.AbstractField[] selection_args = {}; + + internal UpdateBuilder(Database db, Table table) { + base(db); + this.table = table; + this.table_name = table.name; + } + + internal UpdateBuilder.for_name(Database db, string table) { + base(db); + this.table_name = table; + } + + public UpdateBuilder or(string or) { + this.or_val = or; + return this; + } + + public UpdateBuilder set(Column column, T value) { + fields += new Field(column, value); + return this; + } + + public UpdateBuilder set_null(Column column) { + if (column.not_null) error("Can't set non-null column %s to null", column.name); + fields += new NullField(column); + return this; + } + + public UpdateBuilder where(string selection, string[] selection_args = {}) { + if (this.selection != "1") error("selection was already done, but where() was called."); + this.selection = selection; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public UpdateBuilder with(Column column, string comp, T value) { + selection_args += new Field(column, value); + selection = @"($selection) AND $(column.name) $comp ?"; + return this; + } + + public UpdateBuilder with_null(Column column) { + selection = @"($selection) AND $(column.name) ISNULL"; + return this; + } + + public UpdateBuilder without_null(Column column) { + selection = @"($selection) AND $(column.name) NOT NULL"; + return this; + } + + internal override Statement prepare() { + string sql = "UPDATE"; + if (or_val != null) sql += @" OR $((!)or_val)"; + sql += @" $table_name SET "; + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + sql += ", "; + } + sql += @"$(((!)fields[i].column).name) = ?"; + } + sql += @" WHERE $selection"; + Statement stmt = db.prepare(sql); + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i+1); + } + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i + fields.length + 1); + } + return stmt; + } + + public void perform() { + if (fields.length == 0) return; + if (prepare().step() != DONE) { + critical("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + +} + +} diff --git a/libdino/src/qlite/upsert_builder.vala b/libdino/src/qlite/upsert_builder.vala new file mode 100644 index 00000000..e9a73e4f --- /dev/null +++ b/libdino/src/qlite/upsert_builder.vala @@ -0,0 +1,93 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class UpsertBuilder : StatementBuilder { + // INTO [...] + private Table table; + private string table_name; + + // VALUES [...] + private StatementBuilder.AbstractField[] keys = {}; + private StatementBuilder.AbstractField[] fields = {}; + + internal UpsertBuilder(Database db, Table table) { + base(db); + this.table = table; + this.table_name = table.name; + } + + public UpsertBuilder value(Column column, T value, bool key = false) { + if (key) { + keys += new Field(column, value); + } else { + fields += new Field(column, value); + } + return this; + } + + public UpsertBuilder value_null(Column column, bool key = false) { + if (column.not_null) error("Can't set non-null column %s to null", column.name); + if (key) { + keys += new NullField(column); + } else { + fields += new NullField(column); + } + return this; + } + + internal override Statement prepare() { + error("prepare() not available for upsert."); + } + + internal Statement prepare_upsert() { + var unique_fields = new StringBuilder(); + var unique_values = new StringBuilder(); + var update_fields = new StringBuilder(); + var update_values = new StringBuilder(); + var update_fields_vals = new StringBuilder(); + + for (int i = 0; i < keys.length; i++) { + if (i != 0) { + unique_fields.append(", "); + unique_values.append(", "); + } + unique_fields.append(keys[i].column.name); + unique_values.append("?"); + } + + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + update_fields.append(", "); + update_values.append(", "); + update_fields_vals.append(", "); + } + update_fields.append(fields[i].column.name); + update_values.append("?"); + update_fields_vals.append(fields[i].column.name).append("=excluded.").append(fields[i].column.name); + } + + string sql = @"INSERT INTO $table_name ($(unique_fields.str), $(update_fields.str)) VALUES ($(unique_values.str), $(update_values.str)) " + + @"ON CONFLICT ($(unique_fields.str)) DO UPDATE SET $(update_fields_vals.str)"; + + Statement stmt = db.prepare(sql); + for (int i = 0; i < keys.length; i++) { + keys[i].bind(stmt, i + 1); + } + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i + keys.length + 1); + } + + return stmt; + } + + public int64 perform() { + if (prepare_upsert().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + return db.last_insert_rowid(); + } + +} + +} diff --git a/libdino/src/service/avatar_manager.vala b/libdino/src/service/avatar_manager.vala index 0c98a8f3..ac4971ef 100644 --- a/libdino/src/service/avatar_manager.vala +++ b/libdino/src/service/avatar_manager.vala @@ -1,9 +1,9 @@ using Gdk; using Gee; -using Qlite; -using Xmpp; using Dino.Entities; +using Dino.Qlite; +using Xmpp; namespace Dino { diff --git a/libdino/src/service/call_store.vala b/libdino/src/service/call_store.vala index bfc8255f..9e32517f 100644 --- a/libdino/src/service/call_store.vala +++ b/libdino/src/service/call_store.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/contact_model.vala b/libdino/src/service/contact_model.vala index 33f6126b..3e52e040 100644 --- a/libdino/src/service/contact_model.vala +++ b/libdino/src/service/contact_model.vala @@ -1,6 +1,5 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; diff --git a/libdino/src/service/content_item_store.vala b/libdino/src/service/content_item_store.vala index cf4c6975..5e440c76 100644 --- a/libdino/src/service/content_item_store.vala +++ b/libdino/src/service/content_item_store.vala @@ -1,7 +1,7 @@ using Gee; using Dino.Entities; -using Qlite; +using Dino.Qlite; using Xmpp; namespace Dino { diff --git a/libdino/src/service/database.vala b/libdino/src/service/database.vala index 8432ff40..4319e027 100644 --- a/libdino/src/service/database.vala +++ b/libdino/src/service/database.vala @@ -1,8 +1,8 @@ using Gee; -using Qlite; using Xmpp; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/entity_info.vala b/libdino/src/service/entity_info.vala index 03828d1d..e9a20df1 100644 --- a/libdino/src/service/entity_info.vala +++ b/libdino/src/service/entity_info.vala @@ -1,6 +1,6 @@ using Gee; using Dino.Entities; -using Qlite; +using Dino.Qlite; using Xmpp; using Xmpp.Xep; using Xmpp.Xep.ServiceDiscovery; diff --git a/libdino/src/service/fallback_body.vala b/libdino/src/service/fallback_body.vala index 0ce89ade..09aa839a 100644 --- a/libdino/src/service/fallback_body.vala +++ b/libdino/src/service/fallback_body.vala @@ -1,5 +1,4 @@ using Gee; -using Qlite; using Xmpp; using Xmpp.Xep; diff --git a/libdino/src/service/file_transfer_storage.vala b/libdino/src/service/file_transfer_storage.vala index b4a4db3e..33ebcbce 100644 --- a/libdino/src/service/file_transfer_storage.vala +++ b/libdino/src/service/file_transfer_storage.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/history_sync.vala b/libdino/src/service/history_sync.vala index 9bd3f54f..a7a99d2d 100644 --- a/libdino/src/service/history_sync.vala +++ b/libdino/src/service/history_sync.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; public class Dino.HistorySync { diff --git a/libdino/src/service/message_correction.vala b/libdino/src/service/message_correction.vala index 164106e0..02151ac8 100644 --- a/libdino/src/service/message_correction.vala +++ b/libdino/src/service/message_correction.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/message_deletion.vala b/libdino/src/service/message_deletion.vala index 4467311e..0060a7e2 100644 --- a/libdino/src/service/message_deletion.vala +++ b/libdino/src/service/message_deletion.vala @@ -3,7 +3,6 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; namespace Dino { diff --git a/libdino/src/service/message_processor.vala b/libdino/src/service/message_processor.vala index 9190cd9d..7997af67 100644 --- a/libdino/src/service/message_processor.vala +++ b/libdino/src/service/message_processor.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/message_storage.vala b/libdino/src/service/message_storage.vala index d6b8d6e3..2567738c 100644 --- a/libdino/src/service/message_storage.vala +++ b/libdino/src/service/message_storage.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/occupant_id_store.vala b/libdino/src/service/occupant_id_store.vala index 662b9cbb..d2849652 100644 --- a/libdino/src/service/occupant_id_store.vala +++ b/libdino/src/service/occupant_id_store.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/reactions.vala b/libdino/src/service/reactions.vala index 16849c68..8f3aa4fa 100644 --- a/libdino/src/service/reactions.vala +++ b/libdino/src/service/reactions.vala @@ -1,9 +1,9 @@ using Gee; -using Qlite; +using Dino.Entities; +using Dino.Qlite; using Xmpp; using Xmpp.Xep; -using Dino.Entities; public class Dino.Reactions : StreamInteractionModule, Object { public static ModuleIdentity IDENTITY = new ModuleIdentity("reactions"); diff --git a/libdino/src/service/replies.vala b/libdino/src/service/replies.vala index ea10cf88..95c28ef1 100644 --- a/libdino/src/service/replies.vala +++ b/libdino/src/service/replies.vala @@ -1,9 +1,9 @@ using Gee; -using Qlite; using Xmpp; using Xmpp.Xep; using Dino.Entities; +using Dino.Qlite; public class Dino.Replies : StreamInteractionModule, Object { public static ModuleIdentity IDENTITY = new ModuleIdentity("reply"); diff --git a/libdino/src/service/search_processor.vala b/libdino/src/service/search_processor.vala index 2b5ebe49..aaec990a 100644 --- a/libdino/src/service/search_processor.vala +++ b/libdino/src/service/search_processor.vala @@ -1,8 +1,8 @@ using Gee; -using Xmpp; -using Qlite; using Dino.Entities; +using Dino.Qlite; +using Xmpp; namespace Dino { diff --git a/libdino/src/service/util.vala b/libdino/src/service/util.vala index e85e2005..ac596cad 100644 --- a/libdino/src/service/util.vala +++ b/libdino/src/service/util.vala @@ -1,5 +1,4 @@ using Dino.Entities; -using Qlite; namespace Dino { diff --git a/main/meson.build b/main/meson.build index 8b9404c9..3c15db32 100644 --- a/main/meson.build +++ b/main/meson.build @@ -8,7 +8,6 @@ dependencies = [ dep_icu_uc, dep_libadwaita, dep_m, - dep_qlite, dep_xmpp_vala, meson.get_compiler('vala').find_library('posix'), ] diff --git a/meson.build b/meson.build index b9df102b..ad0f7e4e 100644 --- a/meson.build +++ b/meson.build @@ -110,7 +110,6 @@ if get_option('set-install-rpath') default_install_rpath = get_option('prefix') / get_option('libdir') endif -subdir('qlite') subdir('xmpp-vala') subdir('libdino') subdir('main') diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 5161b123..99f8e6a1 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -5,7 +5,6 @@ dependencies = [ dep_glib, dep_gmodule, dep_nice, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/notification-sound/meson.build b/plugins/notification-sound/meson.build index d6eebe18..80a1d062 100644 --- a/plugins/notification-sound/meson.build +++ b/plugins/notification-sound/meson.build @@ -4,7 +4,6 @@ dependencies = [ dep_glib, dep_gmodule, dep_libcanberra, - dep_qlite, dep_xmpp_vala, dep_gio, ] diff --git a/plugins/omemo/meson.build b/plugins/omemo/meson.build index 978fb9a6..7838a8d6 100644 --- a/plugins/omemo/meson.build +++ b/plugins/omemo/meson.build @@ -9,7 +9,6 @@ dependencies = [ dep_libqrencode, dep_libomemo_c, dep_m, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/omemo/src/logic/database.vala b/plugins/omemo/src/logic/database.vala index ec5a0924..f2a92259 100644 --- a/plugins/omemo/src/logic/database.vala +++ b/plugins/omemo/src/logic/database.vala @@ -1,7 +1,7 @@ using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/decrypt.vala b/plugins/omemo/src/logic/decrypt.vala index 2861b42f..698d3f76 100644 --- a/plugins/omemo/src/logic/decrypt.vala +++ b/plugins/omemo/src/logic/decrypt.vala @@ -1,6 +1,7 @@ -using Dino.Entities; -using Qlite; using Gee; + +using Dino.Entities; +using Dino.Qlite; using Omemo; using Xmpp; diff --git a/plugins/omemo/src/logic/manager.vala b/plugins/omemo/src/logic/manager.vala index 71f17aae..f171a1c0 100644 --- a/plugins/omemo/src/logic/manager.vala +++ b/plugins/omemo/src/logic/manager.vala @@ -1,8 +1,9 @@ +using Gee; + using Dino.Entities; +using Dino.Qlite; using Omemo; -using Qlite; using Xmpp; -using Gee; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/pre_key_store.vala b/plugins/omemo/src/logic/pre_key_store.vala index c15acc84..beb2d87a 100644 --- a/plugins/omemo/src/logic/pre_key_store.vala +++ b/plugins/omemo/src/logic/pre_key_store.vala @@ -1,5 +1,5 @@ +using Dino.Qlite; using Omemo; -using Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/session_store.vala b/plugins/omemo/src/logic/session_store.vala index ea5738fd..bb9ca83f 100644 --- a/plugins/omemo/src/logic/session_store.vala +++ b/plugins/omemo/src/logic/session_store.vala @@ -1,5 +1,5 @@ +using Dino.Qlite; using Omemo; -using Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/signed_pre_key_store.vala b/plugins/omemo/src/logic/signed_pre_key_store.vala index d73cbe71..68f3092c 100644 --- a/plugins/omemo/src/logic/signed_pre_key_store.vala +++ b/plugins/omemo/src/logic/signed_pre_key_store.vala @@ -1,4 +1,4 @@ -using Qlite; +using Dino.Qlite; using Omemo; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/trust_manager.vala b/plugins/omemo/src/logic/trust_manager.vala index 8cf1ddeb..f17ade99 100644 --- a/plugins/omemo/src/logic/trust_manager.vala +++ b/plugins/omemo/src/logic/trust_manager.vala @@ -1,8 +1,9 @@ -using Dino.Entities; using Gee; -using Xmpp; + +using Dino.Entities; +using Dino.Qlite; using Omemo; -using Qlite; +using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/bad_messages_populator.vala b/plugins/omemo/src/ui/bad_messages_populator.vala index 9dacba95..c291a422 100644 --- a/plugins/omemo/src/ui/bad_messages_populator.vala +++ b/plugins/omemo/src/ui/bad_messages_populator.vala @@ -1,8 +1,8 @@ using Gee; using Gtk; -using Qlite; using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/call_encryption_entry.vala b/plugins/omemo/src/ui/call_encryption_entry.vala index 69b7b686..04f0443c 100644 --- a/plugins/omemo/src/ui/call_encryption_entry.vala +++ b/plugins/omemo/src/ui/call_encryption_entry.vala @@ -1,6 +1,7 @@ -using Dino.Entities; using Gtk; -using Qlite; + +using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/contact_details_provider.vala b/plugins/omemo/src/ui/contact_details_provider.vala index 7c733cd7..1b61f31d 100644 --- a/plugins/omemo/src/ui/contact_details_provider.vala +++ b/plugins/omemo/src/ui/contact_details_provider.vala @@ -1,6 +1,5 @@ using Gtk; using Gee; -using Qlite; using Dino.Entities; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/encryption_list_entry.vala b/plugins/omemo/src/ui/encryption_list_entry.vala index 3bb76c52..dfec813a 100644 --- a/plugins/omemo/src/ui/encryption_list_entry.vala +++ b/plugins/omemo/src/ui/encryption_list_entry.vala @@ -1,6 +1,7 @@ -using Dino.Entities; using Gtk; -using Qlite; + +using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/encryption_preferences_entry.vala b/plugins/omemo/src/ui/encryption_preferences_entry.vala index f0aedb6a..cea856bb 100644 --- a/plugins/omemo/src/ui/encryption_preferences_entry.vala +++ b/plugins/omemo/src/ui/encryption_preferences_entry.vala @@ -1,10 +1,11 @@ -using Qlite; -using Qrencode; using Gee; -using Xmpp; -using Dino.Entities; using Gtk; +using Qrencode; + +using Dino.Entities; +using Dino.Qlite; using Omemo; +using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/manage_key_dialog.vala b/plugins/omemo/src/ui/manage_key_dialog.vala index ac8896a5..117149b6 100644 --- a/plugins/omemo/src/ui/manage_key_dialog.vala +++ b/plugins/omemo/src/ui/manage_key_dialog.vala @@ -1,5 +1,6 @@ using Gtk; -using Qlite; + +using Dino.Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/openpgp/meson.build b/plugins/openpgp/meson.build index 23588fca..56bc9d0c 100644 --- a/plugins/openpgp/meson.build +++ b/plugins/openpgp/meson.build @@ -7,7 +7,6 @@ dependencies = [ dep_gmodule, dep_gpgme, dep_gtk4, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/openpgp/src/database.vala b/plugins/openpgp/src/database.vala index fb575a3b..4c05571e 100644 --- a/plugins/openpgp/src/database.vala +++ b/plugins/openpgp/src/database.vala @@ -1,6 +1,5 @@ -using Qlite; - using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.OpenPgp { diff --git a/plugins/rtp/meson.build b/plugins/rtp/meson.build index b4ba5cf6..2772ad88 100644 --- a/plugins/rtp/meson.build +++ b/plugins/rtp/meson.build @@ -10,7 +10,6 @@ dependencies = [ dep_gstreamer_video, dep_gtk4, dep_m, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/qlite/meson.build b/qlite/meson.build deleted file mode 100644 index 162d6aa8..00000000 --- a/qlite/meson.build +++ /dev/null @@ -1,27 +0,0 @@ -dependencies = [ - dep_gee, - dep_glib, - dep_sqlite3, -] -sources = files( - 'src/column.vala', - 'src/database.vala', - 'src/delete_builder.vala', - 'src/insert_builder.vala', - 'src/query_builder.vala', - 'src/row.vala', - 'src/statement_builder.vala', - 'src/table.vala', - 'src/update_builder.vala', - 'src/upsert_builder.vala', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="qlite"', -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] -lib_qlite = library('qlite', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, version: '0.1', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) -dep_qlite = declare_dependency(link_with: lib_qlite, include_directories: include_directories('.')) - -install_data('qlite.deps', install_dir: get_option('datadir') / 'vala/vapi', install_tag: 'devel') # TODO: workaround for https://github.com/mesonbuild/meson/issues/9756 diff --git a/qlite/qlite.deps b/qlite/qlite.deps deleted file mode 100644 index d9b15e78..00000000 --- a/qlite/qlite.deps +++ /dev/null @@ -1,3 +0,0 @@ -gee-0.8 -glib-2.0 -sqlite3 diff --git a/qlite/src/column.vala b/qlite/src/column.vala deleted file mode 100644 index 36c8fcff..00000000 --- a/qlite/src/column.vala +++ /dev/null @@ -1,190 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public abstract class Column { - public const string DEFAULT_TABLE_NAME = ""; - - public string name { get; private set; } - public string? default { get; set; } - public int sqlite_type { get; private set; } - public bool primary_key { get; set; } - public bool auto_increment { get; set; } - public bool unique { get; set; } - public virtual bool not_null { get; set; } - public long min_version { get; set; default = -1; } - public long max_version { get; set; default = long.MAX; } - internal Table table { get; set; } - - public abstract T get(Row row, string? table_name = DEFAULT_TABLE_NAME); - - public virtual bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return false; - } - - internal abstract void bind(Statement stmt, int index, T value); - - public string to_string() { - return table == null ? name : (table.name + "." + name); - } - - public string to_column_definition() { - string res = name; - switch (sqlite_type) { - case INTEGER: - res += " INTEGER"; - break; - case FLOAT: - res += " REAL"; - break; - case TEXT: - res += " TEXT"; - break; - default: - res += " UNKNOWN"; - break; - } - if (primary_key) { - res += " PRIMARY KEY"; - if (auto_increment) res += " AUTOINCREMENT"; - } - if (not_null) res += " NOT NULL"; - if (unique) res += " UNIQUE"; - if (default != null) res += @" DEFAULT $((!) default)"; - - return res; - } - - Column(string name, int type) { - this.name = name; - this.sqlite_type = type; - } - - public class Integer : Column { - public Integer(string name) { - base(name, INTEGER); - } - - public override int get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (int) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, int value) { - stmt.bind_int(index, value); - } - } - - public class Long : Column { - public Long(string name) { - base(name, INTEGER); - } - - public override long get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (long) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, long value) { - stmt.bind_int64(index, value); - } - } - - public class NullableReal : Column { - public NullableReal(string name) { - base(name, FLOAT); - } - - public override bool not_null { get { return false; } set {} } - - public override double? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, double? value) { - stmt.bind_double(index, value); - } - } - - public class Text : Column { - public Text(string name) { - base(name, TEXT); - } - - public override string? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return get(row, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == null; - } - - internal override void bind(Statement stmt, int index, string? value) { - if (value != null) { - stmt.bind_text(index, (!) value); - } else { - stmt.bind_null(index); - } - } - } - - public class NonNullText : Column { - public NonNullText(string name) { - base(name, TEXT); - } - - public override bool not_null { get { return true; } set {} } - - public override string get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (!)row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return false; - } - - internal override void bind(Statement stmt, int index, string value) { - stmt.bind_text(index, (!) value); - } - } - - public class BoolText : Column { - public BoolText(string name) { - base(name, TEXT); - } - - public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == "1"; - } - - internal override void bind(Statement stmt, int index, bool value) { - stmt.bind_text(index, value ? "1" : "0"); - } - } - - public class BoolInt : Column { - public BoolInt(string name) { - base(name, INTEGER); - } - - public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == 1; - } - - internal override void bind(Statement stmt, int index, bool value) { - stmt.bind_int(index, value ? 1 : 0); - } - } -} - -} diff --git a/qlite/src/database.vala b/qlite/src/database.vala deleted file mode 100644 index 8b2f447d..00000000 --- a/qlite/src/database.vala +++ /dev/null @@ -1,163 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class Database { - private string file_name; - private Sqlite.Database db; - private long expected_version; - private Table[]? tables; - - private Column meta_name = new Column.Text("name") { primary_key = true }; - private Column meta_int_val = new Column.Long("int_val"); - private Column meta_text_val = new Column.Text("text_val"); - private Table meta_table; - - public bool debug = false; - - public Database(string file_name, long expected_version) { - this.file_name = file_name; - this.expected_version = expected_version; - meta_table = new Table(this, "_meta"); - meta_table.init({meta_name, meta_int_val, meta_text_val}); - } - - public void init(Table[] tables) { - Sqlite.config(Config.SERIALIZED); - int ec = Sqlite.Database.open_v2(file_name, out db, OPEN_READWRITE | OPEN_CREATE | 0x00010000); - if (ec != Sqlite.OK) { - error(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - this.tables = tables; - if (debug) db.trace((message) => print(@"Qlite trace: $message\n")); - start_migration(); - } - - public void ensure_init() { - if (tables == null) error(@"Database $file_name was not initialized, call init()"); - } - - private void start_migration() { - try { - exec("BEGIN TRANSACTION"); - } catch (Error e) { - error("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - meta_table.create_table_at_version(expected_version); - long old_version = 0; - old_version = meta_table.row_with(meta_name, "version")[meta_int_val, -1]; - if (old_version == -1) { - foreach (Table t in tables) { - t.create_table_at_version(expected_version); - } - meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); - } else if (expected_version != old_version) { - foreach (Table t in tables) { - t.create_table_at_version(old_version); - } - foreach (Table t in tables) { - t.add_columns_for_version(old_version, expected_version); - } - migrate(old_version); - foreach (Table t in tables) { - t.delete_columns_for_version(old_version, expected_version); - } - if (old_version == -1) { - meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); - } else { - meta_table.update().with(meta_name, "=", "version").set(meta_int_val, expected_version).perform(); - } - } - foreach (Table t in tables) { - t.post(); - } - try { - exec("END TRANSACTION"); - } catch (Error e) { - error("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - - internal int errcode() { - return db.errcode(); - } - - internal string errmsg() { - return db.errmsg(); - } - - internal int64 last_insert_rowid() { - return db.last_insert_rowid(); - } - - // To be implemented by actual implementation if required - // new table columns are added, outdated columns are still present and will be removed afterwards - public virtual void migrate(long old_version) { - } - - public QueryBuilder select(Column[]? columns = null) { - ensure_init(); - return new QueryBuilder(this).select(columns); - } - - internal MatchQueryBuilder match_query(Table table) { - ensure_init(); - return new MatchQueryBuilder(this, table); - } - - public InsertBuilder insert() { - ensure_init(); - return new InsertBuilder(this); - } - - public UpdateBuilder update(Table table) { - ensure_init(); - return new UpdateBuilder(this, table); - } - - public UpsertBuilder upsert(Table table) { - ensure_init(); - return new UpsertBuilder(this, table); - } - - public UpdateBuilder update_named(string table) { - ensure_init(); - return new UpdateBuilder.for_name(this, table); - } - - public DeleteBuilder delete() { - ensure_init(); - return new DeleteBuilder(this); - } - - public RowIterator query_sql(string sql, string[]? args = null) { - ensure_init(); - return new RowIterator(this, sql, args); - } - - internal Statement prepare(string sql) { - ensure_init(); - Sqlite.Statement statement; - if (db.prepare_v2(sql, sql.length, out statement) != OK) { - error("SQLite error: %d - %s: %s", db.errcode(), db.errmsg(), sql); - } - return statement; - } - - public void exec(string sql) throws Error { - ensure_init(); - if (db.exec(sql) != OK) { - throw new Error(-1, 0, "SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - - public bool is_known_column(string table, string field) { - ensure_init(); - foreach (Table t in tables) { - if (t.is_known_column(field)) return true; - } - return false; - } -} - -} diff --git a/qlite/src/delete_builder.vala b/qlite/src/delete_builder.vala deleted file mode 100644 index 45e09dc7..00000000 --- a/qlite/src/delete_builder.vala +++ /dev/null @@ -1,62 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class DeleteBuilder : StatementBuilder { - - // DELETE FROM [...] - private Table? table; - private string table_name; - - // WHERE [...] - private string selection = "1"; - private StatementBuilder.AbstractField[] selection_args = {}; - - internal DeleteBuilder(Database db) { - base(db); - } - - public DeleteBuilder from(Table table) { - if (this.table != null) error("Qlite Error: ILLEGAL QUERY: cannot use from() multiple times."); - this.table = table; - this.table_name = table.name; - return this; - } - - public DeleteBuilder from_name(string table) { - this.table_name = table; - return this; - } - - public DeleteBuilder where(string selection, string[]? selection_args = null) { - if (this.selection != "1") error("selection was already done, but where() was called."); - this.selection = selection; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public DeleteBuilder with(Column column, string comp, T value) { - selection_args += new Field(column, value); - selection = @"($selection) AND $(column.name) $comp ?"; - return this; - } - - internal override Statement prepare() { - Statement stmt = db.prepare(@"DELETE FROM $table_name WHERE $selection"); - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i+1); - } - return stmt; - } - - public void perform() { - if (prepare().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - -} - -} diff --git a/qlite/src/insert_builder.vala b/qlite/src/insert_builder.vala deleted file mode 100644 index 8b14b33f..00000000 --- a/qlite/src/insert_builder.vala +++ /dev/null @@ -1,84 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class InsertBuilder : StatementBuilder { - - // INSERT [OR ...] - private bool replace_val; - private string? or_val; - - // INTO [...] - private Table table; - private string table_name; - - // VALUES [...] - private StatementBuilder.AbstractField[] fields = {}; - - internal InsertBuilder(Database db) { - base(db); - } - - public InsertBuilder replace() { - this.replace_val = true; - return this; - } - - public InsertBuilder or(string or) { - this.or_val = or; - return this; - } - - public InsertBuilder into(Table table) { - this.table = table; - this.table_name = table.name; - return this; - } - - public InsertBuilder into_name(string table) { - this.table_name = table; - return this; - } - - public InsertBuilder value(Column column, T value) { - fields += new Field(column, value); - return this; - } - - public InsertBuilder value_null(Column column) { - if (column.not_null) error("Qlite Error: ILLEGAL QUERY: Can't set non-null column %s to null", column.name); - fields += new NullField(column); - return this; - } - - internal override Statement prepare() { - string fields_text = ""; - string value_qs = ""; - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - value_qs += ", "; - fields_text += ", "; - } - fields_text += ((!)fields[i].column).name; - value_qs += "?"; - } - string sql = replace_val ? "REPLACE" : "INSERT"; - if (!replace_val && or_val != null) sql += @" OR $((!)or_val)"; - sql += @" INTO $table_name ( $fields_text ) VALUES ($value_qs)"; - Statement stmt = db.prepare(sql); - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i+1); - } - return stmt; - } - - public int64 perform() { - if (prepare().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - return db.last_insert_rowid(); - } - -} - -} diff --git a/qlite/src/query_builder.vala b/qlite/src/query_builder.vala deleted file mode 100644 index 88f05e04..00000000 --- a/qlite/src/query_builder.vala +++ /dev/null @@ -1,238 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class QueryBuilder : StatementBuilder { - private bool single_result; - - // SELECT [...] - private string column_selector = "*"; - private Column[] columns = {}; - - // FROM [...] - protected Table? table; - protected string? table_name; - - // JOIN [...] - private string joins = ""; - - // WHERE [...] - protected string selection = "1"; - internal StatementBuilder.AbstractField[] selection_args = {}; - - // ORDER BY [...] - private OrderingTerm[]? order_by_terms = {}; - - // GROUP BY [...] - private string? group_by_term; - - // LIMIT [...] OFFSET [...] - private int limit_val; - private int offset_val; - - internal QueryBuilder(Database db) { - base(db); - } - - public QueryBuilder select(Column[] columns = {}) { - this.columns = columns; - if (columns.length != 0) { - for (int i = 0; i < columns.length; i++) { - if (column_selector == "*") { - column_selector = columns[i].to_string(); - } else { - column_selector += ", " + columns[i].to_string(); - } - } - } else { - column_selector = "*"; - } - return this; - } - - public QueryBuilder select_string(string column_selector) { - this.columns = {}; - this.column_selector = column_selector; - return this; - } - - public virtual QueryBuilder from(Table table) { - if (this.table_name != null) error("cannot use from() multiple times."); - this.table = table; - this.table_name = table.name; - return this; - } - - public virtual QueryBuilder from_name(string table) { - this.table_name = table; - return this; - } - - public QueryBuilder outer_join_with(Table table, Column lhs, Column rhs, string? as = null) { - return outer_join_on(table, @"$lhs = $rhs", as); - } - - public QueryBuilder outer_join_on(Table table, string on, string? as = null) { - if (as == null) as = table.name; - joins += @" LEFT OUTER JOIN $(table.name) AS $as ON $on"; - return this; - } - - public QueryBuilder join_with(Table table, Column lhs, Column rhs, string? as = null) { - return join_on(table, @"$lhs = $rhs", as); - } - - public QueryBuilder join_on(Table table, string on, string? as = null) { - if (as == null) as = table.name; - joins += @" JOIN $(table.name) AS $as ON $on"; - return this; - } - - internal QueryBuilder join_name(string table_name, string on) { - joins += @" JOIN $table_name ON $on"; - return this; - } - - public QueryBuilder where(string selection, string[] selection_args = {}) { - this.selection = @"($(this.selection)) AND ($selection)"; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public QueryBuilder with(Column column, string comp, T value) { - if ((column.unique || column.primary_key) && comp == "=") single_result = true; - selection_args += new Field(column, value); - selection = @"($selection) AND $column $comp ?"; - return this; - } - - public QueryBuilder with_null(Column column) { - selection = @"($selection) AND $column ISNULL"; - return this; - } - - public QueryBuilder without_null(Column column) { - selection = @"($selection) AND $column NOT NULL"; - return this; - } - - public QueryBuilder order_by(Column column, string dir = "ASC") { - order_by_terms += new OrderingTerm(column, dir); - return this; - } - - public QueryBuilder order_by_name(string name, string dir) { - order_by_terms += new OrderingTerm.by_name(name, dir); - return this; - } - - public QueryBuilder group_by(Column[] columns) { - foreach(Column col in columns) { - if (group_by_term == null) { - group_by_term = col.to_string(); - } else { - group_by_term += @", $col"; - } - } - return this; - } - - public QueryBuilder limit(int limit) { - if (this.limit_val != 0 && limit > this.limit_val) error("tried to increase an existing limit"); - this.limit_val = limit; - return this; - } - - public QueryBuilder offset(int offset) { - if (this.limit_val == 0) error("limit required before offset"); - this.offset_val = offset; - return this; - } - - public QueryBuilder single() { - this.single_result = true; - return limit(1); - } - - public int64 count() { - this.column_selector = @"COUNT($column_selector) AS count"; - this.single_result = true; - return row().get_integer("count"); - } - - private Row? row_() { - if (!single_result) error("query is not suited to return a single row, but row() was called."); - return iterator().get_next(); - } - - public RowOption row() { - return new RowOption(row_()); - } - - public T get(Column field, T def = null) { - return row().get(field, def); - } - - internal override Statement prepare() { - Statement stmt = db.prepare(@"SELECT $column_selector $(table_name == null ? "" : @"FROM $((!) table_name)") $joins WHERE $selection $(group_by_term == null ? "" : @"GROUP BY $group_by_term") $(OrderingTerm.all_to_string(order_by_terms)) $(limit_val > 0 ? @" LIMIT $limit_val OFFSET $offset_val" : "")"); - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i+1); - } - return stmt; - } - - public RowIterator iterator() { - return new RowIterator.from_query_builder(db, this); - } - - class OrderingTerm { - Column? column; - string column_name; - string dir; - - public OrderingTerm(Column column, string dir) { - this.column = column; - this.column_name = column.to_string(); - this.dir = dir; - } - - public OrderingTerm.by_name(string column_name, string dir) { - this.column_name = column_name; - this.dir = dir; - } - - public string to_string() { - return @"$column_name $dir"; - } - - public static string all_to_string(OrderingTerm[]? terms) { - if (terms == null || terms.length == 0) return ""; - string res = "ORDER BY "+terms[0].to_string(); - for (int i = 1; i < terms.length; i++) { - res += @", $(terms[i])"; - } - return res; - } - } -} - -public class MatchQueryBuilder : QueryBuilder { - internal MatchQueryBuilder(Database db, Table table) { - base(db); - if (table.fts_columns == null) error("MATCH query on non FTS table"); - from(table); - join_name(@"_fts_$table_name", @"_fts_$table_name.docid = $table_name.rowid"); - } - - public MatchQueryBuilder match(Column column, string match) { - if (table == null) error("MATCH must occur after FROM statement"); - if (!(column in table.fts_columns)) error("MATCH selection on non FTS column"); - selection_args += new StatementBuilder.StringField(match); - selection = @"($selection) AND _fts_$table_name.$(column.name) MATCH ?"; - return this; - } -} - -} diff --git a/qlite/src/row.vala b/qlite/src/row.vala deleted file mode 100644 index 4671db20..00000000 --- a/qlite/src/row.vala +++ /dev/null @@ -1,147 +0,0 @@ -using Gee; -using Sqlite; - -namespace Qlite { - -public class Row { - private Map text_map = new HashMap(); - private Map int_map = new HashMap(); - private Map real_map = new HashMap(); - - internal Row(Statement stmt) { - for (int i = 0; i < stmt.column_count(); i++) { - string column_name; - if (stmt.column_origin_name(i) != null) { - column_name = @"$(stmt.column_table_name(i)).$(stmt.column_origin_name(i))"; - } else { - column_name = stmt.column_name(i); - } - switch(stmt.column_type(i)) { - case TEXT: - text_map[column_name] = stmt.column_text(i); - break; - case INTEGER: - int_map[column_name] = (long) stmt.column_int64(i); - break; - case FLOAT: - real_map[column_name] = stmt.column_double(i); - break; - } - } - } - - public T get(Column field) { - return field[this]; - } - - private string field_name(string field, string? table) { - if (table != null) { - return @"$table.$field"; - } else { - return field; - } - } - - public string? get_text(string field, string? table = null) { - if (text_map.has_key(field_name(field, table))) { - return text_map[field_name(field, table)]; - } - return null; - } - - public long get_integer(string field, string? table = null) { - return int_map[field_name(field, table)]; - } - - public bool has_integer(string field, string? table = null) { - return int_map.has_key(field_name(field, table)); - } - - public double get_real(string field, string? table = null, double def = 0) { - return real_map[field_name(field, table)] ?? def; - } - - public bool has_real(string field, string? table = null) { - return real_map.has_key(field_name(field, table)) && real_map[field_name(field, table)] != null; - } - - public string to_string() { - string ret = "{"; - - foreach (string key in text_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: \"$(text_map[key])\""; - } - foreach (string key in int_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: $(int_map[key])"; - } - foreach (string key in real_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: $(real_map[key])"; - } - - return ret + "}"; - } -} - -public class RowIterator { - private Database db; - private Statement stmt; - - public RowIterator.from_query_builder(Database db, QueryBuilder query) { - this.db = db; - this.stmt = query.prepare(); - } - - public RowIterator(Database db, string sql, string[]? args = null) { - this.db = db; - this.stmt = db.prepare(sql); - if (args != null) { - for (int i = 0; i < args.length; i++) { - stmt.bind_text(i, sql, sql.length); - } - } - } - - public bool next() { - int r = stmt.step(); - if (r == Sqlite.ROW) return true; - if (r == Sqlite.DONE) return false; - warning(@"SQLite error: $(db.errcode()) - $(db.errmsg())"); - return false; - } - - public Row get() { - return new Row(stmt); - } - - public Row? get_next() { - if (next()) return get(); - return null; - } -} - -public class RowOption { - public Row? inner { get; private set; } - - public RowOption(Row? row) { - this.inner = row; - } - - public bool is_present() { - return inner != null; - } - - public T get(Column field, T def = null) { - if (inner == null || field.is_null((!)inner)) return def; - return field[(!)inner]; - } - - internal long get_integer(string field, long def = 0) { - if (inner == null || !((!)inner).has_integer(field)) return def; - return ((!)inner).get_integer(field); - } -} - -} diff --git a/qlite/src/statement_builder.vala b/qlite/src/statement_builder.vala deleted file mode 100644 index dca6983e..00000000 --- a/qlite/src/statement_builder.vala +++ /dev/null @@ -1,58 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public abstract class StatementBuilder { - protected Database db; - - internal StatementBuilder(Database db) { - this.db = db; - } - - internal abstract Statement prepare(); - - internal abstract class AbstractField { - public T value; - public Column? column; - - AbstractField(T value) { - this.value = value; - } - - internal abstract void bind(Statement stmt, int index); - } - - internal class Field : AbstractField { - public Field(Column column, T value) { - base(value); - this.column = column; - } - - internal override void bind(Statement stmt, int index) { - ((!)column).bind(stmt, index, value); - } - } - - internal class NullField : AbstractField { - public NullField(Column column) { - base(null); - this.column = column; - } - - internal override void bind(Statement stmt, int index) { - stmt.bind_null(index); - } - } - - internal class StringField : AbstractField { - public StringField(string value) { - base(value); - } - - internal override void bind(Statement stmt, int index) { - stmt.bind_text(index, value); - } - } -} - -} diff --git a/qlite/src/table.vala b/qlite/src/table.vala deleted file mode 100644 index a5a57c49..00000000 --- a/qlite/src/table.vala +++ /dev/null @@ -1,218 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class Table { - protected Database db; - public string name { get; private set; } - protected Column[]? columns; - private string constraints = ""; - private string[] post_statements = {}; - private string[] create_statements = {}; - internal Column[]? fts_columns; - - public Table(Database db, string name) { - this.db = db; - this.name = name; - } - - public void init(Column[] columns, string constraints = "") { - this.columns = columns; - this.constraints = constraints; - - foreach(Column c in columns) { - c.table = this; - } - } - - public void fts(Column[] columns) { - if (fts_columns != null) error("Only one FTS index may be used per table."); - fts_columns = columns; - string cs = ""; - string cnames = ""; - string cnews = ""; - foreach (Column c in columns) { - cs += @", $(c.to_column_definition())"; - cnames += @", $(c.name)"; - cnews += @", new.$(c.name)"; - } - add_create_statement(@"CREATE VIRTUAL TABLE IF NOT EXISTS _fts_$name USING fts4(tokenize=unicode61, content=\"$name\"$cs)"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bu_$(name) BEFORE UPDATE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bd_$(name) BEFORE DELETE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_au_$(name) AFTER UPDATE ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_ai_$(name) AFTER INSERT ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); - } - - public void fts_rebuild() { - if (fts_columns == null) error("FTS not available on this table."); - try { - db.exec(@"INSERT INTO _fts_$name(_fts_$name) VALUES('rebuild');"); - } catch (Error e) { - critical(@"Qlite Error: Rebuilding FTS index: $(e.message)"); - } - } - - public void unique(Column[] columns, string? on_conflict = null) { - constraints += ", UNIQUE ("; - bool first = true; - foreach (Column c in columns) { - if (!first) constraints += ", "; - constraints += c.name; - first = false; - } - constraints += ")"; - if (on_conflict != null) { - constraints += " ON CONFLICT " + (!)on_conflict; - } - } - - public void add_post_statement(string stmt) { - post_statements += stmt; - } - - public void add_create_statement(string stmt) { - create_statements += stmt; - } - - public void index(string index_name, Column[] columns, bool unique = false) { - string stmt = @"CREATE $(unique ? "UNIQUE" : "") INDEX IF NOT EXISTS $index_name ON $name ("; - bool first = true; - foreach (Column c in columns) { - if (!first) stmt += ", "; - stmt += c.name; - first = false; - } - stmt += ")"; - add_post_statement(stmt); - } - - private void ensure_init() { - if (columns == null) error("Table %s was not initialized, call init()", name); - } - - public QueryBuilder select(Column[]? columns = null) { - ensure_init(); - return db.select(columns).from(this); - } - - private MatchQueryBuilder match_query() { - ensure_init(); - return db.match_query(this); - } - - public MatchQueryBuilder match(Column column, string query) { - return match_query().match(column, query); - } - - public InsertBuilder insert() { - ensure_init(); - return db.insert().into(this); - } - - public UpdateBuilder update() { - ensure_init(); - return db.update(this); - } - - public UpsertBuilder upsert() { - ensure_init(); - return db.upsert(this); - } - - public DeleteBuilder delete() { - ensure_init(); - return db.delete().from(this); - } - - public RowOption row_with(Column column, T value) { - ensure_init(); - if (!column.unique && !column.primary_key) error("%s is not suited to identify a row, but used with row_with()", column.name); - return select().with(column, "=", value).row(); - } - - public bool is_known_column(string column) { - ensure_init(); - foreach (Column c in columns) { - if (c.name == column) return true; - } - return false; - } - - public void create_table_at_version(long version) { - ensure_init(); - string sql = @"CREATE TABLE IF NOT EXISTS $name ("; - bool first = true; - for (int i = 0; i < columns.length; i++) { - Column c = columns[i]; - if (c.min_version <= version && c.max_version >= version) { - sql += @"$(!first ? "," : "") $(c.to_column_definition())"; - first = false; - } - } - sql += @"$constraints)"; - try { - db.exec(sql); - } catch (Error e) { - error(@"Qlite Error: Create table at version: $(e.message)"); - } - foreach (string stmt in create_statements) { - try { - db.exec(stmt); - } catch (Error e) { - error(@"Qlite Error: Create table at version: $(e.message)"); - } - } - } - - public void add_columns_for_version(long old_version, long new_version) { - ensure_init(); - foreach (Column c in columns) { - if (c.min_version <= new_version && c.max_version >= new_version && c.min_version > old_version) { - try { - db.exec(@"ALTER TABLE $name ADD COLUMN $(c.to_column_definition())"); - } catch (Error e) { - critical(@"Qlite Error: Add columns for version: $(e.message)"); - } - } - } - } - - public void delete_columns_for_version(long old_version, long new_version) { - bool column_deletion_required = false; - string column_list = ""; - foreach (Column c in columns) { - if (c.min_version <= new_version && c.max_version >= new_version) { - if (column_list == "") { - column_list = c.name; - } else { - column_list += ", " + c.name; - } - } - if (!(c.min_version <= new_version && c.max_version >= new_version) && c.min_version <= old_version && c.max_version >= old_version) { - column_deletion_required = true; - } - } - if (column_deletion_required) { - try { - db.exec(@"ALTER TABLE $name RENAME TO _$(name)_$old_version"); - create_table_at_version(new_version); - db.exec(@"INSERT INTO $name ($column_list) SELECT $column_list FROM _$(name)_$old_version"); - db.exec(@"DROP TABLE _$(name)_$old_version"); - } catch (Error e) { - error(@"Qlite Error: Delete columns for version change: $(e.message)"); - } - } - } - - internal void post() { - foreach (string stmt in post_statements) { - try { - db.exec(stmt); - } catch (Error e) { - error(@"Qlite Error: Post: $(e.message)"); - } - } - } -} - -} diff --git a/qlite/src/update_builder.vala b/qlite/src/update_builder.vala deleted file mode 100644 index 0bf83aee..00000000 --- a/qlite/src/update_builder.vala +++ /dev/null @@ -1,103 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class UpdateBuilder : StatementBuilder { - - // UPDATE [OR ...] - private string? or_val; - - // [...] - private Table? table; - private string table_name; - - // SET [...] - private StatementBuilder.AbstractField[] fields = {}; - - // WHERE [...] - private string selection = "1"; - private StatementBuilder.AbstractField[] selection_args = {}; - - internal UpdateBuilder(Database db, Table table) { - base(db); - this.table = table; - this.table_name = table.name; - } - - internal UpdateBuilder.for_name(Database db, string table) { - base(db); - this.table_name = table; - } - - public UpdateBuilder or(string or) { - this.or_val = or; - return this; - } - - public UpdateBuilder set(Column column, T value) { - fields += new Field(column, value); - return this; - } - - public UpdateBuilder set_null(Column column) { - if (column.not_null) error("Can't set non-null column %s to null", column.name); - fields += new NullField(column); - return this; - } - - public UpdateBuilder where(string selection, string[] selection_args = {}) { - if (this.selection != "1") error("selection was already done, but where() was called."); - this.selection = selection; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public UpdateBuilder with(Column column, string comp, T value) { - selection_args += new Field(column, value); - selection = @"($selection) AND $(column.name) $comp ?"; - return this; - } - - public UpdateBuilder with_null(Column column) { - selection = @"($selection) AND $(column.name) ISNULL"; - return this; - } - - public UpdateBuilder without_null(Column column) { - selection = @"($selection) AND $(column.name) NOT NULL"; - return this; - } - - internal override Statement prepare() { - string sql = "UPDATE"; - if (or_val != null) sql += @" OR $((!)or_val)"; - sql += @" $table_name SET "; - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - sql += ", "; - } - sql += @"$(((!)fields[i].column).name) = ?"; - } - sql += @" WHERE $selection"; - Statement stmt = db.prepare(sql); - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i+1); - } - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i + fields.length + 1); - } - return stmt; - } - - public void perform() { - if (fields.length == 0) return; - if (prepare().step() != DONE) { - critical("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - -} - -} diff --git a/qlite/src/upsert_builder.vala b/qlite/src/upsert_builder.vala deleted file mode 100644 index 79104972..00000000 --- a/qlite/src/upsert_builder.vala +++ /dev/null @@ -1,93 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class UpsertBuilder : StatementBuilder { - // INTO [...] - private Table table; - private string table_name; - - // VALUES [...] - private StatementBuilder.AbstractField[] keys = {}; - private StatementBuilder.AbstractField[] fields = {}; - - internal UpsertBuilder(Database db, Table table) { - base(db); - this.table = table; - this.table_name = table.name; - } - - public UpsertBuilder value(Column column, T value, bool key = false) { - if (key) { - keys += new Field(column, value); - } else { - fields += new Field(column, value); - } - return this; - } - - public UpsertBuilder value_null(Column column, bool key = false) { - if (column.not_null) error("Can't set non-null column %s to null", column.name); - if (key) { - keys += new NullField(column); - } else { - fields += new NullField(column); - } - return this; - } - - internal override Statement prepare() { - error("prepare() not available for upsert."); - } - - internal Statement prepare_upsert() { - var unique_fields = new StringBuilder(); - var unique_values = new StringBuilder(); - var update_fields = new StringBuilder(); - var update_values = new StringBuilder(); - var update_fields_vals = new StringBuilder(); - - for (int i = 0; i < keys.length; i++) { - if (i != 0) { - unique_fields.append(", "); - unique_values.append(", "); - } - unique_fields.append(keys[i].column.name); - unique_values.append("?"); - } - - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - update_fields.append(", "); - update_values.append(", "); - update_fields_vals.append(", "); - } - update_fields.append(fields[i].column.name); - update_values.append("?"); - update_fields_vals.append(fields[i].column.name).append("=excluded.").append(fields[i].column.name); - } - - string sql = @"INSERT INTO $table_name ($(unique_fields.str), $(update_fields.str)) VALUES ($(unique_values.str), $(update_values.str)) " + - @"ON CONFLICT ($(unique_fields.str)) DO UPDATE SET $(update_fields_vals.str)"; - - Statement stmt = db.prepare(sql); - for (int i = 0; i < keys.length; i++) { - keys[i].bind(stmt, i + 1); - } - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i + keys.length + 1); - } - - return stmt; - } - - public int64 perform() { - if (prepare_upsert().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - return db.last_insert_rowid(); - } - -} - -} -- cgit v1.3 From cd0d992b9b5d3ea29c7d4a3aab76ad53319ea162 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sat, 3 Oct 2026 13:22:02 +0200 Subject: Move ICE into libdino --- libdino/meson.build | 2 + libdino/src/service/ice.vala | 538 +++++++++++++++++++++ libdino/src/service/module_manager.vala | 5 +- libdino/src/service/util.vala | 12 +- libdino/vapi/metadata/Nice-0.1.metadata | 11 + libdino/vapi/nice.vapi | 386 +++++++++++++++ plugins/ice/meson.build | 25 - plugins/ice/src/module.vala | 57 --- plugins/ice/src/plugin.vala | 104 ---- plugins/ice/src/register_plugin.vala | 3 - plugins/ice/src/transport_parameters.vala | 391 --------------- plugins/ice/src/util.vala | 18 - plugins/ice/vapi/metadata/Nice-0.1.metadata | 11 - plugins/ice/vapi/nice.vapi | 386 --------------- plugins/meson.build | 1 - .../src/module/xep/0065_socks5_bytestreams.vala | 4 + xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala | 4 + 17 files changed, 956 insertions(+), 1002 deletions(-) create mode 100644 libdino/src/service/ice.vala create mode 100644 libdino/vapi/metadata/Nice-0.1.metadata create mode 100644 libdino/vapi/nice.vapi delete mode 100644 plugins/ice/meson.build delete mode 100644 plugins/ice/src/module.vala delete mode 100644 plugins/ice/src/plugin.vala delete mode 100644 plugins/ice/src/register_plugin.vala delete mode 100644 plugins/ice/src/transport_parameters.vala delete mode 100644 plugins/ice/src/util.vala delete mode 100644 plugins/ice/vapi/metadata/Nice-0.1.metadata delete mode 100644 plugins/ice/vapi/nice.vapi (limited to 'libdino/src/service') diff --git a/libdino/meson.build b/libdino/meson.build index 67ac6a83..e680b662 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -9,6 +9,7 @@ dependencies = [ dep_gmodule, dep_libsoup, dep_libsrtp2, + dep_nice, dep_sqlite3, dep_xmpp_vala ] @@ -63,6 +64,7 @@ sources = files( 'src/service/file_manager.vala', 'src/service/file_transfer_storage.vala', 'src/service/history_sync.vala', + 'src/service/ice.vala', 'src/service/jingle_file_transfers.vala', 'src/service/message_correction.vala', 'src/service/message_deletion.vala', diff --git a/libdino/src/service/ice.vala b/libdino/src/service/ice.vala new file mode 100644 index 00000000..0e168be9 --- /dev/null +++ b/libdino/src/service/ice.vala @@ -0,0 +1,538 @@ +using Gee; + +using Dino.Crypto; +using Xmpp; +using Xmpp.Xep; + +private extern const size_t NICE_ADDRESS_STRING_LEN; + +public class Dino.IceUdpModule : Xmpp.Xep.JingleIceUdp.Module { + + public string? stun_ip = null; + public uint stun_port = 0; + public string? turn_ip = null; + public Xep.ExternalServiceDiscovery.Service? turn_service = null; + + private static weak Nice.Agent? agent; + private HashMap cerds = new HashMap(); + + private uint timeout = 0; + + public override void attach(XmppStream stream) { + base.attach(stream); + external_discovery_refresh_services.begin(stream); + } + public override void detach(XmppStream stream) { + base.detach(stream); + stop_external_discovery_refresh_services(); + } + + private Nice.Agent get_agent() { + Nice.Agent? agent = this.agent; + if (agent == null) { + Nice.debug_enable(true); + agent = new Nice.Agent(MainContext.@default(), Nice.Compatibility.RFC5245); + if (stun_ip != null) { + agent.stun_server = stun_ip; + agent.stun_server_port = stun_port; + } + agent.ice_tcp = false; + agent.set_software("Dino"); + agent.weak_ref(agent_unweak); + this.agent = agent; + debug("STUN server for libnice %s %u", agent.stun_server, agent.stun_server_port); + } + return agent; + } + + private void agent_unweak() { + this.agent = null; + } + + public override Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) { + DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); + return new IceUdpTransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid); + } + + public override Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError { + DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); + return new IceUdpTransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid, transport); + } + + private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) { + string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); + try { + if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); + } catch (GLib.Error e) { + warning("Error creating dtls credentials: %s", e.message); + } + return cerds[from_to_id]; + } + + private void stop_external_discovery_refresh_services() { + if (timeout != 0) { + Source.remove(timeout); + timeout = 0; + } + } + + private async void external_discovery_refresh_services(XmppStream stream) { + stop_external_discovery_refresh_services(); + Gee.List services = yield ExternalServiceDiscovery.request_services(stream); + foreach (Xep.ExternalServiceDiscovery.Service service in services) { + if (service.transport == "udp" && (service.ty == "stun" || service.ty == "turn")) { + InetAddress? ip = yield lookup_ipv4_addess(service.host); + if (ip == null) continue; + + if (ip.is_any || ip.is_link_local || ip.is_loopback || ip.is_multicast || ip.is_site_local) { + warning("Ignoring STUN/TURN server at %s", service.host); + continue; + } + + if (service.ty == "stun") { + debug("Server offers STUN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); + stun_ip = ip.to_string(); + stun_port = service.port; + } else if (service.ty == "turn") { + debug("Server offers TURN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); + turn_ip = ip.to_string(); + turn_service = service; + } + } + } + if (stun_ip == null) { + InetAddress ip = yield lookup_ipv4_addess("stun.dino.im"); + if (ip == null) return; + + debug("Using fallback STUN server: stun.dino.im:7886, resolved to %s", ip.to_string()); + + stun_ip = ip.to_string(); + stun_port = 7886; + } + + // Refresh TURN credentials before they expire + if (turn_service != null) { + DateTime? expires = turn_service.expires; + if (expires != null) { + uint refresh_delay = (uint) (expires.to_unix() - new DateTime.now_utc().to_unix()) / 2; + + if (refresh_delay >= 300 && refresh_delay <= (int64) uint.MAX) { // 5 min < refetch < max + debug("Re-fetching TURN credentials in %u sec", refresh_delay); + + stop_external_discovery_refresh_services(); + timeout = Timeout.add_seconds((uint) refresh_delay, () => { + timeout = 0; + external_discovery_refresh_services.begin(stream); + return false; + }); + } else { + warning("TURN credentials' expiry time = %u, *not* re-fetching", refresh_delay); + } + } + } + } + + private async InetAddress? lookup_ipv4_addess(string host) { + try { + Resolver resolver = Resolver.get_default(); + GLib.List? ips = yield resolver.lookup_by_name_async(host); + foreach (GLib.InetAddress ina in ips) { + if (ina.get_family() != SocketFamily.IPV4) continue; + return ina; + } + } catch (GLib.Error e) { + warning("Failed looking up IP address of %s", host); + } + return null; + } +} + +public class Dino.IceUdpTransportParameters : JingleIceUdp.IceUdpTransportParameters { + private Nice.Agent agent; + private uint stream_id; + private bool we_want_connection; + private bool remote_credentials_set; + private Map connections = new HashMap(); + private DtlsSrtp.Handler? dtls_srtp_handler; + private MainContext thread_context; + private MainLoop thread_loop; + + private static bool is_component_ready(Nice.Agent agent, uint stream_id, uint component_id) { + var state = agent.get_component_state(stream_id, component_id); + return state == Nice.ComponentState.CONNECTED || state == Nice.ComponentState.READY; + } + + private class DatagramConnection : Jingle.DatagramConnection { + private Nice.Agent agent; + private DtlsSrtp.Handler? dtls_srtp_handler; + private uint stream_id; + private string? error; + private ulong datagram_received_id; + + internal DatagramConnection(Nice.Agent agent, DtlsSrtp.Handler? dtls_srtp_handler, uint stream_id, uint8 component_id) { + this.agent = agent; + this.dtls_srtp_handler = dtls_srtp_handler; + this.stream_id = stream_id; + this.component_id = component_id; + this.datagram_received_id = this.datagram_received.connect((datagram) => { + bytes_received += datagram.length; + }); + } + + public override async void terminate(bool we_terminated, string? reason_string = null, string? reason_text = null) { + yield base.terminate(we_terminated, reason_string, reason_text); + this.disconnect(datagram_received_id); + agent = null; + dtls_srtp_handler = null; + } + + public override void send_datagram(Bytes datagram) { + if (this.agent != null && is_component_ready(agent, stream_id, component_id)) { + try { + if (dtls_srtp_handler != null) { + uint8[] encrypted_data = dtls_srtp_handler.process_outgoing_data(component_id, datagram.get_data()); + if (encrypted_data == null) return; + GLib.OutputVector vector = { encrypted_data, encrypted_data.length }; + GLib.OutputVector[] vectors = { vector }; + Nice.OutputMessage message = { vectors }; + Nice.OutputMessage[] messages = { message }; + agent.send_messages_nonblocking(stream_id, component_id, messages); + } else { + GLib.OutputVector vector = { datagram.get_data(), datagram.get_size() }; + GLib.OutputVector[] vectors = { vector }; + Nice.OutputMessage message = { vectors }; + Nice.OutputMessage[] messages = { message }; + agent.send_messages_nonblocking(stream_id, component_id, messages); + } + bytes_sent += datagram.length; + } catch (GLib.Error e) { + warning("%s while send_datagram stream %u component %u", e.message, stream_id, component_id); + } + } + } + } + + internal IceUdpTransportParameters(Nice.Agent agent, DtlsSrtp.CredentialsCapsule? credentials, Xep.ExternalServiceDiscovery.Service? turn_service, string? turn_ip, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode? node = null) { + base(components, local_full_jid, peer_full_jid, node); + this.we_want_connection = (node == null); + this.agent = agent; + + if (this.peer_fingerprint != null || !incoming) { + dtls_srtp_handler = setup_dtls(this, credentials); + own_fingerprint = dtls_srtp_handler.own_fingerprint; + if (incoming) { + own_setup = "active"; + dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } else { + own_setup = "actpass"; + dtls_srtp_handler.mode = DtlsSrtp.Mode.SERVER; + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (content_encryption != null) { + this.content.encryptions[content_encryption.encryption_ns] = content_encryption; + } + }); + } + } + + agent.candidate_gathering_done.connect(on_candidate_gathering_done); + agent.initial_binding_request_received.connect(on_initial_binding_request_received); + agent.component_state_changed.connect(on_component_state_changed); + agent.new_selected_pair_full.connect(on_new_selected_pair_full); + agent.new_candidate_full.connect(on_new_candidate); + + agent.controlling_mode = !incoming; + stream_id = agent.add_stream(components); + thread_context = new MainContext(); + new Thread(@"ice-thread-$stream_id", () => { + thread_context.push_thread_default(); + thread_loop = new MainLoop(thread_context, false); + thread_loop.run(); + thread_context.pop_thread_default(); + return null; + }); + + if (turn_ip != null) { + for (uint8 component_id = 1; component_id <= components; component_id++) { + agent.set_relay_info(stream_id, component_id, turn_ip, turn_service.port, turn_service.username, turn_service.password, Nice.RelayType.UDP); + debug("TURN info (component %i) %s:%u", component_id, turn_ip, turn_service.port); + } + } + string ufrag; + string pwd; + agent.get_local_credentials(stream_id, out ufrag, out pwd); + init(ufrag, pwd); + + for (uint8 component_id = 1; component_id <= components; component_id++) { + // We don't properly get local candidates before this call + agent.attach_recv(stream_id, component_id, thread_context, on_recv); + } + + agent.gather_candidates(stream_id); + } + + private static DtlsSrtp.Handler setup_dtls(IceUdpTransportParameters tp, DtlsSrtp.CredentialsCapsule credentials) { + var weak_self = WeakRef(tp); + DtlsSrtp.Handler dtls_srtp = new DtlsSrtp.Handler.with_cert(credentials); + dtls_srtp.send_data.connect((data) => { + IceUdpTransportParameters self = (IceUdpTransportParameters) weak_self.get(); + if (self != null) self.agent.send(self.stream_id, 1, data); + }); + return dtls_srtp; + } + + private void on_candidate_gathering_done(uint stream_id) { + if (stream_id != this.stream_id) return; + debug("on_candidate_gathering_done in %u", stream_id); + + for (uint8 i = 1; i <= components; i++) { + foreach (unowned Nice.Candidate nc in agent.get_local_candidates(stream_id, i)) { + if (nc.transport == Nice.CandidateTransport.UDP) { + JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); + if (candidate == null) continue; + debug("Local candidate summary: %s", agent.generate_local_candidate_sdp(nc)); + } + } + } + } + + private void on_new_candidate(Nice.Candidate nc) { + if (nc.stream_id != stream_id) return; + JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); + if (candidate == null) return; + + if (nc.transport == Nice.CandidateTransport.UDP) { + // Execution was in the agent thread before + add_local_candidate_threadsafe(candidate); + } + } + + private bool bytes_equal(uint8[] a1, uint8[] a2) { + return a1.length == a2.length && Memory.cmp(a1, a2, a1.length) == 0; + } + + public override void handle_transport_accept(StanzaNode transport) throws Jingle.IqError { + debug("on_transport_accept from %s", peer_full_jid.to_string()); + base.handle_transport_accept(transport); + + if (dtls_srtp_handler != null && peer_fingerprint != null) { + if (dtls_srtp_handler.peer_fingerprint != null) { + if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { + warning("Tried to replace certificate fingerprint mid use. We don't allow that."); + peer_fingerprint = dtls_srtp_handler.peer_fingerprint; + peer_fp_algo = dtls_srtp_handler.peer_fp_algo; + } + } else { + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } + if (peer_setup == "passive") { + dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; + dtls_srtp_handler.stop_dtls_connection(); + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (content_encryption != null) { + this.content.encryptions[content_encryption.encryption_ns] = content_encryption; + } + }); + } + } else { + dtls_srtp_handler = null; + } + } + + public override void handle_transport_info(StanzaNode transport) throws Jingle.IqError { + debug("on_transport_info from %s", peer_full_jid.to_string()); + base.handle_transport_info(transport); + + if (dtls_srtp_handler != null && peer_fingerprint != null) { + if (dtls_srtp_handler.peer_fingerprint != null) { + if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { + warning("Tried to replace certificate fingerprint mid use. We don't allow that."); + peer_fingerprint = dtls_srtp_handler.peer_fingerprint; + peer_fp_algo = dtls_srtp_handler.peer_fp_algo; + } + } else { + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } + } + + if (!we_want_connection) return; + + if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { + agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); + remote_credentials_set = true; + } + for (uint8 i = 1; i <= components; i++) { + SList candidates = new SList(); + foreach (JingleIceUdp.Candidate candidate in remote_candidates) { + if (candidate.component == i) { + candidates.append(candidate_to_nice(candidate)); + } + } + int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); + debug("Updated to %i remote candidates for candidate %u via transport info", new_candidates, i); + } + } + + public override void create_transport_connection(XmppStream stream, Jingle.Content content) { + debug("create_transport_connection: %s", content.session.sid); + debug("local_credentials: %s %s", local_ufrag, local_pwd); + debug("remote_credentials: %s %s", remote_ufrag, remote_pwd); + debug("expected incoming credentials: %s %s", local_ufrag + ":" + remote_ufrag, local_pwd); + debug("expected outgoing credentials: %s %s", remote_ufrag + ":" + local_ufrag, remote_pwd); + + we_want_connection = true; + + if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { + agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); + remote_credentials_set = true; + } + for (uint8 i = 1; i <= components; i++) { + SList candidates = new SList(); + foreach (JingleIceUdp.Candidate candidate in remote_candidates) { + if (candidate.ip.has_prefix("fe80::")) continue; + if (candidate.component == i) { + candidates.append(candidate_to_nice(candidate)); + debug("remote candidate: %s", agent.generate_local_candidate_sdp(candidate_to_nice(candidate))); + } + } + int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); + debug("Initiated component %u with %i remote candidates", i, new_candidates); + + connections[i] = new DatagramConnection(agent, dtls_srtp_handler, stream_id, i); + content.set_transport_connection(connections[i], i); + } + + base.create_transport_connection(stream, content); + } + + private void on_component_state_changed(uint stream_id, uint component_id, uint state) { + if (stream_id != this.stream_id) return; + debug("stream %u component %u state changed to %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); + may_consider_ready(stream_id, component_id); + if (incoming && dtls_srtp_handler != null && !dtls_srtp_handler.ready && is_component_ready(agent, stream_id, component_id) && dtls_srtp_handler.mode == DtlsSrtp.Mode.CLIENT) { + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + Jingle.ContentEncryption? encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (encryption != null) { + this.content.encryptions[encryption.encryption_ns] = encryption; + } + }); + } + } + + private void may_consider_ready(uint stream_id, uint component_id) { + if (stream_id != this.stream_id) return; + if (connections.has_key((uint8) component_id) && !connections[(uint8)component_id].ready && is_component_ready(agent, stream_id, component_id) && (dtls_srtp_handler == null || dtls_srtp_handler.ready)) { + connections[(uint8)component_id].ready = true; + } + } + + private void on_initial_binding_request_received(uint stream_id) { + if (stream_id != this.stream_id) return; + debug("initial_binding_request_received"); + } + + private void on_new_selected_pair_full(uint stream_id, uint component_id, Nice.Candidate p1, Nice.Candidate p2) { + if (stream_id != this.stream_id) return; + debug("new_selected_pair_full %u [%s, %s]", component_id, agent.generate_local_candidate_sdp(p1), agent.generate_local_candidate_sdp(p2)); + } + + private void on_recv(Nice.Agent agent, uint stream_id, uint component_id, uint8[] data) { + if (stream_id != this.stream_id) return; + uint8[] decrypt_data = null; + if (dtls_srtp_handler != null) { + try { + decrypt_data = dtls_srtp_handler.process_incoming_data(component_id, data); + if (decrypt_data == null) return; + } catch (Crypto.Error e) { + warning("%s while on_recv stream %u component %u", e.message, stream_id, component_id); + return; + } + } + may_consider_ready(stream_id, component_id); + if (connections.has_key((uint8) component_id)) { + if (!connections[(uint8) component_id].ready) { + debug("on_recv stream %u component %u when state %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); + } + connections[(uint8) component_id].datagram_received(new Bytes(decrypt_data ?? data)); + } else { + debug("on_recv stream %u component %u length %u", stream_id, component_id, data.length); + } + } + + private static Nice.Candidate candidate_to_nice(JingleIceUdp.Candidate c) { + Nice.CandidateType type; + switch (c.type_) { + case JingleIceUdp.Candidate.Type.HOST: type = Nice.CandidateType.HOST; break; + case JingleIceUdp.Candidate.Type.PRFLX: type = Nice.CandidateType.PEER_REFLEXIVE; break; + case JingleIceUdp.Candidate.Type.RELAY: type = Nice.CandidateType.RELAYED; break; + case JingleIceUdp.Candidate.Type.SRFLX: type = Nice.CandidateType.SERVER_REFLEXIVE; break; + default: assert_not_reached(); + } + + Nice.Candidate candidate = new Nice.Candidate(type); + candidate.component_id = c.component; + char[] foundation = new char[Nice.CANDIDATE_MAX_FOUNDATION]; + Memory.copy(foundation, c.foundation.data, size_t.min(c.foundation.length, Nice.CANDIDATE_MAX_FOUNDATION - 1)); + candidate.foundation = foundation; + candidate.addr = Nice.Address(); + candidate.addr.init(); + candidate.addr.set_from_string(c.ip); + candidate.addr.set_port(c.port); + candidate.priority = c.priority; + if (c.rel_addr != null) { + candidate.base_addr = Nice.Address(); + candidate.base_addr.init(); + candidate.base_addr.set_from_string(c.rel_addr); + candidate.base_addr.set_port(c.rel_port); + } + candidate.transport = Nice.CandidateTransport.UDP; + return candidate; + } + + private static JingleIceUdp.Candidate? candidate_to_jingle(Nice.Candidate nc) { + JingleIceUdp.Candidate candidate = new JingleIceUdp.Candidate(); + switch (nc.type) { + case Nice.CandidateType.HOST: candidate.type_ = JingleIceUdp.Candidate.Type.HOST; break; + case Nice.CandidateType.PEER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.PRFLX; break; + case Nice.CandidateType.RELAYED: candidate.type_ = JingleIceUdp.Candidate.Type.RELAY; break; + case Nice.CandidateType.SERVER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.SRFLX; break; + default: assert_not_reached(); + } + candidate.component = (uint8) nc.component_id; + candidate.foundation = ((string)nc.foundation).dup(); + candidate.generation = 0; + candidate.id = Random.next_int().to_string("%08x"); // TODO + + char[] res = new char[NICE_ADDRESS_STRING_LEN]; + nc.addr.to_string(res); + candidate.ip = (string) res; + candidate.network = 0; // TODO + candidate.port = (uint16) nc.addr.get_port(); + candidate.priority = nc.priority; + candidate.protocol = "udp"; + if (nc.base_addr.is_valid() && !nc.base_addr.equal(nc.addr)) { + res = new char[NICE_ADDRESS_STRING_LEN]; + nc.base_addr.to_string(res); + candidate.rel_addr = (string) res; + candidate.rel_port = (uint16) nc.base_addr.get_port(); + } + if (candidate.ip.has_prefix("fe80::")) return null; + + return candidate; + } + + public override void dispose() { + base.dispose(); + agent = null; + dtls_srtp_handler = null; + connections.clear(); + if (thread_loop != null) { + thread_loop.quit(); + } + } +} diff --git a/libdino/src/service/module_manager.vala b/libdino/src/service/module_manager.vala index f7cad0fe..a6efe629 100644 --- a/libdino/src/service/module_manager.vala +++ b/libdino/src/service/module_manager.vala @@ -85,7 +85,7 @@ public class ModuleManager { module_map[account].add(new Xep.InBandRegistration.Module()); module_map[account].add(new Xep.HttpFileUpload.Module()); module_map[account].add(new Xep.Reactions.Module()); - module_map[account].add(new Xep.Socks5Bytestreams.Module()); + module_map[account].add(new Xep.Socks5Bytestreams.Module.with_local_ip_address_handler(Util.get_local_ip_addresses)); module_map[account].add(new Xep.InBandBytestreams.Module()); module_map[account].add(new Xep.Jingle.Module()); module_map[account].add(new Xep.JingleSocks5Bytestreams.Module()); @@ -97,11 +97,12 @@ public class ModuleManager { module_map[account].add(new Xep.JingleMessageInitiation.Module()); module_map[account].add(new Xep.OccupantIds.Module()); module_map[account].add(new Xep.MessageRetraction.Module()); - module_map[account].add(new Xep.JingleRawUdp.Module()); + module_map[account].add(new Xep.JingleRawUdp.Module.with_local_ip_address_handler(Util.get_local_ip_addresses)); module_map[account].add(new Xep.Muji.Module()); module_map[account].add(new Xep.CallInvites.Module()); module_map[account].add(new Xep.Coin.Module()); module_map[account].add(new Xep.MessageDisplayedSynchronization.Module()); + module_map[account].add(new IceUdpModule()); initialize_account_modules(account, module_map[account]); } } diff --git a/libdino/src/service/util.vala b/libdino/src/service/util.vala index ac596cad..577bc6cc 100644 --- a/libdino/src/service/util.vala +++ b/libdino/src/service/util.vala @@ -1,8 +1,6 @@ using Dino.Entities; -namespace Dino { - -public class Util { +namespace Dino.Util { public static Message.Type get_message_type_for_conversation(Conversation conversation) { switch (conversation.type_) { case Conversation.Type.CHAT: @@ -41,6 +39,12 @@ public class Util { } return false; } -} + public static Gee.List get_local_ip_addresses() { + Gee.List result = new Gee.ArrayList(); + foreach (string ip_address in Nice.interfaces_get_local_ips(false)) { + result.add(ip_address); + } + return result; + } } diff --git a/libdino/vapi/metadata/Nice-0.1.metadata b/libdino/vapi/metadata/Nice-0.1.metadata new file mode 100644 index 00000000..7fcf046a --- /dev/null +++ b/libdino/vapi/metadata/Nice-0.1.metadata @@ -0,0 +1,11 @@ +Nice cheader_filename="nice.h" +Address.to_string.dst type="char[]" +Agent.new_reliable#constructor name="create_reliable" +Agent.attach_recv skip=false +Agent.send.buf type="uint8[]" array_length_idx=2 +AgentRecvFunc.buf type="uint8[]" array_length_idx=3 +PseudoTcpCallbacks#record skip +PseudoTcpSocket#class skip + +# Not yet supported by vapigen +# Candidate copy_function="nice_candidate_copy" free_function="nice_candidate_free" type_id="" diff --git a/libdino/vapi/nice.vapi b/libdino/vapi/nice.vapi new file mode 100644 index 00000000..540e2b4e --- /dev/null +++ b/libdino/vapi/nice.vapi @@ -0,0 +1,386 @@ +/* nice.vapi generated by vapigen, do not modify. */ + +[CCode (cprefix = "Nice", gir_namespace = "Nice", gir_version = "0.1", lower_case_cprefix = "nice_")] +namespace Nice { + [CCode (cheader_filename = "nice.h", type_id = "nice_agent_get_type ()")] + public class Agent : GLib.Object { + [CCode (has_construct_function = false)] + public Agent (GLib.MainContext ctx, Nice.Compatibility compat); + public bool add_local_address (Nice.Address addr); + public uint add_stream (uint n_components); + public bool attach_recv (uint stream_id, uint component_id, GLib.MainContext ctx, Nice.AgentRecvFunc func); + [Version (since = "0.1.16")] + public async void close_async (); + [CCode (cname = "nice_agent_new_reliable", has_construct_function = false)] + [Version (since = "0.0.11")] + public Agent.create_reliable (GLib.MainContext ctx, Nice.Compatibility compat); + [Version (since = "0.1.6")] + public bool forget_relays (uint stream_id, uint component_id); + [CCode (has_construct_function = false)] + [Version (since = "0.1.15")] + public Agent.full (GLib.MainContext ctx, Nice.Compatibility compat, Nice.AgentOption flags); + public bool gather_candidates (uint stream_id); + [Version (since = "0.1.4")] + public string generate_local_candidate_sdp (Nice.Candidate candidate); + [Version (since = "0.1.4")] + public string generate_local_sdp (); + [Version (since = "0.1.4")] + public string generate_local_stream_sdp (uint stream_id, bool include_non_ice); + [Version (since = "0.1.8")] + public Nice.ComponentState get_component_state (uint stream_id, uint component_id); + public Nice.Candidate get_default_local_candidate (uint stream_id, uint component_id); + [Version (since = "0.1.5")] + public GLib.IOStream get_io_stream (uint stream_id, uint component_id); + public GLib.SList get_local_candidates (uint stream_id, uint component_id); + public bool get_local_credentials (uint stream_id, out string ufrag, out string pwd); + public GLib.SList get_remote_candidates (uint stream_id, uint component_id); + public bool get_selected_pair (uint stream_id, uint component_id, Nice.Candidate local, Nice.Candidate remote); + [Version (since = "0.1.5")] + public GLib.Socket? get_selected_socket (uint stream_id, uint component_id); + [Version (since = "0.1.4")] + public unowned string get_stream_name (uint stream_id); + [Version (since = "0.1.4")] + public Nice.Candidate parse_remote_candidate_sdp (uint stream_id, string sdp); + [Version (since = "0.1.4")] + public int parse_remote_sdp (string sdp); + [Version (since = "0.1.4")] + public GLib.SList parse_remote_stream_sdp (uint stream_id, string sdp, string ufrag, string pwd); + [Version (since = "0.1.16")] + public bool peer_candidate_gathering_done (uint stream_id); + [Version (since = "0.1.5")] + public ssize_t recv (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public int recv_messages (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public int recv_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public ssize_t recv_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; + public void remove_stream (uint stream_id); + public bool restart (); + [Version (since = "0.1.6")] + public bool restart_stream (uint stream_id); + public int send (uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 2.5, array_length_type = "guint", type = "const gchar*")] uint8[] buf); + [Version (since = "0.1.5")] + public int send_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] Nice.OutputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + public bool set_local_credentials (uint stream_id, string ufrag, string pwd); + public void set_port_range (uint stream_id, uint component_id, uint min_port, uint max_port); + public bool set_relay_info (uint stream_id, uint component_id, string server_ip, uint server_port, string username, string password, Nice.RelayType type); + public int set_remote_candidates (uint stream_id, uint component_id, GLib.SList candidates); + public bool set_remote_credentials (uint stream_id, string ufrag, string pwd); + public bool set_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); + public bool set_selected_remote_candidate (uint stream_id, uint component_id, Nice.Candidate candidate); + [Version (since = "0.0.10")] + public void set_software (string software); + [Version (since = "0.1.4")] + public bool set_stream_name (uint stream_id, string name); + [Version (since = "0.0.9")] + public void set_stream_tos (uint stream_id, int tos); + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool bytestream_tcp { get; } + [NoAccessorMethod] + public uint compatibility { get; construct; } + [NoAccessorMethod] + public bool controlling_mode { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.14")] + public bool force_relay { get; set; } + [NoAccessorMethod] + public bool full_mode { get; construct; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool ice_tcp { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.16")] + public bool ice_trickle { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool ice_udp { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool keepalive_conncheck { get; set; } + [NoAccessorMethod] + public void* main_context { get; construct; } + [NoAccessorMethod] + public uint max_connectivity_checks { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_ip { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_password { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public uint proxy_port { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public uint proxy_type { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_username { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.11")] + public bool reliable { get; construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_initial_timeout { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_max_retransmissions { get; set construct; } + [NoAccessorMethod] + public uint stun_pacing_timer { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_reliable_timeout { get; set construct; } + [NoAccessorMethod] + public string stun_server { owned get; set; } + [NoAccessorMethod] + public uint stun_server_port { get; set; } + [NoAccessorMethod] + public bool support_renomination { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.7")] + public bool upnp { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.0.7")] + public uint upnp_timeout { get; set construct; } + public signal void candidate_gathering_done (uint stream_id); + public signal void component_state_changed (uint stream_id, uint component_id, uint state); + public signal void initial_binding_request_received (uint stream_id); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_candidate (uint stream_id, uint component_id, string foundation); + [Version (since = "0.1.8")] + public signal void new_candidate_full (Nice.Candidate candidate); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_remote_candidate (uint stream_id, uint component_id, string foundation); + [Version (since = "0.1.8")] + public signal void new_remote_candidate_full (Nice.Candidate candidate); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); + [Version (since = "0.1.8")] + public signal void new_selected_pair_full (uint stream_id, uint component_id, Nice.Candidate lcandidate, Nice.Candidate rcandidate); + [Version (since = "0.0.11")] + public signal void reliable_transport_writable (uint stream_id, uint component_id); + [Version (since = "0.1.5")] + public signal void streams_removed ([CCode (array_length = false, array_null_terminated = true)] uint[] stream_ids); + } + [CCode (cheader_filename = "nice.h", copy_function = "nice_candidate_copy", free_function = "nice_candidate_free")] + [Compact] + public class Candidate { + public Nice.Address addr; + public Nice.Address base_addr; + public uint component_id; + [CCode (array_length = false)] + public weak char foundation[33]; + public weak string password; + public uint32 priority; + public void* sockptr; + public uint stream_id; + public Nice.CandidateTransport transport; + public Nice.TurnServer turn; + public Nice.CandidateType type; + public weak string username; + [CCode (has_construct_function = false)] + public Candidate (Nice.CandidateType type); + public Nice.Candidate copy (); + [Version (since = "0.1.15")] + public bool equal_target (Nice.Candidate candidate2); + public void free (); + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + public struct Address { + [CCode (cname = "s.addr")] + public void* s_addr; + [CCode (cname = "s.ip4")] + public void* s_ip4; + [CCode (cname = "s.ip6")] + public void* s_ip6; + public void copy_to_sockaddr (void* sin); + public bool equal (Nice.Address b); + [Version (since = "0.1.8")] + public bool equal_no_port (Nice.Address b); + public void free (); + public uint get_port (); + public void init (); + public int ip_version (); + public bool is_private (); + public bool is_valid (); + public void set_from_sockaddr (void* sin); + public bool set_from_string (string str); + public void set_ipv4 (uint32 addr_ipv4); + public void set_ipv6 (uint8 addr_ipv6); + public void set_port (uint port); + public void to_string ([CCode (array_length = false, type = "gchar*")] char[] dst); + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + [Version (since = "0.1.5")] + public struct InputMessage { + [CCode (array_length_cname = "n_buffers")] + public weak GLib.InputVector[] buffers; + public int n_buffers; + public Nice.Address from; + public size_t length; + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + [Version (since = "0.1.5")] + public struct OutputMessage { + [CCode (array_length_cname = "n_buffers")] + public weak GLib.OutputVector[] buffers; + public int n_buffers; + } + [CCode (cheader_filename = "nice.h", cname = "TurnServer", has_type_id = false)] + public struct TurnServer { + public int ref_count; + public Nice.Address server; + public weak string username; + public weak string password; + public Nice.RelayType type; + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_AGENT_OPTION_", has_type_id = false)] + [Flags] + [Version (since = "0.1.15")] + public enum AgentOption { + REGULAR_NOMINATION, + RELIABLE, + LITE_MODE, + ICE_TRICKLE, + SUPPORT_RENOMINATION + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TRANSPORT_", has_type_id = false)] + public enum CandidateTransport { + UDP, + TCP_ACTIVE, + TCP_PASSIVE, + TCP_SO + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TYPE_", has_type_id = false)] + public enum CandidateType { + HOST, + SERVER_REFLEXIVE, + PEER_REFLEXIVE, + RELAYED + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPATIBILITY_", has_type_id = false)] + public enum Compatibility { + RFC5245, + DRAFT19, + GOOGLE, + MSN, + WLM2009, + OC2007, + OC2007R2, + LAST + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_STATE_", has_type_id = false)] + public enum ComponentState { + DISCONNECTED, + GATHERING, + CONNECTING, + CONNECTED, + READY, + FAILED, + LAST; + [Version (since = "0.1.6")] + public unowned string to_string (); + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_TYPE_", has_type_id = false)] + public enum ComponentType { + RTP, + RTCP + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_NOMINATION_MODE_", has_type_id = false)] + [Version (since = "0.1.15")] + public enum NominationMode { + REGULAR, + AGGRESSIVE + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_PROXY_TYPE_", has_type_id = false)] + [Version (since = "0.0.4")] + public enum ProxyType { + NONE, + SOCKS5, + HTTP, + LAST + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpDebugLevel", cprefix = "PSEUDO_TCP_DEBUG_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpDebugLevel { + NONE, + NORMAL, + VERBOSE + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpShutdown", cprefix = "PSEUDO_TCP_SHUTDOWN_", has_type_id = false)] + [Version (since = "0.1.8")] + public enum PseudoTcpShutdown { + RD, + WR, + RDWR + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpState", cprefix = "PSEUDO_TCP_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpState { + LISTEN, + SYN_SENT, + SYN_RECEIVED, + ESTABLISHED, + CLOSED, + FIN_WAIT_1, + FIN_WAIT_2, + CLOSING, + TIME_WAIT, + CLOSE_WAIT, + LAST_ACK + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpWriteResult", cprefix = "WR_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpWriteResult { + SUCCESS, + TOO_LARGE, + FAIL + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_RELAY_TYPE_TURN_", has_type_id = false)] + public enum RelayType { + UDP, + TCP, + TLS + } + [CCode (cheader_filename = "nice.h", instance_pos = 4.9)] + public delegate void AgentRecvFunc (Nice.Agent agent, uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 3.5, array_length_type = "guint", type = "gchar*")] uint8[] buf); + [CCode (cheader_filename = "nice.h", cname = "NICE_AGENT_MAX_REMOTE_CANDIDATES")] + public const int AGENT_MAX_REMOTE_CANDIDATES; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_ACTIVE")] + public const int CANDIDATE_DIRECTION_MS_PREF_ACTIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_PASSIVE")] + public const int CANDIDATE_DIRECTION_MS_PREF_PASSIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_MAX_FOUNDATION")] + public const int CANDIDATE_MAX_FOUNDATION; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_TCP")] + public const int CANDIDATE_TRANSPORT_MS_PREF_TCP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_UDP")] + public const int CANDIDATE_TRANSPORT_MS_PREF_UDP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_HOST")] + public const int CANDIDATE_TYPE_PREF_HOST; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_NAT_ASSISTED")] + public const int CANDIDATE_TYPE_PREF_NAT_ASSISTED; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_PEER_REFLEXIVE")] + public const int CANDIDATE_TYPE_PREF_PEER_REFLEXIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED")] + public const int CANDIDATE_TYPE_PREF_RELAYED; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED_UDP")] + public const int CANDIDATE_TYPE_PREF_RELAYED_UDP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE")] + public const int CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE; + [CCode (cheader_filename = "nice.h")] + public static void debug_disable (bool with_stun); + [CCode (cheader_filename = "nice.h")] + public static void debug_enable (bool with_stun); + [CCode (cheader_filename = "nice.h")] + public static string? interfaces_get_ip_for_interface (string interface_name); + [CCode (cheader_filename = "nice.h")] + public static GLib.List interfaces_get_local_interfaces (); + [CCode (cheader_filename = "nice.h")] + public static GLib.List interfaces_get_local_ips (bool include_loopback); + [CCode (cheader_filename = "nice.h", cname = "pseudo_tcp_set_debug_level")] + [Version (since = "0.0.11")] + public static void pseudo_tcp_set_debug_level (Nice.PseudoTcpDebugLevel level); +} diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build deleted file mode 100644 index 19030259..00000000 --- a/plugins/ice/meson.build +++ /dev/null @@ -1,25 +0,0 @@ -dependencies = [ - dep_dino, - dep_gee, - dep_gio, - dep_glib, - dep_gmodule, - dep_nice, - dep_xmpp_vala, -] -sources = files( - 'src/module.vala', - 'src/plugin.vala', - 'src/transport_parameters.vala', - 'src/util.vala', - 'src/register_plugin.vala', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="ice"', -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] -lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) -dep_ice = declare_dependency(link_with: lib_ice, include_directories: include_directories('.')) -summary('Peer-to-peer communication (ice)', dep_ice.found(), bool_yn: true, section: 'Plugins') diff --git a/plugins/ice/src/module.vala b/plugins/ice/src/module.vala deleted file mode 100644 index c3c92124..00000000 --- a/plugins/ice/src/module.vala +++ /dev/null @@ -1,57 +0,0 @@ -using Gee; - -using Dino.Crypto; -using Xmpp; -using Xmpp.Xep; - -public class Dino.Plugins.Ice.Module : JingleIceUdp.Module { - - public string? stun_ip = null; - public uint stun_port = 0; - public string? turn_ip = null; - public Xep.ExternalServiceDiscovery.Service? turn_service = null; - - private weak Nice.Agent? agent; - private HashMap cerds = new HashMap(); - - private Nice.Agent get_agent() { - Nice.Agent? agent = this.agent; - if (agent == null) { - agent = new Nice.Agent(MainContext.@default(), Nice.Compatibility.RFC5245); - if (stun_ip != null) { - agent.stun_server = stun_ip; - agent.stun_server_port = stun_port; - } - agent.ice_tcp = false; - agent.set_software("Dino"); - agent.weak_ref(agent_unweak); - this.agent = agent; - debug("STUN server for libnice %s %u", agent.stun_server, agent.stun_server_port); - } - return agent; - } - - public override Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) { - DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); - return new TransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid); - } - - public override Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError { - DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); - return new TransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid, transport); - } - - private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) { - string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); - try { - if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); - } catch (GLib.Error e) { - warning("Error creating dtls credentials: %s", e.message); - } - return cerds[from_to_id]; - } - - private void agent_unweak() { - this.agent = null; - } -} \ No newline at end of file diff --git a/plugins/ice/src/plugin.vala b/plugins/ice/src/plugin.vala deleted file mode 100644 index d1655a74..00000000 --- a/plugins/ice/src/plugin.vala +++ /dev/null @@ -1,104 +0,0 @@ -using Gee; -using Dino.Entities; -using Xmpp; -using Xmpp.Xep; - -private extern const size_t NICE_ADDRESS_STRING_LEN; - -public class Dino.Plugins.Ice.Plugin : RootInterface, Object { - private HashMap timeouts = new HashMap(Account.hash_func, Account.equals_func); - - public Dino.Application app; - - public void registered(Dino.Application app) { - Nice.debug_enable(true); - this.app = app; - app.stream_interactor.module_manager.initialize_account_modules.connect((account, list) => { - list.add(new Module()); - }); - app.stream_interactor.stream_attached_modules.connect((account, stream) => { - if (stream.get_module(Socks5Bytestreams.Module.IDENTITY) != null) { - stream.get_module(Socks5Bytestreams.Module.IDENTITY).set_local_ip_address_handler(get_local_ip_addresses); - } - if (stream.get_module(JingleRawUdp.Module.IDENTITY) != null) { - stream.get_module(JingleRawUdp.Module.IDENTITY).set_local_ip_address_handler(get_local_ip_addresses); - } - }); - app.stream_interactor.stream_negotiated.connect(external_discovery_refresh_services); - } - - private async void external_discovery_refresh_services(Account account, XmppStream stream) { - Module? ice_udp_module = stream.get_module(JingleIceUdp.Module.IDENTITY) as Module; - if (ice_udp_module == null) return; - - Gee.List services = yield ExternalServiceDiscovery.request_services(stream); - foreach (Xep.ExternalServiceDiscovery.Service service in services) { - if (service.transport == "udp" && (service.ty == "stun" || service.ty == "turn")) { - InetAddress? ip = yield lookup_ipv4_addess(service.host); - if (ip == null) continue; - - if (ip.is_any || ip.is_link_local || ip.is_loopback || ip.is_multicast || ip.is_site_local) { - warning("Ignoring STUN/TURN server at %s", service.host); - continue; - } - - if (service.ty == "stun") { - debug("Server offers STUN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); - ice_udp_module.stun_ip = ip.to_string(); - ice_udp_module.stun_port = service.port; - } else if (service.ty == "turn") { - debug("Server offers TURN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); - ice_udp_module.turn_ip = ip.to_string(); - ice_udp_module.turn_service = service; - } - } - } - if (ice_udp_module.stun_ip == null) { - InetAddress ip = yield lookup_ipv4_addess("stun.dino.im"); - if (ip == null) return; - - debug("Using fallback STUN server: stun.dino.im:7886, resolved to %s", ip.to_string()); - - ice_udp_module.stun_ip = ip.to_string(); - ice_udp_module.stun_port = 7886; - } - - // Refresh TURN credentials before they expire - if (ice_udp_module.turn_service != null) { - DateTime? expires = ice_udp_module.turn_service.expires; - if (expires != null) { - uint refresh_delay = (uint) (expires.to_unix() - new DateTime.now_utc().to_unix()) / 2; - - if (refresh_delay >= 300 && refresh_delay <= (int64) uint.MAX) { // 5 min < refetch < max - debug("Re-fetching TURN credentials in %u sec", refresh_delay); - - timeouts.unset(account); - timeouts[account] = Timeout.add_seconds((uint) refresh_delay, () => { - external_discovery_refresh_services.begin(account, stream); - return false; - }); - } else { - warning("TURN credentials' expiry time = %u, *not* re-fetching", refresh_delay); - } - } - } - } - - public void shutdown() { - // Nothing to do - } - - private async InetAddress? lookup_ipv4_addess(string host) { - try { - Resolver resolver = Resolver.get_default(); - GLib.List? ips = yield resolver.lookup_by_name_async(host); - foreach (GLib.InetAddress ina in ips) { - if (ina.get_family() != SocketFamily.IPV4) continue; - return ina; - } - } catch (Error e) { - warning("Failed looking up IP address of %s", host); - } - return null; - } -} \ No newline at end of file diff --git a/plugins/ice/src/register_plugin.vala b/plugins/ice/src/register_plugin.vala deleted file mode 100644 index b2ed56c1..00000000 --- a/plugins/ice/src/register_plugin.vala +++ /dev/null @@ -1,3 +0,0 @@ -public Type register_plugin(Module module) { - return typeof (Dino.Plugins.Ice.Plugin); -} diff --git a/plugins/ice/src/transport_parameters.vala b/plugins/ice/src/transport_parameters.vala deleted file mode 100644 index 122207c5..00000000 --- a/plugins/ice/src/transport_parameters.vala +++ /dev/null @@ -1,391 +0,0 @@ -using Gee; - -using Dino.Crypto; -using Xmpp; -using Xmpp.Xep; - - -public class Dino.Plugins.Ice.TransportParameters : JingleIceUdp.IceUdpTransportParameters { - private Nice.Agent agent; - private uint stream_id; - private bool we_want_connection; - private bool remote_credentials_set; - private Map connections = new HashMap(); - private DtlsSrtp.Handler? dtls_srtp_handler; - private MainContext thread_context; - private MainLoop thread_loop; - - private class DatagramConnection : Jingle.DatagramConnection { - private Nice.Agent agent; - private DtlsSrtp.Handler? dtls_srtp_handler; - private uint stream_id; - private string? error; - private ulong datagram_received_id; - - public DatagramConnection(Nice.Agent agent, DtlsSrtp.Handler? dtls_srtp_handler, uint stream_id, uint8 component_id) { - this.agent = agent; - this.dtls_srtp_handler = dtls_srtp_handler; - this.stream_id = stream_id; - this.component_id = component_id; - this.datagram_received_id = this.datagram_received.connect((datagram) => { - bytes_received += datagram.length; - }); - } - - public override async void terminate(bool we_terminated, string? reason_string = null, string? reason_text = null) { - yield base.terminate(we_terminated, reason_string, reason_text); - this.disconnect(datagram_received_id); - agent = null; - dtls_srtp_handler = null; - } - - public override void send_datagram(Bytes datagram) { - if (this.agent != null && is_component_ready(agent, stream_id, component_id)) { - try { - if (dtls_srtp_handler != null) { - uint8[] encrypted_data = dtls_srtp_handler.process_outgoing_data(component_id, datagram.get_data()); - if (encrypted_data == null) return; - GLib.OutputVector vector = { encrypted_data, encrypted_data.length }; - GLib.OutputVector[] vectors = { vector }; - Nice.OutputMessage message = { vectors }; - Nice.OutputMessage[] messages = { message }; - agent.send_messages_nonblocking(stream_id, component_id, messages); - } else { - GLib.OutputVector vector = { datagram.get_data(), datagram.get_size() }; - GLib.OutputVector[] vectors = { vector }; - Nice.OutputMessage message = { vectors }; - Nice.OutputMessage[] messages = { message }; - agent.send_messages_nonblocking(stream_id, component_id, messages); - } - bytes_sent += datagram.length; - } catch (GLib.Error e) { - warning("%s while send_datagram stream %u component %u", e.message, stream_id, component_id); - } - } - } - } - - public TransportParameters(Nice.Agent agent, DtlsSrtp.CredentialsCapsule? credentials, Xep.ExternalServiceDiscovery.Service? turn_service, string? turn_ip, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode? node = null) { - base(components, local_full_jid, peer_full_jid, node); - this.we_want_connection = (node == null); - this.agent = agent; - - if (this.peer_fingerprint != null || !incoming) { - dtls_srtp_handler = setup_dtls(this, credentials); - own_fingerprint = dtls_srtp_handler.own_fingerprint; - if (incoming) { - own_setup = "active"; - dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } else { - own_setup = "actpass"; - dtls_srtp_handler.mode = DtlsSrtp.Mode.SERVER; - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (content_encryption != null) { - this.content.encryptions[content_encryption.encryption_ns] = content_encryption; - } - }); - } - } - - agent.candidate_gathering_done.connect(on_candidate_gathering_done); - agent.initial_binding_request_received.connect(on_initial_binding_request_received); - agent.component_state_changed.connect(on_component_state_changed); - agent.new_selected_pair_full.connect(on_new_selected_pair_full); - agent.new_candidate_full.connect(on_new_candidate); - - agent.controlling_mode = !incoming; - stream_id = agent.add_stream(components); - thread_context = new MainContext(); - new Thread(@"ice-thread-$stream_id", () => { - thread_context.push_thread_default(); - thread_loop = new MainLoop(thread_context, false); - thread_loop.run(); - thread_context.pop_thread_default(); - return null; - }); - - if (turn_ip != null) { - for (uint8 component_id = 1; component_id <= components; component_id++) { - agent.set_relay_info(stream_id, component_id, turn_ip, turn_service.port, turn_service.username, turn_service.password, Nice.RelayType.UDP); - debug("TURN info (component %i) %s:%u", component_id, turn_ip, turn_service.port); - } - } - string ufrag; - string pwd; - agent.get_local_credentials(stream_id, out ufrag, out pwd); - init(ufrag, pwd); - - for (uint8 component_id = 1; component_id <= components; component_id++) { - // We don't properly get local candidates before this call - agent.attach_recv(stream_id, component_id, thread_context, on_recv); - } - - agent.gather_candidates(stream_id); - } - - private static DtlsSrtp.Handler setup_dtls(TransportParameters tp, DtlsSrtp.CredentialsCapsule credentials) { - var weak_self = WeakRef(tp); - DtlsSrtp.Handler dtls_srtp = new DtlsSrtp.Handler.with_cert(credentials); - dtls_srtp.send_data.connect((data) => { - TransportParameters self = (TransportParameters) weak_self.get(); - if (self != null) self.agent.send(self.stream_id, 1, data); - }); - return dtls_srtp; - } - - private void on_candidate_gathering_done(uint stream_id) { - if (stream_id != this.stream_id) return; - debug("on_candidate_gathering_done in %u", stream_id); - - for (uint8 i = 1; i <= components; i++) { - foreach (unowned Nice.Candidate nc in agent.get_local_candidates(stream_id, i)) { - if (nc.transport == Nice.CandidateTransport.UDP) { - JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); - if (candidate == null) continue; - debug("Local candidate summary: %s", agent.generate_local_candidate_sdp(nc)); - } - } - } - } - - private void on_new_candidate(Nice.Candidate nc) { - if (nc.stream_id != stream_id) return; - JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); - if (candidate == null) return; - - if (nc.transport == Nice.CandidateTransport.UDP) { - // Execution was in the agent thread before - add_local_candidate_threadsafe(candidate); - } - } - - private bool bytes_equal(uint8[] a1, uint8[] a2) { - return a1.length == a2.length && Memory.cmp(a1, a2, a1.length) == 0; - } - - public override void handle_transport_accept(StanzaNode transport) throws Jingle.IqError { - debug("on_transport_accept from %s", peer_full_jid.to_string()); - base.handle_transport_accept(transport); - - if (dtls_srtp_handler != null && peer_fingerprint != null) { - if (dtls_srtp_handler.peer_fingerprint != null) { - if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { - warning("Tried to replace certificate fingerprint mid use. We don't allow that."); - peer_fingerprint = dtls_srtp_handler.peer_fingerprint; - peer_fp_algo = dtls_srtp_handler.peer_fp_algo; - } - } else { - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } - if (peer_setup == "passive") { - dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; - dtls_srtp_handler.stop_dtls_connection(); - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (content_encryption != null) { - this.content.encryptions[content_encryption.encryption_ns] = content_encryption; - } - }); - } - } else { - dtls_srtp_handler = null; - } - } - - public override void handle_transport_info(StanzaNode transport) throws Jingle.IqError { - debug("on_transport_info from %s", peer_full_jid.to_string()); - base.handle_transport_info(transport); - - if (dtls_srtp_handler != null && peer_fingerprint != null) { - if (dtls_srtp_handler.peer_fingerprint != null) { - if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { - warning("Tried to replace certificate fingerprint mid use. We don't allow that."); - peer_fingerprint = dtls_srtp_handler.peer_fingerprint; - peer_fp_algo = dtls_srtp_handler.peer_fp_algo; - } - } else { - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } - } - - if (!we_want_connection) return; - - if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { - agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); - remote_credentials_set = true; - } - for (uint8 i = 1; i <= components; i++) { - SList candidates = new SList(); - foreach (JingleIceUdp.Candidate candidate in remote_candidates) { - if (candidate.component == i) { - candidates.append(candidate_to_nice(candidate)); - } - } - int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); - debug("Updated to %i remote candidates for candidate %u via transport info", new_candidates, i); - } - } - - public override void create_transport_connection(XmppStream stream, Jingle.Content content) { - debug("create_transport_connection: %s", content.session.sid); - debug("local_credentials: %s %s", local_ufrag, local_pwd); - debug("remote_credentials: %s %s", remote_ufrag, remote_pwd); - debug("expected incoming credentials: %s %s", local_ufrag + ":" + remote_ufrag, local_pwd); - debug("expected outgoing credentials: %s %s", remote_ufrag + ":" + local_ufrag, remote_pwd); - - we_want_connection = true; - - if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { - agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); - remote_credentials_set = true; - } - for (uint8 i = 1; i <= components; i++) { - SList candidates = new SList(); - foreach (JingleIceUdp.Candidate candidate in remote_candidates) { - if (candidate.ip.has_prefix("fe80::")) continue; - if (candidate.component == i) { - candidates.append(candidate_to_nice(candidate)); - debug("remote candidate: %s", agent.generate_local_candidate_sdp(candidate_to_nice(candidate))); - } - } - int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); - debug("Initiated component %u with %i remote candidates", i, new_candidates); - - connections[i] = new DatagramConnection(agent, dtls_srtp_handler, stream_id, i); - content.set_transport_connection(connections[i], i); - } - - base.create_transport_connection(stream, content); - } - - private void on_component_state_changed(uint stream_id, uint component_id, uint state) { - if (stream_id != this.stream_id) return; - debug("stream %u component %u state changed to %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); - may_consider_ready(stream_id, component_id); - if (incoming && dtls_srtp_handler != null && !dtls_srtp_handler.ready && is_component_ready(agent, stream_id, component_id) && dtls_srtp_handler.mode == DtlsSrtp.Mode.CLIENT) { - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - Jingle.ContentEncryption? encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (encryption != null) { - this.content.encryptions[encryption.encryption_ns] = encryption; - } - }); - } - } - - private void may_consider_ready(uint stream_id, uint component_id) { - if (stream_id != this.stream_id) return; - if (connections.has_key((uint8) component_id) && !connections[(uint8)component_id].ready && is_component_ready(agent, stream_id, component_id) && (dtls_srtp_handler == null || dtls_srtp_handler.ready)) { - connections[(uint8)component_id].ready = true; - } - } - - private void on_initial_binding_request_received(uint stream_id) { - if (stream_id != this.stream_id) return; - debug("initial_binding_request_received"); - } - - private void on_new_selected_pair_full(uint stream_id, uint component_id, Nice.Candidate p1, Nice.Candidate p2) { - if (stream_id != this.stream_id) return; - debug("new_selected_pair_full %u [%s, %s]", component_id, agent.generate_local_candidate_sdp(p1), agent.generate_local_candidate_sdp(p2)); - } - - private void on_recv(Nice.Agent agent, uint stream_id, uint component_id, uint8[] data) { - if (stream_id != this.stream_id) return; - uint8[] decrypt_data = null; - if (dtls_srtp_handler != null) { - try { - decrypt_data = dtls_srtp_handler.process_incoming_data(component_id, data); - if (decrypt_data == null) return; - } catch (Crypto.Error e) { - warning("%s while on_recv stream %u component %u", e.message, stream_id, component_id); - return; - } - } - may_consider_ready(stream_id, component_id); - if (connections.has_key((uint8) component_id)) { - if (!connections[(uint8) component_id].ready) { - debug("on_recv stream %u component %u when state %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); - } - connections[(uint8) component_id].datagram_received(new Bytes(decrypt_data ?? data)); - } else { - debug("on_recv stream %u component %u length %u", stream_id, component_id, data.length); - } - } - - private static Nice.Candidate candidate_to_nice(JingleIceUdp.Candidate c) { - Nice.CandidateType type; - switch (c.type_) { - case JingleIceUdp.Candidate.Type.HOST: type = Nice.CandidateType.HOST; break; - case JingleIceUdp.Candidate.Type.PRFLX: type = Nice.CandidateType.PEER_REFLEXIVE; break; - case JingleIceUdp.Candidate.Type.RELAY: type = Nice.CandidateType.RELAYED; break; - case JingleIceUdp.Candidate.Type.SRFLX: type = Nice.CandidateType.SERVER_REFLEXIVE; break; - default: assert_not_reached(); - } - - Nice.Candidate candidate = new Nice.Candidate(type); - candidate.component_id = c.component; - char[] foundation = new char[Nice.CANDIDATE_MAX_FOUNDATION]; - Memory.copy(foundation, c.foundation.data, size_t.min(c.foundation.length, Nice.CANDIDATE_MAX_FOUNDATION - 1)); - candidate.foundation = foundation; - candidate.addr = Nice.Address(); - candidate.addr.init(); - candidate.addr.set_from_string(c.ip); - candidate.addr.set_port(c.port); - candidate.priority = c.priority; - if (c.rel_addr != null) { - candidate.base_addr = Nice.Address(); - candidate.base_addr.init(); - candidate.base_addr.set_from_string(c.rel_addr); - candidate.base_addr.set_port(c.rel_port); - } - candidate.transport = Nice.CandidateTransport.UDP; - return candidate; - } - - private static JingleIceUdp.Candidate? candidate_to_jingle(Nice.Candidate nc) { - JingleIceUdp.Candidate candidate = new JingleIceUdp.Candidate(); - switch (nc.type) { - case Nice.CandidateType.HOST: candidate.type_ = JingleIceUdp.Candidate.Type.HOST; break; - case Nice.CandidateType.PEER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.PRFLX; break; - case Nice.CandidateType.RELAYED: candidate.type_ = JingleIceUdp.Candidate.Type.RELAY; break; - case Nice.CandidateType.SERVER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.SRFLX; break; - default: assert_not_reached(); - } - candidate.component = (uint8) nc.component_id; - candidate.foundation = ((string)nc.foundation).dup(); - candidate.generation = 0; - candidate.id = Random.next_int().to_string("%08x"); // TODO - - char[] res = new char[NICE_ADDRESS_STRING_LEN]; - nc.addr.to_string(res); - candidate.ip = (string) res; - candidate.network = 0; // TODO - candidate.port = (uint16) nc.addr.get_port(); - candidate.priority = nc.priority; - candidate.protocol = "udp"; - if (nc.base_addr.is_valid() && !nc.base_addr.equal(nc.addr)) { - res = new char[NICE_ADDRESS_STRING_LEN]; - nc.base_addr.to_string(res); - candidate.rel_addr = (string) res; - candidate.rel_port = (uint16) nc.base_addr.get_port(); - } - if (candidate.ip.has_prefix("fe80::")) return null; - - return candidate; - } - - public override void dispose() { - base.dispose(); - agent = null; - dtls_srtp_handler = null; - connections.clear(); - if (thread_loop != null) { - thread_loop.quit(); - } - } -} diff --git a/plugins/ice/src/util.vala b/plugins/ice/src/util.vala deleted file mode 100644 index dd89d2f4..00000000 --- a/plugins/ice/src/util.vala +++ /dev/null @@ -1,18 +0,0 @@ -using Gee; - -namespace Dino.Plugins.Ice { - -internal static bool is_component_ready(Nice.Agent agent, uint stream_id, uint component_id) { - var state = agent.get_component_state(stream_id, component_id); - return state == Nice.ComponentState.CONNECTED || state == Nice.ComponentState.READY; -} - -internal Gee.List get_local_ip_addresses() { - Gee.List result = new ArrayList(); - foreach (string ip_address in Nice.interfaces_get_local_ips(false)) { - result.add(ip_address); - } - return result; -} - -} \ No newline at end of file diff --git a/plugins/ice/vapi/metadata/Nice-0.1.metadata b/plugins/ice/vapi/metadata/Nice-0.1.metadata deleted file mode 100644 index 7fcf046a..00000000 --- a/plugins/ice/vapi/metadata/Nice-0.1.metadata +++ /dev/null @@ -1,11 +0,0 @@ -Nice cheader_filename="nice.h" -Address.to_string.dst type="char[]" -Agent.new_reliable#constructor name="create_reliable" -Agent.attach_recv skip=false -Agent.send.buf type="uint8[]" array_length_idx=2 -AgentRecvFunc.buf type="uint8[]" array_length_idx=3 -PseudoTcpCallbacks#record skip -PseudoTcpSocket#class skip - -# Not yet supported by vapigen -# Candidate copy_function="nice_candidate_copy" free_function="nice_candidate_free" type_id="" diff --git a/plugins/ice/vapi/nice.vapi b/plugins/ice/vapi/nice.vapi deleted file mode 100644 index 540e2b4e..00000000 --- a/plugins/ice/vapi/nice.vapi +++ /dev/null @@ -1,386 +0,0 @@ -/* nice.vapi generated by vapigen, do not modify. */ - -[CCode (cprefix = "Nice", gir_namespace = "Nice", gir_version = "0.1", lower_case_cprefix = "nice_")] -namespace Nice { - [CCode (cheader_filename = "nice.h", type_id = "nice_agent_get_type ()")] - public class Agent : GLib.Object { - [CCode (has_construct_function = false)] - public Agent (GLib.MainContext ctx, Nice.Compatibility compat); - public bool add_local_address (Nice.Address addr); - public uint add_stream (uint n_components); - public bool attach_recv (uint stream_id, uint component_id, GLib.MainContext ctx, Nice.AgentRecvFunc func); - [Version (since = "0.1.16")] - public async void close_async (); - [CCode (cname = "nice_agent_new_reliable", has_construct_function = false)] - [Version (since = "0.0.11")] - public Agent.create_reliable (GLib.MainContext ctx, Nice.Compatibility compat); - [Version (since = "0.1.6")] - public bool forget_relays (uint stream_id, uint component_id); - [CCode (has_construct_function = false)] - [Version (since = "0.1.15")] - public Agent.full (GLib.MainContext ctx, Nice.Compatibility compat, Nice.AgentOption flags); - public bool gather_candidates (uint stream_id); - [Version (since = "0.1.4")] - public string generate_local_candidate_sdp (Nice.Candidate candidate); - [Version (since = "0.1.4")] - public string generate_local_sdp (); - [Version (since = "0.1.4")] - public string generate_local_stream_sdp (uint stream_id, bool include_non_ice); - [Version (since = "0.1.8")] - public Nice.ComponentState get_component_state (uint stream_id, uint component_id); - public Nice.Candidate get_default_local_candidate (uint stream_id, uint component_id); - [Version (since = "0.1.5")] - public GLib.IOStream get_io_stream (uint stream_id, uint component_id); - public GLib.SList get_local_candidates (uint stream_id, uint component_id); - public bool get_local_credentials (uint stream_id, out string ufrag, out string pwd); - public GLib.SList get_remote_candidates (uint stream_id, uint component_id); - public bool get_selected_pair (uint stream_id, uint component_id, Nice.Candidate local, Nice.Candidate remote); - [Version (since = "0.1.5")] - public GLib.Socket? get_selected_socket (uint stream_id, uint component_id); - [Version (since = "0.1.4")] - public unowned string get_stream_name (uint stream_id); - [Version (since = "0.1.4")] - public Nice.Candidate parse_remote_candidate_sdp (uint stream_id, string sdp); - [Version (since = "0.1.4")] - public int parse_remote_sdp (string sdp); - [Version (since = "0.1.4")] - public GLib.SList parse_remote_stream_sdp (uint stream_id, string sdp, string ufrag, string pwd); - [Version (since = "0.1.16")] - public bool peer_candidate_gathering_done (uint stream_id); - [Version (since = "0.1.5")] - public ssize_t recv (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public int recv_messages (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public int recv_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public ssize_t recv_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; - public void remove_stream (uint stream_id); - public bool restart (); - [Version (since = "0.1.6")] - public bool restart_stream (uint stream_id); - public int send (uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 2.5, array_length_type = "guint", type = "const gchar*")] uint8[] buf); - [Version (since = "0.1.5")] - public int send_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] Nice.OutputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - public bool set_local_credentials (uint stream_id, string ufrag, string pwd); - public void set_port_range (uint stream_id, uint component_id, uint min_port, uint max_port); - public bool set_relay_info (uint stream_id, uint component_id, string server_ip, uint server_port, string username, string password, Nice.RelayType type); - public int set_remote_candidates (uint stream_id, uint component_id, GLib.SList candidates); - public bool set_remote_credentials (uint stream_id, string ufrag, string pwd); - public bool set_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); - public bool set_selected_remote_candidate (uint stream_id, uint component_id, Nice.Candidate candidate); - [Version (since = "0.0.10")] - public void set_software (string software); - [Version (since = "0.1.4")] - public bool set_stream_name (uint stream_id, string name); - [Version (since = "0.0.9")] - public void set_stream_tos (uint stream_id, int tos); - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool bytestream_tcp { get; } - [NoAccessorMethod] - public uint compatibility { get; construct; } - [NoAccessorMethod] - public bool controlling_mode { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.14")] - public bool force_relay { get; set; } - [NoAccessorMethod] - public bool full_mode { get; construct; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool ice_tcp { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.16")] - public bool ice_trickle { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool ice_udp { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool keepalive_conncheck { get; set; } - [NoAccessorMethod] - public void* main_context { get; construct; } - [NoAccessorMethod] - public uint max_connectivity_checks { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_ip { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_password { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public uint proxy_port { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public uint proxy_type { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_username { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.11")] - public bool reliable { get; construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_initial_timeout { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_max_retransmissions { get; set construct; } - [NoAccessorMethod] - public uint stun_pacing_timer { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_reliable_timeout { get; set construct; } - [NoAccessorMethod] - public string stun_server { owned get; set; } - [NoAccessorMethod] - public uint stun_server_port { get; set; } - [NoAccessorMethod] - public bool support_renomination { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.7")] - public bool upnp { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.0.7")] - public uint upnp_timeout { get; set construct; } - public signal void candidate_gathering_done (uint stream_id); - public signal void component_state_changed (uint stream_id, uint component_id, uint state); - public signal void initial_binding_request_received (uint stream_id); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_candidate (uint stream_id, uint component_id, string foundation); - [Version (since = "0.1.8")] - public signal void new_candidate_full (Nice.Candidate candidate); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_remote_candidate (uint stream_id, uint component_id, string foundation); - [Version (since = "0.1.8")] - public signal void new_remote_candidate_full (Nice.Candidate candidate); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); - [Version (since = "0.1.8")] - public signal void new_selected_pair_full (uint stream_id, uint component_id, Nice.Candidate lcandidate, Nice.Candidate rcandidate); - [Version (since = "0.0.11")] - public signal void reliable_transport_writable (uint stream_id, uint component_id); - [Version (since = "0.1.5")] - public signal void streams_removed ([CCode (array_length = false, array_null_terminated = true)] uint[] stream_ids); - } - [CCode (cheader_filename = "nice.h", copy_function = "nice_candidate_copy", free_function = "nice_candidate_free")] - [Compact] - public class Candidate { - public Nice.Address addr; - public Nice.Address base_addr; - public uint component_id; - [CCode (array_length = false)] - public weak char foundation[33]; - public weak string password; - public uint32 priority; - public void* sockptr; - public uint stream_id; - public Nice.CandidateTransport transport; - public Nice.TurnServer turn; - public Nice.CandidateType type; - public weak string username; - [CCode (has_construct_function = false)] - public Candidate (Nice.CandidateType type); - public Nice.Candidate copy (); - [Version (since = "0.1.15")] - public bool equal_target (Nice.Candidate candidate2); - public void free (); - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - public struct Address { - [CCode (cname = "s.addr")] - public void* s_addr; - [CCode (cname = "s.ip4")] - public void* s_ip4; - [CCode (cname = "s.ip6")] - public void* s_ip6; - public void copy_to_sockaddr (void* sin); - public bool equal (Nice.Address b); - [Version (since = "0.1.8")] - public bool equal_no_port (Nice.Address b); - public void free (); - public uint get_port (); - public void init (); - public int ip_version (); - public bool is_private (); - public bool is_valid (); - public void set_from_sockaddr (void* sin); - public bool set_from_string (string str); - public void set_ipv4 (uint32 addr_ipv4); - public void set_ipv6 (uint8 addr_ipv6); - public void set_port (uint port); - public void to_string ([CCode (array_length = false, type = "gchar*")] char[] dst); - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - [Version (since = "0.1.5")] - public struct InputMessage { - [CCode (array_length_cname = "n_buffers")] - public weak GLib.InputVector[] buffers; - public int n_buffers; - public Nice.Address from; - public size_t length; - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - [Version (since = "0.1.5")] - public struct OutputMessage { - [CCode (array_length_cname = "n_buffers")] - public weak GLib.OutputVector[] buffers; - public int n_buffers; - } - [CCode (cheader_filename = "nice.h", cname = "TurnServer", has_type_id = false)] - public struct TurnServer { - public int ref_count; - public Nice.Address server; - public weak string username; - public weak string password; - public Nice.RelayType type; - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_AGENT_OPTION_", has_type_id = false)] - [Flags] - [Version (since = "0.1.15")] - public enum AgentOption { - REGULAR_NOMINATION, - RELIABLE, - LITE_MODE, - ICE_TRICKLE, - SUPPORT_RENOMINATION - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TRANSPORT_", has_type_id = false)] - public enum CandidateTransport { - UDP, - TCP_ACTIVE, - TCP_PASSIVE, - TCP_SO - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TYPE_", has_type_id = false)] - public enum CandidateType { - HOST, - SERVER_REFLEXIVE, - PEER_REFLEXIVE, - RELAYED - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPATIBILITY_", has_type_id = false)] - public enum Compatibility { - RFC5245, - DRAFT19, - GOOGLE, - MSN, - WLM2009, - OC2007, - OC2007R2, - LAST - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_STATE_", has_type_id = false)] - public enum ComponentState { - DISCONNECTED, - GATHERING, - CONNECTING, - CONNECTED, - READY, - FAILED, - LAST; - [Version (since = "0.1.6")] - public unowned string to_string (); - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_TYPE_", has_type_id = false)] - public enum ComponentType { - RTP, - RTCP - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_NOMINATION_MODE_", has_type_id = false)] - [Version (since = "0.1.15")] - public enum NominationMode { - REGULAR, - AGGRESSIVE - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_PROXY_TYPE_", has_type_id = false)] - [Version (since = "0.0.4")] - public enum ProxyType { - NONE, - SOCKS5, - HTTP, - LAST - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpDebugLevel", cprefix = "PSEUDO_TCP_DEBUG_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpDebugLevel { - NONE, - NORMAL, - VERBOSE - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpShutdown", cprefix = "PSEUDO_TCP_SHUTDOWN_", has_type_id = false)] - [Version (since = "0.1.8")] - public enum PseudoTcpShutdown { - RD, - WR, - RDWR - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpState", cprefix = "PSEUDO_TCP_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpState { - LISTEN, - SYN_SENT, - SYN_RECEIVED, - ESTABLISHED, - CLOSED, - FIN_WAIT_1, - FIN_WAIT_2, - CLOSING, - TIME_WAIT, - CLOSE_WAIT, - LAST_ACK - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpWriteResult", cprefix = "WR_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpWriteResult { - SUCCESS, - TOO_LARGE, - FAIL - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_RELAY_TYPE_TURN_", has_type_id = false)] - public enum RelayType { - UDP, - TCP, - TLS - } - [CCode (cheader_filename = "nice.h", instance_pos = 4.9)] - public delegate void AgentRecvFunc (Nice.Agent agent, uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 3.5, array_length_type = "guint", type = "gchar*")] uint8[] buf); - [CCode (cheader_filename = "nice.h", cname = "NICE_AGENT_MAX_REMOTE_CANDIDATES")] - public const int AGENT_MAX_REMOTE_CANDIDATES; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_ACTIVE")] - public const int CANDIDATE_DIRECTION_MS_PREF_ACTIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_PASSIVE")] - public const int CANDIDATE_DIRECTION_MS_PREF_PASSIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_MAX_FOUNDATION")] - public const int CANDIDATE_MAX_FOUNDATION; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_TCP")] - public const int CANDIDATE_TRANSPORT_MS_PREF_TCP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_UDP")] - public const int CANDIDATE_TRANSPORT_MS_PREF_UDP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_HOST")] - public const int CANDIDATE_TYPE_PREF_HOST; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_NAT_ASSISTED")] - public const int CANDIDATE_TYPE_PREF_NAT_ASSISTED; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_PEER_REFLEXIVE")] - public const int CANDIDATE_TYPE_PREF_PEER_REFLEXIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED")] - public const int CANDIDATE_TYPE_PREF_RELAYED; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED_UDP")] - public const int CANDIDATE_TYPE_PREF_RELAYED_UDP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE")] - public const int CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE; - [CCode (cheader_filename = "nice.h")] - public static void debug_disable (bool with_stun); - [CCode (cheader_filename = "nice.h")] - public static void debug_enable (bool with_stun); - [CCode (cheader_filename = "nice.h")] - public static string? interfaces_get_ip_for_interface (string interface_name); - [CCode (cheader_filename = "nice.h")] - public static GLib.List interfaces_get_local_interfaces (); - [CCode (cheader_filename = "nice.h")] - public static GLib.List interfaces_get_local_ips (bool include_loopback); - [CCode (cheader_filename = "nice.h", cname = "pseudo_tcp_set_debug_level")] - [Version (since = "0.0.11")] - public static void pseudo_tcp_set_debug_level (Nice.PseudoTcpDebugLevel level); -} diff --git a/plugins/meson.build b/plugins/meson.build index 8aa05215..3f804fcb 100644 --- a/plugins/meson.build +++ b/plugins/meson.build @@ -1,4 +1,3 @@ -subdir('ice') subdir('notification-sound') subdir('omemo') subdir('openpgp') diff --git a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala index 97674f3f..9cfb4afc 100644 --- a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala +++ b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala @@ -25,6 +25,10 @@ public class Module : XmppStreamModule, Iq.Handler { private GetLocalIpAddresses? get_local_ip_addresses_impl = null; + public Module.with_local_ip_address_handler(owned GetLocalIpAddresses get_local_ip_addresses) { + set_local_ip_address_handler((owned) get_local_ip_addresses); + } + public override void attach(XmppStream stream) { stream.add_flag(new Flag()); query_availability.begin(stream); diff --git a/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala b/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala index 200cdfa9..b59c1b06 100644 --- a/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala +++ b/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala @@ -13,6 +13,10 @@ namespace Xmpp.Xep.JingleRawUdp { private GetLocalIpAddresses? get_local_ip_addresses_impl = null; + public Module.with_local_ip_address_handler(owned GetLocalIpAddresses get_local_ip_addresses) { + set_local_ip_address_handler((owned) get_local_ip_addresses); + } + public override void attach(XmppStream stream) { stream.get_module(Jingle.Module.IDENTITY).register_transport(this); stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI); -- cgit v1.3 From 2413442905e31f34cb0f77c9167003b3725760fe Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sat, 3 Oct 2026 16:05:51 +0200 Subject: Drop supported for outdated dependency versions --- libdino/meson.build | 3 -- libdino/src/service/stream_interactor.vala | 5 --- main/meson.build | 29 +-------------- .../file_transmission_progress.vala | 13 ------- main/src/ui/util/helper.vala | 11 ------ main/src/ui/widgets/avatar_picture.vala | 4 -- main/src/ui/widgets/fixed_ratio_picture.vala | 2 - main/src/windows/conversation_details.vala | 4 -- meson.build | 29 ++++++++------- .../omemo/src/ui/encryption_preferences_entry.vala | 5 --- plugins/openpgp/meson.build | 3 -- plugins/rtp/meson.build | 9 ----- plugins/rtp/src/codec_util.vala | 2 - plugins/rtp/src/plugin.vala | 2 - plugins/rtp/src/stream.vala | 43 +++------------------- plugins/rtp/src/video_widget.vala | 15 -------- xmpp-vala/meson.build | 3 -- xmpp-vala/src/core/direct_tls_xmpp_stream.vala | 2 - xmpp-vala/src/core/module_flag.vala | 10 ----- 19 files changed, 22 insertions(+), 172 deletions(-) (limited to 'libdino/src/service') diff --git a/libdino/meson.build b/libdino/meson.build index e680b662..a3430200 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -119,9 +119,6 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if meson.get_compiler('vala').version().version_compare('=0.56.11') - vala_args += ['-D', 'VALA_0_56_11'] -endif lib_dino = library('libdino', sources, c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, name_prefix: '', version: '0.0', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) dep_dino = declare_dependency(link_with: lib_dino, include_directories: include_directories('.', 'src')) diff --git a/libdino/src/service/stream_interactor.vala b/libdino/src/service/stream_interactor.vala index 2ac13103..2cd0c45c 100644 --- a/libdino/src/service/stream_interactor.vala +++ b/libdino/src/service/stream_interactor.vala @@ -100,12 +100,7 @@ public class ModuleIdentity : Object { } public T? cast(StreamInteractionModule module) { -#if VALA_0_56_11 - // We can't typecheck due to compiler bug - return (T) module; -#else return module.get_type().is_a(typeof(T)) ? (T?) module : null; -#endif } public bool matches(StreamInteractionModule module) { diff --git a/main/meson.build b/main/meson.build index 3c15db32..fbe78573 100644 --- a/main/meson.build +++ b/main/meson.build @@ -47,6 +47,7 @@ sources = files( 'src/ui/conversation_content_view/date_separator_populator.vala', 'src/ui/conversation_content_view/file_default_widget.vala', 'src/ui/conversation_content_view/file_image_widget.vala', + 'src/ui/conversation_content_view/file_transmission_progress.c', 'src/ui/conversation_content_view/file_transmission_progress.vala', 'src/ui/conversation_content_view/file_group_widget.vala', 'src/ui/conversation_content_view/file_widget.vala', @@ -113,34 +114,6 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if dep_gtk4.version() == 'unknown' or dep_gtk4.version().version_compare('>=4.6') - vala_args += ['-D', 'GTK_4_6'] -endif -if dep_gtk4.version() == 'unknown' or dep_gtk4.version().version_compare('>=4.8') - vala_args += ['-D', 'GTK_4_8'] -endif -if dep_gtk4.version() == 'unknown' or dep_gtk4.version().version_compare('>=4.12') - vala_args += ['-D', 'GTK_4_12'] -endif -if dep_gtk4.version() == 'unknown' or dep_gtk4.version().version_compare('>=4.14') - vala_args += ['-D', 'GTK_4_14'] - sources += files('src/ui/conversation_content_view/file_transmission_progress.c') -endif -if dep_libadwaita.version() == 'unknown' or dep_libadwaita.version().version_compare('>=1.4') - vala_args += ['-D', 'Adw_1_4'] -endif -if meson.get_compiler('vala').version().version_compare('>=0.56.5') and meson.get_compiler('vala').version().version_compare('<0.58') - vala_args += ['-D', 'VALA_0_56_GREATER_5'] -endif -if meson.get_compiler('vala').version().version_compare('>=0.56.11') and meson.get_compiler('vala').version().version_compare('<0.58') - vala_args += ['-D', 'VALA_0_56_GREATER_11'] -endif -if meson.get_compiler('vala').version().version_compare('=0.56.11') - vala_args += ['-D', 'VALA_0_56_11'] -endif -if meson.get_compiler('vala').version().version_compare('=0.56.12') - vala_args += ['-D', 'VALA_0_56_12'] -endif exe_dino = executable('dino', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, install: true, install_rpath: default_install_rpath) install_data('data/icons/scalable/apps/im.dino.Dino-symbolic.svg', install_dir: get_option('datadir') / 'icons/hicolor/symbolic/apps') diff --git a/main/src/ui/conversation_content_view/file_transmission_progress.vala b/main/src/ui/conversation_content_view/file_transmission_progress.vala index 43885c1b..3d893f52 100644 --- a/main/src/ui/conversation_content_view/file_transmission_progress.vala +++ b/main/src/ui/conversation_content_view/file_transmission_progress.vala @@ -84,9 +84,7 @@ namespace Dino.Ui { } } -#if GTK_4_14 private static extern Gsk.Path create_progress_arc(Gsk.Path circle, float percentage); -#endif public override void snapshot(Gtk.Snapshot snapshot) { base.snapshot(snapshot); @@ -97,7 +95,6 @@ namespace Dino.Ui { float line_width = (float) LINE_WIDTH; snapshot.translate({get_width() / 2, get_height() / 2}); -#if GTK_4_14 var fg_color = get_color(); get_style_context().lookup_color("accent_color", out fg_color); var builder = new Gsk.PathBuilder(); @@ -107,16 +104,6 @@ namespace Dino.Ui { stroke.set_line_cap(Gsk.LineCap.ROUND); var arc_path = create_progress_arc(circle_path, (float) progress_animation.value); snapshot.append_stroke(arc_path, stroke, fg_color); -#else - var fg_color = get_style_context().get_color(); - get_style_context().lookup_color("accent_color", out fg_color); - var context = snapshot.append_cairo({{-radius, -radius}, {radius*2, radius*2}}); - context.set_line_cap(Cairo.LineCap.ROUND); - context.set_line_width(line_width); - context.set_source_rgba(fg_color.red, fg_color.green, fg_color.blue, fg_color.alpha); - context.arc(0, 0, radius - line_width / 2, -0.5 * Math.PI, (progress_animation.value - 0.25) * 2 * Math.PI); - context.stroke(); -#endif } } diff --git a/main/src/ui/util/helper.vala b/main/src/ui/util/helper.vala index e9035be0..a126a196 100644 --- a/main/src/ui/util/helper.vala +++ b/main/src/ui/util/helper.vala @@ -415,18 +415,7 @@ public bool use_tooltips() { } public static void menu_button_set_icon_with_size(MenuButton menu_button, string icon_name, int pixel_size) { -#if GTK_4_6 && VALA_0_52 menu_button.set_child(new Image.from_icon_name(icon_name) { pixel_size=pixel_size }); -#else - menu_button.set_icon_name(icon_name); - var button = menu_button.get_first_child() as Button; - if (button == null) return; - var box = button.child as Box; - if (box == null) return; - var image = box.get_first_child() as Image; - if (image == null) return; - image.pixel_size = pixel_size; -#endif } } diff --git a/main/src/ui/widgets/avatar_picture.vala b/main/src/ui/widgets/avatar_picture.vala index 155c9440..12c635aa 100644 --- a/main/src/ui/widgets/avatar_picture.vala +++ b/main/src/ui/widgets/avatar_picture.vala @@ -455,11 +455,7 @@ public class Dino.Ui.AvatarPicture : Gtk.Widget { label.insert_after(this, null); label.attributes = new Pango.AttrList(); label.attributes.insert(Pango.attr_foreground_new(uint16.MAX, uint16.MAX, uint16.MAX)); -#if GTK_4_8 && (VALA_0_56_GREATER_5 || VALA_0_58) picture.content_fit = Gtk.ContentFit.COVER; -#elif GTK_4_8 - picture.@set("content-fit", 2); -#endif picture.insert_after(this, label); this.notify["model"].connect(on_model_changed); check_widget_leak(this); diff --git a/main/src/ui/widgets/fixed_ratio_picture.vala b/main/src/ui/widgets/fixed_ratio_picture.vala index 6b04ea61..1898efa7 100644 --- a/main/src/ui/widgets/fixed_ratio_picture.vala +++ b/main/src/ui/widgets/fixed_ratio_picture.vala @@ -8,9 +8,7 @@ class Dino.Ui.FixedRatioPicture : Gtk.Widget { public int max_height { get; set; default = int.MAX; } public File file { get { return inner.file; } set { inner.file = value; } } public Gdk.Paintable paintable { get { return inner.paintable; } set { inner.paintable = value; } } -#if GTK_4_8 && (VALA_0_56_GREATER_5 || VALA_0_58) public Gtk.ContentFit content_fit { get { return inner.content_fit; } set { inner.content_fit = value; } } -#endif private Gtk.Picture inner = new Gtk.Picture(); construct { diff --git a/main/src/windows/conversation_details.vala b/main/src/windows/conversation_details.vala index e1f3061f..8ec3125b 100644 --- a/main/src/windows/conversation_details.vala +++ b/main/src/windows/conversation_details.vala @@ -160,11 +160,7 @@ namespace Dino.Ui.ConversationDetails { } private void create_members() { -#if GTK_4_8 && (VALA_0_56_GREATER_5 || VALA_0_58) if (model.members_sorted.n_items == 0) return; -#else - if (model.members_sorted.model.get_n_items() == 0) return; -#endif var selection_model = new NoSelection(model.members_sorted); var item_factory = new BuilderListItemFactory.from_resource(null, "/im/dino/Dino/muc_member_list_row.ui"); diff --git a/meson.build b/meson.build index ad0f7e4e..7752f7d0 100644 --- a/meson.build +++ b/meson.build @@ -17,6 +17,12 @@ gnome = import('gnome') i18n = import('i18n') cc = meson.get_compiler('c') +vala_version_required = '0.56.14' +vala = meson.get_compiler('vala') +if not vala.version().version_compare('>= @0@'.format(vala_version_required)) + error('valac >= @0@ required!'.format(vala_version_required)) +endif + # Trigger recomnfiguration on version change version_stamp = configure_file( command: [ @@ -74,23 +80,23 @@ endif dep_gdk_pixbuf = dependency('gdk-pixbuf-2.0') dep_gee = dependency('gee-0.8') dep_gio = dependency('gio-2.0') -dep_glib = dependency('glib-2.0') +dep_glib = dependency('glib-2.0', version: '>=2.66') dep_gmodule = dependency('gmodule-2.0') dep_gpgme = dependency('gpgme', disabler: true, required: get_option('plugin-openpgp')) -dep_gstreamer = dependency('gstreamer-1.0', disabler: true, required: get_option('plugin-rtp')) -dep_gstreamer_app = dependency('gstreamer-app-1.0', disabler: true, required: get_option('plugin-rtp')) -dep_gstreamer_audio = dependency('gstreamer-audio-1.0', disabler: true, required: get_option('plugin-rtp')) -dep_gstreamer_rtp = dependency('gstreamer-rtp-1.0', disabler: true, required: get_option('plugin-rtp')) -dep_gstreamer_video = dependency('gstreamer-video-1.0', disabler: true, required: get_option('plugin-rtp')) -dep_gtk4 = dependency('gtk4') +dep_gstreamer = dependency('gstreamer-1.0', version: '>=1.20') +dep_gstreamer_app = dependency('gstreamer-app-1.0', version: '>=1.20') +dep_gstreamer_audio = dependency('gstreamer-audio-1.0', version: '>=1.20') +dep_gstreamer_rtp = dependency('gstreamer-rtp-1.0', version: '>=1.20') +dep_gstreamer_video = dependency('gstreamer-video-1.0', version: '>=1.20') +dep_gtk4 = dependency('gtk4', version: '>=4.14') dep_icu_uc = dependency('icu-uc') dep_libadwaita = dependency('libadwaita-1', version: '>=1.5') dep_libcanberra = dependency('libcanberra', disabler: true, required: get_option('plugin-notification-sound')) dep_libqrencode = dependency('libqrencode', disabler: true, required: get_option('plugin-omemo')) -dep_libsrtp2 = dependency('libsrtp2', disabler: true, required: true) +dep_libsrtp2 = dependency('libsrtp2') dep_libomemo_c = dependency('libomemo-c', disabler: true, required: get_option('plugin-omemo')) dep_libsoup = dependency('libsoup-3.0') -dep_nice = dependency('nice', version: '>=0.1.15', disabler: true, required: get_option('plugin-ice')) +dep_nice = dependency('nice', version: '>=0.1.15') dep_m = meson.get_compiler('c').find_library('m', required: false) dep_sqlite3 = dependency('sqlite3', version: '>=3.24') @@ -99,10 +105,7 @@ if not dep_webrtc_audio_processing.found() dep_webrtc_audio_processing = dependency('webrtc-audio-processing', version: ['>=0.2'], required: false) endif if not dep_webrtc_audio_processing.found() - dep_webrtc_audio_processing = dependency('webrtc-audio-processing-2', required: false) -endif -if not dep_webrtc_audio_processing.found() - dep_webrtc_audio_processing = disabler() + dep_webrtc_audio_processing = dependency('webrtc-audio-processing-2', required: false, disabler: true) endif default_install_rpath = '' diff --git a/plugins/omemo/src/ui/encryption_preferences_entry.vala b/plugins/omemo/src/ui/encryption_preferences_entry.vala index cea856bb..cb14978b 100644 --- a/plugins/omemo/src/ui/encryption_preferences_entry.vala +++ b/plugins/omemo/src/ui/encryption_preferences_entry.vala @@ -166,12 +166,7 @@ public class OmemoPreferencesWidget : Adw.PreferencesGroup { // Create and set QR code popover int sid = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.device_id]; var iri_query = @"omemo-sid-$(sid)=$(fingerprint)"; -#if GLIB_2_66 && VALA_0_50 string iri = GLib.Uri.join(UriFlags.NONE, "xmpp", null, null, 0, jid.to_string(), iri_query, null); -#else - var iri_path_seg = escape_for_iri_path_segment(jid.to_string()); - var iri = @"xmpp:$(iri_path_seg)?$(iri_query)"; -#endif const int QUIET_ZONE_MODULES = 4; // MUST be at least 4 const int MODULE_SIZE_PX = 4; // arbitrary diff --git a/plugins/openpgp/meson.build b/plugins/openpgp/meson.build index 56bc9d0c..78641012 100644 --- a/plugins/openpgp/meson.build +++ b/plugins/openpgp/meson.build @@ -38,9 +38,6 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if dep_libadwaita.version() == 'unknown' or dep_libadwaita.version().version_compare('>=1.4') - vala_args += ['-D', 'Adw_1_4'] -endif lib_openpgp = shared_library('openpgp', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) dep_openpgp = declare_dependency(link_with: lib_openpgp, include_directories: include_directories('.')) summary('End-to-end encryption using PGP (openpgp)', dep_openpgp.found(), bool_yn: true, section: 'Plugins') diff --git a/plugins/rtp/meson.build b/plugins/rtp/meson.build index 2772ad88..f10fbc25 100644 --- a/plugins/rtp/meson.build +++ b/plugins/rtp/meson.build @@ -52,15 +52,6 @@ if dep_webrtc_audio_processing.found() and get_option('plugin-rtp-webrtc-audio-p elif get_option('plugin-rtp-webrtc-audio-processing').enabled() error('No compatible webrtc-audio-processing found, but plugin-rtp-webrtc-audio-processing option set.') endif -if dep_gstreamer_rtp.version() == 'unknown' or dep_gstreamer_rtp.version().version_compare('>=1.16') - vala_args += ['-D', 'GST_1_16'] -endif -if dep_gstreamer_rtp.version() == 'unknown' or dep_gstreamer_rtp.version().version_compare('>=1.18') - vala_args += ['-D', 'GST_1_18'] -endif -if dep_gstreamer_rtp.version() == 'unknown' or dep_gstreamer_rtp.version().version_compare('>=1.20') - vala_args += ['-D', 'GST_1_20'] -endif if meson.get_compiler('vala').version().version_compare('<0.56.1') vala_args += ['--vapidir', meson.current_source_dir() / 'vapi'] endif diff --git a/plugins/rtp/src/codec_util.vala b/plugins/rtp/src/codec_util.vala index 12fcfed7..9f21f5a6 100644 --- a/plugins/rtp/src/codec_util.vala +++ b/plugins/rtp/src/codec_util.vala @@ -280,9 +280,7 @@ public class Dino.Plugins.Rtp.CodecUtil { } public static string? get_depay_args(string media, string codec, string encode, JingleRtp.PayloadType? payload_type) { -#if GST_1_18 if (codec == "vp8") return " wait-for-keyframe=true"; -#endif return null; } diff --git a/plugins/rtp/src/plugin.vala b/plugins/rtp/src/plugin.vala index a94c0ba0..d09b7edf 100644 --- a/plugins/rtp/src/plugin.vala +++ b/plugins/rtp/src/plugin.vala @@ -243,13 +243,11 @@ public class Dino.Plugins.Rtp.Plugin : RootInterface, VideoCallPlugin, Object { device = new Device(this, gst_device); devices.add(device); break; -#if GST_1_16 case Gst.MessageType.DEVICE_CHANGED: message.parse_device_changed(out gst_device, out old_gst_device); device = devices.first_match((it) => it.matches(old_gst_device)); if (device != null) device.update(gst_device); break; -#endif case Gst.MessageType.DEVICE_REMOVED: message.parse_device_removed(out gst_device); device = devices.first_match((it) => it.matches(gst_device)); diff --git a/plugins/rtp/src/stream.vala b/plugins/rtp/src/stream.vala index aa2b080d..9a46d9ff 100644 --- a/plugins/rtp/src/stream.vala +++ b/plugins/rtp/src/stream.vala @@ -102,9 +102,7 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { send_rtp.drop = true; send_rtp.wait_on_eos = false; send_rtp.new_sample.connect(on_new_sample); -#if GST_1_20 send_rtp.new_serialized_event.connect(on_new_event); -#endif send_rtp.connect("signal::eos", on_eos_static, this); pipe.add(send_rtp); @@ -299,7 +297,7 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { bool flip = false; uint8 rotation = 0; -#if GST_1_20 + private bool on_new_event(Gst.App.Sink sink) { if (sink == null || sink != send_rtp) { return false; @@ -349,7 +347,7 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { } return false; } -#endif + private Gst.FlowReturn on_new_sample(Gst.App.Sink sink) { if (sink == null) { @@ -373,14 +371,11 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { next_timestamp_offset_stamp = get_monotonic_time(); rtp_buffer.unmap(); } -#if GLIB_2_64 if (our_ssrc != buffer_ssrc) { warning_once("Sending RTP %s buffer seq %u with SSRC %u when our ssrc is %u", media, buffer_seq, buffer_ssrc, our_ssrc); } -#endif } -#if GST_1_20 if (sink == send_rtp) { Xmpp.Xep.JingleRtp.HeaderExtension? ext = header_extensions.first_match((it) => it.uri == "urn:3gpp:video-orientation"); if (ext != null) { @@ -396,7 +391,6 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { } } } -#endif prepare_local_crypto(); @@ -574,18 +568,7 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { on_recv_rtcp_data(bytes); return; } -#if GST_1_16 - { - Gst.Buffer buffer = new Gst.Buffer.wrapped_bytes(bytes); - Gst.RTP.Buffer rtp_buffer; - uint buffer_ssrc = 0, buffer_seq = 0; - if (Gst.RTP.Buffer.map(buffer, Gst.MapFlags.READ, out rtp_buffer)) { - buffer_ssrc = rtp_buffer.get_ssrc(); - buffer_seq = rtp_buffer.get_seq(); - rtp_buffer.unmap(); - } - } -#endif + if (push_recv_data) { prepare_remote_crypto(); @@ -598,15 +581,13 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { return; } } else { -#if GST_1_16 buffer = new Gst.Buffer.wrapped_bytes(bytes); -#else - buffer = new Gst.Buffer.wrapped(bytes.get_data()); -#endif } Gst.RTP.Buffer rtp_buffer; if (Gst.RTP.Buffer.map(buffer, Gst.MapFlags.READ, out rtp_buffer)) { + uint buffer_ssrc = rtp_buffer.get_ssrc(); + uint buffer_seq = rtp_buffer.get_seq(); if (rtp_buffer.get_extension()) { Xmpp.Xep.JingleRtp.HeaderExtension? ext = header_extensions.first_match((it) => it.uri == "urn:3gpp:video-orientation"); if (ext != null) { @@ -632,12 +613,7 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { rtp_buffer.unmap(); } -#if VALA_0_50 recv_rtp.push_buffer((owned) buffer); -#else - Gst.FlowReturn ret; - GLib.Signal.emit_by_name(recv_rtp, "push-buffer", buffer, out ret); -#endif } } @@ -654,19 +630,10 @@ public class Dino.Plugins.Rtp.Stream : Xmpp.Xep.JingleRtp.Stream { return; } } else { -#if GST_1_16 buffer = new Gst.Buffer.wrapped_bytes(bytes); -#else - buffer = new Gst.Buffer.wrapped(bytes.get_data()); -#endif } -#if VALA_0_50 recv_rtcp.push_buffer((owned) buffer); -#else - Gst.FlowReturn ret; - GLib.Signal.emit_by_name(recv_rtcp, "push-buffer", buffer, out ret); -#endif } } diff --git a/plugins/rtp/src/video_widget.vala b/plugins/rtp/src/video_widget.vala index 5557ec76..af6eb14e 100644 --- a/plugins/rtp/src/video_widget.vala +++ b/plugins/rtp/src/video_widget.vala @@ -75,17 +75,10 @@ public class Dino.Plugins.Rtp.Sink : Gst.Video.Sink { set_drop_out_of_segment(false); } -#if GST_1_20 public override bool set_info(Gst.Caps caps, Gst.Video.Info info) { this.info = info; return true; } -#else - public override bool set_caps(Gst.Caps caps) { - base.set_caps(caps); - return info.from_caps(caps); - } -#endif public override void get_times(Gst.Buffer buffer, out Gst.ClockTime start, out Gst.ClockTime end) { if (buffer.pts != -1) { @@ -250,21 +243,13 @@ public class Dino.Plugins.Rtp.VideoWidget : Gtk.Widget, Dino.Plugins.VideoCallWi if (connected_device == null) return; plugin.pause(); pipe.add(sink); -#if GST_1_20 prepare = Gst.parse_bin_from_description(@"videoflip video-direction=auto name=video_widget_$(id)_orientation ! videoflip method=horizontal-flip name=video_widget_$(id)_flip ! videoconvert name=video_widget_$(id)_convert", true); -#else - prepare = Gst.parse_bin_from_description(@"videoflip method=horizontal-flip name=video_widget_$(id)_flip ! videoconvert name=video_widget_$(id)_convert", true); -#endif prepare.name = @"video_widget_$(id)_prepare"; -#if GST_1_20 if (prepare is Gst.Bin) { ((Gst.Bin) prepare).get_by_name(@"video_widget_$(id)_flip").get_static_pad("sink").notify["caps"].connect(input_caps_changed); } else { -#endif prepare.get_static_pad("sink").notify["caps"].connect(input_caps_changed); -#if GST_1_20 } -#endif pipe.add(prepare); connected_device_element = connected_device.link_source(); connected_device_element.link(prepare); diff --git a/xmpp-vala/meson.build b/xmpp-vala/meson.build index 971f77fa..210526a5 100644 --- a/xmpp-vala/meson.build +++ b/xmpp-vala/meson.build @@ -147,9 +147,6 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if meson.get_compiler('vala').version().version_compare('=0.56.11') - vala_args += ['-D', 'VALA_0_56_11'] -endif lib_xmpp_vala = library('xmpp-vala', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, version: '0.1', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) dep_xmpp_vala = declare_dependency(link_with: lib_xmpp_vala, include_directories: include_directories('.')) diff --git a/xmpp-vala/src/core/direct_tls_xmpp_stream.vala b/xmpp-vala/src/core/direct_tls_xmpp_stream.vala index 2f159ab6..55488eb5 100644 --- a/xmpp-vala/src/core/direct_tls_xmpp_stream.vala +++ b/xmpp-vala/src/core/direct_tls_xmpp_stream.vala @@ -19,9 +19,7 @@ public class Xmpp.DirectTlsXmppStream : TlsXmppStream { debug("Connecting to %s:%i (tls)", host, port); IOStream? io_stream = yield client.connect_to_host_async(host, port, cancellable); TlsConnection tls_connection = TlsClientConnection.new(io_stream, new NetworkAddress(remote_name.to_string(), port)); -#if GLIB_2_60 tls_connection.set_advertised_protocols(ADVERTISED_PROTOCOLS); -#endif tls_connection.accept_certificate.connect(on_invalid_certificate); tls_connection.accept_certificate.connect((cert, flags) => on_invalid_cert.func(cert, flags)); reset_stream(tls_connection); diff --git a/xmpp-vala/src/core/module_flag.vala b/xmpp-vala/src/core/module_flag.vala index 76ae4dc1..95547852 100644 --- a/xmpp-vala/src/core/module_flag.vala +++ b/xmpp-vala/src/core/module_flag.vala @@ -10,12 +10,7 @@ namespace Xmpp { } public T? cast(XmppStreamFlag flag) { -#if VALA_0_56_11 - // We can't typecheck due to compiler bug - return (T) module; -#else return flag.get_type().is_a(typeof(T)) ? (T?) flag : null; -#endif } public bool matches(XmppStreamFlag module) { @@ -39,12 +34,7 @@ namespace Xmpp { } public T? cast(XmppStreamModule module) { -#if VALA_0_56_11 - // We can't typecheck due to compiler bug - return (T) module; -#else return module.get_type().is_a(typeof(T)) ? (T?) module : null; -#endif } public bool matches(XmppStreamModule module) { -- cgit v1.3 From 3e136fc57a2e509e5a4dd265a798b196205b0a80 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sun, 4 Oct 2026 22:02:19 +0200 Subject: Fix more warnings --- libdino/src/service/avatar_manager.vala | 2 +- main/meson.build | 2 +- plugins/omemo/meson.build | 51 --------------------- xmpp-vala/src/core/stanza_node.vala | 2 +- xmpp-vala/src/core/stanza_reader.vala | 11 ++++- xmpp-vala/src/file_content_type.vala | 8 +++- xmpp-vala/src/module/xep/0004_data_forms.vala | 5 -- .../module/xep/0030_service_discovery/module.vala | 17 +++++-- xmpp-vala/src/module/xep/0084_user_avatars.vala | 9 ++-- .../xep/0261_jingle_in_band_bytestreams.vala | 4 -- xmpp-vala/src/module/xep/0272_muji.vala | 10 ++-- .../src/module/xep/0363_http_file_upload.vala | 36 ++++++++------- .../module/xep/0388_extensible_sasl_profile.vala | 24 ++++++---- .../module/xep/0392_consistent_color/hsluv.vala | 53 ++++++++++------------ xmpp-vala/src/module/xep/0410_muc_self_ping.vala | 18 +++++--- .../src/module/xep/0425_message_moderation.vala | 18 +++++--- .../module/xep/0447_stateless_file_sharing.vala | 2 +- .../0490_message_displayed_synchronization.vala | 37 ++++++++++----- xmpp-vala/tests/color.vala | 20 ++++---- xmpp-vala/tests/common.vala | 12 ++--- xmpp-vala/tests/weak_map.vala | 8 ++-- 21 files changed, 171 insertions(+), 178 deletions(-) delete mode 100644 plugins/omemo/meson.build (limited to 'libdino/src/service') diff --git a/libdino/src/service/avatar_manager.vala b/libdino/src/service/avatar_manager.vala index ac4971ef..7f69f508 100644 --- a/libdino/src/service/avatar_manager.vala +++ b/libdino/src/service/avatar_manager.vala @@ -142,7 +142,7 @@ public class AvatarManager : StreamInteractionModule, Object { public void unset_avatar(Account account) { XmppStream stream = stream_interactor.get_stream(account); if (stream == null) return; - Xmpp.Xep.UserAvatars.unset_avatar(stream); + Xmpp.Xep.UserAvatars.unset_avatar(stream, get_avatar_hash(account, account.bare_jid)); } private void on_account_added(Account account) { diff --git a/main/meson.build b/main/meson.build index cdefcbf7..d9f56e81 100644 --- a/main/meson.build +++ b/main/meson.build @@ -142,7 +142,7 @@ if get_option('rtp').allowed() and dep_gstreamer.found() and dep_gstreamer_app.f voice_sources = files( 'src/plugins/rtp/voice_processor_native.cpp', ) - voice_c_args = c_args + voice_c_args = ['-DG_LOG_DOMAIN="dino"'] if dep_webrtc_audio_processing.version().version_compare('>=2.0') voice_c_args += ['-DWEBRTC2'] elif dep_webrtc_audio_processing.version().version_compare('>=1.0') diff --git a/plugins/omemo/meson.build b/plugins/omemo/meson.build deleted file mode 100644 index 70279946..00000000 --- a/plugins/omemo/meson.build +++ /dev/null @@ -1,51 +0,0 @@ -subdir('po') -dependencies = [ - dep_libadwaita, - dep_dino, - dep_gee, - dep_glib, - dep_gmodule, - dep_gtk4, - dep_libomemo_c, - dep_m, - dep_xmpp_vala, -] -sources = files( -) -sources += gnome.compile_resources( - 'resources', - 'data/gresource.xml', - source_dir: 'data', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="OMEMO"', - '-DGETTEXT_PACKAGE="dino-omemo"', - '-DLOCALE_INSTALL_DIR="@0@"'.format(get_option('prefix') / get_option('localedir')), -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', - # This is to build internal vapi for tests - '--header', meson.current_build_dir() / 'omemo.h', - '--internal-vapi', meson.current_build_dir() / 'omemo-internal.vapi', - '--internal-header', meson.current_build_dir() / 'omemo-internal.h', -] -lib_omemo = shared_library('omemo', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) -dep_omemo = declare_dependency(link_with: lib_omemo, include_directories: include_directories('.')) -# This is to use the internal vapi instead of the regular -vapi_omemo_internal = custom_target('omemo-internal-vapi', command: [find_program('touch'), meson.current_build_dir() / 'omemo-internal.vapi'], output: ['omemo-internal.vapi'], depends: lib_omemo) -dep_omemo_internal = declare_dependency(link_args: [lib_omemo.full_path()], include_directories: include_directories('.', 'src'), sources: [vapi_omemo_internal]) - -test_sources = [ - 'tests/native/common.vala', - 'tests/native/testcase.vala', - - 'tests/native/curve25519.vala', - 'tests/native/hkdf.vala', - 'tests/native/session_builder.vala', -] -test_vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] - -exe_omemo_test = executable('omemo-test', test_sources, c_args: c_args, vala_args: test_vala_args, dependencies: dependencies + dep_omemo_internal, build_rpath: '$ORIGIN', install: false) -test('Tests for omemo', exe_omemo_test) diff --git a/xmpp-vala/src/core/stanza_node.vala b/xmpp-vala/src/core/stanza_node.vala index 7a68da62..56f857d4 100644 --- a/xmpp-vala/src/core/stanza_node.vala +++ b/xmpp-vala/src/core/stanza_node.vala @@ -29,7 +29,7 @@ public abstract class StanzaEntry { case '\'': result_builder.append("'"); break; case '<': result_builder.append("<"); break; case '>': result_builder.append(">"); break; - default: error("Unreachable"); break; + default: error("Unreachable"); } return false; }); diff --git a/xmpp-vala/src/core/stanza_reader.vala b/xmpp-vala/src/core/stanza_reader.vala index ff512497..4828600d 100644 --- a/xmpp-vala/src/core/stanza_reader.vala +++ b/xmpp-vala/src/core/stanza_reader.vala @@ -38,8 +38,15 @@ public class StanzaReader { if (cancellable != null && cancellable.is_cancelled()) throw new IOError.CANCELLED("Input stream is canceled."); try { buffer_fill = (int) yield ((!)input).read_async(buffer, GLib.Priority.DEFAULT, cancellable); - } catch (TlsError.EOF e) { - throw new IOError.CLOSED("End of TLS stream reached"); + } catch (Error e) { + if (e is IOError) { + throw (IOError) e; + } else if (e is TlsError.EOF) { + // The error can be TlsError.EOF instead of IOError.CLOSED, fixing that + throw new IOError.CLOSED("End of TLS stream reached"); + } else { + throw new IOError.FAILED("Unknown error: %s", e.message); + } } if (buffer_fill == 0) throw new IOError.CLOSED("End of input stream reached."); buffer_pos = 0; diff --git a/xmpp-vala/src/file_content_type.vala b/xmpp-vala/src/file_content_type.vala index 3656435e..bae493f6 100644 --- a/xmpp-vala/src/file_content_type.vala +++ b/xmpp-vala/src/file_content_type.vala @@ -14,8 +14,12 @@ namespace Xmpp { } public FileContentType.from_file(File file) { - FileInfo file_info = file.query_info("*", FileQueryInfoFlags.NONE); - this.from_file_info(file_info); + try { + FileInfo file_info = file.query_info("*", FileQueryInfoFlags.NONE); + this.from_file_info(file_info); + } catch (Error e) { + warning("Failed reading file content type: %s", e.message); + } } public string? get_mime_type() { diff --git a/xmpp-vala/src/module/xep/0004_data_forms.vala b/xmpp-vala/src/module/xep/0004_data_forms.vala index f481e174..6c16a53d 100644 --- a/xmpp-vala/src/module/xep/0004_data_forms.vala +++ b/xmpp-vala/src/module/xep/0004_data_forms.vala @@ -83,11 +83,6 @@ public class DataForm { value_node.put_node(new StanzaNode.text(val)); } - internal void add_value_string(string val) { - StanzaNode node = new StanzaNode.build("value"); - node.put_node(new StanzaNode.text(val)); - } - internal Gee.List