diff options
31 files changed, 1244 insertions, 871 deletions
diff --git a/libdino/CMakeLists.txt b/libdino/CMakeLists.txt index 73386d0a..31ba69d3 100644 --- a/libdino/CMakeLists.txt +++ b/libdino/CMakeLists.txt @@ -35,7 +35,7 @@ SOURCES src/service/database.vala src/service/entity_capabilities_storage.vala src/service/file_manager.vala - src/service/jingle_file_manager.vala + src/service/jingle_file_transfers.vala src/service/message_processor.vala src/service/message_storage.vala src/service/module_manager.vala diff --git a/libdino/src/application.vala b/libdino/src/application.vala index 396aa91f..da098fb4 100644 --- a/libdino/src/application.vala +++ b/libdino/src/application.vala @@ -37,7 +37,6 @@ public interface Dino.Application : GLib.Application { RosterManager.start(stream_interactor, db); ChatInteraction.start(stream_interactor); FileManager.start(stream_interactor, db); - JingleFileManager.start(stream_interactor); ContentItemStore.start(stream_interactor, db); NotificationEvents.start(stream_interactor); SearchProcessor.start(stream_interactor, db); diff --git a/libdino/src/entity/file_transfer.vala b/libdino/src/entity/file_transfer.vala index 68234a48..4e4103b9 100644 --- a/libdino/src/entity/file_transfer.vala +++ b/libdino/src/entity/file_transfer.vala @@ -9,7 +9,7 @@ public class FileTransfer : Object { public enum State { COMPLETE, - IN_PROCESS, + IN_PROGRESS, NOT_STARTED, FAILED } @@ -27,7 +27,7 @@ public class FileTransfer : Object { public bool direction { get; set; } public DateTime time { get; set; } public DateTime? local_time { get; set; } - public Encryption encryption { get; set; } + public Encryption encryption { get; set; default=Encryption.NONE; } private InputStream? input_stream_ = null; public InputStream input_stream { @@ -54,9 +54,9 @@ public class FileTransfer : Object { public string path { get; set; } public string? mime_type { get; set; } // TODO(hrxi): expand to 64 bit - public int size { get; set; } + public int size { get; set; default=-1; } - public State state { get; set; } + public State state { get; set; default=State.NOT_STARTED; } public int provider { get; set; } public string info { get; set; } @@ -110,12 +110,15 @@ public class FileTransfer : Object { .value(db.file_transfer.local_time, (long) local_time.to_unix()) .value(db.file_transfer.encryption, encryption) .value(db.file_transfer.file_name, file_name) - .value(db.file_transfer.path, path) - .value(db.file_transfer.mime_type, mime_type) .value(db.file_transfer.size, size) .value(db.file_transfer.state, state) .value(db.file_transfer.provider, provider) .value(db.file_transfer.info, info); + + if (file_name != null) builder.value(db.file_transfer.file_name, file_name); + if (path != null) builder.value(db.file_transfer.path, path); + if (mime_type != null) builder.value(db.file_transfer.mime_type, mime_type); + id = (int) builder.perform(); notify.connect(on_update); } @@ -142,7 +145,14 @@ public class FileTransfer : Object { update_builder.set(db.file_transfer.encryption, encryption); break; case "file-name": update_builder.set(db.file_transfer.file_name, file_name); break; + case "path": + update_builder.set(db.file_transfer.path, path); break; + case "mime-type": + update_builder.set(db.file_transfer.mime_type, mime_type); break; + case "size": + update_builder.set(db.file_transfer.size, size); break; case "state": + if (state == State.IN_PROGRESS) return; update_builder.set(db.file_transfer.state, state); break; case "provider": update_builder.set(db.file_transfer.provider, provider); break; diff --git a/libdino/src/service/content_item_store.vala b/libdino/src/service/content_item_store.vala index 9f39ce59..3800f35d 100644 --- a/libdino/src/service/content_item_store.vala +++ b/libdino/src/service/content_item_store.vala @@ -257,18 +257,24 @@ public class FileItem : ContentItem { public FileItem(FileTransfer file_transfer, int id) { Jid jid = file_transfer.direction == FileTransfer.DIRECTION_SENT ? file_transfer.account.bare_jid.with_resource(file_transfer.account.resourcepart) : file_transfer.counterpart; - base(id, TYPE, jid, file_transfer.local_time, file_transfer.time, file_transfer.encryption, file_to_message_state(file_transfer.state)); + Entities.Message.Marked mark = Entities.Message.Marked.NONE; + if (file_transfer.direction == FileTransfer.DIRECTION_SENT) { + mark = file_to_message_state(file_transfer.state); + } + base(id, TYPE, jid, file_transfer.local_time, file_transfer.time, file_transfer.encryption, mark); this.file_transfer = file_transfer; - file_transfer.notify["state"].connect_after(() => { - this.mark = file_to_message_state(file_transfer.state); - }); + if (file_transfer.direction == FileTransfer.DIRECTION_SENT) { + file_transfer.notify["state"].connect_after(() => { + this.mark = file_to_message_state(file_transfer.state); + }); + } } private static Entities.Message.Marked file_to_message_state(FileTransfer.State state) { switch (state) { - case FileTransfer.State.IN_PROCESS: + case FileTransfer.State.IN_PROGRESS: return Entities.Message.Marked.UNSENT; case FileTransfer.State.COMPLETE: return Entities.Message.Marked.NONE; diff --git a/libdino/src/service/file_manager.vala b/libdino/src/service/file_manager.vala index 7665936c..50b38f01 100644 --- a/libdino/src/service/file_manager.vala +++ b/libdino/src/service/file_manager.vala @@ -16,8 +16,9 @@ public class FileManager : StreamInteractionModule, Object { private StreamInteractor stream_interactor; private Database db; private Gee.List<FileSender> file_senders = new ArrayList<FileSender>(); - public Gee.List<IncomingFileProcessor> incoming_processors = new ArrayList<IncomingFileProcessor>(); - private Gee.List<OutgoingFileProcessor> outgoing_processors = new ArrayList<OutgoingFileProcessor>(); + private Gee.List<FileEncryptor> file_encryptors = new ArrayList<FileEncryptor>(); + private Gee.List<FileDecryptor> file_decryptors = new ArrayList<FileDecryptor>(); + private Gee.List<FileProvider> file_providers = new ArrayList<FileProvider>(); public static void start(StreamInteractor stream_interactor, Database db) { FileManager m = new FileManager(stream_interactor, db); @@ -32,6 +33,9 @@ public class FileManager : StreamInteractionModule, Object { this.stream_interactor = stream_interactor; this.db = db; DirUtils.create_with_parents(get_storage_dir(), 0700); + + this.add_provider(new JingleFileProvider(stream_interactor)); + this.add_sender(new JingleFileSender(stream_interactor)); } public async void send_file(string uri, Conversation conversation) { @@ -43,6 +47,7 @@ public class FileManager : StreamInteractionModule, Object { file_transfer.time = new DateTime.now_utc(); file_transfer.local_time = new DateTime.now_utc(); file_transfer.encryption = conversation.encryption; + try { File file = File.new_for_path(uri); FileInfo file_info = file.query_info("*", FileQueryInfoFlags.NONE); @@ -50,26 +55,79 @@ public class FileManager : StreamInteractionModule, Object { file_transfer.mime_type = file_info.get_content_type(); file_transfer.size = (int)file_info.get_size(); file_transfer.input_stream = yield file.read_async(); + + yield save_file(file_transfer); + + file_transfer.persist(db); + received_file(file_transfer, conversation); } catch (Error e) { file_transfer.state = FileTransfer.State.FAILED; + warning("Error saving outgoing file: %s", e.message); + return; } - yield save_file(file_transfer); - file_transfer.persist(db); + try { + var file_meta = new FileMeta(); + file_meta.size = file_transfer.size; + file_meta.mime_type = file_transfer.mime_type; + + bool encrypted = false; + foreach (FileEncryptor file_encryptor in file_encryptors) { + if (file_encryptor.can_encrypt_file(conversation, file_transfer)) { + file_meta = file_encryptor.encrypt_file(conversation, file_transfer); + encrypted = true; + break; + } + } + if (conversation.encryption != Encryption.NONE && !encrypted) { + throw new FileSendError.ENCRYPTION_FAILED("File was not encrypted"); + } + + FileSendData file_send_data = null; + foreach (FileSender file_sender in file_senders) { + if (file_sender.can_send(conversation, file_transfer)) { + file_send_data = yield file_sender.prepare_send_file(conversation, file_transfer); + break; + } + } + + foreach (FileEncryptor file_encryptor in file_encryptors) { + if (file_encryptor.can_encrypt_file(conversation, file_transfer)) { + file_send_data = file_encryptor.preprocess_send_file(conversation, file_transfer, file_send_data, file_meta); + break; + } + } - foreach (OutgoingFileProcessor processor in outgoing_processors) { - if (processor.can_process(conversation, file_transfer)) { - processor.process(conversation, file_transfer); + bool sent = false; + foreach (FileSender file_sender in file_senders) { + if (file_sender.can_send(conversation, file_transfer)) { + yield file_sender.send_file(conversation, file_transfer, file_send_data); + sent = true; + break; + } } + if (!sent) { + throw new FileSendError.UPLOAD_FAILED("File was not sent"); + } + + conversation.last_active = file_transfer.time; + } catch (Error e) { + warning("Send file error: %s", e.message); + file_transfer.state = FileTransfer.State.FAILED; } + } - foreach (FileSender file_sender in file_senders) { - if (file_sender.can_send(conversation, file_transfer)) { - file_sender.send_file(conversation, file_transfer); - break; + public async void download_file(FileTransfer file_transfer) { + Conversation conversation = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(file_transfer.counterpart.bare_jid, file_transfer.account); + + FileProvider? file_provider = null; + foreach (FileProvider fp in file_providers) { + if (file_transfer.provider == fp.get_id()) { + file_provider = fp; } } - received_file(file_transfer, conversation); + + yield download_file_internal(file_provider, file_transfer, conversation); } public bool is_upload_available(Conversation conversation) { @@ -117,24 +175,28 @@ public class FileManager : StreamInteractionModule, Object { } public void add_provider(FileProvider file_provider) { - file_provider.file_incoming.connect((file_transfer, conversation) => { handle_incoming_file.begin(file_provider, file_transfer, conversation); }); + file_providers.add(file_provider); + file_provider.file_incoming.connect((info, from, time, local_time, conversation, receive_data, file_meta) => { + handle_incoming_file.begin(file_provider, info, from, time, local_time, conversation, receive_data, file_meta); + }); } public void add_sender(FileSender file_sender) { - // Order file_senders in reverse order of adding them -- HTTP is added - // later than Jingle. - file_senders.insert(0, file_sender); + file_senders.add(file_sender); file_sender.upload_available.connect((account) => { upload_available(account); }); + file_senders.sort((a, b) => { + return (int) (b.get_priority() - a.get_priority()); + }); } - public void add_incoming_processor(IncomingFileProcessor processor) { - incoming_processors.add(processor); + public void add_file_encryptor(FileEncryptor encryptor) { + file_encryptors.add(encryptor); } - public void add_outgoing_processor(OutgoingFileProcessor processor) { - outgoing_processors.add(processor); + public void add_file_decryptor(FileDecryptor decryptor) { + file_decryptors.add(decryptor); } public bool is_sender_trustworthy(FileTransfer file_transfer, Conversation conversation) { @@ -143,29 +205,124 @@ public class FileManager : StreamInteractionModule, Object { return file_transfer.direction == FileTransfer.DIRECTION_SENT || in_roster; } - private async void handle_incoming_file(FileProvider file_provider, FileTransfer file_transfer, Conversation conversation) { - if (!is_sender_trustworthy(file_transfer, conversation)) return; + 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); + + if (file_meta.size == -1) { + foreach (FileDecryptor file_decryptor in file_decryptors) { + if (file_decryptor.can_decrypt_file(conversation, file_transfer, receive_data)) { + receive_data = file_decryptor.prepare_get_meta_info(conversation, file_transfer, receive_data); + break; + } + } + + file_meta = yield file_provider.get_meta_info(file_transfer, receive_data, file_meta); - if (file_transfer.size == -1) { - yield file_provider.get_meta_info(file_transfer); + file_transfer.size = (int)file_meta.size; + file_transfer.file_name = file_meta.file_name; + file_transfer.mime_type = file_meta.mime_type; } + return file_meta; + } - if (file_transfer.size >= 0 && file_transfer.size < 5000000) { - string filename = Random.next_int().to_string("%x") + "_" + file_transfer.file_name; + private async void download_file_internal(FileProvider file_provider, FileTransfer file_transfer, Conversation conversation) { + try { + // Get meta info + FileReceiveData receive_data = file_provider.get_file_receive_data(file_transfer); + foreach (FileDecryptor file_decryptor in file_decryptors) { + if (file_decryptor.can_decrypt_file(conversation, file_transfer, receive_data)) { + receive_data = file_decryptor.prepare_get_meta_info(conversation, file_transfer, receive_data); + break; + } + } + FileMeta file_meta = yield get_file_meta(file_provider, file_transfer, conversation, receive_data); + + + InputStream? input_stream = null; + + // Download and decrypt file + file_transfer.state = FileTransfer.State.IN_PROGRESS; + + foreach (FileDecryptor file_decryptor in file_decryptors) { + if (file_decryptor.can_decrypt_file(conversation, file_transfer, receive_data)) { + file_meta = file_decryptor.prepare_download_file(conversation, file_transfer, receive_data, file_meta); + break; + } + } + + input_stream = yield file_provider.download(file_transfer, receive_data, file_meta); + + foreach (FileDecryptor file_decryptor in file_decryptors) { + if (file_decryptor.can_decrypt_file(conversation, file_transfer, receive_data)) { + input_stream = yield file_decryptor.decrypt_file(input_stream, conversation, file_transfer, receive_data); + break; + } + } + + // Save file + string filename = Random.next_int().to_string("%x") + "_" + file_meta.file_name; File file = File.new_for_path(Path.build_filename(get_storage_dir(), filename)); - yield file_provider.download(file_transfer, file); - try { - FileInfo file_info = file_transfer.get_file().query_info("*", FileQueryInfoFlags.NONE); - file_transfer.mime_type = file_info.get_content_type(); - } catch (Error e) { } + if (file_transfer.encryption == Encryption.PGP || file.get_path().has_suffix(".pgp")) { + file = File.new_for_path(file.get_path().substring(0, file.get_path().length - 4)); + } - file_transfer.persist(db); - received_file(file_transfer, conversation); + OutputStream os = file.create(FileCreateFlags.REPLACE_DESTINATION); + yield os.splice_async(input_stream, 0); + os.close(); + file_transfer.size = (int)file_meta.size; + file_transfer.file_name = file_meta.file_name; + file_transfer.path = file.get_basename(); + file_transfer.input_stream = yield file.read_async(); + + FileInfo file_info = file_transfer.get_file().query_info("*", FileQueryInfoFlags.NONE); + file_transfer.mime_type = file_info.get_content_type(); + + file_transfer.state = FileTransfer.State.COMPLETE; + } catch (Error e) { + warning("Error downloading file: %s", e.message); + file_transfer.state = FileTransfer.State.FAILED; } } - private async void save_file(FileTransfer file_transfer) { + private async void handle_incoming_file(FileProvider file_provider, string info, Jid from, DateTime time, DateTime local_time, Conversation conversation, FileReceiveData receive_data, FileMeta file_meta) { + FileTransfer file_transfer = new FileTransfer(); + file_transfer.account = conversation.account; + file_transfer.direction = from.bare_jid.equals(conversation.account.bare_jid) ? FileTransfer.DIRECTION_SENT : FileTransfer.DIRECTION_RECEIVED; + file_transfer.counterpart = file_transfer.direction == FileTransfer.DIRECTION_RECEIVED ? from : conversation.counterpart; + if (conversation.type_ in new Conversation.Type[]{Conversation.Type.GROUPCHAT, Conversation.Type.GROUPCHAT_PM}) { + file_transfer.ourpart = stream_interactor.get_module(MucManager.IDENTITY).get_own_jid(conversation.counterpart, conversation.account) ?? conversation.account.bare_jid; + } else { + file_transfer.ourpart = conversation.account.bare_jid.with_resource(conversation.account.resourcepart); + } + file_transfer.time = time; + file_transfer.local_time = local_time; + file_transfer.provider = file_provider.get_id(); + file_transfer.file_name = file_meta.file_name; + file_transfer.size = (int)file_meta.size; + file_transfer.info = info; + + file_transfer.persist(db); + + if (is_sender_trustworthy(file_transfer, conversation)) { + try { + yield get_file_meta(file_provider, file_transfer, conversation, receive_data); + + if (file_transfer.size >= 0 && file_transfer.size < 5000000) { + yield download_file_internal(file_provider, file_transfer, conversation); + } + } catch (Error e) { + warning("Error downloading file: %s", e.message); + file_transfer.state = FileTransfer.State.FAILED; + } + } + + conversation.last_active = file_transfer.time; + 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)); @@ -176,33 +333,84 @@ public class FileManager : StreamInteractionModule, Object { file_transfer.path = filename; file_transfer.input_stream = yield file.read_async(); } catch (Error e) { - file_transfer.state = FileTransfer.State.FAILED; + throw new FileSendError.SAVE_FAILED("Saving file error: %s".printf(e.message)); } } +} +public errordomain FileSendError { + ENCRYPTION_FAILED, + UPLOAD_FAILED, + SAVE_FAILED +} + +public errordomain FileReceiveError { + GET_METADATA_FAILED, + DECRYPTION_FAILED, + DOWNLOAD_FAILED +} + +public class FileMeta { + public int64 size = -1; + public string? mime_type = null; + public string? file_name = null; + public Encryption encryption = Encryption.NONE; +} + +public class HttpFileMeta : FileMeta { + public Message message; +} + +public class FileSendData { } + +public class HttpFileSendData : FileSendData { + public string url_down { get; set; } + public string url_up { get; set; } + + public bool encrypt_message { get; set; default=true; } +} + +public class FileReceiveData { } + +public class HttpFileReceiveData : FileReceiveData { + public string url { get; set; } } public interface FileProvider : Object { - public signal void file_incoming(FileTransfer file_transfer, Conversation conversation); - public abstract async void get_meta_info(FileTransfer file_transfer); - public abstract async void download(FileTransfer file_transfer, File file); + public signal void file_incoming(string info, Jid from, DateTime time, DateTime local_time, Conversation conversation, FileReceiveData receive_data, FileMeta file_meta); + + public abstract FileMeta get_file_meta(FileTransfer file_transfer) throws FileReceiveError; + public abstract FileReceiveData? get_file_receive_data(FileTransfer file_transfer); + + public abstract async FileMeta get_meta_info(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError; + public abstract async InputStream download(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError; + + public abstract int get_id(); } public interface FileSender : Object { public signal void upload_available(Account account); + public abstract bool is_upload_available(Conversation conversation); public abstract bool can_send(Conversation conversation, FileTransfer file_transfer); - public abstract void send_file(Conversation conversation, FileTransfer file_transfer); + public abstract async FileSendData? prepare_send_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError; + public abstract async void send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data) throws FileSendError; + + public abstract int get_id(); + public abstract float get_priority(); } -public interface IncomingFileProcessor : Object { - public abstract bool can_process(FileTransfer file_transfer); - public abstract void process(FileTransfer file_transfer); +public interface FileEncryptor : Object { + public abstract bool can_encrypt_file(Conversation conversation, FileTransfer file_transfer); + public abstract FileMeta encrypt_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError; + public abstract FileSendData? preprocess_send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data, FileMeta file_meta) throws FileSendError; } -public interface OutgoingFileProcessor : Object { - public abstract bool can_process(Conversation conversation, FileTransfer file_transfer); - public abstract void process(Conversation conversation, FileTransfer file_transfer); +public interface FileDecryptor : Object { + public abstract FileReceiveData prepare_get_meta_info(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data); + public abstract FileMeta prepare_download_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta); + public abstract bool can_decrypt_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data); + public abstract async InputStream decrypt_file(InputStream encrypted_stream, Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) throws FileReceiveError; } } diff --git a/libdino/src/service/jingle_file_manager.vala b/libdino/src/service/jingle_file_manager.vala deleted file mode 100644 index 595afae0..00000000 --- a/libdino/src/service/jingle_file_manager.vala +++ /dev/null @@ -1,122 +0,0 @@ -using Gdk; -using Gee; - -using Xmpp; -using Dino.Entities; - -namespace Dino { - -public class JingleFileManager : StreamInteractionModule, FileProvider, FileSender, Object { - public static ModuleIdentity<JingleFileManager> IDENTITY = new ModuleIdentity<JingleFileManager>("jingle_files"); - public string id { get { return IDENTITY.id; } } - - private StreamInteractor stream_interactor; - private HashMap<string, Xmpp.Xep.JingleFileTransfer.FileTransfer> file_transfers - = new HashMap<string, Xmpp.Xep.JingleFileTransfer.FileTransfer>(); - - public static void start(StreamInteractor stream_interactor) { - JingleFileManager m = new JingleFileManager(stream_interactor); - stream_interactor.add_module(m); - } - - private JingleFileManager(StreamInteractor stream_interactor) { - this.stream_interactor = stream_interactor; - - stream_interactor.get_module(FileManager.IDENTITY).add_sender(this); - stream_interactor.get_module(FileManager.IDENTITY).add_provider(this); - stream_interactor.stream_negotiated.connect(on_stream_negotiated); - } - - private void on_stream_negotiated(Account account, XmppStream stream) { - stream_interactor.module_manager.get_module(account, Xmpp.Xep.JingleFileTransfer.Module.IDENTITY).file_incoming.connect((stream, jingle_file_transfer) => { - Conversation? conversation = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(jingle_file_transfer.peer.bare_jid, account); - if (conversation == null) { - // TODO(hrxi): What to do? - return; - } - string id = random_uuid(); - - FileTransfer file_transfer = new FileTransfer(); - file_transfer.account = account; - file_transfer.counterpart = jingle_file_transfer.peer.bare_jid; - file_transfer.ourpart = account.bare_jid; - file_transfer.encryption = Encryption.NONE; - file_transfer.time = new DateTime.now_utc(); - file_transfer.local_time = new DateTime.now_utc(); - file_transfer.direction = FileTransfer.DIRECTION_RECEIVED; - file_transfer.file_name = jingle_file_transfer.file_name; - file_transfer.size = (int)jingle_file_transfer.size; - file_transfer.state = FileTransfer.State.NOT_STARTED; - file_transfer.provider = 1; - file_transfer.info = id; - file_transfers[id] = jingle_file_transfer; - - file_incoming(file_transfer, conversation); - }); - } - - async void get_meta_info(FileTransfer file_transfer) { - // In Jingle, all the metadata is provided up-front, so there's no more - // metadata to get. - } - async void download(FileTransfer file_transfer, File file_) { - // TODO(hrxi) What should happen if `stream == null`? - XmppStream? stream = stream_interactor.get_stream(file_transfer.account); - Xmpp.Xep.JingleFileTransfer.FileTransfer jingle_file_transfer = file_transfers[file_transfer.info]; - jingle_file_transfer.accept(stream); - file_transfer.input_stream = jingle_file_transfer.stream; - - // TODO(hrxi): BEGIN: Copied from plugins/http-files/src/file_provider.vala - foreach (IncomingFileProcessor processor in stream_interactor.get_module(FileManager.IDENTITY).incoming_processors) { - if (processor.can_process(file_transfer)) { - processor.process(file_transfer); - } - } - - // TODO(hrxi): should this be an &&? - File file = file_; - if (file_transfer.encryption == Encryption.PGP || file.get_path().has_suffix(".pgp")) { - file = File.new_for_path(file.get_path().substring(0, file.get_path().length - 4)); - } - // TODO(hrxi): END: Copied from plugins/http-files/src/file_provider.vala - - try { - OutputStream os = file.create(FileCreateFlags.REPLACE_DESTINATION); - yield os.splice_async(file_transfer.input_stream, OutputStreamSpliceFlags.CLOSE_SOURCE|OutputStreamSpliceFlags.CLOSE_TARGET); - file_transfer.path = file.get_basename(); - file_transfer.input_stream = yield file.read_async(); - - file_transfer.state = FileTransfer.State.COMPLETE; - } catch (Error e) { - file_transfer.state = FileTransfer.State.FAILED; - return; - } - } - - public bool is_upload_available(Conversation conversation) { - // TODO(hrxi) Here and in `send_file`: What should happen if `stream == null`? - XmppStream? stream = stream_interactor.get_stream(conversation.account); - foreach (Jid full_jid in stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart)) { - if (stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).is_available(stream, full_jid)) { - return true; - } - } - return false; - } - public bool can_send(Conversation conversation, FileTransfer file_transfer) { - return file_transfer.encryption != Encryption.OMEMO; - } - public void send_file(Conversation conversation, FileTransfer file_transfer) { - XmppStream? stream = stream_interactor.get_stream(file_transfer.account); - foreach (Jid full_jid in stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart)) { - // TODO(hrxi): Prioritization of transports (and resources?). - if (!stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).is_available(stream, full_jid)) { - continue; - } - stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).offer_file_stream.begin(stream, full_jid, file_transfer.input_stream, file_transfer.file_name, file_transfer.size); - return; - } - } -} - -} diff --git a/libdino/src/service/jingle_file_transfers.vala b/libdino/src/service/jingle_file_transfers.vala new file mode 100644 index 00000000..c90986d2 --- /dev/null +++ b/libdino/src/service/jingle_file_transfers.vala @@ -0,0 +1,127 @@ +using Gdk; +using Gee; + +using Xmpp; +using Dino.Entities; + +namespace Dino { + +public class JingleFileProvider : FileProvider, Object { + + private StreamInteractor stream_interactor; + private HashMap<string, Xmpp.Xep.JingleFileTransfer.FileTransfer> file_transfers = new HashMap<string, Xmpp.Xep.JingleFileTransfer.FileTransfer>(); + + public JingleFileProvider(StreamInteractor stream_interactor) { + this.stream_interactor = stream_interactor; + + stream_interactor.stream_negotiated.connect(on_stream_negotiated); + } + + public FileMeta get_file_meta(FileTransfer file_transfer) throws FileReceiveError { + var file_meta = new FileMeta(); + file_meta.file_name = file_transfer.file_name; + file_meta.size = file_transfer.size; + return file_meta; + } + + public FileReceiveData? get_file_receive_data(FileTransfer file_transfer) { + return new FileReceiveData(); + } + + public async FileMeta get_meta_info(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError { + return file_meta; + } + + public async InputStream download(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError { + // TODO(hrxi) What should happen if `stream == null`? + XmppStream? stream = stream_interactor.get_stream(file_transfer.account); + Xmpp.Xep.JingleFileTransfer.FileTransfer? jingle_file_transfer = file_transfers[file_transfer.info]; + if (jingle_file_transfer == null) { + throw new FileReceiveError.DOWNLOAD_FAILED("Transfer data not available anymore"); + } + jingle_file_transfer.accept(stream); + return jingle_file_transfer.stream; + } + + public int get_id() { + return 1; + } + + private void on_stream_negotiated(Account account, XmppStream stream) { + stream_interactor.module_manager.get_module(account, Xmpp.Xep.JingleFileTransfer.Module.IDENTITY).file_incoming.connect((stream, jingle_file_transfer) => { + Conversation? conversation = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(jingle_file_transfer.peer.bare_jid, account); + if (conversation == null) { + // TODO(hrxi): What to do? + return; + } + string id = random_uuid(); + + file_transfers[id] = jingle_file_transfer; + + FileMeta file_meta = new FileMeta(); + file_meta.size = jingle_file_transfer.size; + file_meta.file_name = jingle_file_transfer.file_name; + + var time = new DateTime.now_utc(); + var from = jingle_file_transfer.peer.bare_jid; + + file_incoming(id, from, time, time, conversation, new FileReceiveData(), file_meta); + }); + } +} + +public class JingleFileSender : FileSender, Object { + + private StreamInteractor stream_interactor; + + public JingleFileSender(StreamInteractor stream_interactor) { + this.stream_interactor = stream_interactor; + } + + public bool is_upload_available(Conversation conversation) { + XmppStream? stream = stream_interactor.get_stream(conversation.account); + if (stream == null) return false; + + foreach (Jid full_jid in stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart)) { + if (stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).is_available(stream, full_jid)) { + return true; + } + } + return false; + } + + public bool can_send(Conversation conversation, FileTransfer file_transfer) { + XmppStream? stream = stream_interactor.get_stream(file_transfer.account); + if (stream == null) return false; + + foreach (Jid full_jid in stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart)) { + if (stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).is_available(stream, full_jid)) { + return true; + } + } + return false; + } + + public async FileSendData? prepare_send_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError { + return new FileSendData(); + } + + public async void send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data) throws FileSendError { + // TODO(hrxi) What should happen if `stream == null`? + XmppStream? stream = stream_interactor.get_stream(file_transfer.account); + foreach (Jid full_jid in stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart)) { + // TODO(hrxi): Prioritization of transports (and resources?). + if (!stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).is_available(stream, full_jid)) { + continue; + } + stream.get_module(Xep.JingleFileTransfer.Module.IDENTITY).offer_file_stream.begin(stream, full_jid, file_transfer.input_stream, file_transfer.file_name, file_transfer.size); + return; + } + } + + public int get_id() { return 1; } + + public float get_priority() { return 50; } +} + +} diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 278f3360..e2c929a1 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -111,6 +111,7 @@ SOURCES src/ui/conversation_summary/conversation_item_skeleton.vala src/ui/conversation_summary/conversation_view.vala src/ui/conversation_summary/date_separator_populator.vala + src/ui/conversation_summary/file_widget.vala src/ui/conversation_summary/subscription_notification.vala src/ui/conversation_titlebar/menu_entry.vala src/ui/conversation_titlebar/occupants_entry.vala diff --git a/main/data/theme.css b/main/data/theme.css index 8a1b50ad..d1e41d5b 100644 --- a/main/data/theme.css +++ b/main/data/theme.css @@ -47,6 +47,20 @@ window.dino-main .dino-sidebar > frame { border-bottom: 1px solid @borders; } +.message-box { + transition: background .05s ease; +} + +.file-box-outer { + background: @theme_base_color; + border-radius: 3px; + border: 1px solid alpha(@theme_fg_color, 0.1); +} + +.file-box { + margin: 12px; +} + window.dino-main .dino-sidebar > frame.collapsed { border-bottom: 1px solid @borders; } diff --git a/main/src/ui/conversation_selector/conversation_selector.vala b/main/src/ui/conversation_selector/conversation_selector.vala index 290e297f..66cb3495 100644 --- a/main/src/ui/conversation_selector/conversation_selector.vala +++ b/main/src/ui/conversation_selector/conversation_selector.vala @@ -11,7 +11,6 @@ public class ConversationSelector : ListBox { public signal void conversation_selected(Conversation conversation); private StreamInteractor stream_interactor; - private string[]? filter_values; private HashMap<Conversation, ConversationSelectorRow> rows = new HashMap<Conversation, ConversationSelectorRow>(Conversation.hash_func, Conversation.equals_func); public ConversationSelector init(StreamInteractor stream_interactor) { @@ -19,8 +18,7 @@ public class ConversationSelector : ListBox { stream_interactor.get_module(ConversationManager.IDENTITY).conversation_activated.connect(add_conversation); stream_interactor.get_module(ConversationManager.IDENTITY).conversation_deactivated.connect(remove_conversation); - stream_interactor.get_module(MessageProcessor.IDENTITY).message_received.connect(on_message_received); - stream_interactor.get_module(MessageProcessor.IDENTITY).message_sent.connect(on_message_received); + stream_interactor.get_module(ContentItemStore.IDENTITY).new_item.connect(on_content_item_received); Timeout.add_seconds(60, () => { foreach (ConversationSelectorRow row in rows.values) row.update(); return true; @@ -34,7 +32,6 @@ public class ConversationSelector : ListBox { construct { get_style_context().add_class("sidebar"); - set_filter_func(filter); set_header_func(header); set_sort_func(sort); @@ -54,14 +51,6 @@ public class ConversationSelector : ListBox { } } - public void set_filter_values(string[]? values) { - if (filter_values == values) { - return; - } - filter_values = values; - invalidate_filter(); - } - public void on_conversation_selected(Conversation conversation) { if (!rows.has_key(conversation)) { add_conversation(conversation); @@ -70,7 +59,7 @@ public class ConversationSelector : ListBox { this.select_row(rows[conversation]); } - private void on_message_received(Entities.Message message, Conversation conversation) { + private void on_content_item_received(ContentItem item, Conversation conversation) { if (rows.has_key(conversation)) { invalidate_sort(); } @@ -128,21 +117,6 @@ public class ConversationSelector : ListBox { } } - private bool filter(ListBoxRow r) { - ConversationSelectorRow? row = r as ConversationSelectorRow; - if (row != null) { - if (filter_values != null && filter_values.length != 0) { - foreach (string filter in filter_values) { - if (!(Util.get_conversation_display_name(stream_interactor, row.conversation).down().contains(filter.down()) || - row.conversation.counterpart.to_string().down().contains(filter.down()))) { - return false; - } - } - } - } - return true; - } - private int sort(ListBoxRow row1, ListBoxRow row2) { ConversationSelectorRow cr1 = row1 as ConversationSelectorRow; ConversationSelectorRow cr2 = row2 as ConversationSelectorRow; diff --git a/main/src/ui/conversation_summary/content_item_widget_factory.vala b/main/src/ui/conversation_summary/content_item_widget_factory.vala index 2415eb38..533b2af1 100644 --- a/main/src/ui/conversation_summary/content_item_widget_factory.vala +++ b/main/src/ui/conversation_summary/content_item_widget_factory.vala @@ -108,136 +108,7 @@ public class FileItemWidgetGenerator : WidgetGenerator, Object { FileItem file_item = item as FileItem; FileTransfer transfer = file_item.file_transfer; - if (transfer.mime_type != null) { - foreach (PixbufFormat pixbuf_format in Pixbuf.get_formats()) { - foreach (string mime_type in pixbuf_format.get_mime_types()) { - if (mime_type == transfer.mime_type) - return getImageWidget(transfer); - } - } - } - - return getDefaultWidget(transfer); - } - - private Widget getImageWidget(FileTransfer file_transfer) { - Image image = new Image() { halign=Align.START, visible = true }; - Gdk.Pixbuf pixbuf; - try { - pixbuf = new Gdk.Pixbuf.from_file(file_transfer.get_file().get_path()); - } catch (Error error) { - return null; - } - - pixbuf = pixbuf.apply_embedded_orientation(); - - int max_scaled_height = MAX_HEIGHT * image.scale_factor; - if (pixbuf.height > max_scaled_height) { - pixbuf = pixbuf.scale_simple((int) ((double) max_scaled_height / pixbuf.height * pixbuf.width), max_scaled_height, Gdk.InterpType.BILINEAR); - } - int max_scaled_width = MAX_WIDTH * image.scale_factor; - if (pixbuf.width > max_scaled_width) { - pixbuf = pixbuf.scale_simple(max_scaled_width, (int) ((double) max_scaled_width / pixbuf.width * pixbuf.height), Gdk.InterpType.BILINEAR); - } - pixbuf = crop_corners(pixbuf, 3 * image.get_scale_factor()); - Util.image_set_from_scaled_pixbuf(image, pixbuf); - Util.force_css(image, "* { box-shadow: 0px 0px 2px 0px rgba(0,0,0,0.1); margin: 2px; border-radius: 3px; }"); - - Builder builder = new Builder.from_resource("/im/dino/Dino/conversation_summary/image_toolbar.ui"); - Widget toolbar = builder.get_object("main") as Widget; - Util.force_background(toolbar, "rgba(0, 0, 0, 0.5)"); - Util.force_css(toolbar, "* { padding: 3px; border-radius: 3px; }"); - - Label url_label = builder.get_object("url_label") as Label; - Util.force_color(url_label, "#eee"); - - if (file_transfer.file_name != null && file_transfer.file_name != "") { - string caption = file_transfer.file_name; - url_label.label = caption; - } else { - url_label.visible = false; - } - - Image open_image = builder.get_object("open_image") as Image; - Util.force_css(open_image, "*:not(:hover) { color: #eee; }"); - Button open_button = builder.get_object("open_button") as Button; - Util.force_css(open_button, "*:hover { background-color: rgba(255,255,255,0.3); border-color: transparent; }"); - open_button.clicked.connect(() => { - try{ - AppInfo.launch_default_for_uri(file_transfer.get_file().get_uri(), null); - } catch (Error err) { - info("Could not to open file://%s: %s", file_transfer.get_file().get_path(), err.message); - } - }); - - Revealer toolbar_revealer = new Revealer() { transition_type=RevealerTransitionType.CROSSFADE, transition_duration=400, visible=true }; - toolbar_revealer.add(toolbar); - - Grid grid = new Grid() { visible=true }; - grid.attach(toolbar_revealer, 0, 0, 1, 1); - grid.attach(image, 0, 0, 1, 1); - - EventBox event_box = new EventBox() { halign=Align.START, visible=true }; - event_box.events = EventMask.POINTER_MOTION_MASK; - event_box.add(grid); - event_box.enter_notify_event.connect(() => { toolbar_revealer.reveal_child = true; return false; }); - event_box.leave_notify_event.connect(() => { toolbar_revealer.reveal_child = false; return false; }); - - return event_box; - } - - private static Gdk.Pixbuf crop_corners(Gdk.Pixbuf pixbuf, double radius = 3) { - Cairo.Context ctx = new Cairo.Context(new Cairo.ImageSurface(Cairo.Format.ARGB32, pixbuf.width, pixbuf.height)); - Gdk.cairo_set_source_pixbuf(ctx, pixbuf, 0, 0); - double degrees = Math.PI / 180.0; - ctx.new_sub_path(); - ctx.arc(pixbuf.width - radius, radius, radius, -90 * degrees, 0 * degrees); - ctx.arc(pixbuf.width - radius, pixbuf.height - radius, radius, 0 * degrees, 90 * degrees); - ctx.arc(radius, pixbuf.height - radius, radius, 90 * degrees, 180 * degrees); - ctx.arc(radius, radius, radius, 180 * degrees, 270 * degrees); - ctx.close_path(); - ctx.clip(); - ctx.paint(); - return Gdk.pixbuf_get_from_surface(ctx.get_target(), 0, 0, pixbuf.width, pixbuf.height); - } - - private Widget getDefaultWidget(FileTransfer file_transfer) { - Box main_box = new Box(Orientation.HORIZONTAL, 4) { halign=Align.START, visible=true }; - string? icon_name = file_transfer.mime_type != null ? ContentType.get_generic_icon_name(file_transfer.mime_type) : null; - Image content_type_image = new Image.from_icon_name(icon_name, IconSize.DND) { visible=true }; - main_box.add(content_type_image); - - Box right_box = new Box(Orientation.VERTICAL, 0) { visible=true }; - Label name_label = new Label(file_transfer.file_name) { ellipsize=EllipsizeMode.END, xalign=0, yalign=0, visible=true}; - right_box.add(name_label); - Label mime_label = new Label("<span size='small'>" + _("File") + ": " + file_transfer.mime_type + "</span>") { use_markup=true, xalign=0, yalign=1, visible=true}; - mime_label.get_style_context().add_class("dim-label"); - right_box.add(mime_label); - main_box.add(right_box); - - EventBox event_box = new EventBox() { halign=Align.START, visible=true }; - event_box.add(main_box); - - event_box.enter_notify_event.connect((event) => { - event.get_window().set_cursor(new Cursor.for_display(Gdk.Display.get_default(), CursorType.HAND2)); - return false; - }); - event_box.leave_notify_event.connect((event) => { - event.get_window().set_cursor(new Cursor.for_display(Gdk.Display.get_default(), CursorType.XTERM)); - return false; - }); - event_box.button_release_event.connect((event_button) => { - if (event_button.button == 1) { - try{ - AppInfo.launch_default_for_uri(file_transfer.get_file().get_uri(), null); - } catch (Error err) { - print("Tried to open " + file_transfer.get_file().get_path()); - } - } - return false; - }); - - return event_box; + return new FileWidget(stream_interactor, transfer) { visible=true }; } } diff --git a/main/src/ui/conversation_summary/file_widget.vala b/main/src/ui/conversation_summary/file_widget.vala new file mode 100644 index 00000000..19b89906 --- /dev/null +++ b/main/src/ui/conversation_summary/file_widget.vala @@ -0,0 +1,309 @@ +using Gee; +using Gdk; +using Gtk; +using Pango; + +using Dino.Entities; + +namespace Dino.Ui.ConversationSummary { + +public class FileWidget : Box { + + enum State { + IMAGE, + DEFAULT + } + + private const int MAX_HEIGHT = 300; + private const int MAX_WIDTH = 600; + + private StreamInteractor stream_interactor; + private FileTransfer file_transfer; + private State state; + + // default box + private Box main_box; + private string? icon_name; + private Image content_type_image; + private Image download_image; + private Spinner spinner; + private Label mime_label; + private Stack image_stack; + + private Widget content; + + private bool pointer_inside = false; + + public FileWidget(StreamInteractor stream_interactor, FileTransfer file_transfer) { + this.stream_interactor = stream_interactor; + this.file_transfer = file_transfer; + + if (show_image()) { + content = getImageWidget(file_transfer); + if (content != null) { + this.state = State.IMAGE; + this.add(content); + return; + } + } + + content = getDefaultWidget(file_transfer); + this.state = State.DEFAULT; + this.add(content); + } + + private Widget? getImageWidget(FileTransfer file_transfer) { + Image image = new Image() { halign=Align.START, visible = true }; + Gdk.Pixbuf pixbuf; + try { + pixbuf = new Gdk.Pixbuf.from_file(file_transfer.get_file().get_path()); + } catch (Error error) { + warning("Can't load picture %s", file_transfer.get_file().get_path()); + return null; + } + + pixbuf = pixbuf.apply_embedded_orientation(); + + int max_scaled_height = MAX_HEIGHT * image.scale_factor; + if (pixbuf.height > max_scaled_height) { + pixbuf = pixbuf.scale_simple((int) ((double) max_scaled_height / pixbuf.height * pixbuf.width), max_scaled_height, Gdk.InterpType.BILINEAR); + } + int max_scaled_width = MAX_WIDTH * image.scale_factor; + if (pixbuf.width > max_scaled_width) { + pixbuf = pixbuf.scale_simple(max_scaled_width, (int) ((double) max_scaled_width / pixbuf.width * pixbuf.height), Gdk.InterpType.BILINEAR); + } + pixbuf = crop_corners(pixbuf, 3 * image.get_scale_factor()); + Util.image_set_from_scaled_pixbuf(image, pixbuf); + Util.force_css(image, "* { box-shadow: 0px 0px 2px 0px rgba(0,0,0,0.1); margin: 2px; border-radius: 3px; }"); + + Builder builder = new Builder.from_resource("/im/dino/Dino/conversation_summary/image_toolbar.ui"); + Widget toolbar = builder.get_object("main") as Widget; + Util.force_background(toolbar, "rgba(0, 0, 0, 0.5)"); + Util.force_css(toolbar, "* { padding: 3px; border-radius: 3px; }"); + + Label url_label = builder.get_object("url_label") as Label; + Util.force_color(url_label, "#eee"); + + if (file_transfer.file_name != null && file_transfer.file_name != "") { + string caption = file_transfer.file_name; + url_label.label = caption; + } else { + url_label.visible = false; + } + + Image open_image = builder.get_object("open_image") as Image; + Util.force_css(open_image, "*:not(:hover) { color: #eee; }"); + Button open_button = builder.get_object("open_button") as Button; + Util.force_css(open_button, "*:hover { background-color: rgba(255,255,255,0.3); border-color: transparent; }"); + open_button.clicked.connect(() => { + try{ + AppInfo.launch_default_for_uri(file_transfer.get_file().get_uri(), null); + } catch (Error err) { + info("Could not to open file://%s: %s", file_transfer.get_file().get_path(), err.message); + } + }); + + Revealer toolbar_revealer = new Revealer() { transition_type=RevealerTransitionType.CROSSFADE, transition_duration=400, visible=true }; + toolbar_revealer.add(toolbar); + + Grid grid = new Grid() { visible=true }; + grid.attach(toolbar_revealer, 0, 0, 1, 1); + grid.attach(image, 0, 0, 1, 1); + + EventBox event_box = new EventBox() { margin_top=5, halign=Align.START, visible=true }; + event_box.events = EventMask.POINTER_MOTION_MASK; + event_box.add(grid); + event_box.enter_notify_event.connect(() => { toolbar_revealer.reveal_child = true; return false; }); + event_box.leave_notify_event.connect(() => { toolbar_revealer.reveal_child = false; return false; }); + + return event_box; + } + + private static Gdk.Pixbuf crop_corners(Gdk.Pixbuf pixbuf, double radius = 3) { + Cairo.Context ctx = new Cairo.Context(new Cairo.ImageSurface(Cairo.Format.ARGB32, pixbuf.width, pixbuf.height)); + Gdk.cairo_set_source_pixbuf(ctx, pixbuf, 0, 0); + double degrees = Math.PI / 180.0; + ctx.new_sub_path(); + ctx.arc(pixbuf.width - radius, radius, radius, -90 * degrees, 0 * degrees); + ctx.arc(pixbuf.width - radius, pixbuf.height - radius, radius, 0 * degrees, 90 * degrees); + ctx.arc(radius, pixbuf.height - radius, radius, 90 * degrees, 180 * degrees); + ctx.arc(radius, radius, radius, 180 * degrees, 270 * degrees); + ctx.close_path(); + ctx.clip(); + ctx.paint(); + return Gdk.pixbuf_get_from_surface(ctx.get_target(), 0, 0, pixbuf.width, pixbuf.height); + } + + private Widget getDefaultWidget(FileTransfer file_transfer) { + main_box = new Box(Orientation.HORIZONTAL, 4) { halign=Align.FILL, hexpand=true, visible=true }; + icon_name = ContentType.get_generic_icon_name(file_transfer.mime_type ?? "application/octet-stream"); + content_type_image = new Image.from_icon_name(icon_name + "-symbolic", IconSize.DND) { visible=true }; + download_image = new Image.from_icon_name("folder-download-symbolic", IconSize.MENU) { visible=true }; + spinner = new Spinner() { active=true, visible=true }; + + EventBox stack_event_box = new EventBox() { visible=true }; + image_stack = new Stack() { transition_type = StackTransitionType.CROSSFADE, transition_duration=50, valign=Align.CENTER, visible=true }; + image_stack.add_named(download_image, "download_image"); + image_stack.add_named(spinner, "spinner"); + image_stack.add_named(content_type_image, "content_type_image"); + stack_event_box.add(image_stack); + + main_box.add(stack_event_box); + + Box right_box = new Box(Orientation.VERTICAL, 0) { hexpand=true, visible=true }; + Label name_label = new Label(file_transfer.file_name) { ellipsize=EllipsizeMode.MIDDLE, max_width_chars=1, hexpand=true, xalign=0, yalign=0, visible=true}; + right_box.add(name_label); + + EventBox mime_label_event_box = new EventBox() { visible=true }; + mime_label = new Label("") { use_markup=true, xalign=0, yalign=1, visible=true}; + + mime_label_event_box.add(mime_label); + mime_label.get_style_context().add_class("dim-label"); + + right_box.add(mime_label_event_box); + main_box.add(right_box); + + EventBox event_box = new EventBox() { margin_top=5, width_request=500, halign=Align.START, visible=true }; + event_box.get_style_context().add_class("file-box-outer"); + event_box.add(main_box); + main_box.get_style_context().add_class("file-box"); + + event_box.enter_notify_event.connect((event) => { + pointer_inside = true; + Timeout.add(20, () => { + if (pointer_inside) { + event.get_window().set_cursor(new Cursor.for_display(Gdk.Display.get_default(), CursorType.HAND2)); + if (file_transfer.state == FileTransfer.State.NOT_STARTED) { + image_stack.set_visible_child_name("download_image"); + } else if (file_transfer.state == FileTransfer.State.COMPLETE) { + content_type_image.opacity = 1; + } + } + return false; + }); + return false; + }); + stack_event_box.enter_notify_event.connect((event) => { pointer_inside = true; return false; }); + mime_label_event_box.enter_notify_event.connect((event) => { pointer_inside = true; return false; }); + mime_label.enter_notify_event.connect((event) => { pointer_inside = true; return false; }); + event_box.leave_notify_event.connect((event) => { + pointer_inside = false; + Timeout.add(20, () => { + if (!pointer_inside) { + event.get_window().set_cursor(new Cursor.for_display(Gdk.Display.get_default(), CursorType.XTERM)); + if (file_transfer.state == FileTransfer.State.NOT_STARTED) { + image_stack.set_visible_child_name("content_type_image"); + } else if (file_transfer.state == FileTransfer.State.COMPLETE) { + content_type_image.opacity = 0.5; + } + } + return false; + }); + return false; + }); + stack_event_box.leave_notify_event.connect((event) => { pointer_inside = true; return false; }); + mime_label_event_box.leave_notify_event.connect((event) => { pointer_inside = true; return false; }); + mime_label.leave_notify_event.connect((event) => { pointer_inside = true; return false; }); + event_box.button_release_event.connect((event_button) => { + switch (file_transfer.state) { + case FileTransfer.State.COMPLETE: + if (event_button.button == 1) { + try{ + AppInfo.launch_default_for_uri(file_transfer.get_file().get_uri(), null); + } catch (Error err) { + print("Tried to open " + file_transfer.get_file().get_path()); + } + } + break; + case FileTransfer.State.NOT_STARTED: + stream_interactor.get_module(FileManager.IDENTITY).download_file.begin(file_transfer); + break; + } + return false; + }); + + main_box.events = EventMask.POINTER_MOTION_MASK; + content_type_image.events = EventMask.POINTER_MOTION_MASK; + download_image.events = EventMask.POINTER_MOTION_MASK; + spinner.events = EventMask.POINTER_MOTION_MASK; + image_stack.events = EventMask.POINTER_MOTION_MASK; + right_box.events = EventMask.POINTER_MOTION_MASK; + name_label.events = EventMask.POINTER_MOTION_MASK; + mime_label.events = EventMask.POINTER_MOTION_MASK; + event_box.events = EventMask.POINTER_MOTION_MASK; + mime_label.events = EventMask.POINTER_MOTION_MASK; + mime_label_event_box.events = EventMask.POINTER_MOTION_MASK; + + file_transfer.notify["path"].connect(update_file_info); + file_transfer.notify["state"].connect(update_file_info); + file_transfer.notify["mime-type"].connect(update_file_info); + update_file_info(); + + return event_box; + } + + private void update_file_info() { + if (file_transfer.state == FileTransfer.State.COMPLETE && show_image() && state != State.IMAGE) { + this.remove(content); + this.add(getImageWidget(file_transfer)); + state = State.IMAGE; + } + + content_type_image.opacity = 0.5; + + var mime_split = (file_transfer.mime_type ?? "").split("/"); + var mime_caps = mime_split.length == 2 ? mime_split[1].up() : file_transfer.mime_type; + + switch (file_transfer.state) { + case FileTransfer.State.COMPLETE: + mime_label.label = "<span size='small'>" + _("%s file").printf(mime_caps) + "</span>"; + image_stack.set_visible_child_name("content_type_image"); + break; + case FileTransfer.State.IN_PROGRESS: + mime_label.label = "<span size='small'>" + _("Downloading %s…").printf(get_size_string(file_transfer.size)) + "</span>"; + image_stack.set_visible_child_name("spinner"); + break; + case FileTransfer.State.NOT_STARTED: + if (mime_caps != null) { + mime_label.label = "<span size='small'>" + _("%s file offered: %s").printf(mime_caps, get_size_string(file_transfer.size)) + "</span>"; + } else if (file_transfer.size != -1) { + mime_label.label = "<span size='small'>" + _("File offered: %s").printf(get_size_string(file_transfer.size)) + "</span>"; + } else { + mime_label.label = "<span size='small'>" + _("File offered") + "</span>"; + } + image_stack.set_visible_child_name("content_type_image"); + break; + case FileTransfer.State.FAILED: + mime_label.label = "<span size='small' foreground=\"#f44336\">" + _("File transfer failed") + "</span>"; + image_stack.set_visible_child_name("content_type_image"); + break; + } + } + + private static string get_size_string(int size) { + if (size < 1024) { + return @"$(size) B"; + } else if (size < 1000 * 1000) { + return @"$(size / 1000) kB"; + } else if (size < 1000 * 1000 * 1000) { + return @"$(size / 1000 / 1000) MB"; + } else { + return @"$(size / 1000 / 1000 / 1000) GB"; + } + } + + private bool show_image() { + if (file_transfer.mime_type == null || file_transfer.state != FileTransfer.State.COMPLETE) return false; + + foreach (PixbufFormat pixbuf_format in Pixbuf.get_formats()) { + foreach (string mime_type in pixbuf_format.get_mime_types()) { + if (mime_type == file_transfer.mime_type) { + return true; + } + } + } + return false; + } +} + +} diff --git a/plugins/http-files/CMakeLists.txt b/plugins/http-files/CMakeLists.txt index 93ccbf67..625c215f 100644 --- a/plugins/http-files/CMakeLists.txt +++ b/plugins/http-files/CMakeLists.txt @@ -10,7 +10,8 @@ find_packages(HTTP_FILES_PACKAGES REQUIRED vala_precompile(HTTP_FILES_VALA_C SOURCES src/file_provider.vala - src/manager.vala + src/file_sender.vala + src/message_filter.vala src/plugin.vala src/register_plugin.vala CUSTOM_VAPIS diff --git a/plugins/http-files/src/file_provider.vala b/plugins/http-files/src/file_provider.vala index b7d18e36..38687863 100644 --- a/plugins/http-files/src/file_provider.vala +++ b/plugins/http-files/src/file_provider.vala @@ -7,16 +7,15 @@ using Xmpp; namespace Dino.Plugins.HttpFiles { public class FileProvider : Dino.FileProvider, Object { - public string id { get { return "http"; } } private StreamInteractor stream_interactor; private Dino.Database dino_db; - private Regex url_regex; + private Regex url_regex = /^(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))$/; + private Regex omemo_url_regex = /^aesgcm:\/\/(.*)#(([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44})$/; public FileProvider(StreamInteractor stream_interactor, Dino.Database dino_db) { this.stream_interactor = stream_interactor; this.dino_db = dino_db; - this.url_regex = /^(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))$/; stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(new ReceivedMessageListener(this)); } @@ -38,7 +37,11 @@ public class FileProvider : Dino.FileProvider, Object { public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { if (outer.url_regex.match(message.body)) { string? oob_url = Xmpp.Xep.OutOfBandData.get_url_from_message(stanza); - if (oob_url != null && oob_url == message.body) { + + bool normal_file = oob_url != null && oob_url == message.body; + bool omemo_file = outer.omemo_url_regex.match(message.body); + + if (normal_file || omemo_file) { yield outer.on_file_message(message, conversation); } } @@ -47,83 +50,102 @@ public class FileProvider : Dino.FileProvider, Object { } private async void on_file_message(Entities.Message message, Conversation conversation) { - FileTransfer file_transfer = new FileTransfer(); - file_transfer.account = conversation.account; - file_transfer.counterpart = message.counterpart; - file_transfer.ourpart = message.ourpart; - file_transfer.encryption = Encryption.NONE; - file_transfer.time = message.time; - file_transfer.local_time = message.local_time; - file_transfer.direction = message.direction; - file_transfer.file_name = message.body.substring(message.body.last_index_of("/") + 1); - file_transfer.size = -1; - file_transfer.state = FileTransfer.State.NOT_STARTED; - file_transfer.provider = 0; - file_transfer.info = message.id.to_string(); - - if (stream_interactor.get_module(FileManager.IDENTITY).is_sender_trustworthy(file_transfer, conversation)) { - yield get_meta_info(file_transfer); - if (file_transfer.size >= 0 && file_transfer.size < 5000000) { - ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, message.id); - if (content_item != null) { - stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); - } - } - file_incoming(file_transfer, conversation); + // Hide message + ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, message.id); + if (content_item != null) { + stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); } + + var additional_info = message.id.to_string(); + + var receive_data = new HttpFileReceiveData(); + receive_data.url = message.body; + + var file_meta = new HttpFileMeta(); + file_meta.file_name = Uri.unescape_string(message.body.substring(message.body.last_index_of("/") + 1)); + file_meta.message = message; + + file_incoming(additional_info, message.from, message.time, message.local_time, conversation, receive_data, file_meta); } - public async void get_meta_info(FileTransfer file_transfer) { - string url_body = dino_db.message.select({dino_db.message.body}).with(dino_db.message.id, "=", int.parse(file_transfer.info))[dino_db.message.body]; + public async FileMeta get_meta_info(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError { + HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData; + if (http_receive_data == null) return file_meta; + var session = new Soup.Session(); - var head_message = new Soup.Message("HEAD", url_body); + var head_message = new Soup.Message("HEAD", http_receive_data.url); + if (head_message != null) { - yield session.send_async(head_message, null); + try { + yield session.send_async(head_message, null); + } catch (Error e) { + throw new FileReceiveError.GET_METADATA_FAILED("HEAD request failed"); + } string? content_type = null, content_length = null; - print(url_body + ":\n"); head_message.response_headers.foreach((name, val) => { - print(name + " " + val + "\n"); if (name == "Content-Type") content_type = val; if (name == "Content-Length") content_length = val; }); - file_transfer.mime_type = content_type; + file_meta.mime_type = content_type; if (content_length != null) { - file_transfer.size = int.parse(content_length); + file_meta.size = int.parse(content_length); } } + + return file_meta; } - public async void download(FileTransfer file_transfer, File file_) { + public async InputStream download(FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) throws FileReceiveError { + HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData; + if (http_receive_data == null) assert(false); + try { - File file = file_; - string url_body = dino_db.message.select({dino_db.message.body}).with(dino_db.message.id, "=", int.parse(file_transfer.info))[dino_db.message.body]; var session = new Soup.Session(); - Soup.Request request = session.request(url_body); + Soup.Request request = session.request(http_receive_data.url); - file_transfer.input_stream = yield request.send_async(null); + return yield request.send_async(null); + } catch (Error e) { + throw new FileReceiveError.DOWNLOAD_FAILED("Downloading file error: %s".printf(e.message)); + } + } - foreach (IncomingFileProcessor processor in stream_interactor.get_module(FileManager.IDENTITY).incoming_processors) { - if (processor.can_process(file_transfer)) { - processor.process(file_transfer); - } - } + public FileMeta get_file_meta(FileTransfer file_transfer) throws FileReceiveError { + Conversation? conversation = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(file_transfer.counterpart.bare_jid, file_transfer.account); + if (conversation == null) throw new FileReceiveError.GET_METADATA_FAILED("No conversation"); - if (file_transfer.encryption == Encryption.PGP || file.get_path().has_suffix(".pgp")) { - file = File.new_for_path(file.get_path().substring(0, file.get_path().length - 4)); - } + Message? message = stream_interactor.get_module(MessageStorage.IDENTITY).get_message_by_id(int.parse(file_transfer.info), conversation); + if (message == null) throw new FileReceiveError.GET_METADATA_FAILED("No message"); - OutputStream os = file.create(FileCreateFlags.REPLACE_DESTINATION); - yield os.splice_async(file_transfer.input_stream, 0); - os.close(); - file_transfer.path = file.get_basename(); - file_transfer.input_stream = yield file.read_async(); + var file_meta = new HttpFileMeta(); + file_meta.size = file_transfer.size; + file_meta.mime_type = file_transfer.mime_type; - file_transfer.state = FileTransfer.State.COMPLETE; - } catch (Error e) { - file_transfer.state = FileTransfer.State.FAILED; + // Extract file name from URL + file_meta.file_name = Uri.unescape_string(message.body.substring(message.body.last_index_of("/") + 1)); + if (file_meta.file_name.contains("#")) { + file_meta.file_name = file_meta.file_name.substring(0, file_meta.file_name.last_index_of("#")); } + + file_meta.message = message; + + return file_meta; } + + public FileReceiveData? get_file_receive_data(FileTransfer file_transfer) { + Conversation? conversation = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(file_transfer.counterpart.bare_jid, file_transfer.account); + if (conversation == null) return null; + + Message? message = stream_interactor.get_module(MessageStorage.IDENTITY).get_message_by_id(int.parse(file_transfer.info), conversation); + if (message == null) return null; + + var receive_data = new HttpFileReceiveData(); + receive_data.url = message.body; + + return receive_data; + } + + public int get_id() { return 0; } } } diff --git a/plugins/http-files/src/file_sender.vala b/plugins/http-files/src/file_sender.vala new file mode 100644 index 00000000..ce40d2f8 --- /dev/null +++ b/plugins/http-files/src/file_sender.vala @@ -0,0 +1,126 @@ +using Dino.Entities; +using Xmpp; +using Gee; + +namespace Dino.Plugins.HttpFiles { + +public class HttpFileSender : FileSender, Object { + private StreamInteractor stream_interactor; + private Database db; + private HashMap<Account, long> max_file_sizes = new HashMap<Account, long>(Account.hash_func, Account.equals_func); + + public HttpFileSender(StreamInteractor stream_interactor, Database db) { + this.stream_interactor = stream_interactor; + this.db = db; + + stream_interactor.stream_negotiated.connect(on_stream_negotiated); + stream_interactor.get_module(MessageProcessor.IDENTITY).build_message_stanza.connect(check_add_oob); + } + + public async FileSendData? prepare_send_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError { + HttpFileSendData send_data = new HttpFileSendData(); + if (send_data == null) return null; + + Xmpp.XmppStream? stream = stream_interactor.get_stream(file_transfer.account); + if (stream == null) return null; + + try { + var slot_result = yield stream_interactor.module_manager.get_module(file_transfer.account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).request_slot(stream, file_transfer.server_file_name, file_transfer.size, file_transfer.mime_type); + send_data.url_down = slot_result.url_get; + send_data.url_up = slot_result.url_put; + } catch (Xep.HttpFileUpload.HttpFileTransferError e) { + throw new FileSendError.UPLOAD_FAILED("Http file upload XMPP error: %s".printf(e.message)); + } + + return send_data; + } + + public async void send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data) throws FileSendError { + HttpFileSendData? send_data = file_send_data as HttpFileSendData; + if (send_data == null) return; + + yield upload(file_transfer, send_data); + + file_transfer.info = send_data.url_down; // store the message content temporarily so the message gets filtered out + + Entities.Message message = stream_interactor.get_module(MessageProcessor.IDENTITY).create_out_message(send_data.url_down, conversation); + + message.encryption = send_data.encrypt_message ? conversation.encryption : Encryption.NONE; + stream_interactor.get_module(MessageProcessor.IDENTITY).send_message(message, conversation); + + file_transfer.info = message.id.to_string(); + + ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, message.id); + if (content_item != null) { + stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); + } + } + + public bool can_send(Conversation conversation, FileTransfer file_transfer) { + if (!max_file_sizes.has_key(conversation.account)) return false; + + return file_transfer.size < max_file_sizes[conversation.account]; + } + + public bool is_upload_available(Conversation conversation) { + lock (max_file_sizes) { + return max_file_sizes.has_key(conversation.account); + } + } + + public long get_max_file_size(Account account) { + lock (max_file_sizes) { + return max_file_sizes[account]; + } + } + + private async void upload(FileTransfer file_transfer, HttpFileSendData file_send_data) throws FileSendError { + Xmpp.XmppStream? stream = stream_interactor.get_stream(file_transfer.account); + if (stream == null) return; + + uint8[] buf = new uint8[256]; + Array<uint8> data = new Array<uint8>(false, true, 0); + size_t len = -1; + do { + try { + len = file_transfer.input_stream.read(buf); + } catch (IOError e) { + throw new FileSendError.UPLOAD_FAILED("HTTP upload: IOError reading stream: %s".printf(e.message)); + } + data.append_vals(buf, (uint) len); + } while(len > 0); + + Soup.Message message = new Soup.Message("PUT", file_send_data.url_up); + message.set_request(file_transfer.mime_type, Soup.MemoryUse.COPY, data.data); + Soup.Session session = new Soup.Session(); + try { + yield session.send_async(message); + if (message.status_code < 200 && message.status_code >= 300) { + throw new FileSendError.UPLOAD_FAILED("HTTP status code %s".printf(message.status_code.to_string())); + } + } catch (Error e) { + throw new FileSendError.UPLOAD_FAILED("HTTP upload error: %s".printf(e.message)); + } + } + + private void on_stream_negotiated(Account account, XmppStream stream) { + stream_interactor.module_manager.get_module(account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).feature_available.connect((stream, max_file_size) => { + lock (max_file_sizes) { + max_file_sizes[account] = max_file_size; + } + upload_available(account); + }); + } + + private void check_add_oob(Entities.Message message, Xmpp.MessageStanza message_stanza, Conversation conversation) { + if (message.encryption == Encryption.NONE && message_is_file(db, message) && message.body.has_prefix("http")) { + Xep.OutOfBandData.add_url_to_message(message_stanza, message_stanza.body); + } + } + + public int get_id() { return 0; } + + public float get_priority() { return 100; } +} + +} diff --git a/plugins/http-files/src/manager.vala b/plugins/http-files/src/manager.vala deleted file mode 100644 index 2f702be3..00000000 --- a/plugins/http-files/src/manager.vala +++ /dev/null @@ -1,147 +0,0 @@ -using Dino.Entities; -using Xmpp; -using Gee; - -namespace Dino.Plugins.HttpFiles { - -public class Manager : StreamInteractionModule, FileSender, Object { - public static ModuleIdentity<Manager> IDENTITY = new ModuleIdentity<Manager>("http_files"); - public string id { get { return IDENTITY.id; } } - - public signal void uploading(FileTransfer file_transfer); - public signal void uploaded(FileTransfer file_transfer, string url); - - private StreamInteractor stream_interactor; - private Database db; - private HashMap<Account, long> max_file_sizes = new HashMap<Account, long>(Account.hash_func, Account.equals_func); - - public static void start(StreamInteractor stream_interactor, Database db) { - Manager m = new Manager(stream_interactor, db); - stream_interactor.add_module(m); - } - - private Manager(StreamInteractor stream_interactor, Database db) { - this.stream_interactor = stream_interactor; - this.db = db; - - stream_interactor.get_module(FileManager.IDENTITY).add_sender(this); - stream_interactor.stream_negotiated.connect(on_stream_negotiated); - stream_interactor.get_module(MessageProcessor.IDENTITY).build_message_stanza.connect(check_add_oob); - } - - public delegate void OnUploadOk(XmppStream stream, string url_down); - public delegate void OnError(XmppStream stream, string error); - public void upload(XmppStream stream, FileTransfer file_transfer, owned OnUploadOk listener, owned OnError error_listener) { - uint8[] buf = new uint8[256]; - Array<uint8> data = new Array<uint8>(false, true, 0); - size_t len = -1; - do { - try { - len = file_transfer.input_stream.read(buf); - } catch (IOError error) { - error_listener(stream, @"HTTP upload: IOError reading stream: $(error.message)"); - } - data.append_vals(buf, (uint) len); - } while(len > 0); - - stream_interactor.module_manager.get_module(file_transfer.account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).request_slot(stream, file_transfer.server_file_name, (int) data.length, file_transfer.mime_type, - (stream, url_down, url_up) => { - Soup.Message message = new Soup.Message("PUT", url_up); - message.set_request(file_transfer.mime_type, Soup.MemoryUse.COPY, data.data); - Soup.Session session = new Soup.Session(); - session.send_async.begin(message, null, (obj, res) => { - try { - session.send_async.end(res); - if (message.status_code >= 200 && message.status_code < 300) { - listener(stream, url_down); - } else { - error_listener(stream, "HTTP status code " + message.status_code.to_string()); - } - } catch (Error e) { - error_listener(stream, e.message); - } - }); - }, - (stream, error) => error_listener(stream, error)); - } - - public void send_file(Conversation conversation, FileTransfer file_transfer) { - Xmpp.XmppStream? stream = stream_interactor.get_stream(file_transfer.account); - if (stream != null) { - upload(stream, file_transfer, - (stream, url_down) => { - uploaded(file_transfer, url_down); - file_transfer.info = url_down; // store the message content temporarily so the message gets filtered out - Entities.Message message = stream_interactor.get_module(MessageProcessor.IDENTITY).create_out_message(url_down, conversation); - message.encryption = Encryption.NONE; - stream_interactor.get_module(MessageProcessor.IDENTITY).send_message(message, conversation); - file_transfer.info = message.id.to_string(); - - ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, message.id); - if (content_item != null) { - stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); - } - }, - (stream, error_str) => { - warning("Failed getting upload url: %s", error_str); - file_transfer.state = FileTransfer.State.FAILED; - } - ); - } - } - - public bool can_send(Conversation conversation, FileTransfer file_transfer) { - return file_transfer.encryption != Encryption.OMEMO; - } - - public bool is_upload_available(Conversation conversation) { - lock (max_file_sizes) { - return max_file_sizes.has_key(conversation.account); - } - } - - public long get_max_file_size(Account account) { - lock (max_file_sizes) { - return max_file_sizes[account]; - } - } - - private void on_stream_negotiated(Account account, XmppStream stream) { - stream_interactor.module_manager.get_module(account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).feature_available.connect((stream, max_file_size) => { - lock (max_file_sizes) { - max_file_sizes[account] = max_file_size; - } - upload_available(account); - }); - } - - private void check_add_oob(Entities.Message message, Xmpp.MessageStanza message_stanza, Conversation conversation) { - if (message_is_file(db, message) && message.body.has_prefix("http")) { - Xep.OutOfBandData.add_url_to_message(message_stanza, message_stanza.body); - } - } -} - -public class FileMessageFilter : ContentFilter, Object { - public Database db; - - public FileMessageFilter(Dino.Database db) { - this.db = db; - } - - public bool discard(ContentItem content_item) { - if (content_item.type_ == MessageItem.TYPE) { - MessageItem message_item = content_item as MessageItem; - return message_is_file(db, message_item.message); - } - return false; - } -} - -private bool message_is_file(Database db, Entities.Message message) { - Qlite.QueryBuilder builder = db.file_transfer.select({db.file_transfer.id}).with(db.file_transfer.info, "=", message.id.to_string()); - Qlite.QueryBuilder builder2 = db.file_transfer.select({db.file_transfer.id}).with(db.file_transfer.info, "=", message.body); - return builder.count() > 0 || builder2.count() > 0; -} - -} diff --git a/plugins/http-files/src/message_filter.vala b/plugins/http-files/src/message_filter.vala new file mode 100644 index 00000000..01035c4c --- /dev/null +++ b/plugins/http-files/src/message_filter.vala @@ -0,0 +1,23 @@ +using Dino.Entities; +using Xmpp; +using Gee; + +namespace Dino.Plugins.HttpFiles { + +public class FileMessageFilter : ContentFilter, Object { + public Database db; + + public FileMessageFilter(Dino.Database db) { + this.db = db; + } + + public bool discard(ContentItem content_item) { + if (content_item.type_ == MessageItem.TYPE) { + MessageItem message_item = content_item as MessageItem; + return message_is_file(db, message_item.message); + } + return false; + } +} + +} diff --git a/plugins/http-files/src/plugin.vala b/plugins/http-files/src/plugin.vala index e2ce5ad9..bdf48770 100644 --- a/plugins/http-files/src/plugin.vala +++ b/plugins/http-files/src/plugin.vala @@ -7,14 +7,17 @@ public class Plugin : RootInterface, Object { public Dino.Application app; public FileProvider file_provider; + public FileSender file_sender; public void registered(Dino.Application app) { this.app = app; - Manager.start(this.app.stream_interactor, app.db); file_provider = new FileProvider(app.stream_interactor, app.db); + file_sender = new HttpFileSender(app.stream_interactor, app.db); app.stream_interactor.get_module(FileManager.IDENTITY).add_provider(file_provider); + app.stream_interactor.get_module(FileManager.IDENTITY).add_sender(file_sender); + app.stream_interactor.get_module(ContentItemStore.IDENTITY).add_filter(new FileMessageFilter(app.db)); } @@ -23,4 +26,10 @@ public class Plugin : RootInterface, Object { } } +private bool message_is_file(Database db, Entities.Message message) { + Qlite.QueryBuilder builder = db.file_transfer.select({db.file_transfer.id}).with(db.file_transfer.info, "=", message.id.to_string()); + Qlite.QueryBuilder builder2 = db.file_transfer.select({db.file_transfer.id}).with(db.file_transfer.info, "=", message.body); + return builder.count() > 0 || builder2.count() > 0; +} + } diff --git a/plugins/omemo/CMakeLists.txt b/plugins/omemo/CMakeLists.txt index 8639478c..482b49fa 100644 --- a/plugins/omemo/CMakeLists.txt +++ b/plugins/omemo/CMakeLists.txt @@ -34,8 +34,8 @@ SOURCES src/register_plugin.vala src/trust_level.vala - src/file_transfer/file_provider.vala - src/file_transfer/file_sender.vala + src/file_transfer/file_decryptor.vala + src/file_transfer/file_encryptor.vala src/logic/database.vala src/logic/encrypt_state.vala diff --git a/plugins/omemo/src/file_transfer/file_decryptor.vala b/plugins/omemo/src/file_transfer/file_decryptor.vala new file mode 100644 index 00000000..dcb65301 --- /dev/null +++ b/plugins/omemo/src/file_transfer/file_decryptor.vala @@ -0,0 +1,89 @@ +using Dino.Entities; + +using Signal; + +namespace Dino.Plugins.Omemo { + +public class OmemoHttpFileReceiveData : HttpFileReceiveData { + public string original_url; +} + +public class OmemoFileDecryptor : FileDecryptor, Object { + + private Regex url_regex = /^aesgcm:\/\/(.*)#(([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44})$/; + + public FileReceiveData prepare_get_meta_info(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData; + if (http_receive_data == null) assert(false); +// if ((receive_data as OmemoHttpFileReceiveData) != null) return receive_data; + + var omemo_http_receive_data = new OmemoHttpFileReceiveData(); + omemo_http_receive_data.url = aesgcm_to_https_link(http_receive_data.url); + omemo_http_receive_data.original_url = http_receive_data.url; + + return omemo_http_receive_data; + } + + public FileMeta prepare_download_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) { + if (file_meta.file_name != null) { + file_meta.file_name = file_meta.file_name.split("#")[0]; + } + return file_meta; + } + + public bool can_decrypt_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + HttpFileReceiveData? http_file_receive = receive_data as HttpFileReceiveData; + if (http_file_receive == null) return false; + + return this.url_regex.match(http_file_receive.url) || (receive_data as OmemoHttpFileReceiveData) != null; + } + + public async InputStream decrypt_file(InputStream encrypted_stream, Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + OmemoHttpFileReceiveData? omemo_http_receive_data = receive_data as OmemoHttpFileReceiveData; + if (omemo_http_receive_data == null) assert(false); + + // Decode IV and key + MatchInfo match_info; + this.url_regex.match(omemo_http_receive_data.original_url, 0, out match_info); + uint8[] iv_and_key = hex_to_bin(match_info.fetch(2).up()); + uint8[] iv, key; + if (iv_and_key.length == 44) { + iv = iv_and_key[0:12]; + key = iv_and_key[12:44]; + } else { + iv = iv_and_key[0:16]; + key = iv_and_key[16:48]; + } + + // Read data + uint8[] buf = new uint8[256]; + Array<uint8> data = new Array<uint8>(false, true, 0); + size_t len = -1; + do { + len = yield encrypted_stream.read_async(buf); + data.append_vals(buf, (uint) len); + } while(len > 0); + + // Decrypt + uint8[] cleartext = Signal.aes_decrypt(Cipher.AES_GCM_NOPADDING, key, iv, data.data); + file_transfer.encryption = Encryption.OMEMO; + return new MemoryInputStream.from_data(cleartext); + } + + private uint8[] hex_to_bin(string hex) { + uint8[] bin = new uint8[hex.length / 2]; + const string HEX = "0123456789ABCDEF"; + for (int i = 0; i < hex.length / 2; i++) { + bin[i] = (uint8) (HEX.index_of_char(hex[i*2]) << 4) | HEX.index_of_char(hex[i*2+1]); + } + return bin; + } + + private string aesgcm_to_https_link(string aesgcm_link) { + MatchInfo match_info; + this.url_regex.match(aesgcm_link, 0, out match_info); + return "https://" + match_info.fetch(1); + } +} + +} diff --git a/plugins/omemo/src/file_transfer/file_encryptor.vala b/plugins/omemo/src/file_transfer/file_encryptor.vala new file mode 100644 index 00000000..a5445153 --- /dev/null +++ b/plugins/omemo/src/file_transfer/file_encryptor.vala @@ -0,0 +1,74 @@ +using Gee; +using Gtk; + +using Dino.Entities; +using Xmpp; +using Signal; + +namespace Dino.Plugins.Omemo { + +public class OmemoHttpFileMeta : HttpFileMeta { + public uint8[] iv; + public uint8[] key; +} + +public class OmemoFileEncryptor : Dino.FileEncryptor, Object { + + public bool can_encrypt_file(Conversation conversation, FileTransfer file_transfer) { + return file_transfer.encryption == Encryption.OMEMO; + } + + public FileMeta encrypt_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError { + var omemo_http_file_meta = new OmemoHttpFileMeta(); + + try { + uint8[] buf = new uint8[256]; + Array<uint8> data = new Array<uint8>(false, true, 0); + size_t len = -1; + do { + len = file_transfer.input_stream.read(buf); + data.append_vals(buf, (uint) len); + } while(len > 0); + + //Create a key and use it to encrypt the file + uint8[] iv = new uint8[16]; + Plugin.get_context().randomize(iv); + uint8[] key = new uint8[32]; + Plugin.get_context().randomize(key); + uint8[] ciphertext = aes_encrypt(Cipher.AES_GCM_NOPADDING, key, iv, data.data); + + omemo_http_file_meta.iv = iv; + omemo_http_file_meta.key = key; + omemo_http_file_meta.size = ciphertext.length; + omemo_http_file_meta.mime_type = "pgp"; + file_transfer.input_stream = new MemoryInputStream.from_data(ciphertext, GLib.free); + } catch (Error error) { + throw new FileSendError.ENCRYPTION_FAILED("HTTP upload: Error encrypting stream: %s".printf(error.message)); + } + + return omemo_http_file_meta; + } + + public FileSendData? preprocess_send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data, FileMeta file_meta) { + HttpFileSendData? send_data = file_send_data as HttpFileSendData; + if (send_data == null) return null; + + OmemoHttpFileMeta? omemo_http_file_meta = file_meta as OmemoHttpFileMeta; + if (omemo_http_file_meta == null) return null; + + // Convert iv and key to hex + string iv_and_key = ""; + foreach (uint8 byte in omemo_http_file_meta.iv) iv_and_key += byte.to_string("%02x"); + foreach (uint8 byte in omemo_http_file_meta.key) iv_and_key += byte.to_string("%02x"); + + string aesgcm_link = send_data.url_down + "#" + iv_and_key; + aesgcm_link = "aesgcm://" + aesgcm_link.substring(8); // replace https:// by aesgcm:// + + send_data.url_down = aesgcm_link; + send_data.encrypt_message = true; + + return file_send_data; + } +} + +} diff --git a/plugins/omemo/src/file_transfer/file_provider.vala b/plugins/omemo/src/file_transfer/file_provider.vala deleted file mode 100644 index 938ec0cf..00000000 --- a/plugins/omemo/src/file_transfer/file_provider.vala +++ /dev/null @@ -1,168 +0,0 @@ -using Gee; -using Gtk; - -using Dino.Entities; -using Xmpp; -using Signal; - -namespace Dino.Plugins.Omemo { - -public class FileProvider : Dino.FileProvider, Object { - public string id { get { return "aesgcm"; } } - - private StreamInteractor stream_interactor; - private Dino.Database dino_db; - private Regex url_regex; - - public FileProvider(StreamInteractor stream_interactor, Dino.Database dino_db) { - this.stream_interactor = stream_interactor; - this.dino_db = dino_db; - this.url_regex = /^aesgcm:\/\/(.*)#(([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44})$/; - - stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(new ReceivedMessageListener(this)); - } - - private class ReceivedMessageListener : MessageListener { - - public string[] after_actions_const = new string[]{ "STORE" }; - public override string action_group { get { return ""; } } - public override string[] after_actions { get { return after_actions_const; } } - - private FileProvider outer; - private StreamInteractor stream_interactor; - - public ReceivedMessageListener(FileProvider outer) { - this.outer = outer; - this.stream_interactor = outer.stream_interactor; - } - - public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { - if (message.body.has_prefix("aesgcm://") && outer.url_regex.match(message.body)) { - yield outer.on_file_message(message, conversation); - } - return false; - } - } - - private async void on_file_message(Entities.Message message, Conversation conversation) { - MatchInfo match_info; - this.url_regex.match(message.body, 0, out match_info); - string url_without_hash = match_info.fetch(1); - - FileTransfer file_transfer = new FileTransfer(); - file_transfer.account = conversation.account; - file_transfer.counterpart = message.counterpart; - file_transfer.ourpart = message.ourpart; - file_transfer.encryption = Encryption.NONE; - file_transfer.time = message.time; - file_transfer.local_time = message.local_time; - file_transfer.direction = message.direction; - file_transfer.file_name = url_without_hash.substring(url_without_hash.last_index_of("/") + 1); - file_transfer.size = -1; - file_transfer.state = FileTransfer.State.NOT_STARTED; - file_transfer.provider = 0; - file_transfer.info = message.id.to_string(); - - if (stream_interactor.get_module(FileManager.IDENTITY).is_sender_trustworthy(file_transfer, conversation)) { - yield get_meta_info(file_transfer); - if (file_transfer.size >= 0 && file_transfer.size < 5000000) { - ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, message.id); - if (content_item != null) { - stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); - } - } - file_incoming(file_transfer, conversation); - } - } - - public async void get_meta_info(FileTransfer file_transfer) { - string url_body = dino_db.message.select({dino_db.message.body}).with(dino_db.message.id, "=", int.parse(file_transfer.info))[dino_db.message.body]; - string url = this.aesgcm_to_https_link(url_body); - var session = new Soup.Session(); - var head_message = new Soup.Message("HEAD", url); - if (head_message != null) { - yield session.send_async(head_message, null); - - if (head_message.status_code >= 200 && head_message.status_code < 300) { - string? content_type = null, content_length = null; - head_message.response_headers.foreach((name, val) => { - if (name == "Content-Type") content_type = val; - if (name == "Content-Length") content_length = val; - }); - file_transfer.mime_type = content_type; - if (content_length != null) { - file_transfer.size = int.parse(content_length); - } - } else { - warning("HTTP HEAD download status code " + head_message.status_code.to_string()); - } - } - } - - public async void download(FileTransfer file_transfer, File file) { - try { - string url_body = dino_db.message.select({dino_db.message.body}).with(dino_db.message.id, "=", int.parse(file_transfer.info))[dino_db.message.body]; - string url = this.aesgcm_to_https_link(url_body); - var session = new Soup.Session(); - Soup.Request request = session.request(url); - - file_transfer.input_stream = yield decrypt_file(yield request.send_async(null), url_body); - file_transfer.encryption = Encryption.OMEMO; - - OutputStream os = file.create(FileCreateFlags.REPLACE_DESTINATION); - yield os.splice_async(file_transfer.input_stream, 0); - os.close(); - file_transfer.path = file.get_basename(); - file_transfer.input_stream = yield file.read_async(); - - file_transfer.state = FileTransfer.State.COMPLETE; - } catch (Error e) { - file_transfer.state = FileTransfer.State.FAILED; - } - } - - public async InputStream? decrypt_file(InputStream input_stream, string url) { - // Decode IV and key - MatchInfo match_info; - this.url_regex.match(url, 0, out match_info); - uint8[] iv_and_key = hex_to_bin(match_info.fetch(2).up()); - uint8[] iv, key; - if (iv_and_key.length == 44) { - iv = iv_and_key[0:12]; - key = iv_and_key[12:44]; - } else { - iv = iv_and_key[0:16]; - key = iv_and_key[16:48]; - } - - // Read data - uint8[] buf = new uint8[256]; - Array<uint8> data = new Array<uint8>(false, true, 0); - size_t len = -1; - do { - len = yield input_stream.read_async(buf); - data.append_vals(buf, (uint) len); - } while(len > 0); - - // Decrypt - uint8[] cleartext = Signal.aes_decrypt(Cipher.AES_GCM_NOPADDING, key, iv, data.data); - return new MemoryInputStream.from_data(cleartext); - } - - private uint8[] hex_to_bin(string hex) { - uint8[] bin = new uint8[hex.length / 2]; - const string HEX = "0123456789ABCDEF"; - for (int i = 0; i < hex.length / 2; i++) { - bin[i] = (uint8) (HEX.index_of_char(hex[i*2]) << 4) | HEX.index_of_char(hex[i*2+1]); - } - return bin; - } - - private string aesgcm_to_https_link(string aesgcm_link) { - MatchInfo match_info; - this.url_regex.match(aesgcm_link, 0, out match_info); - return "https://" + match_info.fetch(1); - } -} - -} diff --git a/plugins/omemo/src/file_transfer/file_sender.vala b/plugins/omemo/src/file_transfer/file_sender.vala deleted file mode 100644 index b63d3dc5..00000000 --- a/plugins/omemo/src/file_transfer/file_sender.vala +++ /dev/null @@ -1,108 +0,0 @@ -using Dino.Entities; -using Gee; -using Signal; -using Xmpp; - -namespace Dino.Plugins.Omemo { - -public class AesGcmFileSender : StreamInteractionModule, FileSender, Object { - public static ModuleIdentity<Manager> IDENTITY = new ModuleIdentity<Manager>("http_files"); - public string id { get { return IDENTITY.id; } } - - - private StreamInteractor stream_interactor; - private HashMap<Account, long> max_file_sizes = new HashMap<Account, long>(Account.hash_func, Account.equals_func); - - public AesGcmFileSender(StreamInteractor stream_interactor) { - this.stream_interactor = stream_interactor; - - stream_interactor.stream_negotiated.connect(on_stream_negotiated); - } - - public void send_file(Conversation conversation, FileTransfer file_transfer) { - Xmpp.XmppStream? stream = stream_interactor.get_stream(file_transfer.account); - uint8[] buf = new uint8[256]; - Array<uint8> data = new Array<uint8>(false, true, 0); - size_t len = -1; - do { - try { - len = file_transfer.input_stream.read(buf); - } catch (IOError error) { - warning(@"HTTP upload: IOError reading stream: $(error.message)"); - file_transfer.state = FileTransfer.State.FAILED; - } - data.append_vals(buf, (uint) len); - } while(len > 0); - - //Create a key and use it to encrypt the file - uint8[] iv = new uint8[16]; - Plugin.get_context().randomize(iv); - uint8[] key = new uint8[32]; - Plugin.get_context().randomize(key); - uint8[] ciphertext = aes_encrypt(Cipher.AES_GCM_NOPADDING, key, iv, data.data); - - // Convert iv and key to hex - string iv_and_key = ""; - foreach (uint8 byte in iv) iv_and_key += byte.to_string("%02x"); - foreach (uint8 byte in key) iv_and_key += byte.to_string("%02x"); - - stream_interactor.module_manager.get_module(file_transfer.account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).request_slot(stream, file_transfer.server_file_name, (int) ciphertext.length, file_transfer.mime_type, - (stream, url_down, url_up) => { - Soup.Message message = new Soup.Message("PUT", url_up); - message.set_request(file_transfer.mime_type, Soup.MemoryUse.COPY, ciphertext); - Soup.Session session = new Soup.Session(); - session.send_async.begin(message, null, (obj, res) => { - try { - session.send_async.end(res); - if (message.status_code >= 200 && message.status_code < 300) { - string aesgcm_link = url_down + "#" + iv_and_key; - aesgcm_link = "aesgcm://" + aesgcm_link.substring(8); // replace https:// by aesgcm:// - - file_transfer.info = aesgcm_link; // store the message content temporarily so the message gets filtered out - Entities.Message xmpp_message = stream_interactor.get_module(MessageProcessor.IDENTITY).create_out_message(aesgcm_link, conversation); - xmpp_message.encryption = Encryption.OMEMO; - stream_interactor.get_module(MessageProcessor.IDENTITY).send_message(xmpp_message, conversation); - file_transfer.info = xmpp_message.id.to_string(); - - ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item(conversation, 1, xmpp_message.id); - if (content_item != null) { - stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); - } - } else { - warning("HTTP upload status code " + message.status_code.to_string()); - file_transfer.state = FileTransfer.State.FAILED; - } - } catch (Error e) { - warning("HTTP upload error: " + e.message); - file_transfer.state = FileTransfer.State.FAILED; - } - }); - }, - (stream, error) => { - warning("HTTP upload error: " + error); - file_transfer.state = FileTransfer.State.FAILED; - } - ); - } - - public bool can_send(Conversation conversation, FileTransfer file_transfer) { - return file_transfer.encryption == Encryption.OMEMO; - } - - public bool is_upload_available(Conversation conversation) { - lock (max_file_sizes) { - return max_file_sizes.has_key(conversation.account); - } - } - - private void on_stream_negotiated(Account account, XmppStream stream) { - stream_interactor.module_manager.get_module(account, Xmpp.Xep.HttpFileUpload.Module.IDENTITY).feature_available.connect((stream, max_file_size) => { - lock (max_file_sizes) { - max_file_sizes[account] = max_file_size; - } - upload_available(account); - }); - } -} - -} diff --git a/plugins/omemo/src/plugin.vala b/plugins/omemo/src/plugin.vala index 2cb96e10..9f1252c0 100644 --- a/plugins/omemo/src/plugin.vala +++ b/plugins/omemo/src/plugin.vala @@ -50,8 +50,9 @@ public class Plugin : RootInterface, Object { this.own_notifications = new OwnNotifications(this, this.app.stream_interactor, account); }); - app.stream_interactor.get_module(FileManager.IDENTITY).add_provider(new FileProvider(app.stream_interactor, app.db)); - this.app.stream_interactor.get_module(FileManager.IDENTITY).add_sender(new AesGcmFileSender(app.stream_interactor)); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_decryptor(new OmemoFileDecryptor()); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_encryptor(new OmemoFileEncryptor()); + Manager.start(this.app.stream_interactor, db, trust_manager); SimpleAction own_keys_action = new SimpleAction("own-keys", VariantType.INT32); diff --git a/plugins/openpgp/CMakeLists.txt b/plugins/openpgp/CMakeLists.txt index ab406123..eb50dc71 100644 --- a/plugins/openpgp/CMakeLists.txt +++ b/plugins/openpgp/CMakeLists.txt @@ -28,14 +28,15 @@ compile_gresources( vala_precompile(OPENPGP_VALA_C SOURCES + src/file_transfer/file_decryptor.vala + src/file_transfer/file_encryptor.vala + src/account_settings_entry.vala src/account_settings_widget.vala src/contact_details_provider.vala src/database.vala src/encryption_list_entry.vala - src/in_file_processor.vala src/manager.vala - src/out_file_processor.vala src/plugin.vala src/register_plugin.vala src/stream_flag.vala diff --git a/plugins/openpgp/src/in_file_processor.vala b/plugins/openpgp/src/file_transfer/file_decryptor.vala index 918f824a..7668023e 100644 --- a/plugins/openpgp/src/in_file_processor.vala +++ b/plugins/openpgp/src/file_transfer/file_decryptor.vala @@ -2,31 +2,40 @@ using Dino.Entities; namespace Dino.Plugins.OpenPgp { -public class InFileProcessor : IncomingFileProcessor, Object { - public bool can_process(FileTransfer file_transfer) { +public class PgpFileDecryptor : FileDecryptor, Object { + + public FileReceiveData prepare_get_meta_info(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + return receive_data; + } + + public FileMeta prepare_download_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) { + return file_meta; + } + + public bool can_decrypt_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { return file_transfer.file_name.has_suffix("pgp") || file_transfer.mime_type == "application/pgp-encrypted"; } - public void process(FileTransfer file_transfer) { + public async InputStream decrypt_file(InputStream encrypted_stream, Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) throws FileReceiveError { try { uint8[] buf = new uint8[256]; Array<uint8> data = new Array<uint8>(false, true, 0); size_t len = -1; do { - len = file_transfer.input_stream.read(buf); + len = encrypted_stream.read(buf); data.append_vals(buf, (uint) len); } while(len > 0); GPGHelper.DecryptedData clear_data = GPGHelper.decrypt_data(data.data); - file_transfer.input_stream = new MemoryInputStream.from_data(clear_data.data, GLib.free); file_transfer.encryption = Encryption.PGP; if (clear_data.filename != null && clear_data.filename != "") { file_transfer.file_name = clear_data.filename; } else if (file_transfer.file_name.has_suffix(".pgp")) { file_transfer.file_name = file_transfer.file_name.substring(0, file_transfer.file_name.length - 4); } + return new MemoryInputStream.from_data(clear_data.data, GLib.free); } catch (Error e) { - file_transfer.state = FileTransfer.State.FAILED; + throw new FileReceiveError.DECRYPTION_FAILED("PGP file decrypt error: %s".printf(e.message)); } } } diff --git a/plugins/openpgp/src/file_transfer/file_encryptor.vala b/plugins/openpgp/src/file_transfer/file_encryptor.vala new file mode 100644 index 00000000..7d51be60 --- /dev/null +++ b/plugins/openpgp/src/file_transfer/file_encryptor.vala @@ -0,0 +1,41 @@ +using Dino.Entities; + +namespace Dino.Plugins.OpenPgp { + +public class PgpFileEncryptor : Dino.FileEncryptor, Object { + + StreamInteractor stream_interactor; + + public PgpFileEncryptor(StreamInteractor stream_interactor) { + this.stream_interactor = stream_interactor; + } + + public bool can_encrypt_file(Conversation conversation, FileTransfer file_transfer) { + return conversation.encryption == Encryption.PGP; + } + + public FileMeta encrypt_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError { + try { + GPG.Key[] keys = stream_interactor.get_module(Manager.IDENTITY).get_key_fprs(conversation); + uint8[] enc_content = GPGHelper.encrypt_file(file_transfer.get_file().get_path(), keys, GPG.EncryptFlags.ALWAYS_TRUST, file_transfer.file_name); + file_transfer.input_stream = new MemoryInputStream.from_data(enc_content, GLib.free); + file_transfer.encryption = Encryption.PGP; + file_transfer.server_file_name = Xmpp.random_uuid() + ".pgp"; + } catch (Error e) { + throw new FileSendError.ENCRYPTION_FAILED("PGP file encryption error: %s".printf(e.message)); + } + + return new FileMeta(); + } + + public FileSendData? preprocess_send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data, FileMeta file_meta) { + HttpFileSendData? send_data = file_send_data as HttpFileSendData; + if (send_data == null) return null; + + send_data.encrypt_message = false; + + return file_send_data; + } +} + +} diff --git a/plugins/openpgp/src/out_file_processor.vala b/plugins/openpgp/src/out_file_processor.vala deleted file mode 100644 index 40eef7f5..00000000 --- a/plugins/openpgp/src/out_file_processor.vala +++ /dev/null @@ -1,32 +0,0 @@ -using Dino.Entities; - -namespace Dino.Plugins.OpenPgp { - -public class OutFileProcessor : OutgoingFileProcessor, Object { - - StreamInteractor stream_interactor; - - public OutFileProcessor(StreamInteractor stream_interactor) { - this.stream_interactor = stream_interactor; - } - - public bool can_process(Conversation conversation, FileTransfer file_transfer) { - return conversation.encryption == Encryption.PGP; - } - - public void process(Conversation conversation, FileTransfer file_transfer) { - string path = file_transfer.get_file().get_path(); - try { - GPG.Key[] keys = stream_interactor.get_module(Manager.IDENTITY).get_key_fprs(conversation); - uint8[] enc_content = GPGHelper.encrypt_file(path, keys, GPG.EncryptFlags.ALWAYS_TRUST, file_transfer.file_name); - file_transfer.input_stream = new MemoryInputStream.from_data(enc_content, GLib.free); - file_transfer.encryption = Encryption.PGP; - file_transfer.server_file_name = Xmpp.random_uuid() + ".pgp"; - } catch (Error e) { - warning(@"PGP file encryption error: $(e.message)\n"); - file_transfer.state = FileTransfer.State.FAILED; - } - } -} - -} diff --git a/plugins/openpgp/src/plugin.vala b/plugins/openpgp/src/plugin.vala index 1d4f5203..35ede01e 100644 --- a/plugins/openpgp/src/plugin.vala +++ b/plugins/openpgp/src/plugin.vala @@ -29,8 +29,8 @@ public class Plugin : Plugins.RootInterface, Object { app.stream_interactor.module_manager.initialize_account_modules.connect(on_initialize_account_modules); Manager.start(app.stream_interactor, db); - app.stream_interactor.get_module(FileManager.IDENTITY).add_outgoing_processor(new OutFileProcessor(app.stream_interactor)); - app.stream_interactor.get_module(FileManager.IDENTITY).add_incoming_processor(new InFileProcessor()); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_encryptor(new PgpFileEncryptor(app.stream_interactor)); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_decryptor(new PgpFileDecryptor()); internationalize(GETTEXT_PACKAGE, app.search_path_generator.get_locale_path(GETTEXT_PACKAGE, LOCALE_INSTALL_DIR)); } diff --git a/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala b/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala index 57222bae..2e636491 100644 --- a/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala +++ b/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala @@ -62,11 +62,13 @@ public class Module : Jingle.ContentType, XmppStreamModule { } public class Parameters : Jingle.ContentParameters, Object { + Module parent; string? media_type; public string? name { get; private set; } public int64 size { get; private set; } public StanzaNode original_description { get; private set; } + public Parameters(Module parent, StanzaNode original_description, string? media_type, string? name, int64? size) { this.parent = parent; this.original_description = original_description; @@ -74,6 +76,7 @@ public class Parameters : Jingle.ContentParameters, Object { this.name = name; this.size = size; } + public static Parameters parse(Module parent, StanzaNode description) throws Jingle.IqError { Gee.List<StanzaNode> files = description.get_subnodes("file", NS_URI); if (files.size != 1) { @@ -98,7 +101,8 @@ public class Parameters : Jingle.ContentParameters, Object { return new Parameters(parent, description, media_type, name, size); } - void on_session_initiate(XmppStream stream, Jingle.Session session) { + + public void on_session_initiate(XmppStream stream, Jingle.Session session) { parent.file_incoming(stream, new FileTransfer(session, this)); } } @@ -122,6 +126,7 @@ public class FileTransfer : Object { session.accept(stream, parameters.original_description); session.conn.output_stream.close(); } + public void reject(XmppStream stream) { session.reject(stream); } diff --git a/xmpp-vala/src/module/xep/0363_http_file_upload.vala b/xmpp-vala/src/module/xep/0363_http_file_upload.vala index 1d808ed1..eefe05eb 100644 --- a/xmpp-vala/src/module/xep/0363_http_file_upload.vala +++ b/xmpp-vala/src/module/xep/0363_http_file_upload.vala @@ -6,6 +6,10 @@ namespace Xmpp.Xep.HttpFileUpload { private const string NS_URI = "urn:xmpp:http:upload"; private const string NS_URI_0 = "urn:xmpp:http:upload:0"; +public errordomain HttpFileTransferError { + SLOT_REQUEST +} + public class Module : XmppStreamModule { public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0363_http_file_upload"); @@ -14,9 +18,15 @@ public class Module : XmppStreamModule { public delegate void OnSlotOk(XmppStream stream, string url_get, string url_put); public delegate void OnError(XmppStream stream, string error); - public void request_slot(XmppStream stream, string filename, int file_size, string? content_type, owned OnSlotOk listener, owned OnError error_listener) { + public struct SlotResult { + public string url_get { get; set; } + public string url_put { get; set; } + } + public async SlotResult request_slot(XmppStream stream, string filename, int file_size, string? content_type) throws HttpFileTransferError { Flag? flag = stream.get_flag(Flag.IDENTITY); - if (flag == null) return; + if (flag == null) { + throw new HttpFileTransferError.SLOT_REQUEST("No flag"); + } StanzaNode? request_node = null; switch (flag.ns_ver) { @@ -34,10 +44,17 @@ public class Module : XmppStreamModule { } break; } + + SourceFunc callback = request_slot.callback; + var slot_result = SlotResult(); + Iq.Stanza iq = new Iq.Stanza.get(request_node) { to=flag.file_store_jid }; + + HttpFileTransferError? e = null; stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => { if (iq.is_error()) { - error_listener(stream, "Error getting upload/download url (Error Iq)"); + e = new HttpFileTransferError.SLOT_REQUEST("Error getting upload/download url (Error Iq)"); + Idle.add((owned) callback); return; } string? url_get = null, url_put = null; @@ -49,10 +66,23 @@ public class Module : XmppStreamModule { url_put = iq.stanza.get_deep_string_content(flag.ns_ver + ":slot", flag.ns_ver + ":put"); } if (url_get == null || url_put == null) { - error_listener(stream, "Error getting upload/download url"); + e = new HttpFileTransferError.SLOT_REQUEST("Error getting upload/download url: %s".printf(iq.stanza.to_string())); + Idle.add((owned) callback); + return; } - listener(stream, url_get, url_put); + + slot_result.url_get = url_get; + slot_result.url_put = url_put; + + Idle.add((owned) callback); }); + yield; + + if (e != null) { + throw e; + } + + return slot_result; } public override void attach(XmppStream stream) { |