diff --git a/.editorconfig b/.editorconfig index 140cc085c5..231d35cfe4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,901 +1,901 @@ -[*] -charset = utf-8 -end_of_line = lf -indent_size = 4 -indent_style = space -insert_final_newline = true -max_line_length = 160 -tab_width = 4 -ij_continuation_indent_size = 8 -ij_formatter_off_tag = @formatter:off -ij_formatter_on_tag = @formatter:on -ij_formatter_tags_enabled = false -ij_smart_tabs = false -ij_visual_guides = none -ij_wrap_on_typing = false - -[*.java] -ij_java_align_consecutive_assignments = false -ij_java_align_consecutive_variable_declarations = false -ij_java_align_group_field_declarations = false -ij_java_align_multiline_annotation_parameters = false -ij_java_align_multiline_array_initializer_expression = false -ij_java_align_multiline_assignment = false -ij_java_align_multiline_binary_operation = false -ij_java_align_multiline_chained_methods = false -ij_java_align_multiline_extends_list = false -ij_java_align_multiline_for = true -ij_java_align_multiline_method_parentheses = false -ij_java_align_multiline_parameters = true -ij_java_align_multiline_parameters_in_calls = false -ij_java_align_multiline_parenthesized_expression = false -ij_java_align_multiline_records = true -ij_java_align_multiline_resources = true -ij_java_align_multiline_ternary_operation = false -ij_java_align_multiline_text_blocks = false -ij_java_align_multiline_throws_list = false -ij_java_align_subsequent_simple_methods = false -ij_java_align_throws_keyword = false -ij_java_annotation_parameter_wrap = off -ij_java_array_initializer_new_line_after_left_brace = false -ij_java_array_initializer_right_brace_on_new_line = false -ij_java_array_initializer_wrap = off -ij_java_assert_statement_colon_on_next_line = false -ij_java_assert_statement_wrap = off -ij_java_assignment_wrap = off -ij_java_binary_operation_sign_on_next_line = false -ij_java_binary_operation_wrap = off -ij_java_blank_lines_after_anonymous_class_header = 0 -ij_java_blank_lines_after_class_header = 0 -ij_java_blank_lines_after_imports = 1 -ij_java_blank_lines_after_package = 1 -ij_java_blank_lines_around_class = 1 -ij_java_blank_lines_around_field = 0 -ij_java_blank_lines_around_field_in_interface = 0 -ij_java_blank_lines_around_initializer = 1 -ij_java_blank_lines_around_method = 1 -ij_java_blank_lines_around_method_in_interface = 1 -ij_java_blank_lines_before_class_end = 0 -ij_java_blank_lines_before_imports = 1 -ij_java_blank_lines_before_method_body = 0 -ij_java_blank_lines_before_package = 0 -ij_java_block_brace_style = end_of_line -ij_java_block_comment_at_first_column = true -ij_java_builder_methods = none -ij_java_call_parameters_new_line_after_left_paren = false -ij_java_call_parameters_right_paren_on_new_line = false -ij_java_call_parameters_wrap = off -ij_java_case_statement_on_separate_line = true -ij_java_catch_on_new_line = false -ij_java_class_annotation_wrap = split_into_lines -ij_java_class_brace_style = end_of_line -ij_java_class_count_to_use_import_on_demand = 99 -ij_java_class_names_in_javadoc = 1 -ij_java_do_not_indent_top_level_class_members = false -ij_java_do_not_wrap_after_single_annotation = false -ij_java_do_while_brace_force = never -ij_java_doc_add_blank_line_after_description = true -ij_java_doc_add_blank_line_after_param_comments = false -ij_java_doc_add_blank_line_after_return = false -ij_java_doc_add_p_tag_on_empty_lines = true -ij_java_doc_align_exception_comments = true -ij_java_doc_align_param_comments = true -ij_java_doc_do_not_wrap_if_one_line = false -ij_java_doc_enable_formatting = true -ij_java_doc_enable_leading_asterisks = true -ij_java_doc_indent_on_continuation = false -ij_java_doc_keep_empty_lines = true -ij_java_doc_keep_empty_parameter_tag = true -ij_java_doc_keep_empty_return_tag = true -ij_java_doc_keep_empty_throws_tag = true -ij_java_doc_keep_invalid_tags = true -ij_java_doc_param_description_on_new_line = false -ij_java_doc_preserve_line_breaks = false -ij_java_doc_use_throws_not_exception_tag = true -ij_java_else_on_new_line = false -ij_java_enum_constants_wrap = off -ij_java_extends_keyword_wrap = off -ij_java_extends_list_wrap = off -ij_java_field_annotation_wrap = split_into_lines -ij_java_finally_on_new_line = false -ij_java_for_brace_force = never -ij_java_for_statement_new_line_after_left_paren = false -ij_java_for_statement_right_paren_on_new_line = false -ij_java_for_statement_wrap = off -ij_java_generate_final_locals = false -ij_java_generate_final_parameters = false -ij_java_if_brace_force = never -ij_java_imports_layout = $android.**,$androidx.**,$com.**,$junit.**,$net.**,$org.**,$java.**,$javax.**,$*,|,android.**,|,androidx.**,|,com.**,|,junit.**,|,net.**,|,org.**,|,java.**,|,javax.**,|,*,| -ij_java_indent_case_from_switch = true -ij_java_insert_inner_class_imports = false -ij_java_insert_override_annotation = true -ij_java_keep_blank_lines_before_right_brace = 2 -ij_java_keep_blank_lines_between_package_declaration_and_header = 2 -ij_java_keep_blank_lines_in_code = 2 -ij_java_keep_blank_lines_in_declarations = 2 -ij_java_keep_builder_methods_indents = false -ij_java_keep_control_statement_in_one_line = true -ij_java_keep_first_column_comment = true -ij_java_keep_indents_on_empty_lines = false -ij_java_keep_line_breaks = true -ij_java_keep_multiple_expressions_in_one_line = false -ij_java_keep_simple_blocks_in_one_line = false -ij_java_keep_simple_classes_in_one_line = false -ij_java_keep_simple_lambdas_in_one_line = false -ij_java_keep_simple_methods_in_one_line = false -ij_java_label_indent_absolute = false -ij_java_label_indent_size = 0 -ij_java_lambda_brace_style = end_of_line -ij_java_layout_static_imports_separately = true -ij_java_line_comment_add_space = false -ij_java_line_comment_at_first_column = true -ij_java_method_annotation_wrap = split_into_lines -ij_java_method_brace_style = end_of_line -ij_java_method_call_chain_wrap = off -ij_java_method_parameters_new_line_after_left_paren = false -ij_java_method_parameters_right_paren_on_new_line = false -ij_java_method_parameters_wrap = off -ij_java_modifier_list_wrap = false -ij_java_names_count_to_use_import_on_demand = 99 -ij_java_new_line_after_lparen_in_record_header = false -ij_java_parameter_annotation_wrap = off -ij_java_parentheses_expression_new_line_after_left_paren = false -ij_java_parentheses_expression_right_paren_on_new_line = false -ij_java_place_assignment_sign_on_next_line = false -ij_java_prefer_longer_names = true -ij_java_prefer_parameters_wrap = false -ij_java_record_components_wrap = normal -ij_java_repeat_synchronized = true -ij_java_replace_instanceof_and_cast = false -ij_java_replace_null_check = true -ij_java_replace_sum_lambda_with_method_ref = true -ij_java_resource_list_new_line_after_left_paren = false -ij_java_resource_list_right_paren_on_new_line = false -ij_java_resource_list_wrap = off -ij_java_rparen_on_new_line_in_record_header = false -ij_java_space_after_closing_angle_bracket_in_type_argument = false -ij_java_space_after_colon = true -ij_java_space_after_comma = true -ij_java_space_after_comma_in_type_arguments = true -ij_java_space_after_for_semicolon = true -ij_java_space_after_quest = true -ij_java_space_after_type_cast = true -ij_java_space_before_annotation_array_initializer_left_brace = false -ij_java_space_before_annotation_parameter_list = false -ij_java_space_before_array_initializer_left_brace = false -ij_java_space_before_catch_keyword = true -ij_java_space_before_catch_left_brace = true -ij_java_space_before_catch_parentheses = true -ij_java_space_before_class_left_brace = true -ij_java_space_before_colon = true -ij_java_space_before_colon_in_foreach = true -ij_java_space_before_comma = false -ij_java_space_before_do_left_brace = true -ij_java_space_before_else_keyword = true -ij_java_space_before_else_left_brace = true -ij_java_space_before_finally_keyword = true -ij_java_space_before_finally_left_brace = true -ij_java_space_before_for_left_brace = true -ij_java_space_before_for_parentheses = true -ij_java_space_before_for_semicolon = false -ij_java_space_before_if_left_brace = true -ij_java_space_before_if_parentheses = true -ij_java_space_before_method_call_parentheses = false -ij_java_space_before_method_left_brace = true -ij_java_space_before_method_parentheses = false -ij_java_space_before_opening_angle_bracket_in_type_parameter = false -ij_java_space_before_quest = true -ij_java_space_before_switch_left_brace = true -ij_java_space_before_switch_parentheses = true -ij_java_space_before_synchronized_left_brace = true -ij_java_space_before_synchronized_parentheses = true -ij_java_space_before_try_left_brace = true -ij_java_space_before_try_parentheses = true -ij_java_space_before_type_parameter_list = false -ij_java_space_before_while_keyword = true -ij_java_space_before_while_left_brace = true -ij_java_space_before_while_parentheses = true -ij_java_space_inside_one_line_enum_braces = false -ij_java_space_within_empty_array_initializer_braces = false -ij_java_space_within_empty_method_call_parentheses = false -ij_java_space_within_empty_method_parentheses = false -ij_java_spaces_around_additive_operators = true -ij_java_spaces_around_assignment_operators = true -ij_java_spaces_around_bitwise_operators = true -ij_java_spaces_around_equality_operators = true -ij_java_spaces_around_lambda_arrow = true -ij_java_spaces_around_logical_operators = true -ij_java_spaces_around_method_ref_dbl_colon = false -ij_java_spaces_around_multiplicative_operators = true -ij_java_spaces_around_relational_operators = true -ij_java_spaces_around_shift_operators = true -ij_java_spaces_around_type_bounds_in_type_parameters = true -ij_java_spaces_around_unary_operator = false -ij_java_spaces_within_angle_brackets = false -ij_java_spaces_within_annotation_parentheses = false -ij_java_spaces_within_array_initializer_braces = false -ij_java_spaces_within_braces = false -ij_java_spaces_within_brackets = false -ij_java_spaces_within_cast_parentheses = false -ij_java_spaces_within_catch_parentheses = false -ij_java_spaces_within_for_parentheses = false -ij_java_spaces_within_if_parentheses = false -ij_java_spaces_within_method_call_parentheses = false -ij_java_spaces_within_method_parentheses = false -ij_java_spaces_within_parentheses = false -ij_java_spaces_within_record_header = false -ij_java_spaces_within_switch_parentheses = false -ij_java_spaces_within_synchronized_parentheses = false -ij_java_spaces_within_try_parentheses = false -ij_java_spaces_within_while_parentheses = false -ij_java_special_else_if_treatment = true -ij_java_subclass_name_suffix = Impl -ij_java_ternary_operation_signs_on_next_line = false -ij_java_ternary_operation_wrap = off -ij_java_test_name_suffix = Test -ij_java_throws_keyword_wrap = off -ij_java_throws_list_wrap = off -ij_java_use_external_annotations = false -ij_java_use_fq_class_names = false -ij_java_use_relative_indents = false -ij_java_use_single_class_imports = true -ij_java_variable_annotation_wrap = off -ij_java_visibility = public -ij_java_while_brace_force = never -ij_java_while_on_new_line = false -ij_java_wrap_comments = false -ij_java_wrap_first_method_in_call_chain = false -ij_java_wrap_long_lines = false - -[*.properties] -ij_properties_align_group_field_declarations = false -ij_properties_keep_blank_lines = false -ij_properties_key_value_delimiter = equals -ij_properties_spaces_around_key_value_delimiter = false - -[.editorconfig] -ij_editorconfig_align_group_field_declarations = false -ij_editorconfig_space_after_colon = false -ij_editorconfig_space_after_comma = true -ij_editorconfig_space_before_colon = false -ij_editorconfig_space_before_comma = false -ij_editorconfig_spaces_around_assignment_operators = true - -[{*.ant,*.fxml,*.jhm,*.jnlp,*.jrxml,*.rng,*.tld,*.wsdl,*.xml,*.xsd,*.xsl,*.xslt,*.xul}] -ij_continuation_indent_size = 4 -ij_xml_align_attributes = false -ij_xml_align_text = false -ij_xml_attribute_wrap = normal -ij_xml_block_comment_at_first_column = true -ij_xml_keep_blank_lines = 2 -ij_xml_keep_indents_on_empty_lines = false -ij_xml_keep_line_breaks = false -ij_xml_keep_line_breaks_in_text = true -ij_xml_keep_whitespaces = false -ij_xml_keep_whitespaces_around_cdata = preserve -ij_xml_keep_whitespaces_inside_cdata = false -ij_xml_line_comment_at_first_column = true -ij_xml_space_after_tag_name = false -ij_xml_space_around_equals_in_attribute = false -ij_xml_space_inside_empty_tag = true -ij_xml_text_wrap = normal -ij_xml_use_custom_settings = true - -[{*.bash,*.sh,*.zsh}] -indent_size = 2 -tab_width = 2 -ij_shell_binary_ops_start_line = false -ij_shell_keep_column_alignment_padding = false -ij_shell_minify_program = false -ij_shell_redirect_followed_by_space = false -ij_shell_switch_cases_indented = false -ij_shell_use_unix_line_separator = true - -[{*.c,*.c++,*.cc,*.cp,*.cpp,*.cu,*.cuh,*.cxx,*.h,*.h++,*.hh,*.hp,*.hpp,*.hxx,*.i,*.icc,*.ii,*.inl,*.ino,*.ipp,*.m,*.mm,*.pch,*.tcc,*.tpp}] -ij_c_add_brief_tag = false -ij_c_add_getter_prefix = true -ij_c_add_setter_prefix = true -ij_c_align_dictionary_pair_values = false -ij_c_align_group_field_declarations = false -ij_c_align_init_list_in_columns = true -ij_c_align_multiline_array_initializer_expression = true -ij_c_align_multiline_assignment = true -ij_c_align_multiline_binary_operation = true -ij_c_align_multiline_chained_methods = false -ij_c_align_multiline_for = true -ij_c_align_multiline_ternary_operation = true -ij_c_array_initializer_comma_on_next_line = false -ij_c_array_initializer_new_line_after_left_brace = false -ij_c_array_initializer_right_brace_on_new_line = false -ij_c_array_initializer_wrap = normal -ij_c_assignment_wrap = off -ij_c_binary_operation_sign_on_next_line = false -ij_c_binary_operation_wrap = normal -ij_c_blank_lines_after_class_header = 0 -ij_c_blank_lines_after_imports = 1 -ij_c_blank_lines_around_class = 1 -ij_c_blank_lines_around_field = 0 -ij_c_blank_lines_around_field_in_interface = 0 -ij_c_blank_lines_around_method = 1 -ij_c_blank_lines_around_method_in_interface = 1 -ij_c_blank_lines_around_namespace = 0 -ij_c_blank_lines_around_properties_in_declaration = 0 -ij_c_blank_lines_around_properties_in_interface = 0 -ij_c_blank_lines_before_imports = 1 -ij_c_blank_lines_before_method_body = 0 -ij_c_block_brace_placement = end_of_line -ij_c_block_brace_style = end_of_line -ij_c_block_comment_at_first_column = true -ij_c_catch_on_new_line = false -ij_c_class_brace_style = end_of_line -ij_c_class_constructor_init_list_align_multiline = true -ij_c_class_constructor_init_list_comma_on_next_line = false -ij_c_class_constructor_init_list_new_line_after_colon = never -ij_c_class_constructor_init_list_new_line_before_colon = if_long -ij_c_class_constructor_init_list_wrap = normal -ij_c_copy_is_deep = false -ij_c_create_interface_for_categories = true -ij_c_declare_generated_methods = true -ij_c_description_include_member_names = true -ij_c_discharged_short_ternary_operator = false -ij_c_do_not_add_breaks = false -ij_c_do_while_brace_force = never -ij_c_else_on_new_line = false -ij_c_enum_constants_comma_on_next_line = false -ij_c_enum_constants_wrap = on_every_item -ij_c_for_brace_force = never -ij_c_for_statement_new_line_after_left_paren = false -ij_c_for_statement_right_paren_on_new_line = false -ij_c_for_statement_wrap = off -ij_c_function_brace_placement = end_of_line -ij_c_function_call_arguments_align_multiline = true -ij_c_function_call_arguments_align_multiline_pars = false -ij_c_function_call_arguments_comma_on_next_line = false -ij_c_function_call_arguments_new_line_after_lpar = false -ij_c_function_call_arguments_new_line_before_rpar = false -ij_c_function_call_arguments_wrap = normal -ij_c_function_non_top_after_return_type_wrap = normal -ij_c_function_parameters_align_multiline = true -ij_c_function_parameters_align_multiline_pars = false -ij_c_function_parameters_comma_on_next_line = false -ij_c_function_parameters_new_line_after_lpar = false -ij_c_function_parameters_new_line_before_rpar = false -ij_c_function_parameters_wrap = normal -ij_c_function_top_after_return_type_wrap = normal -ij_c_generate_additional_eq_operators = true -ij_c_generate_additional_rel_operators = true -ij_c_generate_class_constructor = true -ij_c_generate_comparison_operators_use_std_tie = false -ij_c_generate_instance_variables_for_properties = ask -ij_c_generate_operators_as_members = true -ij_c_header_guard_style_pattern = ${PROJECT_NAME}_${FILE_NAME}_${EXT} -ij_c_if_brace_force = never -ij_c_in_line_short_ternary_operator = true -ij_c_indent_block_comment = true -ij_c_indent_c_struct_members = 4 -ij_c_indent_case_from_switch = true -ij_c_indent_class_members = 4 -ij_c_indent_directive_as_code = false -ij_c_indent_implementation_members = 0 -ij_c_indent_inside_code_block = 4 -ij_c_indent_interface_members = 0 -ij_c_indent_interface_members_except_ivars_block = false -ij_c_indent_namespace_members = 4 -ij_c_indent_preprocessor_directive = 0 -ij_c_indent_visibility_keywords = 0 -ij_c_insert_override = true -ij_c_insert_virtual_with_override = false -ij_c_introduce_auto_vars = false -ij_c_introduce_const_params = false -ij_c_introduce_const_vars = false -ij_c_introduce_generate_property = false -ij_c_introduce_generate_synthesize = true -ij_c_introduce_globals_to_header = true -ij_c_introduce_prop_to_private_category = false -ij_c_introduce_static_consts = true -ij_c_introduce_use_ns_types = false -ij_c_ivars_prefix = _ -ij_c_keep_blank_lines_before_end = 2 -ij_c_keep_blank_lines_before_right_brace = 2 -ij_c_keep_blank_lines_in_code = 2 -ij_c_keep_blank_lines_in_declarations = 2 -ij_c_keep_case_expressions_in_one_line = false -ij_c_keep_control_statement_in_one_line = true -ij_c_keep_directive_at_first_column = true -ij_c_keep_first_column_comment = true -ij_c_keep_line_breaks = true -ij_c_keep_nested_namespaces_in_one_line = false -ij_c_keep_simple_blocks_in_one_line = true -ij_c_keep_simple_methods_in_one_line = true -ij_c_keep_structures_in_one_line = false -ij_c_lambda_capture_list_align_multiline = false -ij_c_lambda_capture_list_align_multiline_bracket = false -ij_c_lambda_capture_list_comma_on_next_line = false -ij_c_lambda_capture_list_new_line_after_lbracket = false -ij_c_lambda_capture_list_new_line_before_rbracket = false -ij_c_lambda_capture_list_wrap = off -ij_c_line_comment_add_space = false -ij_c_line_comment_at_first_column = true -ij_c_method_brace_placement = end_of_line -ij_c_method_call_arguments_align_by_colons = true -ij_c_method_call_arguments_align_multiline = false -ij_c_method_call_arguments_special_dictionary_pairs_treatment = true -ij_c_method_call_arguments_wrap = off -ij_c_method_call_chain_wrap = off -ij_c_method_parameters_align_by_colons = true -ij_c_method_parameters_align_multiline = false -ij_c_method_parameters_wrap = off -ij_c_namespace_brace_placement = end_of_line -ij_c_parentheses_expression_new_line_after_left_paren = false -ij_c_parentheses_expression_right_paren_on_new_line = false -ij_c_place_assignment_sign_on_next_line = false -ij_c_property_nonatomic = true -ij_c_put_ivars_to_implementation = true -ij_c_refactor_compatibility_aliases_and_classes = true -ij_c_refactor_properties_and_ivars = true -ij_c_release_style = ivar -ij_c_retain_object_parameters_in_constructor = true -ij_c_semicolon_after_method_signature = false -ij_c_shift_operation_align_multiline = true -ij_c_shift_operation_wrap = normal -ij_c_show_non_virtual_functions = false -ij_c_space_after_colon = true -ij_c_space_after_colon_in_selector = false -ij_c_space_after_comma = true -ij_c_space_after_cup_in_blocks = false -ij_c_space_after_dictionary_literal_colon = true -ij_c_space_after_for_semicolon = true -ij_c_space_after_init_list_colon = true -ij_c_space_after_method_parameter_type_parentheses = false -ij_c_space_after_method_return_type_parentheses = false -ij_c_space_after_pointer_in_declaration = false -ij_c_space_after_quest = true -ij_c_space_after_reference_in_declaration = false -ij_c_space_after_reference_in_rvalue = false -ij_c_space_after_structures_rbrace = true -ij_c_space_after_superclass_colon = true -ij_c_space_after_type_cast = true -ij_c_space_after_visibility_sign_in_method_declaration = true -ij_c_space_before_autorelease_pool_lbrace = true -ij_c_space_before_catch_keyword = true -ij_c_space_before_catch_left_brace = true -ij_c_space_before_catch_parentheses = true -ij_c_space_before_category_parentheses = true -ij_c_space_before_chained_send_message = true -ij_c_space_before_class_left_brace = true -ij_c_space_before_colon = true -ij_c_space_before_comma = false -ij_c_space_before_dictionary_literal_colon = false -ij_c_space_before_do_left_brace = true -ij_c_space_before_else_keyword = true -ij_c_space_before_else_left_brace = true -ij_c_space_before_for_left_brace = true -ij_c_space_before_for_parentheses = true -ij_c_space_before_for_semicolon = false -ij_c_space_before_if_left_brace = true -ij_c_space_before_if_parentheses = true -ij_c_space_before_init_list = false -ij_c_space_before_init_list_colon = true -ij_c_space_before_method_call_parentheses = false -ij_c_space_before_method_left_brace = true -ij_c_space_before_method_parentheses = false -ij_c_space_before_namespace_lbrace = true -ij_c_space_before_pointer_in_declaration = true -ij_c_space_before_property_attributes_parentheses = false -ij_c_space_before_protocols_brackets = true -ij_c_space_before_quest = true -ij_c_space_before_reference_in_declaration = true -ij_c_space_before_superclass_colon = true -ij_c_space_before_switch_left_brace = true -ij_c_space_before_switch_parentheses = true -ij_c_space_before_template_call_lt = false -ij_c_space_before_template_declaration_lt = false -ij_c_space_before_try_left_brace = true -ij_c_space_before_while_keyword = true -ij_c_space_before_while_left_brace = true -ij_c_space_before_while_parentheses = true -ij_c_space_between_adjacent_brackets = false -ij_c_space_between_operator_and_punctuator = false -ij_c_space_within_empty_array_initializer_braces = false -ij_c_spaces_around_additive_operators = true -ij_c_spaces_around_assignment_operators = true -ij_c_spaces_around_bitwise_operators = true -ij_c_spaces_around_equality_operators = true -ij_c_spaces_around_lambda_arrow = true -ij_c_spaces_around_logical_operators = true -ij_c_spaces_around_multiplicative_operators = true -ij_c_spaces_around_pm_operators = false -ij_c_spaces_around_relational_operators = true -ij_c_spaces_around_shift_operators = true -ij_c_spaces_around_unary_operator = false -ij_c_spaces_within_array_initializer_braces = false -ij_c_spaces_within_braces = true -ij_c_spaces_within_brackets = false -ij_c_spaces_within_cast_parentheses = false -ij_c_spaces_within_catch_parentheses = false -ij_c_spaces_within_category_parentheses = false -ij_c_spaces_within_empty_braces = false -ij_c_spaces_within_empty_function_call_parentheses = false -ij_c_spaces_within_empty_function_declaration_parentheses = false -ij_c_spaces_within_empty_lambda_capture_list_bracket = false -ij_c_spaces_within_empty_template_call_ltgt = false -ij_c_spaces_within_empty_template_declaration_ltgt = false -ij_c_spaces_within_for_parentheses = false -ij_c_spaces_within_function_call_parentheses = false -ij_c_spaces_within_function_declaration_parentheses = false -ij_c_spaces_within_if_parentheses = false -ij_c_spaces_within_lambda_capture_list_bracket = false -ij_c_spaces_within_method_parameter_type_parentheses = false -ij_c_spaces_within_method_return_type_parentheses = false -ij_c_spaces_within_parentheses = false -ij_c_spaces_within_property_attributes_parentheses = false -ij_c_spaces_within_protocols_brackets = false -ij_c_spaces_within_send_message_brackets = false -ij_c_spaces_within_switch_parentheses = false -ij_c_spaces_within_template_call_ltgt = false -ij_c_spaces_within_template_declaration_ltgt = false -ij_c_spaces_within_template_double_gt = true -ij_c_spaces_within_while_parentheses = false -ij_c_special_else_if_treatment = true -ij_c_superclass_list_after_colon = never -ij_c_superclass_list_align_multiline = true -ij_c_superclass_list_before_colon = if_long -ij_c_superclass_list_comma_on_next_line = false -ij_c_superclass_list_wrap = on_every_item -ij_c_tag_prefix_of_block_comment = at -ij_c_tag_prefix_of_line_comment = back_slash -ij_c_template_call_arguments_align_multiline = false -ij_c_template_call_arguments_align_multiline_pars = false -ij_c_template_call_arguments_comma_on_next_line = false -ij_c_template_call_arguments_new_line_after_lt = false -ij_c_template_call_arguments_new_line_before_gt = false -ij_c_template_call_arguments_wrap = off -ij_c_template_declaration_function_body_indent = false -ij_c_template_declaration_function_wrap = split_into_lines -ij_c_template_declaration_struct_body_indent = false -ij_c_template_declaration_struct_wrap = split_into_lines -ij_c_template_parameters_align_multiline = false -ij_c_template_parameters_align_multiline_pars = false -ij_c_template_parameters_comma_on_next_line = false -ij_c_template_parameters_new_line_after_lt = false -ij_c_template_parameters_new_line_before_gt = false -ij_c_template_parameters_wrap = off -ij_c_ternary_operation_signs_on_next_line = true -ij_c_ternary_operation_wrap = normal -ij_c_type_qualifiers_placement = before -ij_c_use_modern_casts = true -ij_c_use_setters_in_constructor = true -ij_c_while_brace_force = never -ij_c_while_on_new_line = false -ij_c_wrap_property_declaration = off - -[{*.cmake,CMakeLists.txt}] -ij_cmake_align_multiline_parameters_in_calls = false -ij_cmake_force_commands_case = 2 -ij_cmake_keep_blank_lines_in_code = 2 -ij_cmake_space_before_for_parentheses = true -ij_cmake_space_before_if_parentheses = true -ij_cmake_space_before_method_call_parentheses = false -ij_cmake_space_before_method_parentheses = false -ij_cmake_space_before_while_parentheses = true -ij_cmake_spaces_within_for_parentheses = false -ij_cmake_spaces_within_if_parentheses = false -ij_cmake_spaces_within_method_call_parentheses = false -ij_cmake_spaces_within_method_parentheses = false -ij_cmake_spaces_within_while_parentheses = false - -[{*.gant,*.gradle,*.groovy,*.gy}] -ij_groovy_align_group_field_declarations = false -ij_groovy_align_multiline_array_initializer_expression = false -ij_groovy_align_multiline_assignment = false -ij_groovy_align_multiline_binary_operation = false -ij_groovy_align_multiline_chained_methods = false -ij_groovy_align_multiline_extends_list = false -ij_groovy_align_multiline_for = true -ij_groovy_align_multiline_list_or_map = true -ij_groovy_align_multiline_method_parentheses = false -ij_groovy_align_multiline_parameters = true -ij_groovy_align_multiline_parameters_in_calls = false -ij_groovy_align_multiline_resources = true -ij_groovy_align_multiline_ternary_operation = false -ij_groovy_align_multiline_throws_list = false -ij_groovy_align_named_args_in_map = true -ij_groovy_align_throws_keyword = false -ij_groovy_array_initializer_new_line_after_left_brace = false -ij_groovy_array_initializer_right_brace_on_new_line = false -ij_groovy_array_initializer_wrap = off -ij_groovy_assert_statement_wrap = off -ij_groovy_assignment_wrap = off -ij_groovy_binary_operation_wrap = off -ij_groovy_blank_lines_after_class_header = 0 -ij_groovy_blank_lines_after_imports = 1 -ij_groovy_blank_lines_after_package = 1 -ij_groovy_blank_lines_around_class = 1 -ij_groovy_blank_lines_around_field = 0 -ij_groovy_blank_lines_around_field_in_interface = 0 -ij_groovy_blank_lines_around_method = 1 -ij_groovy_blank_lines_around_method_in_interface = 1 -ij_groovy_blank_lines_before_imports = 1 -ij_groovy_blank_lines_before_method_body = 0 -ij_groovy_blank_lines_before_package = 0 -ij_groovy_block_brace_style = end_of_line -ij_groovy_block_comment_at_first_column = true -ij_groovy_call_parameters_new_line_after_left_paren = false -ij_groovy_call_parameters_right_paren_on_new_line = false -ij_groovy_call_parameters_wrap = off -ij_groovy_catch_on_new_line = false -ij_groovy_class_annotation_wrap = split_into_lines -ij_groovy_class_brace_style = end_of_line -ij_groovy_class_count_to_use_import_on_demand = 5 -ij_groovy_do_while_brace_force = never -ij_groovy_else_on_new_line = false -ij_groovy_enum_constants_wrap = off -ij_groovy_extends_keyword_wrap = off -ij_groovy_extends_list_wrap = off -ij_groovy_field_annotation_wrap = split_into_lines -ij_groovy_finally_on_new_line = false -ij_groovy_for_brace_force = never -ij_groovy_for_statement_new_line_after_left_paren = false -ij_groovy_for_statement_right_paren_on_new_line = false -ij_groovy_for_statement_wrap = off -ij_groovy_if_brace_force = never -ij_groovy_import_annotation_wrap = 2 -ij_groovy_imports_layout = *,|,javax.**,java.**,|,$* -ij_groovy_indent_case_from_switch = true -ij_groovy_indent_label_blocks = true -ij_groovy_insert_inner_class_imports = false -ij_groovy_keep_blank_lines_before_right_brace = 2 -ij_groovy_keep_blank_lines_in_code = 2 -ij_groovy_keep_blank_lines_in_declarations = 2 -ij_groovy_keep_control_statement_in_one_line = true -ij_groovy_keep_first_column_comment = true -ij_groovy_keep_indents_on_empty_lines = false -ij_groovy_keep_line_breaks = true -ij_groovy_keep_multiple_expressions_in_one_line = false -ij_groovy_keep_simple_blocks_in_one_line = false -ij_groovy_keep_simple_classes_in_one_line = true -ij_groovy_keep_simple_lambdas_in_one_line = true -ij_groovy_keep_simple_methods_in_one_line = true -ij_groovy_label_indent_absolute = false -ij_groovy_label_indent_size = 0 -ij_groovy_lambda_brace_style = end_of_line -ij_groovy_layout_static_imports_separately = true -ij_groovy_line_comment_add_space = false -ij_groovy_line_comment_at_first_column = true -ij_groovy_method_annotation_wrap = split_into_lines -ij_groovy_method_brace_style = end_of_line -ij_groovy_method_call_chain_wrap = off -ij_groovy_method_parameters_new_line_after_left_paren = false -ij_groovy_method_parameters_right_paren_on_new_line = false -ij_groovy_method_parameters_wrap = off -ij_groovy_modifier_list_wrap = false -ij_groovy_names_count_to_use_import_on_demand = 3 -ij_groovy_parameter_annotation_wrap = off -ij_groovy_parentheses_expression_new_line_after_left_paren = false -ij_groovy_parentheses_expression_right_paren_on_new_line = false -ij_groovy_prefer_parameters_wrap = false -ij_groovy_resource_list_new_line_after_left_paren = false -ij_groovy_resource_list_right_paren_on_new_line = false -ij_groovy_resource_list_wrap = off -ij_groovy_space_after_assert_separator = true -ij_groovy_space_after_colon = true -ij_groovy_space_after_comma = true -ij_groovy_space_after_comma_in_type_arguments = true -ij_groovy_space_after_for_semicolon = true -ij_groovy_space_after_quest = true -ij_groovy_space_after_type_cast = true -ij_groovy_space_before_annotation_parameter_list = false -ij_groovy_space_before_array_initializer_left_brace = false -ij_groovy_space_before_assert_separator = false -ij_groovy_space_before_catch_keyword = true -ij_groovy_space_before_catch_left_brace = true -ij_groovy_space_before_catch_parentheses = true -ij_groovy_space_before_class_left_brace = true -ij_groovy_space_before_closure_left_brace = true -ij_groovy_space_before_colon = true -ij_groovy_space_before_comma = false -ij_groovy_space_before_do_left_brace = true -ij_groovy_space_before_else_keyword = true -ij_groovy_space_before_else_left_brace = true -ij_groovy_space_before_finally_keyword = true -ij_groovy_space_before_finally_left_brace = true -ij_groovy_space_before_for_left_brace = true -ij_groovy_space_before_for_parentheses = true -ij_groovy_space_before_for_semicolon = false -ij_groovy_space_before_if_left_brace = true -ij_groovy_space_before_if_parentheses = true -ij_groovy_space_before_method_call_parentheses = false -ij_groovy_space_before_method_left_brace = true -ij_groovy_space_before_method_parentheses = false -ij_groovy_space_before_quest = true -ij_groovy_space_before_switch_left_brace = true -ij_groovy_space_before_switch_parentheses = true -ij_groovy_space_before_synchronized_left_brace = true -ij_groovy_space_before_synchronized_parentheses = true -ij_groovy_space_before_try_left_brace = true -ij_groovy_space_before_try_parentheses = true -ij_groovy_space_before_while_keyword = true -ij_groovy_space_before_while_left_brace = true -ij_groovy_space_before_while_parentheses = true -ij_groovy_space_in_named_argument = true -ij_groovy_space_in_named_argument_before_colon = false -ij_groovy_space_within_empty_array_initializer_braces = false -ij_groovy_space_within_empty_method_call_parentheses = false -ij_groovy_spaces_around_additive_operators = true -ij_groovy_spaces_around_assignment_operators = true -ij_groovy_spaces_around_bitwise_operators = true -ij_groovy_spaces_around_equality_operators = true -ij_groovy_spaces_around_lambda_arrow = true -ij_groovy_spaces_around_logical_operators = true -ij_groovy_spaces_around_multiplicative_operators = true -ij_groovy_spaces_around_regex_operators = true -ij_groovy_spaces_around_relational_operators = true -ij_groovy_spaces_around_shift_operators = true -ij_groovy_spaces_within_annotation_parentheses = false -ij_groovy_spaces_within_array_initializer_braces = false -ij_groovy_spaces_within_braces = true -ij_groovy_spaces_within_brackets = false -ij_groovy_spaces_within_cast_parentheses = false -ij_groovy_spaces_within_catch_parentheses = false -ij_groovy_spaces_within_for_parentheses = false -ij_groovy_spaces_within_gstring_injection_braces = false -ij_groovy_spaces_within_if_parentheses = false -ij_groovy_spaces_within_list_or_map = false -ij_groovy_spaces_within_method_call_parentheses = false -ij_groovy_spaces_within_method_parentheses = false -ij_groovy_spaces_within_parentheses = false -ij_groovy_spaces_within_switch_parentheses = false -ij_groovy_spaces_within_synchronized_parentheses = false -ij_groovy_spaces_within_try_parentheses = false -ij_groovy_spaces_within_tuple_expression = false -ij_groovy_spaces_within_while_parentheses = false -ij_groovy_special_else_if_treatment = true -ij_groovy_ternary_operation_wrap = off -ij_groovy_throws_keyword_wrap = off -ij_groovy_throws_list_wrap = off -ij_groovy_use_flying_geese_braces = false -ij_groovy_use_fq_class_names = false -ij_groovy_use_fq_class_names_in_javadoc = true -ij_groovy_use_relative_indents = false -ij_groovy_use_single_class_imports = true -ij_groovy_variable_annotation_wrap = off -ij_groovy_while_brace_force = never -ij_groovy_while_on_new_line = false -ij_groovy_wrap_long_lines = false - -[{*.gradle.kts,*.kt,*.kts,*.main.kts}] -ij_kotlin_align_in_columns_case_branch = true -ij_kotlin_align_multiline_binary_operation = false -ij_kotlin_align_multiline_extends_list = false -ij_kotlin_align_multiline_method_parentheses = false -ij_kotlin_align_multiline_parameters = true -ij_kotlin_align_multiline_parameters_in_calls = false -ij_kotlin_allow_trailing_comma = false -ij_kotlin_allow_trailing_comma_on_call_site = false -ij_kotlin_assignment_wrap = off -ij_kotlin_blank_lines_after_class_header = 0 -ij_kotlin_blank_lines_around_block_when_branches = 0 -ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1 -ij_kotlin_block_comment_at_first_column = true -ij_kotlin_call_parameters_new_line_after_left_paren = false -ij_kotlin_call_parameters_right_paren_on_new_line = false -ij_kotlin_call_parameters_wrap = off -ij_kotlin_catch_on_new_line = false -ij_kotlin_class_annotation_wrap = off -ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL -ij_kotlin_continuation_indent_for_chained_calls = true -ij_kotlin_continuation_indent_for_expression_bodies = true -ij_kotlin_continuation_indent_in_argument_lists = true -ij_kotlin_continuation_indent_in_elvis = true -ij_kotlin_continuation_indent_in_if_conditions = true -ij_kotlin_continuation_indent_in_parameter_lists = true -ij_kotlin_continuation_indent_in_supertype_lists = true -ij_kotlin_else_on_new_line = false -ij_kotlin_enum_constants_wrap = off -ij_kotlin_extends_list_wrap = off -ij_kotlin_field_annotation_wrap = normal -ij_kotlin_finally_on_new_line = false -ij_kotlin_if_rparen_on_new_line = false -ij_kotlin_import_nested_classes = false -ij_kotlin_imports_layout = *,java.**,javax.**,kotlin.**,^ -ij_kotlin_insert_whitespaces_in_simple_one_line_method = true -ij_kotlin_keep_blank_lines_before_right_brace = 0 -ij_kotlin_keep_blank_lines_in_code = 1 -ij_kotlin_keep_blank_lines_in_declarations = 1 -ij_kotlin_keep_first_column_comment = true -ij_kotlin_keep_indents_on_empty_lines = false -ij_kotlin_keep_line_breaks = true -ij_kotlin_lbrace_on_next_line = false -ij_kotlin_line_comment_add_space = false -ij_kotlin_line_comment_at_first_column = true -ij_kotlin_method_annotation_wrap = split_into_lines -ij_kotlin_method_call_chain_wrap = off -ij_kotlin_method_parameters_new_line_after_left_paren = false -ij_kotlin_method_parameters_right_paren_on_new_line = false -ij_kotlin_method_parameters_wrap = off -ij_kotlin_name_count_to_use_star_import = 2147483647 -ij_kotlin_name_count_to_use_star_import_for_members = 2147483647 -ij_kotlin_packages_to_use_import_on_demand = kotlinx.android.synthetic.** -ij_kotlin_parameter_annotation_wrap = off -ij_kotlin_space_after_comma = true -ij_kotlin_space_after_extend_colon = true -ij_kotlin_space_after_type_colon = true -ij_kotlin_space_before_catch_parentheses = true -ij_kotlin_space_before_comma = false -ij_kotlin_space_before_extend_colon = true -ij_kotlin_space_before_for_parentheses = true -ij_kotlin_space_before_if_parentheses = true -ij_kotlin_space_before_lambda_arrow = true -ij_kotlin_space_before_type_colon = false -ij_kotlin_space_before_when_parentheses = true -ij_kotlin_space_before_while_parentheses = true -ij_kotlin_spaces_around_additive_operators = true -ij_kotlin_spaces_around_assignment_operators = true -ij_kotlin_spaces_around_equality_operators = true -ij_kotlin_spaces_around_function_type_arrow = true -ij_kotlin_spaces_around_logical_operators = true -ij_kotlin_spaces_around_multiplicative_operators = true -ij_kotlin_spaces_around_range = false -ij_kotlin_spaces_around_relational_operators = true -ij_kotlin_spaces_around_unary_operator = false -ij_kotlin_spaces_around_when_arrow = true -ij_kotlin_use_custom_formatting_for_modifiers = true -ij_kotlin_variable_annotation_wrap = off -ij_kotlin_while_on_new_line = false -ij_kotlin_wrap_elvis_expressions = 1 -ij_kotlin_wrap_expression_body_functions = 0 -ij_kotlin_wrap_first_method_in_call_chain = false - -[{*.har,*.json}] -indent_size = 2 -ij_json_keep_blank_lines_in_code = 0 -ij_json_keep_indents_on_empty_lines = false -ij_json_keep_line_breaks = true -ij_json_space_after_colon = true -ij_json_space_after_comma = true -ij_json_space_before_colon = true -ij_json_space_before_comma = false -ij_json_spaces_within_braces = false -ij_json_spaces_within_brackets = false -ij_json_wrap_long_lines = false - -[{*.htm,*.html,*.sht,*.shtm,*.shtml}] -ij_html_add_new_line_before_tags = body,div,p,form,h1,h2,h3 -ij_html_align_attributes = true -ij_html_align_text = false -ij_html_attribute_wrap = normal -ij_html_block_comment_at_first_column = true -ij_html_do_not_align_children_of_min_lines = 0 -ij_html_do_not_break_if_inline_tags = title,h1,h2,h3,h4,h5,h6,p -ij_html_do_not_indent_children_of_tags = html,body,thead,tbody,tfoot -ij_html_enforce_quotes = false -ij_html_inline_tags = a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var -ij_html_keep_blank_lines = 2 -ij_html_keep_indents_on_empty_lines = false -ij_html_keep_line_breaks = true -ij_html_keep_line_breaks_in_text = true -ij_html_keep_whitespaces = false -ij_html_keep_whitespaces_inside = span,pre,textarea -ij_html_line_comment_at_first_column = true -ij_html_new_line_after_last_attribute = never -ij_html_new_line_before_first_attribute = never -ij_html_quote_style = double -ij_html_remove_new_line_before_tags = br -ij_html_space_after_tag_name = false -ij_html_space_around_equality_in_attribute = false -ij_html_space_inside_empty_tag = false -ij_html_text_wrap = normal -ij_html_uniform_ident = false - -[{*.yaml,*.yml}] -indent_size = 2 -ij_yaml_align_values_properties = do_not_align -ij_yaml_autoinsert_sequence_marker = true -ij_yaml_block_mapping_on_new_line = false -ij_yaml_indent_sequence_value = true -ij_yaml_keep_indents_on_empty_lines = false -ij_yaml_keep_line_breaks = true -ij_yaml_sequence_on_new_line = false -ij_yaml_space_before_colon = false -ij_yaml_spaces_within_braces = true -ij_yaml_spaces_within_brackets = true +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 160 +tab_width = 4 +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = false +ij_smart_tabs = false +ij_visual_guides = none +ij_wrap_on_typing = false + +[*.java] +ij_java_align_consecutive_assignments = false +ij_java_align_consecutive_variable_declarations = false +ij_java_align_group_field_declarations = false +ij_java_align_multiline_annotation_parameters = false +ij_java_align_multiline_array_initializer_expression = false +ij_java_align_multiline_assignment = false +ij_java_align_multiline_binary_operation = false +ij_java_align_multiline_chained_methods = false +ij_java_align_multiline_extends_list = false +ij_java_align_multiline_for = true +ij_java_align_multiline_method_parentheses = false +ij_java_align_multiline_parameters = true +ij_java_align_multiline_parameters_in_calls = false +ij_java_align_multiline_parenthesized_expression = false +ij_java_align_multiline_records = true +ij_java_align_multiline_resources = true +ij_java_align_multiline_ternary_operation = false +ij_java_align_multiline_text_blocks = false +ij_java_align_multiline_throws_list = false +ij_java_align_subsequent_simple_methods = false +ij_java_align_throws_keyword = false +ij_java_annotation_parameter_wrap = off +ij_java_array_initializer_new_line_after_left_brace = false +ij_java_array_initializer_right_brace_on_new_line = false +ij_java_array_initializer_wrap = off +ij_java_assert_statement_colon_on_next_line = false +ij_java_assert_statement_wrap = off +ij_java_assignment_wrap = off +ij_java_binary_operation_sign_on_next_line = false +ij_java_binary_operation_wrap = off +ij_java_blank_lines_after_anonymous_class_header = 0 +ij_java_blank_lines_after_class_header = 0 +ij_java_blank_lines_after_imports = 1 +ij_java_blank_lines_after_package = 1 +ij_java_blank_lines_around_class = 1 +ij_java_blank_lines_around_field = 0 +ij_java_blank_lines_around_field_in_interface = 0 +ij_java_blank_lines_around_initializer = 1 +ij_java_blank_lines_around_method = 1 +ij_java_blank_lines_around_method_in_interface = 1 +ij_java_blank_lines_before_class_end = 0 +ij_java_blank_lines_before_imports = 1 +ij_java_blank_lines_before_method_body = 0 +ij_java_blank_lines_before_package = 0 +ij_java_block_brace_style = end_of_line +ij_java_block_comment_at_first_column = true +ij_java_builder_methods = none +ij_java_call_parameters_new_line_after_left_paren = false +ij_java_call_parameters_right_paren_on_new_line = false +ij_java_call_parameters_wrap = off +ij_java_case_statement_on_separate_line = true +ij_java_catch_on_new_line = false +ij_java_class_annotation_wrap = split_into_lines +ij_java_class_brace_style = end_of_line +ij_java_class_count_to_use_import_on_demand = 99 +ij_java_class_names_in_javadoc = 1 +ij_java_do_not_indent_top_level_class_members = false +ij_java_do_not_wrap_after_single_annotation = false +ij_java_do_while_brace_force = never +ij_java_doc_add_blank_line_after_description = true +ij_java_doc_add_blank_line_after_param_comments = false +ij_java_doc_add_blank_line_after_return = false +ij_java_doc_add_p_tag_on_empty_lines = true +ij_java_doc_align_exception_comments = true +ij_java_doc_align_param_comments = true +ij_java_doc_do_not_wrap_if_one_line = false +ij_java_doc_enable_formatting = true +ij_java_doc_enable_leading_asterisks = true +ij_java_doc_indent_on_continuation = false +ij_java_doc_keep_empty_lines = true +ij_java_doc_keep_empty_parameter_tag = true +ij_java_doc_keep_empty_return_tag = true +ij_java_doc_keep_empty_throws_tag = true +ij_java_doc_keep_invalid_tags = true +ij_java_doc_param_description_on_new_line = false +ij_java_doc_preserve_line_breaks = false +ij_java_doc_use_throws_not_exception_tag = true +ij_java_else_on_new_line = false +ij_java_enum_constants_wrap = off +ij_java_extends_keyword_wrap = off +ij_java_extends_list_wrap = off +ij_java_field_annotation_wrap = split_into_lines +ij_java_finally_on_new_line = false +ij_java_for_brace_force = never +ij_java_for_statement_new_line_after_left_paren = false +ij_java_for_statement_right_paren_on_new_line = false +ij_java_for_statement_wrap = off +ij_java_generate_final_locals = false +ij_java_generate_final_parameters = false +ij_java_if_brace_force = never +ij_java_imports_layout = $android.**,$androidx.**,$com.**,$junit.**,$net.**,$org.**,$java.**,$javax.**,$*,|,android.**,|,androidx.**,|,com.**,|,junit.**,|,net.**,|,org.**,|,java.**,|,javax.**,|,*,| +ij_java_indent_case_from_switch = true +ij_java_insert_inner_class_imports = false +ij_java_insert_override_annotation = true +ij_java_keep_blank_lines_before_right_brace = 2 +ij_java_keep_blank_lines_between_package_declaration_and_header = 2 +ij_java_keep_blank_lines_in_code = 2 +ij_java_keep_blank_lines_in_declarations = 2 +ij_java_keep_builder_methods_indents = false +ij_java_keep_control_statement_in_one_line = true +ij_java_keep_first_column_comment = true +ij_java_keep_indents_on_empty_lines = false +ij_java_keep_line_breaks = true +ij_java_keep_multiple_expressions_in_one_line = false +ij_java_keep_simple_blocks_in_one_line = false +ij_java_keep_simple_classes_in_one_line = false +ij_java_keep_simple_lambdas_in_one_line = false +ij_java_keep_simple_methods_in_one_line = false +ij_java_label_indent_absolute = false +ij_java_label_indent_size = 0 +ij_java_lambda_brace_style = end_of_line +ij_java_layout_static_imports_separately = true +ij_java_line_comment_add_space = false +ij_java_line_comment_at_first_column = true +ij_java_method_annotation_wrap = split_into_lines +ij_java_method_brace_style = end_of_line +ij_java_method_call_chain_wrap = off +ij_java_method_parameters_new_line_after_left_paren = false +ij_java_method_parameters_right_paren_on_new_line = false +ij_java_method_parameters_wrap = off +ij_java_modifier_list_wrap = false +ij_java_names_count_to_use_import_on_demand = 99 +ij_java_new_line_after_lparen_in_record_header = false +ij_java_parameter_annotation_wrap = off +ij_java_parentheses_expression_new_line_after_left_paren = false +ij_java_parentheses_expression_right_paren_on_new_line = false +ij_java_place_assignment_sign_on_next_line = false +ij_java_prefer_longer_names = true +ij_java_prefer_parameters_wrap = false +ij_java_record_components_wrap = normal +ij_java_repeat_synchronized = true +ij_java_replace_instanceof_and_cast = false +ij_java_replace_null_check = true +ij_java_replace_sum_lambda_with_method_ref = true +ij_java_resource_list_new_line_after_left_paren = false +ij_java_resource_list_right_paren_on_new_line = false +ij_java_resource_list_wrap = off +ij_java_rparen_on_new_line_in_record_header = false +ij_java_space_after_closing_angle_bracket_in_type_argument = false +ij_java_space_after_colon = true +ij_java_space_after_comma = true +ij_java_space_after_comma_in_type_arguments = true +ij_java_space_after_for_semicolon = true +ij_java_space_after_quest = true +ij_java_space_after_type_cast = true +ij_java_space_before_annotation_array_initializer_left_brace = false +ij_java_space_before_annotation_parameter_list = false +ij_java_space_before_array_initializer_left_brace = false +ij_java_space_before_catch_keyword = true +ij_java_space_before_catch_left_brace = true +ij_java_space_before_catch_parentheses = true +ij_java_space_before_class_left_brace = true +ij_java_space_before_colon = true +ij_java_space_before_colon_in_foreach = true +ij_java_space_before_comma = false +ij_java_space_before_do_left_brace = true +ij_java_space_before_else_keyword = true +ij_java_space_before_else_left_brace = true +ij_java_space_before_finally_keyword = true +ij_java_space_before_finally_left_brace = true +ij_java_space_before_for_left_brace = true +ij_java_space_before_for_parentheses = true +ij_java_space_before_for_semicolon = false +ij_java_space_before_if_left_brace = true +ij_java_space_before_if_parentheses = true +ij_java_space_before_method_call_parentheses = false +ij_java_space_before_method_left_brace = true +ij_java_space_before_method_parentheses = false +ij_java_space_before_opening_angle_bracket_in_type_parameter = false +ij_java_space_before_quest = true +ij_java_space_before_switch_left_brace = true +ij_java_space_before_switch_parentheses = true +ij_java_space_before_synchronized_left_brace = true +ij_java_space_before_synchronized_parentheses = true +ij_java_space_before_try_left_brace = true +ij_java_space_before_try_parentheses = true +ij_java_space_before_type_parameter_list = false +ij_java_space_before_while_keyword = true +ij_java_space_before_while_left_brace = true +ij_java_space_before_while_parentheses = true +ij_java_space_inside_one_line_enum_braces = false +ij_java_space_within_empty_array_initializer_braces = false +ij_java_space_within_empty_method_call_parentheses = false +ij_java_space_within_empty_method_parentheses = false +ij_java_spaces_around_additive_operators = true +ij_java_spaces_around_assignment_operators = true +ij_java_spaces_around_bitwise_operators = true +ij_java_spaces_around_equality_operators = true +ij_java_spaces_around_lambda_arrow = true +ij_java_spaces_around_logical_operators = true +ij_java_spaces_around_method_ref_dbl_colon = false +ij_java_spaces_around_multiplicative_operators = true +ij_java_spaces_around_relational_operators = true +ij_java_spaces_around_shift_operators = true +ij_java_spaces_around_type_bounds_in_type_parameters = true +ij_java_spaces_around_unary_operator = false +ij_java_spaces_within_angle_brackets = false +ij_java_spaces_within_annotation_parentheses = false +ij_java_spaces_within_array_initializer_braces = false +ij_java_spaces_within_braces = false +ij_java_spaces_within_brackets = false +ij_java_spaces_within_cast_parentheses = false +ij_java_spaces_within_catch_parentheses = false +ij_java_spaces_within_for_parentheses = false +ij_java_spaces_within_if_parentheses = false +ij_java_spaces_within_method_call_parentheses = false +ij_java_spaces_within_method_parentheses = false +ij_java_spaces_within_parentheses = false +ij_java_spaces_within_record_header = false +ij_java_spaces_within_switch_parentheses = false +ij_java_spaces_within_synchronized_parentheses = false +ij_java_spaces_within_try_parentheses = false +ij_java_spaces_within_while_parentheses = false +ij_java_special_else_if_treatment = true +ij_java_subclass_name_suffix = Impl +ij_java_ternary_operation_signs_on_next_line = false +ij_java_ternary_operation_wrap = off +ij_java_test_name_suffix = Test +ij_java_throws_keyword_wrap = off +ij_java_throws_list_wrap = off +ij_java_use_external_annotations = false +ij_java_use_fq_class_names = false +ij_java_use_relative_indents = false +ij_java_use_single_class_imports = true +ij_java_variable_annotation_wrap = off +ij_java_visibility = public +ij_java_while_brace_force = never +ij_java_while_on_new_line = false +ij_java_wrap_comments = false +ij_java_wrap_first_method_in_call_chain = false +ij_java_wrap_long_lines = false + +[*.properties] +ij_properties_align_group_field_declarations = false +ij_properties_keep_blank_lines = false +ij_properties_key_value_delimiter = equals +ij_properties_spaces_around_key_value_delimiter = false + +[.editorconfig] +ij_editorconfig_align_group_field_declarations = false +ij_editorconfig_space_after_colon = false +ij_editorconfig_space_after_comma = true +ij_editorconfig_space_before_colon = false +ij_editorconfig_space_before_comma = false +ij_editorconfig_spaces_around_assignment_operators = true + +[{*.ant,*.fxml,*.jhm,*.jnlp,*.jrxml,*.rng,*.tld,*.wsdl,*.xml,*.xsd,*.xsl,*.xslt,*.xul}] +ij_continuation_indent_size = 4 +ij_xml_align_attributes = false +ij_xml_align_text = false +ij_xml_attribute_wrap = normal +ij_xml_block_comment_at_first_column = true +ij_xml_keep_blank_lines = 2 +ij_xml_keep_indents_on_empty_lines = false +ij_xml_keep_line_breaks = false +ij_xml_keep_line_breaks_in_text = true +ij_xml_keep_whitespaces = false +ij_xml_keep_whitespaces_around_cdata = preserve +ij_xml_keep_whitespaces_inside_cdata = false +ij_xml_line_comment_at_first_column = true +ij_xml_space_after_tag_name = false +ij_xml_space_around_equals_in_attribute = false +ij_xml_space_inside_empty_tag = true +ij_xml_text_wrap = normal +ij_xml_use_custom_settings = true + +[{*.bash,*.sh,*.zsh}] +indent_size = 2 +tab_width = 2 +ij_shell_binary_ops_start_line = false +ij_shell_keep_column_alignment_padding = false +ij_shell_minify_program = false +ij_shell_redirect_followed_by_space = false +ij_shell_switch_cases_indented = false +ij_shell_use_unix_line_separator = true + +[{*.c,*.c++,*.cc,*.cp,*.cpp,*.cu,*.cuh,*.cxx,*.h,*.h++,*.hh,*.hp,*.hpp,*.hxx,*.i,*.icc,*.ii,*.inl,*.ino,*.ipp,*.m,*.mm,*.pch,*.tcc,*.tpp}] +ij_c_add_brief_tag = false +ij_c_add_getter_prefix = true +ij_c_add_setter_prefix = true +ij_c_align_dictionary_pair_values = false +ij_c_align_group_field_declarations = false +ij_c_align_init_list_in_columns = true +ij_c_align_multiline_array_initializer_expression = true +ij_c_align_multiline_assignment = true +ij_c_align_multiline_binary_operation = true +ij_c_align_multiline_chained_methods = false +ij_c_align_multiline_for = true +ij_c_align_multiline_ternary_operation = true +ij_c_array_initializer_comma_on_next_line = false +ij_c_array_initializer_new_line_after_left_brace = false +ij_c_array_initializer_right_brace_on_new_line = false +ij_c_array_initializer_wrap = normal +ij_c_assignment_wrap = off +ij_c_binary_operation_sign_on_next_line = false +ij_c_binary_operation_wrap = normal +ij_c_blank_lines_after_class_header = 0 +ij_c_blank_lines_after_imports = 1 +ij_c_blank_lines_around_class = 1 +ij_c_blank_lines_around_field = 0 +ij_c_blank_lines_around_field_in_interface = 0 +ij_c_blank_lines_around_method = 1 +ij_c_blank_lines_around_method_in_interface = 1 +ij_c_blank_lines_around_namespace = 0 +ij_c_blank_lines_around_properties_in_declaration = 0 +ij_c_blank_lines_around_properties_in_interface = 0 +ij_c_blank_lines_before_imports = 1 +ij_c_blank_lines_before_method_body = 0 +ij_c_block_brace_placement = end_of_line +ij_c_block_brace_style = end_of_line +ij_c_block_comment_at_first_column = true +ij_c_catch_on_new_line = false +ij_c_class_brace_style = end_of_line +ij_c_class_constructor_init_list_align_multiline = true +ij_c_class_constructor_init_list_comma_on_next_line = false +ij_c_class_constructor_init_list_new_line_after_colon = never +ij_c_class_constructor_init_list_new_line_before_colon = if_long +ij_c_class_constructor_init_list_wrap = normal +ij_c_copy_is_deep = false +ij_c_create_interface_for_categories = true +ij_c_declare_generated_methods = true +ij_c_description_include_member_names = true +ij_c_discharged_short_ternary_operator = false +ij_c_do_not_add_breaks = false +ij_c_do_while_brace_force = never +ij_c_else_on_new_line = false +ij_c_enum_constants_comma_on_next_line = false +ij_c_enum_constants_wrap = on_every_item +ij_c_for_brace_force = never +ij_c_for_statement_new_line_after_left_paren = false +ij_c_for_statement_right_paren_on_new_line = false +ij_c_for_statement_wrap = off +ij_c_function_brace_placement = end_of_line +ij_c_function_call_arguments_align_multiline = true +ij_c_function_call_arguments_align_multiline_pars = false +ij_c_function_call_arguments_comma_on_next_line = false +ij_c_function_call_arguments_new_line_after_lpar = false +ij_c_function_call_arguments_new_line_before_rpar = false +ij_c_function_call_arguments_wrap = normal +ij_c_function_non_top_after_return_type_wrap = normal +ij_c_function_parameters_align_multiline = true +ij_c_function_parameters_align_multiline_pars = false +ij_c_function_parameters_comma_on_next_line = false +ij_c_function_parameters_new_line_after_lpar = false +ij_c_function_parameters_new_line_before_rpar = false +ij_c_function_parameters_wrap = normal +ij_c_function_top_after_return_type_wrap = normal +ij_c_generate_additional_eq_operators = true +ij_c_generate_additional_rel_operators = true +ij_c_generate_class_constructor = true +ij_c_generate_comparison_operators_use_std_tie = false +ij_c_generate_instance_variables_for_properties = ask +ij_c_generate_operators_as_members = true +ij_c_header_guard_style_pattern = ${PROJECT_NAME}_${FILE_NAME}_${EXT} +ij_c_if_brace_force = never +ij_c_in_line_short_ternary_operator = true +ij_c_indent_block_comment = true +ij_c_indent_c_struct_members = 4 +ij_c_indent_case_from_switch = true +ij_c_indent_class_members = 4 +ij_c_indent_directive_as_code = false +ij_c_indent_implementation_members = 0 +ij_c_indent_inside_code_block = 4 +ij_c_indent_interface_members = 0 +ij_c_indent_interface_members_except_ivars_block = false +ij_c_indent_namespace_members = 4 +ij_c_indent_preprocessor_directive = 0 +ij_c_indent_visibility_keywords = 0 +ij_c_insert_override = true +ij_c_insert_virtual_with_override = false +ij_c_introduce_auto_vars = false +ij_c_introduce_const_params = false +ij_c_introduce_const_vars = false +ij_c_introduce_generate_property = false +ij_c_introduce_generate_synthesize = true +ij_c_introduce_globals_to_header = true +ij_c_introduce_prop_to_private_category = false +ij_c_introduce_static_consts = true +ij_c_introduce_use_ns_types = false +ij_c_ivars_prefix = _ +ij_c_keep_blank_lines_before_end = 2 +ij_c_keep_blank_lines_before_right_brace = 2 +ij_c_keep_blank_lines_in_code = 2 +ij_c_keep_blank_lines_in_declarations = 2 +ij_c_keep_case_expressions_in_one_line = false +ij_c_keep_control_statement_in_one_line = true +ij_c_keep_directive_at_first_column = true +ij_c_keep_first_column_comment = true +ij_c_keep_line_breaks = true +ij_c_keep_nested_namespaces_in_one_line = false +ij_c_keep_simple_blocks_in_one_line = true +ij_c_keep_simple_methods_in_one_line = true +ij_c_keep_structures_in_one_line = false +ij_c_lambda_capture_list_align_multiline = false +ij_c_lambda_capture_list_align_multiline_bracket = false +ij_c_lambda_capture_list_comma_on_next_line = false +ij_c_lambda_capture_list_new_line_after_lbracket = false +ij_c_lambda_capture_list_new_line_before_rbracket = false +ij_c_lambda_capture_list_wrap = off +ij_c_line_comment_add_space = false +ij_c_line_comment_at_first_column = true +ij_c_method_brace_placement = end_of_line +ij_c_method_call_arguments_align_by_colons = true +ij_c_method_call_arguments_align_multiline = false +ij_c_method_call_arguments_special_dictionary_pairs_treatment = true +ij_c_method_call_arguments_wrap = off +ij_c_method_call_chain_wrap = off +ij_c_method_parameters_align_by_colons = true +ij_c_method_parameters_align_multiline = false +ij_c_method_parameters_wrap = off +ij_c_namespace_brace_placement = end_of_line +ij_c_parentheses_expression_new_line_after_left_paren = false +ij_c_parentheses_expression_right_paren_on_new_line = false +ij_c_place_assignment_sign_on_next_line = false +ij_c_property_nonatomic = true +ij_c_put_ivars_to_implementation = true +ij_c_refactor_compatibility_aliases_and_classes = true +ij_c_refactor_properties_and_ivars = true +ij_c_release_style = ivar +ij_c_retain_object_parameters_in_constructor = true +ij_c_semicolon_after_method_signature = false +ij_c_shift_operation_align_multiline = true +ij_c_shift_operation_wrap = normal +ij_c_show_non_virtual_functions = false +ij_c_space_after_colon = true +ij_c_space_after_colon_in_selector = false +ij_c_space_after_comma = true +ij_c_space_after_cup_in_blocks = false +ij_c_space_after_dictionary_literal_colon = true +ij_c_space_after_for_semicolon = true +ij_c_space_after_init_list_colon = true +ij_c_space_after_method_parameter_type_parentheses = false +ij_c_space_after_method_return_type_parentheses = false +ij_c_space_after_pointer_in_declaration = false +ij_c_space_after_quest = true +ij_c_space_after_reference_in_declaration = false +ij_c_space_after_reference_in_rvalue = false +ij_c_space_after_structures_rbrace = true +ij_c_space_after_superclass_colon = true +ij_c_space_after_type_cast = true +ij_c_space_after_visibility_sign_in_method_declaration = true +ij_c_space_before_autorelease_pool_lbrace = true +ij_c_space_before_catch_keyword = true +ij_c_space_before_catch_left_brace = true +ij_c_space_before_catch_parentheses = true +ij_c_space_before_category_parentheses = true +ij_c_space_before_chained_send_message = true +ij_c_space_before_class_left_brace = true +ij_c_space_before_colon = true +ij_c_space_before_comma = false +ij_c_space_before_dictionary_literal_colon = false +ij_c_space_before_do_left_brace = true +ij_c_space_before_else_keyword = true +ij_c_space_before_else_left_brace = true +ij_c_space_before_for_left_brace = true +ij_c_space_before_for_parentheses = true +ij_c_space_before_for_semicolon = false +ij_c_space_before_if_left_brace = true +ij_c_space_before_if_parentheses = true +ij_c_space_before_init_list = false +ij_c_space_before_init_list_colon = true +ij_c_space_before_method_call_parentheses = false +ij_c_space_before_method_left_brace = true +ij_c_space_before_method_parentheses = false +ij_c_space_before_namespace_lbrace = true +ij_c_space_before_pointer_in_declaration = true +ij_c_space_before_property_attributes_parentheses = false +ij_c_space_before_protocols_brackets = true +ij_c_space_before_quest = true +ij_c_space_before_reference_in_declaration = true +ij_c_space_before_superclass_colon = true +ij_c_space_before_switch_left_brace = true +ij_c_space_before_switch_parentheses = true +ij_c_space_before_template_call_lt = false +ij_c_space_before_template_declaration_lt = false +ij_c_space_before_try_left_brace = true +ij_c_space_before_while_keyword = true +ij_c_space_before_while_left_brace = true +ij_c_space_before_while_parentheses = true +ij_c_space_between_adjacent_brackets = false +ij_c_space_between_operator_and_punctuator = false +ij_c_space_within_empty_array_initializer_braces = false +ij_c_spaces_around_additive_operators = true +ij_c_spaces_around_assignment_operators = true +ij_c_spaces_around_bitwise_operators = true +ij_c_spaces_around_equality_operators = true +ij_c_spaces_around_lambda_arrow = true +ij_c_spaces_around_logical_operators = true +ij_c_spaces_around_multiplicative_operators = true +ij_c_spaces_around_pm_operators = false +ij_c_spaces_around_relational_operators = true +ij_c_spaces_around_shift_operators = true +ij_c_spaces_around_unary_operator = false +ij_c_spaces_within_array_initializer_braces = false +ij_c_spaces_within_braces = true +ij_c_spaces_within_brackets = false +ij_c_spaces_within_cast_parentheses = false +ij_c_spaces_within_catch_parentheses = false +ij_c_spaces_within_category_parentheses = false +ij_c_spaces_within_empty_braces = false +ij_c_spaces_within_empty_function_call_parentheses = false +ij_c_spaces_within_empty_function_declaration_parentheses = false +ij_c_spaces_within_empty_lambda_capture_list_bracket = false +ij_c_spaces_within_empty_template_call_ltgt = false +ij_c_spaces_within_empty_template_declaration_ltgt = false +ij_c_spaces_within_for_parentheses = false +ij_c_spaces_within_function_call_parentheses = false +ij_c_spaces_within_function_declaration_parentheses = false +ij_c_spaces_within_if_parentheses = false +ij_c_spaces_within_lambda_capture_list_bracket = false +ij_c_spaces_within_method_parameter_type_parentheses = false +ij_c_spaces_within_method_return_type_parentheses = false +ij_c_spaces_within_parentheses = false +ij_c_spaces_within_property_attributes_parentheses = false +ij_c_spaces_within_protocols_brackets = false +ij_c_spaces_within_send_message_brackets = false +ij_c_spaces_within_switch_parentheses = false +ij_c_spaces_within_template_call_ltgt = false +ij_c_spaces_within_template_declaration_ltgt = false +ij_c_spaces_within_template_double_gt = true +ij_c_spaces_within_while_parentheses = false +ij_c_special_else_if_treatment = true +ij_c_superclass_list_after_colon = never +ij_c_superclass_list_align_multiline = true +ij_c_superclass_list_before_colon = if_long +ij_c_superclass_list_comma_on_next_line = false +ij_c_superclass_list_wrap = on_every_item +ij_c_tag_prefix_of_block_comment = at +ij_c_tag_prefix_of_line_comment = back_slash +ij_c_template_call_arguments_align_multiline = false +ij_c_template_call_arguments_align_multiline_pars = false +ij_c_template_call_arguments_comma_on_next_line = false +ij_c_template_call_arguments_new_line_after_lt = false +ij_c_template_call_arguments_new_line_before_gt = false +ij_c_template_call_arguments_wrap = off +ij_c_template_declaration_function_body_indent = false +ij_c_template_declaration_function_wrap = split_into_lines +ij_c_template_declaration_struct_body_indent = false +ij_c_template_declaration_struct_wrap = split_into_lines +ij_c_template_parameters_align_multiline = false +ij_c_template_parameters_align_multiline_pars = false +ij_c_template_parameters_comma_on_next_line = false +ij_c_template_parameters_new_line_after_lt = false +ij_c_template_parameters_new_line_before_gt = false +ij_c_template_parameters_wrap = off +ij_c_ternary_operation_signs_on_next_line = true +ij_c_ternary_operation_wrap = normal +ij_c_type_qualifiers_placement = before +ij_c_use_modern_casts = true +ij_c_use_setters_in_constructor = true +ij_c_while_brace_force = never +ij_c_while_on_new_line = false +ij_c_wrap_property_declaration = off + +[{*.cmake,CMakeLists.txt}] +ij_cmake_align_multiline_parameters_in_calls = false +ij_cmake_force_commands_case = 2 +ij_cmake_keep_blank_lines_in_code = 2 +ij_cmake_space_before_for_parentheses = true +ij_cmake_space_before_if_parentheses = true +ij_cmake_space_before_method_call_parentheses = false +ij_cmake_space_before_method_parentheses = false +ij_cmake_space_before_while_parentheses = true +ij_cmake_spaces_within_for_parentheses = false +ij_cmake_spaces_within_if_parentheses = false +ij_cmake_spaces_within_method_call_parentheses = false +ij_cmake_spaces_within_method_parentheses = false +ij_cmake_spaces_within_while_parentheses = false + +[{*.gant,*.gradle,*.groovy,*.gy}] +ij_groovy_align_group_field_declarations = false +ij_groovy_align_multiline_array_initializer_expression = false +ij_groovy_align_multiline_assignment = false +ij_groovy_align_multiline_binary_operation = false +ij_groovy_align_multiline_chained_methods = false +ij_groovy_align_multiline_extends_list = false +ij_groovy_align_multiline_for = true +ij_groovy_align_multiline_list_or_map = true +ij_groovy_align_multiline_method_parentheses = false +ij_groovy_align_multiline_parameters = true +ij_groovy_align_multiline_parameters_in_calls = false +ij_groovy_align_multiline_resources = true +ij_groovy_align_multiline_ternary_operation = false +ij_groovy_align_multiline_throws_list = false +ij_groovy_align_named_args_in_map = true +ij_groovy_align_throws_keyword = false +ij_groovy_array_initializer_new_line_after_left_brace = false +ij_groovy_array_initializer_right_brace_on_new_line = false +ij_groovy_array_initializer_wrap = off +ij_groovy_assert_statement_wrap = off +ij_groovy_assignment_wrap = off +ij_groovy_binary_operation_wrap = off +ij_groovy_blank_lines_after_class_header = 0 +ij_groovy_blank_lines_after_imports = 1 +ij_groovy_blank_lines_after_package = 1 +ij_groovy_blank_lines_around_class = 1 +ij_groovy_blank_lines_around_field = 0 +ij_groovy_blank_lines_around_field_in_interface = 0 +ij_groovy_blank_lines_around_method = 1 +ij_groovy_blank_lines_around_method_in_interface = 1 +ij_groovy_blank_lines_before_imports = 1 +ij_groovy_blank_lines_before_method_body = 0 +ij_groovy_blank_lines_before_package = 0 +ij_groovy_block_brace_style = end_of_line +ij_groovy_block_comment_at_first_column = true +ij_groovy_call_parameters_new_line_after_left_paren = false +ij_groovy_call_parameters_right_paren_on_new_line = false +ij_groovy_call_parameters_wrap = off +ij_groovy_catch_on_new_line = false +ij_groovy_class_annotation_wrap = split_into_lines +ij_groovy_class_brace_style = end_of_line +ij_groovy_class_count_to_use_import_on_demand = 5 +ij_groovy_do_while_brace_force = never +ij_groovy_else_on_new_line = false +ij_groovy_enum_constants_wrap = off +ij_groovy_extends_keyword_wrap = off +ij_groovy_extends_list_wrap = off +ij_groovy_field_annotation_wrap = split_into_lines +ij_groovy_finally_on_new_line = false +ij_groovy_for_brace_force = never +ij_groovy_for_statement_new_line_after_left_paren = false +ij_groovy_for_statement_right_paren_on_new_line = false +ij_groovy_for_statement_wrap = off +ij_groovy_if_brace_force = never +ij_groovy_import_annotation_wrap = 2 +ij_groovy_imports_layout = *,|,javax.**,java.**,|,$* +ij_groovy_indent_case_from_switch = true +ij_groovy_indent_label_blocks = true +ij_groovy_insert_inner_class_imports = false +ij_groovy_keep_blank_lines_before_right_brace = 2 +ij_groovy_keep_blank_lines_in_code = 2 +ij_groovy_keep_blank_lines_in_declarations = 2 +ij_groovy_keep_control_statement_in_one_line = true +ij_groovy_keep_first_column_comment = true +ij_groovy_keep_indents_on_empty_lines = false +ij_groovy_keep_line_breaks = true +ij_groovy_keep_multiple_expressions_in_one_line = false +ij_groovy_keep_simple_blocks_in_one_line = false +ij_groovy_keep_simple_classes_in_one_line = true +ij_groovy_keep_simple_lambdas_in_one_line = true +ij_groovy_keep_simple_methods_in_one_line = true +ij_groovy_label_indent_absolute = false +ij_groovy_label_indent_size = 0 +ij_groovy_lambda_brace_style = end_of_line +ij_groovy_layout_static_imports_separately = true +ij_groovy_line_comment_add_space = false +ij_groovy_line_comment_at_first_column = true +ij_groovy_method_annotation_wrap = split_into_lines +ij_groovy_method_brace_style = end_of_line +ij_groovy_method_call_chain_wrap = off +ij_groovy_method_parameters_new_line_after_left_paren = false +ij_groovy_method_parameters_right_paren_on_new_line = false +ij_groovy_method_parameters_wrap = off +ij_groovy_modifier_list_wrap = false +ij_groovy_names_count_to_use_import_on_demand = 3 +ij_groovy_parameter_annotation_wrap = off +ij_groovy_parentheses_expression_new_line_after_left_paren = false +ij_groovy_parentheses_expression_right_paren_on_new_line = false +ij_groovy_prefer_parameters_wrap = false +ij_groovy_resource_list_new_line_after_left_paren = false +ij_groovy_resource_list_right_paren_on_new_line = false +ij_groovy_resource_list_wrap = off +ij_groovy_space_after_assert_separator = true +ij_groovy_space_after_colon = true +ij_groovy_space_after_comma = true +ij_groovy_space_after_comma_in_type_arguments = true +ij_groovy_space_after_for_semicolon = true +ij_groovy_space_after_quest = true +ij_groovy_space_after_type_cast = true +ij_groovy_space_before_annotation_parameter_list = false +ij_groovy_space_before_array_initializer_left_brace = false +ij_groovy_space_before_assert_separator = false +ij_groovy_space_before_catch_keyword = true +ij_groovy_space_before_catch_left_brace = true +ij_groovy_space_before_catch_parentheses = true +ij_groovy_space_before_class_left_brace = true +ij_groovy_space_before_closure_left_brace = true +ij_groovy_space_before_colon = true +ij_groovy_space_before_comma = false +ij_groovy_space_before_do_left_brace = true +ij_groovy_space_before_else_keyword = true +ij_groovy_space_before_else_left_brace = true +ij_groovy_space_before_finally_keyword = true +ij_groovy_space_before_finally_left_brace = true +ij_groovy_space_before_for_left_brace = true +ij_groovy_space_before_for_parentheses = true +ij_groovy_space_before_for_semicolon = false +ij_groovy_space_before_if_left_brace = true +ij_groovy_space_before_if_parentheses = true +ij_groovy_space_before_method_call_parentheses = false +ij_groovy_space_before_method_left_brace = true +ij_groovy_space_before_method_parentheses = false +ij_groovy_space_before_quest = true +ij_groovy_space_before_switch_left_brace = true +ij_groovy_space_before_switch_parentheses = true +ij_groovy_space_before_synchronized_left_brace = true +ij_groovy_space_before_synchronized_parentheses = true +ij_groovy_space_before_try_left_brace = true +ij_groovy_space_before_try_parentheses = true +ij_groovy_space_before_while_keyword = true +ij_groovy_space_before_while_left_brace = true +ij_groovy_space_before_while_parentheses = true +ij_groovy_space_in_named_argument = true +ij_groovy_space_in_named_argument_before_colon = false +ij_groovy_space_within_empty_array_initializer_braces = false +ij_groovy_space_within_empty_method_call_parentheses = false +ij_groovy_spaces_around_additive_operators = true +ij_groovy_spaces_around_assignment_operators = true +ij_groovy_spaces_around_bitwise_operators = true +ij_groovy_spaces_around_equality_operators = true +ij_groovy_spaces_around_lambda_arrow = true +ij_groovy_spaces_around_logical_operators = true +ij_groovy_spaces_around_multiplicative_operators = true +ij_groovy_spaces_around_regex_operators = true +ij_groovy_spaces_around_relational_operators = true +ij_groovy_spaces_around_shift_operators = true +ij_groovy_spaces_within_annotation_parentheses = false +ij_groovy_spaces_within_array_initializer_braces = false +ij_groovy_spaces_within_braces = true +ij_groovy_spaces_within_brackets = false +ij_groovy_spaces_within_cast_parentheses = false +ij_groovy_spaces_within_catch_parentheses = false +ij_groovy_spaces_within_for_parentheses = false +ij_groovy_spaces_within_gstring_injection_braces = false +ij_groovy_spaces_within_if_parentheses = false +ij_groovy_spaces_within_list_or_map = false +ij_groovy_spaces_within_method_call_parentheses = false +ij_groovy_spaces_within_method_parentheses = false +ij_groovy_spaces_within_parentheses = false +ij_groovy_spaces_within_switch_parentheses = false +ij_groovy_spaces_within_synchronized_parentheses = false +ij_groovy_spaces_within_try_parentheses = false +ij_groovy_spaces_within_tuple_expression = false +ij_groovy_spaces_within_while_parentheses = false +ij_groovy_special_else_if_treatment = true +ij_groovy_ternary_operation_wrap = off +ij_groovy_throws_keyword_wrap = off +ij_groovy_throws_list_wrap = off +ij_groovy_use_flying_geese_braces = false +ij_groovy_use_fq_class_names = false +ij_groovy_use_fq_class_names_in_javadoc = true +ij_groovy_use_relative_indents = false +ij_groovy_use_single_class_imports = true +ij_groovy_variable_annotation_wrap = off +ij_groovy_while_brace_force = never +ij_groovy_while_on_new_line = false +ij_groovy_wrap_long_lines = false + +[{*.gradle.kts,*.kt,*.kts,*.main.kts}] +ij_kotlin_align_in_columns_case_branch = false +ij_kotlin_align_multiline_binary_operation = false +ij_kotlin_align_multiline_extends_list = false +ij_kotlin_align_multiline_method_parentheses = false +ij_kotlin_align_multiline_parameters = true +ij_kotlin_align_multiline_parameters_in_calls = false +ij_kotlin_allow_trailing_comma = false +ij_kotlin_allow_trailing_comma_on_call_site = false +ij_kotlin_assignment_wrap = off +ij_kotlin_blank_lines_after_class_header = 0 +ij_kotlin_blank_lines_around_block_when_branches = 0 +ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1 +ij_kotlin_block_comment_at_first_column = true +ij_kotlin_call_parameters_new_line_after_left_paren = false +ij_kotlin_call_parameters_right_paren_on_new_line = false +ij_kotlin_call_parameters_wrap = off +ij_kotlin_catch_on_new_line = false +ij_kotlin_class_annotation_wrap = off +ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL +ij_kotlin_continuation_indent_for_chained_calls = true +ij_kotlin_continuation_indent_for_expression_bodies = true +ij_kotlin_continuation_indent_in_argument_lists = true +ij_kotlin_continuation_indent_in_elvis = true +ij_kotlin_continuation_indent_in_if_conditions = true +ij_kotlin_continuation_indent_in_parameter_lists = true +ij_kotlin_continuation_indent_in_supertype_lists = true +ij_kotlin_else_on_new_line = false +ij_kotlin_enum_constants_wrap = off +ij_kotlin_extends_list_wrap = off +ij_kotlin_field_annotation_wrap = normal +ij_kotlin_finally_on_new_line = false +ij_kotlin_if_rparen_on_new_line = false +ij_kotlin_import_nested_classes = false +ij_kotlin_imports_layout = *,java.**,javax.**,kotlin.**,^ +ij_kotlin_insert_whitespaces_in_simple_one_line_method = true +ij_kotlin_keep_blank_lines_before_right_brace = 0 +ij_kotlin_keep_blank_lines_in_code = 1 +ij_kotlin_keep_blank_lines_in_declarations = 1 +ij_kotlin_keep_first_column_comment = true +ij_kotlin_keep_indents_on_empty_lines = false +ij_kotlin_keep_line_breaks = true +ij_kotlin_lbrace_on_next_line = false +ij_kotlin_line_comment_add_space = false +ij_kotlin_line_comment_at_first_column = true +ij_kotlin_method_annotation_wrap = split_into_lines +ij_kotlin_method_call_chain_wrap = off +ij_kotlin_method_parameters_new_line_after_left_paren = true +ij_kotlin_method_parameters_right_paren_on_new_line = true +ij_kotlin_method_parameters_wrap = off +ij_kotlin_name_count_to_use_star_import = 2147483647 +ij_kotlin_name_count_to_use_star_import_for_members = 2147483647 +ij_kotlin_packages_to_use_import_on_demand = kotlinx.android.synthetic.** +ij_kotlin_parameter_annotation_wrap = off +ij_kotlin_space_after_comma = true +ij_kotlin_space_after_extend_colon = true +ij_kotlin_space_after_type_colon = true +ij_kotlin_space_before_catch_parentheses = true +ij_kotlin_space_before_comma = false +ij_kotlin_space_before_extend_colon = true +ij_kotlin_space_before_for_parentheses = true +ij_kotlin_space_before_if_parentheses = true +ij_kotlin_space_before_lambda_arrow = true +ij_kotlin_space_before_type_colon = false +ij_kotlin_space_before_when_parentheses = true +ij_kotlin_space_before_while_parentheses = true +ij_kotlin_spaces_around_additive_operators = true +ij_kotlin_spaces_around_assignment_operators = true +ij_kotlin_spaces_around_equality_operators = true +ij_kotlin_spaces_around_function_type_arrow = true +ij_kotlin_spaces_around_logical_operators = true +ij_kotlin_spaces_around_multiplicative_operators = true +ij_kotlin_spaces_around_range = false +ij_kotlin_spaces_around_relational_operators = true +ij_kotlin_spaces_around_unary_operator = false +ij_kotlin_spaces_around_when_arrow = true +ij_kotlin_use_custom_formatting_for_modifiers = true +ij_kotlin_variable_annotation_wrap = off +ij_kotlin_while_on_new_line = false +ij_kotlin_wrap_elvis_expressions = 1 +ij_kotlin_wrap_expression_body_functions = 0 +ij_kotlin_wrap_first_method_in_call_chain = false + +[{*.har,*.json}] +indent_size = 2 +ij_json_keep_blank_lines_in_code = 0 +ij_json_keep_indents_on_empty_lines = false +ij_json_keep_line_breaks = true +ij_json_space_after_colon = true +ij_json_space_after_comma = true +ij_json_space_before_colon = true +ij_json_space_before_comma = false +ij_json_spaces_within_braces = false +ij_json_spaces_within_brackets = false +ij_json_wrap_long_lines = false + +[{*.htm,*.html,*.sht,*.shtm,*.shtml}] +ij_html_add_new_line_before_tags = body,div,p,form,h1,h2,h3 +ij_html_align_attributes = true +ij_html_align_text = false +ij_html_attribute_wrap = normal +ij_html_block_comment_at_first_column = true +ij_html_do_not_align_children_of_min_lines = 0 +ij_html_do_not_break_if_inline_tags = title,h1,h2,h3,h4,h5,h6,p +ij_html_do_not_indent_children_of_tags = html,body,thead,tbody,tfoot +ij_html_enforce_quotes = false +ij_html_inline_tags = a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var +ij_html_keep_blank_lines = 2 +ij_html_keep_indents_on_empty_lines = false +ij_html_keep_line_breaks = true +ij_html_keep_line_breaks_in_text = true +ij_html_keep_whitespaces = false +ij_html_keep_whitespaces_inside = span,pre,textarea +ij_html_line_comment_at_first_column = true +ij_html_new_line_after_last_attribute = never +ij_html_new_line_before_first_attribute = never +ij_html_quote_style = double +ij_html_remove_new_line_before_tags = br +ij_html_space_after_tag_name = false +ij_html_space_around_equality_in_attribute = false +ij_html_space_inside_empty_tag = false +ij_html_text_wrap = normal +ij_html_uniform_ident = false + +[{*.yaml,*.yml}] +indent_size = 2 +ij_yaml_align_values_properties = do_not_align +ij_yaml_autoinsert_sequence_marker = true +ij_yaml_block_mapping_on_new_line = false +ij_yaml_indent_sequence_value = true +ij_yaml_keep_indents_on_empty_lines = false +ij_yaml_keep_line_breaks = true +ij_yaml_sequence_on_new_line = false +ij_yaml_space_before_colon = false +ij_yaml_spaces_within_braces = true +ij_yaml_spaces_within_brackets = true diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index a7daaac14b..1ab5d835b2 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -73,3 +73,14 @@ body: - 'No' validations: required: true + - type: dropdown + id: pr + attributes: + label: Are you willing to provide a PR? + description: | + Providing a PR can drastically speed up the process of fixing this bug. Don't worry, it's still OK to answer 'No' :). + options: + - 'Yes' + - 'No' + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/enhancement.yml b/.github/ISSUE_TEMPLATE/enhancement.yml index 71adce718e..2dd968951f 100644 --- a/.github/ISSUE_TEMPLATE/enhancement.yml +++ b/.github/ISSUE_TEMPLATE/enhancement.yml @@ -34,3 +34,14 @@ body: placeholder: Is there anything else you'd like to add? validations: required: false + - type: dropdown + id: pr + attributes: + label: Are you willing to provide a PR? + description: | + Don't worry, it's still OK to answer 'No' :). + options: + - 'Yes' + - 'No' + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/release.yml b/.github/ISSUE_TEMPLATE/release.yml index 7cb47fa952..f012900752 100644 --- a/.github/ISSUE_TEMPLATE/release.yml +++ b/.github/ISSUE_TEMPLATE/release.yml @@ -49,24 +49,34 @@ body: ### Once tested and validated internally - - [ ] Create a new beta release on the GooglePlay console and upload the 4 signed Apks. + - [ ] Create a new open testing release on the GooglePlay console and upload the 4 signed Apks. - [ ] Check that the version codes are correct - [ ] Copy the fastlane change to the GooglePlay console in the section en-GB. - - [ ] Push to beta release to 100% of the users - - [ ] Notify the F-Droid team so that they can schedule the publication on F-Droid + - [ ] Push the open testing release to 100% of the users + - [ ] Notify the F-Droid team [here](https://matrix.to/#/!LAAuJLQXYHjMNWKrCK:matrix.org?via=matrix.org&via=bubu1.eu&via=lant.uk) so that they can schedule the publication on F-Droid + - [ ] The application is available to the PlayStore testers (live). Google can take between 1 hour and up to 7 days to approve the release. + - [ ] The application is available to the F-Droid users. - ### Once Live on PlayStore + ### Once open testing is live on PlayStore - [ ] Ping the Android public room and update its topic - - [ ] Add an entry in the internal diary - ### After at least 2 days + ### Once Live on F-Droid + + - [ ] Update the Android public room topic + + ### After at least 2 days (generally next Monday) - [ ] Check the [rageshakes](https://github.com/matrix-org/element-android-rageshakes/issues) - [ ] Check the crash reports on the GooglePlay console - [ ] Check the Android Element room for any reported issues on the new version - - [ ] If all is OK, push to production and notify Markus (Bubu) to release the F-Droid version - - [ ] Ping the Android public room and update its topic with the new available version + - [ ] If all is OK, promote the open testing release to production. Generally using a 100% roll out, but can be a smaller value depending on the release content. + - [ ] The application is available to the PlayStore users (live). Google can take (again!) between 1 hour and up to 7 days to approve the release. + + ### Once production is live on PlayStore + + - [ ] Ping the Android public room and update its topic + - [ ] Add an entry in the internal diary ### Android SDK2 diff --git a/.github/workflows/post-pr.yml b/.github/workflows/post-pr.yml index 8fe51eb8d5..49669e4201 100644 --- a/.github/workflows/post-pr.yml +++ b/.github/workflows/post-pr.yml @@ -29,200 +29,6 @@ jobs: steps: - run: echo "Run those tests!" # no-op success - # Run Android Tests - integration-tests: - name: Matrix SDK - Running Integration Tests - needs: should-i-run - runs-on: macos-latest - strategy: - fail-fast: false - matrix: - api-level: [ 28 ] - steps: - - uses: actions/checkout@v3 - - uses: gradle/wrapper-validation-action@v1 - - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: 11 - - name: Set up Python 3.8 - uses: actions/setup-python@v3 - with: - python-version: 3.8 - - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - name: Start synapse server - uses: michaelkaye/setup-matrix-synapse@v1.0.3 - with: - uploadLogs: true - httpPort: 8080 - disableRateLimiting: true - public_baseurl: "http://10.0.2.2:8080/" - # package: org.matrix.android.sdk.session - - name: Run integration tests for Matrix SDK [org.matrix.android.sdk.session] API[${{ matrix.api-level }}] - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: ${{ matrix.api-level }} - arch: x86 - profile: Nexus 5X - force-avd-creation: false - emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - emulator-build: 7425822 - script: | - adb root - adb logcat -c - touch emulator-session.log - chmod 777 emulator-session.log - adb logcat >> emulator-session.log & - ./gradlew $CI_GRADLE_ARG_PROPERTIES -Pandroid.testInstrumentationRunnerArguments.package='org.matrix.android.sdk.session' matrix-sdk-android:connectedDebugAndroidTest - - name: Read Results [org.matrix.android.sdk.session] - if: always() - id: get-comment-body-session - run: python3 ./tools/ci/render_test_output.py session ./matrix-sdk-android/build/outputs/androidTest-results/connected/*.xml - - name: Remove adb logcat - if: always() - run: pkill -9 adb - - name: Run integration tests for Matrix SDK [org.matrix.android.sdk.account] API[${{ matrix.api-level }}] - if: always() - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: ${{ matrix.api-level }} - arch: x86 - profile: Nexus 5X - force-avd-creation: false - emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - emulator-build: 7425822 - script: | - adb root - adb logcat -c - touch emulator-account.log - chmod 777 emulator-account.log - adb logcat >> emulator-account.log & - ./gradlew $CI_GRADLE_ARG_PROPERTIES -Pandroid.testInstrumentationRunnerArguments.package='org.matrix.android.sdk.account' matrix-sdk-android:connectedDebugAndroidTest - - name: Read Results [org.matrix.android.sdk.account] - if: always() - id: get-comment-body-account - run: python3 ./tools/ci/render_test_output.py account ./matrix-sdk-android/build/outputs/androidTest-results/connected/*.xml - - name: Remove adb logcat - if: always() - run: pkill -9 adb - # package: org.matrix.android.sdk.internal - - name: Run integration tests for Matrix SDK [org.matrix.android.sdk.internal] API[${{ matrix.api-level }}] - if: always() - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: ${{ matrix.api-level }} - arch: x86 - profile: Nexus 5X - force-avd-creation: false - emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - emulator-build: 7425822 - script: | - adb root - adb logcat -c - touch emulator-internal.log - chmod 777 emulator-internal.log - adb logcat >> emulator-internal.log & - ./gradlew $CI_GRADLE_ARG_PROPERTIES -Pandroid.testInstrumentationRunnerArguments.package='org.matrix.android.sdk.internal' matrix-sdk-android:connectedDebugAndroidTest - - name: Read Results [org.matrix.android.sdk.internal] - if: always() - id: get-comment-body-internal - run: python3 ./tools/ci/render_test_output.py internal ./matrix-sdk-android/build/outputs/androidTest-results/connected/*.xml - - name: Remove adb logcat - if: always() - run: pkill -9 adb - # package: org.matrix.android.sdk.ordering - - name: Run integration tests for Matrix SDK [org.matrix.android.sdk.ordering] API[${{ matrix.api-level }}] - if: always() - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: ${{ matrix.api-level }} - arch: x86 - profile: Nexus 5X - force-avd-creation: false - emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - emulator-build: 7425822 - script: | - adb root - adb logcat -c - touch emulator-ordering.log - chmod 777 emulator-ordering.log - adb logcat >> emulator-ordering.log & - ./gradlew $CI_GRADLE_ARG_PROPERTIES -Pandroid.testInstrumentationRunnerArguments.package='org.matrix.android.sdk.ordering' matrix-sdk-android:connectedDebugAndroidTest - - name: Read Results [org.matrix.android.sdk.ordering] - if: always() - id: get-comment-body-ordering - run: python3 ./tools/ci/render_test_output.py ordering ./matrix-sdk-android/build/outputs/androidTest-results/connected/*.xml - - name: Remove adb logcat - if: always() - run: pkill -9 adb - # package: class PermalinkParserTest - - name: Run integration tests for Matrix SDK class [org.matrix.android.sdk.PermalinkParserTest] API[${{ matrix.api-level }}] - if: always() - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: ${{ matrix.api-level }} - arch: x86 - profile: Nexus 5X - force-avd-creation: false - emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - emulator-build: 7425822 - script: | - adb root - adb logcat -c - touch emulator-permalink.log - chmod 777 emulator-permalink.log - adb logcat >> emulator-permalink.log & - ./gradlew $CI_GRADLE_ARG_PROPERTIES -Pandroid.testInstrumentationRunnerArguments.class='org.matrix.android.sdk.PermalinkParserTest' matrix-sdk-android:connectedDebugAndroidTest - - name: Read Results [org.matrix.android.sdk.PermalinkParserTest] - if: always() - id: get-comment-body-permalink - run: python3 ./tools/ci/render_test_output.py permalink ./matrix-sdk-android/build/outputs/androidTest-results/connected/*.xml - - name: Remove adb logcat - if: always() - run: pkill -9 adb - # package: class PermalinkParserTest - - name: Find Comment - if: always() && github.event_name == 'pull_request' - uses: peter-evans/find-comment@v2 - id: fc - with: - issue-number: ${{ github.event.pull_request.number }} - comment-author: 'github-actions[bot]' - body-includes: Integration Tests Results - - name: Publish results to PR - if: always() && github.event_name == 'pull_request' - uses: peter-evans/create-or-update-comment@v2 - with: - comment-id: ${{ steps.fc.outputs.comment-id }} - issue-number: ${{ github.event.pull_request.number }} - body: | - ### Matrix SDK - ## Integration Tests Results: - - `[org.matrix.android.sdk.session]`
${{ steps.get-comment-body-session.outputs.session }} - - `[org.matrix.android.sdk.account]`
${{ steps.get-comment-body-account.outputs.account }} - - `[org.matrix.android.sdk.internal]`
${{ steps.get-comment-body-internal.outputs.internal }} - - `[org.matrix.android.sdk.ordering]`
${{ steps.get-comment-body-ordering.outputs.ordering }} - - `[org.matrix.android.sdk.PermalinkParserTest]`
${{ steps.get-comment-body-permalink.outputs.permalink }} - edit-mode: replace - - name: Upload Test Report Log - uses: actions/upload-artifact@v3 - if: always() - with: - name: integrationtest-error-results - path: | - emulator-permalink.log - emulator-internal.log - emulator-ordering.log - emulator-account.log - emulator-session.log - ui-tests: name: UI Tests (Synapse) needs: should-i-run @@ -282,42 +88,13 @@ jobs: emulator.log failure_screenshots/ - codecov-units: - name: Unit tests with code coverage - needs: should-i-run - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: '11' - - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - run: ./gradlew allCodeCoverageReport $CI_GRADLE_ARG_PROPERTIES - - name: Upload Codecov data - uses: actions/upload-artifact@v3 - if: always() - with: - name: codecov-xml - path: | - build/reports/jacoco/allCodeCoverageReport/allCodeCoverageReport.xml - # Notify the channel about delayed failures notify: name: Notify matrix runs-on: ubuntu-latest needs: - should-i-run - - integration-tests - ui-tests - - codecov-units if: always() && (needs.should-i-run.result == 'success' ) && ((needs.codecov-units.result != 'success' ) || (needs.ui-tests.result != 'success') || (needs.integration-tests.result != 'success')) # No concurrency required, runs every time on a schedule. steps: diff --git a/.github/workflows/sonarqube.yml b/.github/workflows/sonarqube.yml deleted file mode 100644 index 6809751d91..0000000000 --- a/.github/workflows/sonarqube.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: Sonarqube nightly - -on: - schedule: - - cron: '0 20 * * *' - -# Enrich gradle.properties for CI/CD -env: - CI_GRADLE_ARG_PROPERTIES: > - -Porg.gradle.jvmargs=-Xmx4g - -Porg.gradle.parallel=false -jobs: - codecov-units: - name: Unit tests with code coverage - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: '11' - - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - run: ./gradlew allCodeCoverageReport $CI_GRADLE_ARG_PROPERTIES - - name: Upload Codecov data - uses: actions/upload-artifact@v3 - if: always() - with: - name: codecov-xml - path: | - build/reports/jacoco/allCodeCoverageReport/allCodeCoverageReport.xml - - sonarqube: - name: Sonarqube upload - runs-on: ubuntu-latest - needs: - - codecov-units - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: '11' - - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - uses: actions/download-artifact@v3 - with: - name: codecov-xml # will restore to allCodeCoverageReport.xml by default; we restore to the same location in following tasks - - run: mkdir -p build/reports/jacoco/allCodeCoverageReport/ - - run: mv allCodeCoverageReport.xml build/reports/jacoco/allCodeCoverageReport/ - - run: ./gradlew sonarqube $CI_GRADLE_ARG_PROPERTIES - env: - ORG_GRADLE_PROJECT_SONAR_LOGIN: ${{ secrets.SONAR_TOKEN }} - -# Notify the channel about sonarqube failures - notify: - name: Notify matrix - runs-on: ubuntu-latest - needs: - - sonarqube - - codecov-units - if: always() && (needs.sonarqube.result != 'success' || needs.codecov-units.result != 'success') - steps: - - uses: michaelkaye/matrix-hookshot-action@v1.0.0 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - hookshot_url: ${{ secrets.ELEMENT_ANDROID_HOOKSHOT_URL }} - text_template: "Sonarqube run (on ${{ github.ref }}): {{#each job_statuses }}{{#with this }}{{#if completed }} {{name}} {{conclusion}} at {{completed_at}}, {{/if}}{{/with}}{{/each}}" - html_template: "Sonarqube run (on ${{ github.ref }}): {{#each job_statuses }}{{#with this }}{{#if completed }}
{{icon conclusion}} {{name}} {{conclusion}} at {{completed_at}} [details]{{/if}}{{/with}}{{/each}}" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3e8de8979c..f8d7f2ec33 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -12,73 +12,100 @@ env: -Porg.gradle.parallel=false jobs: - # Build Android Tests - build-android-tests: - name: Build Android Tests - runs-on: ubuntu-latest - concurrency: - group: ${{ github.ref == 'refs/heads/main' && format('unit-tests-main-{0}', github.sha) || github.ref == 'refs/heads/develop' && format('unit-tests-develop-{0}', github.sha) || format('build-android-tests-{0}', github.ref) }} - cancel-in-progress: true - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: 11 - - uses: actions/cache@v3 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - name: Build Android Tests - run: ./gradlew clean assembleAndroidTest $CI_GRADLE_ARG_PROPERTIES --stacktrace - - unit-tests: - name: Run Unit Tests - runs-on: ubuntu-latest + tests: + name: Runs all tests + runs-on: macos-latest # for the emulator # Allow all jobs on main and develop. Just one per PR. concurrency: group: ${{ github.ref == 'refs/heads/main' && format('unit-tests-main-{0}', github.sha) || github.ref == 'refs/heads/develop' && format('unit-tests-develop-{0}', github.sha) || format('unit-tests-{0}', github.ref) }} cancel-in-progress: true steps: - uses: actions/checkout@v3 - - uses: actions/cache@v3 with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - name: Run unit tests - run: ./gradlew clean test $CI_GRADLE_ARG_PROPERTIES --stacktrace + fetch-depth: 0 + - uses: actions/setup-java@v3 + with: + distribution: 'adopt' + java-version: '11' + - uses: gradle/gradle-build-action@v2 + - uses: actions/setup-python@v3 + with: + python-version: 3.8 + - uses: michaelkaye/setup-matrix-synapse@v1.0.3 + with: + uploadLogs: true + httpPort: 8080 + disableRateLimiting: true + public_baseurl: "http://10.0.2.2:8080/" + - name: Run all the codecoverage tests at once + id: tests + uses: reactivecircus/android-emulator-runner@v2 + continue-on-error: true + with: + api-level: 28 + arch: x86 + profile: Nexus 5X + force-avd-creation: false + emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: true + emulator-build: 7425822 + script: ./gradlew theCodeCoverageReport -Pandroid.testInstrumentationRunnerArguments.notPackage=im.vector.app.ui --stacktrace $CI_GRADLE_ARG_PROPERTIES +# NB: continue-on-error marks steps.tests.conclusion = 'success' but leaves stes.tests.outcome = 'failure' + - name: Run all the codecoverage tests at once (retry if emulator failed) + uses: reactivecircus/android-emulator-runner@v2 + if: always() && steps.tests.outcome == 'failure' # don't run if previous step succeeded. + with: + api-level: 28 + arch: x86 + profile: Nexus 5X + force-avd-creation: false + emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: true + emulator-build: 7425822 + script: ./gradlew theCodeCoverageReport -Pandroid.testInstrumentationRunnerArguments.notPackage=im.vector.app.ui --stacktrace $CI_GRADLE_ARG_PROPERTIES + - run: ./gradlew sonarqube $CI_GRADLE_ARG_PROPERTIES + if: always() # we may have failed a previous step and retried, that's OK + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + ORG_GRADLE_PROJECT_SONAR_LOGIN: ${{ secrets.SONAR_TOKEN }} + - name: Format unit test results if: always() run: python3 ./tools/ci/render_test_output.py unit ./**/build/test-results/**/*.xml - - name: Publish Unit Test Results - uses: EnricoMi/publish-unit-test-result-action@v1 - if: always() && - github.event.sender.login != 'dependabot[bot]' && - ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository ) - with: - files: ./**/build/test-results/**/*.xml -# Notify the channel about runs against develop or main that have failures, as PRs should have caught these first. - notify: - runs-on: ubuntu-latest - needs: - - unit-tests - - build-android-tests - if: ${{ (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main' ) && failure() }} - steps: - - uses: michaelkaye/matrix-hookshot-action@v0.3.0 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - matrix_access_token: ${{ secrets.ELEMENT_ANDROID_NOTIFICATION_ACCESS_TOKEN }} - matrix_room_id: ${{ secrets.ELEMENT_ANDROID_INTERNAL_ROOM_ID }} - text_template: "Build is broken for ${{ github.ref }}: {{#each job_statuses }}{{#with this }}{{#if completed }}{{name}} {{conclusion}} at {{completed_at}}, {{/if}}{{/with}}{{/each}}" - html_template: "Build is broken for ${{ github.ref }}: {{#each job_statuses }}{{#with this }}{{#if completed }}
{{icon conclusion }} {{name}} {{conclusion}} at {{completed_at}} [details]{{/if}}{{/with}}{{/each}}" +# can't be run on macos due to containers. +# - name: Publish Unit Test Results +# uses: EnricoMi/publish-unit-test-result-action@v1 +# if: always() && +# github.event.sender.login != 'dependabot[bot]' && +# ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository ) +# with: +# files: ./**/build/test-results/**/*.xml + +# Unneeded as part of the test suite above, kept around in case we want to re-enable them. +# +# # Build Android Tests +# build-android-tests: +# name: Build Android Tests +# runs-on: ubuntu-latest +# concurrency: +# group: ${{ github.ref == 'refs/heads/main' && format('unit-tests-main-{0}', github.sha) || github.ref == 'refs/heads/develop' && format('unit-tests-develop-{0}', github.sha) || format('build-android-tests-{0}', github.ref) }} +# cancel-in-progress: true +# steps: +# - uses: actions/checkout@v3 +# - uses: actions/setup-java@v3 +# with: +# distribution: 'adopt' +# java-version: 11 +# - uses: actions/cache@v3 +# with: +# path: | +# ~/.gradle/caches +# ~/.gradle/wrapper +# key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} +# restore-keys: | +# ${{ runner.os }}-gradle- +# - name: Build Android Tests +# run: ./gradlew clean assembleAndroidTest $CI_GRADLE_ARG_PROPERTIES --stacktrace diff --git a/.github/workflows/triage-labelled.yml b/.github/workflows/triage-labelled.yml index 82d5931ce7..c49b33d582 100644 --- a/.github/workflows/triage-labelled.yml +++ b/.github/workflows/triage-labelled.yml @@ -9,15 +9,15 @@ jobs: name: Add Z-Labs label for features behind labs flags runs-on: ubuntu-latest if: > - contains(github.event.issue.labels.*.name, 'A-Maths') || - contains(github.event.issue.labels.*.name, 'A-Message-Pinning') || - contains(github.event.issue.labels.*.name, 'A-Polls') || - contains(github.event.issue.labels.*.name, 'A-Location-Sharing') || - contains(github.event.issue.labels.*.name, 'A-Message-Bubbles') || - contains(github.event.issue.labels.*.name, 'Z-IA') || - contains(github.event.issue.labels.*.name, 'A-Themes-Custom') || - contains(github.event.issue.labels.*.name, 'A-E2EE-Dehydration') || - contains(github.event.issue.labels.*.name, 'A-Tags') + contains(github.event.issue.labels.*.name, 'A-Maths') || + contains(github.event.issue.labels.*.name, 'A-Message-Pinning') || + contains(github.event.issue.labels.*.name, 'A-Polls') || + contains(github.event.issue.labels.*.name, 'A-Location-Sharing') || + contains(github.event.issue.labels.*.name, 'A-Message-Bubbles') || + contains(github.event.issue.labels.*.name, 'Z-IA') || + contains(github.event.issue.labels.*.name, 'A-Themes-Custom') || + contains(github.event.issue.labels.*.name, 'A-E2EE-Dehydration') || + contains(github.event.issue.labels.*.name, 'A-Tags') steps: - uses: actions/github-script@v5 with: @@ -79,7 +79,7 @@ jobs: name: X-Needs-Product to Design project board runs-on: ubuntu-latest if: > - contains(github.event.issue.labels.*.name, 'X-Needs-Product') + contains(github.event.issue.labels.*.name, 'X-Needs-Product') steps: - uses: octokit/graphql-action@v2.x id: add_to_project @@ -105,10 +105,7 @@ jobs: # Skip in forks if: > github.repository == 'vector-im/element-android' && - (contains(github.event.issue.labels.*.name, 'A-Spaces') || - contains(github.event.issue.labels.*.name, 'A-Space-Settings') || - contains(github.event.issue.labels.*.name, 'A-Subspaces') || - contains(github.event.issue.labels.*.name, 'Z-IA')) + (contains(github.event.issue.labels.*.name, 'Team: Delight')) steps: - uses: octokit/graphql-action@v2.x with: @@ -201,7 +198,7 @@ jobs: env: PROJECT_ID: "PN_kwDOAM0swc3m-g" GITHUB_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }} - + move_ftue_issues: name: Z-FTUE to Mobile FTUE board runs-on: ubuntu-latest diff --git a/.github/workflows/triage-priority-bugs.yml b/.github/workflows/triage-priority-bugs.yml index 70c337e748..6cde154370 100644 --- a/.github/workflows/triage-priority-bugs.yml +++ b/.github/workflows/triage-priority-bugs.yml @@ -14,10 +14,7 @@ jobs: !contains(github.event.issue.labels.*.name, 'A-E2EE-Cross-Signing') && !contains(github.event.issue.labels.*.name, 'A-E2EE-Dehydration') && !contains(github.event.issue.labels.*.name, 'A-E2EE-Key-Backup') && - !contains(github.event.issue.labels.*.name, 'A-E2EE-SAS-Verification') && - !contains(github.event.issue.labels.*.name, 'A-Spaces') && - !contains(github.event.issue.labels.*.name, 'A-Spaces-Settings') && - !contains(github.event.issue.labels.*.name, 'A-Subspaces')) && + !contains(github.event.issue.labels.*.name, 'A-E2EE-SAS-Verification')) && (contains(github.event.issue.labels.*.name, 'T-Defect') && contains(github.event.issue.labels.*.name, 'S-Critical') && (contains(github.event.issue.labels.*.name, 'O-Frequent') || diff --git a/CHANGES.md b/CHANGES.md index 60497402e9..e2991a122b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,43 @@ +Changes in Element v1.4.22 (2022-06-14) +======================================= + +Features ✨ +---------- + - Make read receipt avatar list more compact ([#5970](https://github.com/vector-im/element-android/issues/5970)) + - Allow .well-known configuration to override key sharing mode ([#6147](https://github.com/vector-im/element-android/issues/6147)) + - Re-organize location settings flags ([#6244](https://github.com/vector-im/element-android/issues/6244)) + - Add report action for live location messages ([#6280](https://github.com/vector-im/element-android/issues/6280)) + +Bugfixes 🐛 +---------- + - Fix cases of missing, swapped, or duplicated messages ([#5528](https://github.com/vector-im/element-android/issues/5528)) + - Fix wrong status of live location sharing in timeline ([#6209](https://github.com/vector-im/element-android/issues/6209)) + - Fix StackOverflowError while recording voice message ([#6222](https://github.com/vector-im/element-android/issues/6222)) + - Text cropped: "Secure backup" ([#6232](https://github.com/vector-im/element-android/issues/6232)) + - Fix copyright attributions of map views ([#6247](https://github.com/vector-im/element-android/issues/6247)) + - Fix flickering bottom bar of live location item ([#6264](https://github.com/vector-im/element-android/issues/6264)) + +In development 🚧 +---------------- + - FTUE - Adds Sign Up tracking ([#5285](https://github.com/vector-im/element-android/issues/5285)) + +SDK API changes ⚠️ +------------------ + - Some methods from `Session` have been moved to a new `SyncService`, that you can retrieve from a `Session`. + - `SyncStatusService` method has been moved to the new `SyncService` + - `InitSyncStep` have been moved and renamed to `InitialSyncStep` + - `SyncStatusService.Status` has been renamed to `SyncRequestState` + - The existing `SyncService` has been renamed to `SyncAndroidService` because of name clash with the new SDK Service ([#6029](https://github.com/vector-im/element-android/issues/6029)) + - Allows `AuthenticationService.getLoginFlow` to fail without resetting state from previously successful calls ([#6093](https://github.com/vector-im/element-android/issues/6093)) + - Allows new passwords to be passed at the point of confirmation when resetting a password ([#6169](https://github.com/vector-im/element-android/issues/6169)) + +Other changes +------------- + - Adds support for parsing homeserver versions without a patch number ([#6017](https://github.com/vector-im/element-android/issues/6017)) + - Updating exit onboarding dialog copy formatting to match iOS ([#6087](https://github.com/vector-im/element-android/issues/6087)) + - Disables when arrow alignment in code style ([#6126](https://github.com/vector-im/element-android/issues/6126)) + + Changes in Element 1.4.20 (2022-06-13) ====================================== diff --git a/README.md b/README.md index 54dfb7b288..7acb5aa638 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ [![Buildkite](https://badge.buildkite.com/ad0065c1b70f557cd3b1d3d68f9c2154010f83c4d6f71706a9.svg?branch=develop)](https://buildkite.com/matrix-dot-org/element-android/builds?branch=develop) [![Weblate](https://translate.element.io/widgets/element-android/-/svg-badge.svg)](https://translate.element.io/engage/element-android/?utm_source=widget) [![Element Android Matrix room #element-android:matrix.org](https://img.shields.io/matrix/element-android:matrix.org.svg?label=%23element-android:matrix.org&logo=matrix&server_fqdn=matrix.org)](https://matrix.to/#/#element-android:matrix.org) -[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=im.vector.app.android&metric=alert_status)](https://sonarcloud.io/dashboard?id=im.vector.app.android) -[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=im.vector.app.android&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=im.vector.app.android) -[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=im.vector.app.android&metric=bugs)](https://sonarcloud.io/dashboard?id=im.vector.app.android) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=vector-im_element-android&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=vector-im_element-android) +[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=vector-im_element-android&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=vector-im_element-android) +[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=vector-im_element-android&metric=bugs)](https://sonarcloud.io/summary/new_code?id=vector-im_element-android) # Element Android diff --git a/build.gradle b/build.gradle index 635db83e14..2cb67b7795 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,7 @@ buildscript { classpath libs.gradle.kotlinPlugin classpath libs.gradle.hiltPlugin classpath 'com.google.gms:google-services:4.3.10' - classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.3' + classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.4.0.2513' classpath 'com.google.android.gms:oss-licenses-plugin:0.10.5' classpath "com.likethesalad.android:stem-plugin:2.1.1" classpath 'org.owasp:dependency-check-gradle:7.1.0.1' @@ -43,7 +43,7 @@ plugins { id "io.gitlab.arturbosch.detekt" version "1.20.0" // Dependency Analysis - id 'com.autonomousapps.dependency-analysis' version "1.4.0" + id 'com.autonomousapps.dependency-analysis' version "1.5.0" } // https://github.com/jeremylong/DependencyCheck @@ -180,8 +180,8 @@ apply plugin: 'org.sonarqube' sonarqube { properties { - property "sonar.projectName", "Element-Android" - property "sonar.projectKey", "im.vector.app.android" + property "sonar.projectName", "element-android" + property "sonar.projectKey", "vector-im_element-android" property "sonar.host.url", "https://sonarcloud.io" property "sonar.projectVersion", project(":vector").android.defaultConfig.versionName property "sonar.sourceEncoding", "UTF-8" @@ -191,7 +191,7 @@ sonarqube { property "sonar.links.issue", "https://github.com/vector-im/element-android/issues" property "sonar.organization", "new_vector_ltd_organization" property "sonar.java.coveragePlugin", "jacoco" - property "sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/jacoco/allCodeCoverageReport/allCodeCoverageReport.xml" + property "sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/jacoco/theCodeCoverageReport/theCodeCoverageReport.xml" property "sonar.login", project.hasProperty("SONAR_LOGIN") ? SONAR_LOGIN : "invalid" } } diff --git a/coverage.gradle b/coverage.gradle index b62ce0b4a0..fc69ce7e90 100644 --- a/coverage.gradle +++ b/coverage.gradle @@ -1,8 +1,33 @@ -def excludes = [ ] +def excludes = [ +// dependency injection graph +'**/*Module.*', +'**/*Module*.*', + +// Framework entry points +'**/*Activity*', +'**/*Fragment*', +'**/*Application*', + +// We would like to exclude android widgets as well but our naming is inconsistent + +// Proof of concept +'**/*Login2*', + +// Generated +'**/*JsonAdapter*', +'**/*Item.*', +'**/*$Holder.*', +'**/*ViewHolder.*', +'**/*View.*', +'**/*BottomSheet.*' +] def initializeReport(report, projects, classExcludes) { projects.each { project -> project.apply plugin: 'jacoco' } - report.executionData { fileTree(rootProject.rootDir.absolutePath).include("**/build/jacoco/*.exec") } + report.executionData { fileTree(rootProject.rootDir.absolutePath).include( + "**/build/outputs/unit_test_code_coverage/**/*.exec", + "**/build/outputs/code_coverage/**/coverage.ec" + ) } report.reports { xml.enabled true @@ -18,11 +43,13 @@ def initializeReport(report, projects, classExcludes) { switch (project) { case { project.plugins.hasPlugin("com.android.application") }: androidClassDirs.add("${project.buildDir}/tmp/kotlin-classes/gplayDebug") + androidSourceDirs.add("${project.buildDir}/generated/source/kapt/gplayDebug") androidSourceDirs.add("${project.projectDir}/src/main/kotlin") androidSourceDirs.add("${project.projectDir}/src/main/java") break case { project.plugins.hasPlugin("com.android.library") }: androidClassDirs.add("${project.buildDir}/tmp/kotlin-classes/debug") + androidSourceDirs.add("${project.buildDir}/generated/source/kapt/debug") androidSourceDirs.add("${project.projectDir}/src/main/kotlin") androidSourceDirs.add("${project.projectDir}/src/main/java") break @@ -43,13 +70,18 @@ def collectProjects(predicate) { return subprojects.findAll { it.buildFile.isFile() && predicate(it) } } -task allCodeCoverageReport(type: JacocoReport) { +task theCodeCoverageReport(type: JacocoReport) { outputs.upToDateWhen { false } rootProject.apply plugin: 'jacoco' - // to limit projects in a specific report, add - // def excludedProjects = [ ... ] - // def projects = collectProjects { !excludedProjects.contains(it.name) } - def projects = collectProjects { true } - dependsOn { projects*.test } + tasks.withType(Test) { + jacoco.includeNoLocationClasses = true + } + def projects = collectProjects { ['vector','matrix-sdk-android'].contains(it.name) } + dependsOn { + [':vector:testGplayDebugUnitTest'] + + [':vector:connectedGplayDebugAndroidTest'] + + [':matrix-sdk-android:testDebugUnitTest'] + + [':matrix-sdk-android:connectedDebugAndroidTest'] + } initializeReport(it, projects, excludes) } diff --git a/dependencies.gradle b/dependencies.gradle index 35ab909cf4..451ad4449b 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -49,8 +49,8 @@ ext.libs = [ ], androidx : [ 'activity' : "androidx.activity:activity:1.4.0", - 'appCompat' : "androidx.appcompat:appcompat:1.4.1", - 'core' : "androidx.core:core-ktx:1.7.0", + 'appCompat' : "androidx.appcompat:appcompat:1.4.2", + 'core' : "androidx.core:core-ktx:1.8.0", 'recyclerview' : "androidx.recyclerview:recyclerview:1.2.1", 'exifinterface' : "androidx.exifinterface:exifinterface:1.3.3", 'fragmentKtx' : "androidx.fragment:fragment-ktx:1.4.1", @@ -78,7 +78,7 @@ ext.libs = [ 'transition' : "androidx.transition:transition:1.2.0", ], google : [ - 'material' : "com.google.android.material:material:1.6.0" + 'material' : "com.google.android.material:material:1.6.1" ], dagger : [ 'dagger' : "com.google.dagger:dagger:$dagger", diff --git a/fastlane/README.md b/fastlane/README.md index 7fea7afdd5..dc33f422d6 100644 --- a/fastlane/README.md +++ b/fastlane/README.md @@ -1,64 +1,49 @@ fastlane documentation ----- - +================ # Installation Make sure you have the latest version of the Xcode command line tools installed: -```sh +``` xcode-select --install ``` -For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) +Install _fastlane_ using +``` +[sudo] gem install fastlane -NV +``` +or alternatively using `brew install fastlane` # Available Actions - ## Android - ### android test - -```sh -[bundle exec] fastlane android test ``` - +fastlane android test +``` Runs all the tests - ### android beta - -```sh -[bundle exec] fastlane android beta ``` - +fastlane android beta +``` Submit a new Beta Build to Crashlytics Beta - ### android deploy - -```sh -[bundle exec] fastlane android deploy ``` - +fastlane android deploy +``` Deploy a new version to the Google Play - ### android deployMeta - -```sh -[bundle exec] fastlane android deployMeta ``` - +fastlane android deployMeta +``` Deploy Google Play metadata - ### android getVersionCode - -```sh -[bundle exec] fastlane android getVersionCode ``` - +fastlane android getVersionCode +``` Get version code ---- This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. - -More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). - -The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools). +More information about fastlane can be found on [fastlane.tools](https://fastlane.tools). +The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools). diff --git a/fastlane/metadata/android/cs-CZ/changelogs/40104160.txt b/fastlane/metadata/android/cs-CZ/changelogs/40104160.txt new file mode 100644 index 0000000000..922d4dc76b --- /dev/null +++ b/fastlane/metadata/android/cs-CZ/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Hlavní změny v této verzi: Vylepšena správa šifrovaných zpráv. Opravy různých chyb a vylepšení stability. +Úplný seznam změn: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/en-US/changelogs/40104220.txt b/fastlane/metadata/android/en-US/changelogs/40104220.txt new file mode 100644 index 0000000000..61db61727a --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/40104220.txt @@ -0,0 +1,2 @@ +Main changes in this version: Various bug fixes and stability improvements. +Full changelog: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/et/changelogs/40104160.txt b/fastlane/metadata/android/et/changelogs/40104160.txt new file mode 100644 index 0000000000..aa5a341dd3 --- /dev/null +++ b/fastlane/metadata/android/et/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Põhilised muutused selles versioonis: krüptitud sõnumite parem haldus, lisaks pisiparandused ja stabiilsust parandavad kohendused. +Kogu ingliskeelne muudatuste logi: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/fa/changelogs/40104160.txt b/fastlane/metadata/android/fa/changelogs/40104160.txt new file mode 100644 index 0000000000..1687ba2419 --- /dev/null +++ b/fastlane/metadata/android/fa/changelogs/40104160.txt @@ -0,0 +1,2 @@ +تغییرات عمده در این نگارش: مدیریت بهتر پیام‌های رمزگذاشته. رفع اشکال‌های مختلف و بهبودهای پایداری. +گزارش دگرگونی کامل: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/fr-FR/changelogs/40104160.txt b/fastlane/metadata/android/fr-FR/changelogs/40104160.txt new file mode 100644 index 0000000000..6a19c6ea39 --- /dev/null +++ b/fastlane/metadata/android/fr-FR/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Principaux changements pour cette version : Meilleure gestion des messages chiffrés. Plusieurs corrections de bogues et d’améliorations de stabilité. +Intégralité des changements : https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/id/changelogs/40104160.txt b/fastlane/metadata/android/id/changelogs/40104160.txt new file mode 100644 index 0000000000..8f248ffed4 --- /dev/null +++ b/fastlane/metadata/android/id/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Perubahan utama dalam versi ini: Pengelolaan pesan terenkripsi lebih baik. Banyak perbaikan kutu dan perbaikan stabilitas. +Catatan perubahan lanjutan: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/it-IT/changelogs/40104160.txt b/fastlane/metadata/android/it-IT/changelogs/40104160.txt new file mode 100644 index 0000000000..943a42de99 --- /dev/null +++ b/fastlane/metadata/android/it-IT/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Modifiche principali in questa versione: migliorata la gestione dei messaggi cifrati. Varie correzioni e miglioramenti della stabilità. +Cronologia completa: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/iw-IL/title.txt b/fastlane/metadata/android/iw-IL/title.txt index d8849a5023..56ae517696 100644 --- a/fastlane/metadata/android/iw-IL/title.txt +++ b/fastlane/metadata/android/iw-IL/title.txt @@ -1 +1 @@ -אלמנט (בעבר Riot.im) +אלמנט - התכתבות מאובטחת diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101060.txt b/fastlane/metadata/android/pl-PL/changelogs/40101060.txt new file mode 100644 index 0000000000..17af495632 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101060.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wesji: poprawki dla wesji 1.1.5 +Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.1.6 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101070.txt b/fastlane/metadata/android/pl-PL/changelogs/40101070.txt new file mode 100644 index 0000000000..2959ba88e0 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101070.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Eksperymentalne wsparcie dla przestrzeni, Kompresowanie video przed wysłaniem. +Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.1.7 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101080.txt b/fastlane/metadata/android/pl-PL/changelogs/40101080.txt new file mode 100644 index 0000000000..95f77a0f25 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101080.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Poprawki w przestrzeniach +Pełna lista zmian https://github.com/vector-im/element-android/releases/tag/v1.1.8 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101090.txt b/fastlane/metadata/android/pl-PL/changelogs/40101090.txt new file mode 100644 index 0000000000..0bc111fa70 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101090.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Dodano wsparcie dla sieci gitter.im . +Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.1.9 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101100.txt b/fastlane/metadata/android/pl-PL/changelogs/40101100.txt new file mode 100644 index 0000000000..2eace7771d --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101100.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Nowe funkcje dla przestrzeni i aktualizacja motywu i stylu. +Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.1.10 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40101110.txt b/fastlane/metadata/android/pl-PL/changelogs/40101110.txt new file mode 100644 index 0000000000..5afc3ca5a7 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40101110.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Dodano nowe funkcje do przestrzeni i zaktualizowano motyw i styl aplikacji. (poprawki błędóœ dla wesji 1.1.10) +Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.1.11 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40104160.txt b/fastlane/metadata/android/pl-PL/changelogs/40104160.txt new file mode 100644 index 0000000000..104ed45352 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Lepsze zarządzanie zaszyfrowanymi wiadomościami. , Poprawki błędów i stabilności. +Pełna lista zmian: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pt-BR/changelogs/40104160.txt b/fastlane/metadata/android/pt-BR/changelogs/40104160.txt new file mode 100644 index 0000000000..eec5dca30f --- /dev/null +++ b/fastlane/metadata/android/pt-BR/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Principais mudanças nesta versão: Melhor gerenciamento de mensagens encriptadas. Vários consertos de bugs e melhorias de estabilidade. +Changelog completo: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sk/changelogs/40104160.txt b/fastlane/metadata/android/sk/changelogs/40104160.txt new file mode 100644 index 0000000000..e6e2f45c32 --- /dev/null +++ b/fastlane/metadata/android/sk/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Hlavné zmeny v tejto verzii: Lepšia spravovanie zašifrovaných správ. Rôzne opravy chýb a vylepšenia stability. +Úplný zoznam zmien: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sv-SE/changelogs/40104160.txt b/fastlane/metadata/android/sv-SE/changelogs/40104160.txt new file mode 100644 index 0000000000..cf7eda6ef8 --- /dev/null +++ b/fastlane/metadata/android/sv-SE/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Huvudsakliga ändringar i den här versionen: Bättre hantering av krypterade meddelanden. Diverse buggfixar och stabilitetsförbättringar. +Full ändringslogg: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/uk/changelogs/40104160.txt b/fastlane/metadata/android/uk/changelogs/40104160.txt new file mode 100644 index 0000000000..33ad65f75c --- /dev/null +++ b/fastlane/metadata/android/uk/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Основні зміни в цій версії: Поліпшено керування зашифрованими повідомленнями. Усунуто різні вади й поліпшено стабільність. +Вичерпний перелік змін: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/zh-TW/changelogs/40104160.txt b/fastlane/metadata/android/zh-TW/changelogs/40104160.txt new file mode 100644 index 0000000000..0e64d36868 --- /dev/null +++ b/fastlane/metadata/android/zh-TW/changelogs/40104160.txt @@ -0,0 +1,2 @@ +此版本中的主要變動:對於被加密的訊息有更好的管理方式。多個臭蟲修復與穩定性改善。 +完整的變更紀錄:https://github.com/vector-im/element-android/releases diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentViewerActivity.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentViewerActivity.kt index 21af114c26..764cf8419a 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentViewerActivity.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentViewerActivity.kt @@ -271,7 +271,7 @@ abstract class AttachmentViewerActivity : AppCompatActivity(), AttachmentEventLi directionDetector.handleTouchEvent(event) return when (swipeDirection) { - SwipeDirection.Up, SwipeDirection.Down -> { + SwipeDirection.Up, SwipeDirection.Down -> { if (isSwipeToDismissAllowed && !wasScaled && isImagePagerIdle) { swipeDismissHandler.onTouch(views.rootContainer, event) } else true @@ -279,7 +279,7 @@ abstract class AttachmentViewerActivity : AppCompatActivity(), AttachmentEventLi SwipeDirection.Left, SwipeDirection.Right -> { views.attachmentPager.dispatchTouchEvent(event) } - else -> true + else -> true } } diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentsAdapter.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentsAdapter.kt index 4805a1186b..77ddb27c63 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentsAdapter.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/AttachmentsAdapter.kt @@ -42,18 +42,18 @@ class AttachmentsAdapter : RecyclerView.Adapter() { val inflater = LayoutInflater.from(parent.context) val itemView = inflater.inflate(viewType, parent, false) return when (viewType) { - R.layout.item_image_attachment -> ZoomableImageViewHolder(itemView) + R.layout.item_image_attachment -> ZoomableImageViewHolder(itemView) R.layout.item_animated_image_attachment -> AnimatedImageViewHolder(itemView) - R.layout.item_video_attachment -> VideoViewHolder(itemView) - else -> UnsupportedViewHolder(itemView) + R.layout.item_video_attachment -> VideoViewHolder(itemView) + else -> UnsupportedViewHolder(itemView) } } override fun getItemViewType(position: Int): Int { val info = attachmentSourceProvider!!.getAttachmentInfoAt(position) return when (info) { - is AttachmentInfo.Image -> R.layout.item_image_attachment - is AttachmentInfo.Video -> R.layout.item_video_attachment + is AttachmentInfo.Image -> R.layout.item_image_attachment + is AttachmentInfo.Video -> R.layout.item_video_attachment is AttachmentInfo.AnimatedImage -> R.layout.item_animated_image_attachment // is AttachmentInfo.Audio -> TODO() // is AttachmentInfo.File -> TODO() @@ -68,13 +68,13 @@ class AttachmentsAdapter : RecyclerView.Adapter() { attachmentSourceProvider?.getAttachmentInfoAt(position)?.let { holder.bind(it) when (it) { - is AttachmentInfo.Image -> { + is AttachmentInfo.Image -> { attachmentSourceProvider?.loadImage((holder as ZoomableImageViewHolder).target, it) } is AttachmentInfo.AnimatedImage -> { attachmentSourceProvider?.loadImage((holder as AnimatedImageViewHolder).target, it) } - is AttachmentInfo.Video -> { + is AttachmentInfo.Video -> { attachmentSourceProvider?.loadVideo((holder as VideoViewHolder).target, it) } // else -> { diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirection.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirection.kt index 7948f37ae8..7816a5a2cc 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirection.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirection.kt @@ -27,12 +27,12 @@ sealed class SwipeDirection { companion object { fun fromAngle(angle: Double): SwipeDirection { return when (angle) { - in 0.0..45.0 -> Right - in 45.0..135.0 -> Up + in 0.0..45.0 -> Right + in 45.0..135.0 -> Up in 135.0..225.0 -> Left in 225.0..315.0 -> Down in 315.0..360.0 -> Right - else -> NotDetected + else -> NotDetected } } } diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirectionDetector.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirectionDetector.kt index 6575248b2d..7b72637c06 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirectionDetector.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeDirectionDetector.kt @@ -33,7 +33,7 @@ class SwipeDirectionDetector( fun handleTouchEvent(event: MotionEvent) { when (event.action) { - MotionEvent.ACTION_DOWN -> { + MotionEvent.ACTION_DOWN -> { startX = event.x startY = event.y } @@ -45,7 +45,7 @@ class SwipeDirectionDetector( startX = startY isDetected = false } - MotionEvent.ACTION_MOVE -> if (!isDetected && getEventDistance(event) > touchSlop) { + MotionEvent.ACTION_MOVE -> if (!isDetected && getEventDistance(event) > touchSlop) { isDetected = true onDirectionDetected(getDirection(startX, startY, event.x, event.y)) } diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeToDismissHandler.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeToDismissHandler.kt index ca2c28b498..7a83ee28d4 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeToDismissHandler.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/SwipeToDismissHandler.kt @@ -44,7 +44,7 @@ class SwipeToDismissHandler( @SuppressLint("ClickableViewAccessibility") override fun onTouch(v: View, event: MotionEvent): Boolean { when (event.action) { - MotionEvent.ACTION_DOWN -> { + MotionEvent.ACTION_DOWN -> { if (swipeView.hitRect.contains(event.x.toInt(), event.y.toInt())) { isTracking = true } @@ -58,7 +58,7 @@ class SwipeToDismissHandler( } return true } - MotionEvent.ACTION_MOVE -> { + MotionEvent.ACTION_MOVE -> { if (isTracking) { val translationY = event.y - startY swipeView.translationY = translationY @@ -66,7 +66,7 @@ class SwipeToDismissHandler( } return true } - else -> { + else -> { return false } } @@ -79,8 +79,8 @@ class SwipeToDismissHandler( private fun onTrackingEnd(parentHeight: Int) { val animateTo = when { swipeView.translationY < -translationLimit -> -parentHeight.toFloat() - swipeView.translationY > translationLimit -> parentHeight.toFloat() - else -> 0f + swipeView.translationY > translationLimit -> parentHeight.toFloat() + else -> 0f } if (animateTo != 0f && !shouldAnimateDismiss()) { diff --git a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/VideoViewHolder.kt b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/VideoViewHolder.kt index 12213a8786..92d28d26c9 100644 --- a/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/VideoViewHolder.kt +++ b/library/attachment-viewer/src/main/java/im/vector/lib/attachmentviewer/VideoViewHolder.kt @@ -146,7 +146,7 @@ class VideoViewHolder constructor(itemView: View) : wasPaused = true views.videoView.pause() } - is AttachmentCommands.SeekTo -> { + is AttachmentCommands.SeekTo -> { val duration = views.videoView.duration if (duration > 0) { val seekDuration = duration * (commands.percentProgress / 100f) diff --git a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerEpoxyController.kt b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerEpoxyController.kt index 9f8093f801..24b9f2ec26 100644 --- a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerEpoxyController.kt +++ b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerEpoxyController.kt @@ -43,7 +43,7 @@ internal class JSonViewerEpoxyController(private val context: Context) : text(async.error.localizedMessage?.toEpoxyCharSequence()) } } - else -> { + else -> { async.invoke()?.let { buildRec(it, 0, "") } @@ -98,7 +98,7 @@ internal class JSonViewerEpoxyController(private val context: Context) : } } } - is JSonViewerArray -> { + is JSonViewerArray -> { if (model.isExpanded) { open(id, model.key, model.index, depth, false, model) model.items.forEach { @@ -137,7 +137,7 @@ internal class JSonViewerEpoxyController(private val context: Context) : } } } - is JSonViewerLeaf -> { + is JSonViewerLeaf -> { valueItem { id(id) depth(depth) @@ -172,12 +172,12 @@ internal class JSonViewerEpoxyController(private val context: Context) : private fun valueToSpan(leaf: JSonViewerLeaf): Span { val host = this return when (leaf.type) { - JSONType.STRING -> { + JSONType.STRING -> { span("\"${leaf.stringRes}\"") { textColor = host.styleProvider.stringColor } } - JSONType.NUMBER -> { + JSONType.NUMBER -> { span(leaf.stringRes) { textColor = host.styleProvider.numberColor } @@ -187,7 +187,7 @@ internal class JSonViewerEpoxyController(private val context: Context) : textColor = host.styleProvider.booleanColor } } - JSONType.NULL -> { + JSONType.NULL -> { span("null") { textColor = host.styleProvider.booleanColor } diff --git a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerModel.kt b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerModel.kt index 6940e79e3f..2492b5454c 100644 --- a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerModel.kt +++ b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/JSonViewerModel.kt @@ -82,7 +82,7 @@ internal object ModelParser { } parent.addChild(objectComposed) } - is JSONArray -> { + is JSONArray -> { val objectComposed = JSonViewerArray(key, index, obj) .apply { isExpanded = initialOpenDepth == -1 || depth <= initialOpenDepth } objectComposed.depth = depth @@ -91,25 +91,25 @@ internal object ModelParser { } parent.addChild(objectComposed) } - is String -> { + is String -> { JSonViewerLeaf(key, index, obj, JSONType.STRING).let { it.depth = depth parent.addChild(it) } } - is Number -> { + is Number -> { JSonViewerLeaf(key, index, obj.toString(), JSONType.NUMBER).let { it.depth = depth parent.addChild(it) } } - is Boolean -> { + is Boolean -> { JSonViewerLeaf(key, index, obj.toString(), JSONType.BOOLEAN).let { it.depth = depth parent.addChild(it) } } - else -> { + else -> { if (obj == JSONObject.NULL) { JSonViewerLeaf(key, index, "null", JSONType.NULL).let { it.depth = depth diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt index 13ef5aa637..928fdf894c 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt @@ -48,7 +48,7 @@ class FilePicker : Picker() { type.isMimeTypeVideo() -> selectedUri.toMultiPickerVideoType(context) type.isMimeTypeImage() -> selectedUri.toMultiPickerImageType(context) type.isMimeTypeAudio() -> selectedUri.toMultiPickerAudioType(context) - else -> { + else -> { // Other files context.contentResolver.query(selectedUri, null, null, null, null) ?.use { cursor -> diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt index e7883c9e53..9377345886 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt @@ -31,15 +31,15 @@ class MultiPicker private constructor() { @Suppress("UNCHECKED_CAST") fun get(type: MultiPicker): T { return when (type) { - IMAGE -> ImagePicker() as T - VIDEO -> VideoPicker() as T - MEDIA -> MediaPicker() as T - FILE -> FilePicker() as T - AUDIO -> AudioPicker() as T - CONTACT -> ContactPicker() as T - CAMERA -> CameraPicker() as T + IMAGE -> ImagePicker() as T + VIDEO -> VideoPicker() as T + MEDIA -> MediaPicker() as T + FILE -> FilePicker() as T + AUDIO -> AudioPicker() as T + CONTACT -> ContactPicker() as T + CAMERA -> CameraPicker() as T CAMERA_VIDEO -> CameraVideoPicker() as T - else -> throw IllegalArgumentException("Unsupported type $type") + else -> throw IllegalArgumentException("Unsupported type $type") } } } diff --git a/library/ui-styles/src/main/res/values/dimens_font.xml b/library/ui-styles/src/main/res/values/dimens_font.xml index 1b5a826acb..ad8f012a16 100644 --- a/library/ui-styles/src/main/res/values/dimens_font.xml +++ b/library/ui-styles/src/main/res/values/dimens_font.xml @@ -7,7 +7,8 @@ 14sp 12sp 10sp + 8sp 14sp - \ No newline at end of file + diff --git a/library/ui-styles/src/main/res/values/styles_location.xml b/library/ui-styles/src/main/res/values/styles_location.xml index 9d9fc862f6..6777450a63 100644 --- a/library/ui-styles/src/main/res/values/styles_location.xml +++ b/library/ui-styles/src/main/res/values/styles_location.xml @@ -40,4 +40,9 @@ center + + diff --git a/library/ui-styles/src/main/res/values/styles_text_view.xml b/library/ui-styles/src/main/res/values/styles_text_view.xml index 77e32da345..0dcaf30f48 100644 --- a/library/ui-styles/src/main/res/values/styles_text_view.xml +++ b/library/ui-styles/src/main/res/values/styles_text_view.xml @@ -48,4 +48,9 @@ 16sp - \ No newline at end of file + + + diff --git a/library/ui-styles/src/main/res/values/text_appearances.xml b/library/ui-styles/src/main/res/values/text_appearances.xml index 8e30dd00d6..1e60e05acf 100644 --- a/library/ui-styles/src/main/res/values/text_appearances.xml +++ b/library/ui-styles/src/main/res/values/text_appearances.xml @@ -85,4 +85,11 @@ 0.02 + + diff --git a/matrix-sdk-android-flow/src/main/java/org/matrix/android/sdk/flow/FlowSession.kt b/matrix-sdk-android-flow/src/main/java/org/matrix/android/sdk/flow/FlowSession.kt index 2839e6ab61..1086928dc6 100644 --- a/matrix-sdk-android-flow/src/main/java/org/matrix/android/sdk/flow/FlowSession.kt +++ b/matrix-sdk-android-flow/src/main/java/org/matrix/android/sdk/flow/FlowSession.kt @@ -88,7 +88,7 @@ class FlowSession(private val session: Session) { } fun liveSyncState(): Flow { - return session.getSyncStateLive().asFlow() + return session.syncService().getSyncStateLive().asFlow() } fun livePushers(): Flow> { diff --git a/matrix-sdk-android/build.gradle b/matrix-sdk-android/build.gradle index 3829063836..45e411533b 100644 --- a/matrix-sdk-android/build.gradle +++ b/matrix-sdk-android/build.gradle @@ -56,7 +56,7 @@ android { // that the app's state is completely cleared between tests. testInstrumentationRunnerArguments clearPackageData: 'true' - buildConfigField "String", "SDK_VERSION", "\"1.4.20\"" + buildConfigField "String", "SDK_VERSION", "\"1.4.22\"" buildConfigField "String", "GIT_SDK_REVISION", "\"${gitRevision()}\"" buildConfigField "String", "GIT_SDK_REVISION_UNIX_DATE", "\"${gitRevisionUnixDate()}\"" @@ -74,6 +74,7 @@ android { buildTypes { debug { + testCoverageEnabled true // Set to true to log privacy or sensible data, such as token buildConfigField "boolean", "LOG_PRIVATE_DATA", project.property("vector.debugPrivateData") // Set to BODY instead of NONE to enable logging @@ -151,7 +152,7 @@ dependencies { // - https://github.com/square/okhttp/issues/3278 // - https://github.com/square/okhttp/issues/4455 // - https://github.com/square/okhttp/issues/3146 - implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.3")) + implementation(platform("com.squareup.okhttp3:okhttp-bom:4.10.0")) implementation 'com.squareup.okhttp3:okhttp' implementation 'com.squareup.okhttp3:logging-interceptor' @@ -175,7 +176,7 @@ dependencies { implementation libs.androidx.work // olm lib is now hosted in MavenCentral - implementation 'org.matrix.android:olm-sdk:3.2.11' + implementation 'org.matrix.android:olm-sdk:3.2.12' // DI implementation libs.dagger.dagger @@ -192,7 +193,7 @@ dependencies { implementation libs.apache.commonsImaging // Phone number https://github.com/google/libphonenumber - implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.49' + implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.50' testImplementation libs.tests.junit // Note: version sticks to 1.9.2 due to https://github.com/mockk/mockk/issues/281 diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt index a763766821..f08f0a28ed 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt @@ -19,10 +19,14 @@ package org.matrix.android.sdk import android.content.Context import androidx.test.core.app.ApplicationProvider import org.junit.Rule +import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.test.shared.createTimberTestRule interface InstrumentedTest { + @Rule + fun retryTestRule() = RetryTestRule(3) + @Rule fun timberTestRule() = createTimberTestRule() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index fdfaceeb4d..7dafe33935 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -137,11 +137,11 @@ class CommonTestHelper private constructor(context: Context) { fun syncSession(session: Session, timeout: Long = TestConstants.timeOutMillis * 10) { val lock = CountDownLatch(1) coroutineScope.launch { - session.startSync(true) - val syncLiveData = session.getSyncStateLive() + session.syncService().startSync(true) + val syncLiveData = session.syncService().getSyncStateLive() val syncObserver = object : Observer { override fun onChanged(t: SyncState?) { - if (session.hasAlreadySynced()) { + if (session.syncService().hasAlreadySynced()) { lock.countDown() syncLiveData.removeObserver(this) } @@ -160,10 +160,10 @@ class CommonTestHelper private constructor(context: Context) { fun clearCacheAndSync(session: Session, timeout: Long = TestConstants.timeOutMillis) { waitWithLatch(timeout) { latch -> session.clearCache() - val syncLiveData = session.getSyncStateLive() + val syncLiveData = session.syncService().getSyncStateLive() val syncObserver = object : Observer { override fun onChanged(t: SyncState?) { - if (session.hasAlreadySynced()) { + if (session.syncService().hasAlreadySynced()) { Timber.v("Clear cache and synced") syncLiveData.removeObserver(this) latch.countDown() @@ -171,7 +171,7 @@ class CommonTestHelper private constructor(context: Context) { } } syncLiveData.observeForever(syncObserver) - session.startSync(true) + session.syncService().startSync(true) } } @@ -252,7 +252,8 @@ class CommonTestHelper private constructor(context: Context) { message: String, numberOfMessages: Int, rootThreadEventId: String, - timeout: Long = TestConstants.timeOutMillis): List { + timeout: Long = TestConstants.timeOutMillis + ): List { val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) timeline.start() val sentEvents = sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) @@ -272,9 +273,11 @@ class CommonTestHelper private constructor(context: Context) { * @param testParams test params about the session * @return the session associated with the newly created account */ - private fun createAccount(userNamePrefix: String, - password: String, - testParams: SessionTestParams): Session { + private fun createAccount( + userNamePrefix: String, + password: String, + testParams: SessionTestParams + ): Session { val session = createAccountAndSync( userNamePrefix + "_" + accountNumber++ + "_" + UUID.randomUUID(), password, @@ -294,9 +297,11 @@ class CommonTestHelper private constructor(context: Context) { * @param testParams test params about the session * @return the session associated with the existing account */ - fun logIntoAccount(userId: String, - password: String, - testParams: SessionTestParams): Session { + fun logIntoAccount( + userId: String, + password: String, + testParams: SessionTestParams + ): Session { val session = logAccountAndSync(userId, password, testParams) assertNotNull(session) return session.also { @@ -311,9 +316,11 @@ class CommonTestHelper private constructor(context: Context) { * @param password the password * @param sessionTestParams parameters for the test */ - private fun createAccountAndSync(userName: String, - password: String, - sessionTestParams: SessionTestParams): Session { + private fun createAccountAndSync( + userName: String, + password: String, + sessionTestParams: SessionTestParams + ): Session { val hs = createHomeServerConfig() runBlockingTest { @@ -349,9 +356,11 @@ class CommonTestHelper private constructor(context: Context) { * @param password the password * @param sessionTestParams session test params */ - private fun logAccountAndSync(userName: String, - password: String, - sessionTestParams: SessionTestParams): Session { + private fun logAccountAndSync( + userName: String, + password: String, + sessionTestParams: SessionTestParams + ): Session { val hs = createHomeServerConfig() runBlockingTest { @@ -377,8 +386,10 @@ class CommonTestHelper private constructor(context: Context) { * @param userName the account username * @param password the password */ - fun logAccountWithError(userName: String, - password: String): Throwable { + fun logAccountWithError( + userName: String, + password: String + ): Throwable { val hs = createHomeServerConfig() runBlockingTest { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt index b6bedbd719..41d0d3a7e8 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt @@ -18,8 +18,10 @@ package org.matrix.android.sdk.common import org.matrix.android.sdk.api.session.Session -data class CryptoTestData(val roomId: String, - val sessions: List) { +data class CryptoTestData( + val roomId: String, + val sessions: List +) { val firstSession: Session get() = sessions.first() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/MockOkHttpInterceptor.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/MockOkHttpInterceptor.kt index b6d833a77c..6dfee2f18f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/MockOkHttpInterceptor.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/MockOkHttpInterceptor.kt @@ -73,9 +73,11 @@ class MockOkHttpInterceptor : TestInterceptor { /** * Simple rule that reply with the given body for any request that matches the match param */ - class SimpleRule(match: String, - private val code: Int = HttpsURLConnection.HTTP_OK, - private val body: String = "{}") : Rule(match) { + class SimpleRule( + match: String, + private val code: Int = HttpsURLConnection.HTTP_OK, + private val body: String = "{}" + ) : Rule(match) { override fun process(originalRequest: Request): Response? { return Response.Builder() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixCallback.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixCallback.kt index 9f6d6eb136..a007d684e3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixCallback.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixCallback.kt @@ -27,8 +27,10 @@ import java.util.concurrent.CountDownLatch * @param onlySuccessful true to fail if an error occurs. This is the default behavior * @param */ -open class TestMatrixCallback(private val countDownLatch: CountDownLatch, - private val onlySuccessful: Boolean = true) : MatrixCallback { +open class TestMatrixCallback( + private val countDownLatch: CountDownLatch, + private val onlySuccessful: Boolean = true +) : MatrixCallback { @CallSuper override fun onSuccess(data: T) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixComponent.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixComponent.kt index 525e168cf1..daf6b73313 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixComponent.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrixComponent.kt @@ -47,7 +47,9 @@ internal interface TestMatrixComponent : MatrixComponent { @Component.Factory interface Factory { - fun create(@BindsInstance context: Context, - @BindsInstance matrixConfiguration: MatrixConfiguration): TestMatrixComponent + fun create( + @BindsInstance context: Context, + @BindsInstance matrixConfiguration: MatrixConfiguration + ): TestMatrixComponent } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/AttachmentEncryptionTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/AttachmentEncryptionTest.kt index f5f585a1e0..17c7c28d81 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/AttachmentEncryptionTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/AttachmentEncryptionTest.kt @@ -22,6 +22,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -40,6 +41,7 @@ import java.util.UUID @Suppress("SpellCheckingInspection") @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Ignore class AttachmentEncryptionTest { private fun checkDecryption(input: String, encryptedFileInfo: EncryptedFileInfo): String { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt index cd6c146f03..dbc6929e34 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt @@ -22,6 +22,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Before +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -37,6 +38,7 @@ import org.matrix.olm.OlmSession private const val DUMMY_DEVICE_KEY = "DeviceKey" @RunWith(AndroidJUnit4::class) +@Ignore class CryptoStoreTest : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 010383dab8..5a61eee7fe 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -626,7 +626,7 @@ class E2eeSanityTests : InstrumentedTest { // we can release this latch? oldCompleteLatch.countDown() } - else -> Unit + else -> Unit } } }) @@ -653,17 +653,17 @@ class E2eeSanityTests : InstrumentedTest { IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT -> { // no need to accept as there was a request first it will auto accept } - IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { + IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { if (matchOnce) { sasTx.userHasVerifiedShortCode() newCode = sasTx.getDecimalCodeRepresentation() matchOnce = false } } - IncomingSasVerificationTransaction.UxState.VERIFIED -> { + IncomingSasVerificationTransaction.UxState.VERIFIED -> { newCompleteLatch.countDown() } - else -> Unit + else -> Unit } } }) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ExportEncryptionTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ExportEncryptionTest.kt index c2d8f4fb35..bddb31fc92 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ExportEncryptionTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ExportEncryptionTest.kt @@ -21,6 +21,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -30,6 +31,7 @@ import org.junit.runners.MethodSorters */ @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Ignore class ExportEncryptionTest { @Test @@ -83,7 +85,8 @@ class ExportEncryptionTest { @Test fun checkExportDecrypt1() { val password = "password" - val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx\n" + "cissyYBxjsfsAndErh065A8=\n-----END MEGOLM SESSION DATA-----" + val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx\n" + + "cissyYBxjsfsAndErh065A8=\n-----END MEGOLM SESSION DATA-----" val expectedString = "plain" var decodedString: String? = null @@ -103,7 +106,8 @@ class ExportEncryptionTest { @Test fun checkExportDecrypt2() { val password = "betterpassword" - val input = "-----BEGIN MEGOLM SESSION DATA-----\nAW1vcmVzYWx0bW9yZXNhbHT//////////wAAAAAAAAAAAAAD6KyBpe1Niv5M5NPm4ZATsJo5nghk\n" + "KYu63a0YQ5DRhUWEKk7CcMkrKnAUiZny\n-----END MEGOLM SESSION DATA-----" + val input = "-----BEGIN MEGOLM SESSION DATA-----\nAW1vcmVzYWx0bW9yZXNhbHT//////////wAAAAAAAAAAAAAD6KyBpe1Niv5M5NPm4ZATsJo5nghk\n" + + "KYu63a0YQ5DRhUWEKk7CcMkrKnAUiZny\n-----END MEGOLM SESSION DATA-----" val expectedString = "Hello, World" var decodedString: String? = null @@ -123,7 +127,8 @@ class ExportEncryptionTest { @Test fun checkExportDecrypt3() { val password = "SWORDFISH" - val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXllc3NhbHR5Z29vZG5lc3P//////////wAAAAAAAAAAAAAD6OIW+Je7gwvjd4kYrb+49gKCfExw\n" + "MgJBMD4mrhLkmgAngwR1pHjbWXaoGybtiAYr0moQ93GrBQsCzPbvl82rZhaXO3iH5uHo/RCEpOqp\nPgg29363BGR+/Ripq/VCLKGNbw==\n-----END MEGOLM SESSION DATA-----" + val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXllc3NhbHR5Z29vZG5lc3P//////////wAAAAAAAAAAAAAD6OIW+Je7gwvjd4kYrb+49gKCfExw\n" + + "MgJBMD4mrhLkmgAngwR1pHjbWXaoGybtiAYr0moQ93GrBQsCzPbvl82rZhaXO3iH5uHo/RCEpOqp\nPgg29363BGR+/Ripq/VCLKGNbw==\n-----END MEGOLM SESSION DATA-----" val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically" var decodedString: String? = null @@ -202,7 +207,8 @@ class ExportEncryptionTest { @Test fun checkExportEncrypt4() { - val password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + val password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically" var decodedString: String? = null diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index 5fe7376184..e8a474a54a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -21,6 +21,7 @@ import org.amshove.kluent.shouldBe import org.junit.Assert import org.junit.Before import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -59,6 +60,7 @@ import kotlin.coroutines.resume */ @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) +@Ignore class UnwedgingTest : InstrumentedTest { private lateinit var messagesReceivedByBob: List diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index 05790bfb7d..8cb38ddc87 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -25,6 +25,7 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -47,6 +48,7 @@ import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @LargeTest +@Ignore class XSigningTest : InstrumentedTest { @Test diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index b16e4b82eb..7bb53e139c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -25,6 +25,7 @@ import org.amshove.kluent.internal.assertEquals import org.junit.Assert import org.junit.Assert.assertNull import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -50,6 +51,7 @@ import org.matrix.android.sdk.mustFail @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest +@Ignore class KeyShareTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) @@ -422,7 +424,7 @@ class KeyShareTests : InstrumentedTest { // /!\ Stop initial alice session syncing so that it can't reply aliceSession.cryptoService().enableKeyGossiping(false) - aliceSession.stopSync() + aliceSession.syncService().stopSync() // Let's now try to request aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvents.first().root) @@ -445,7 +447,7 @@ class KeyShareTests : InstrumentedTest { // let's wake up alice aliceSession.cryptoService().enableKeyGossiping(true) - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) // We should now get a reply from first session commonTestHelper.waitWithLatch { latch -> diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index 0aac4297e4..ae420a09b3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -21,6 +21,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Assert import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -46,6 +47,7 @@ import org.matrix.android.sdk.mustFail @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest +@Ignore class WithHeldTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index c6e17e8c44..fb498e0de5 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -24,6 +24,7 @@ import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -55,6 +56,7 @@ import java.util.concurrent.CountDownLatch @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest +@Ignore class KeysBackupTest : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index 4eccdfad1f..38f94c5103 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -33,7 +33,8 @@ import java.util.concurrent.CountDownLatch internal class KeysBackupTestHelper( private val testHelper: CommonTestHelper, - private val cryptoTestHelper: CryptoTestHelper) { + private val cryptoTestHelper: CryptoTestHelper +) { fun waitForKeybackUpBatching() { Thread.sleep(400) @@ -96,8 +97,10 @@ internal class KeysBackupTestHelper( ) } - fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, - password: String? = null): PrepareKeysBackupDataResult { + fun prepareAndCreateKeysBackupData( + keysBackup: KeysBackupService, + password: String? = null + ): PrepareKeysBackupDataResult { val stateObserver = StateObserver(keysBackup) val megolmBackupCreationInfo = testHelper.doSync { @@ -169,9 +172,11 @@ internal class KeysBackupTestHelper( * - The new device must have the same count of megolm keys * - Alice must have the same keys on both devices */ - fun checkRestoreSuccess(testData: KeysBackupScenarioData, - total: Int, - imported: Int) { + fun checkRestoreSuccess( + testData: KeysBackupScenarioData, + total: Int, + imported: Int + ) { // - Imported keys number must be correct Assert.assertEquals(testData.aliceKeys.size, total) Assert.assertEquals(total, imported) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt index 31bd3c9cce..9ee10eddcf 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt @@ -18,5 +18,7 @@ package org.matrix.android.sdk.internal.crypto.keysbackup import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo -data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, - val version: String) +data class PrepareKeysBackupDataResult( + val megolmBackupCreationInfo: MegolmBackupCreationInfo, + val version: String +) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/StateObserver.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/StateObserver.kt index 80e54d82ec..6c97774547 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/StateObserver.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/StateObserver.kt @@ -27,9 +27,11 @@ import java.util.concurrent.CountDownLatch * This class observe the state change of a KeysBackup object and provide a method to check the several state change * It checks all state transitions and detected forbidden transition */ -internal class StateObserver(private val keysBackup: KeysBackupService, - private val latch: CountDownLatch? = null, - private val expectedStateChange: Int = -1) : KeysBackupStateListener { +internal class StateObserver( + private val keysBackup: KeysBackupService, + private val latch: CountDownLatch? = null, + private val expectedStateChange: Int = -1 +) : KeysBackupStateListener { private val allowedStateTransitions = listOf( KeysBackupState.BackingUp to KeysBackupState.ReadyToBackUp, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index c4d9ba4ee3..c2e74abc59 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -52,6 +52,7 @@ import java.util.concurrent.CountDownLatch @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Ignore class SASTest : InstrumentedTest { @Test @@ -264,14 +265,16 @@ class SASTest : InstrumentedTest { assertEquals("Request should be cancelled with m.unknown_method", CancelCode.UnknownMethod.value, cancelReq.code) } - private fun fakeBobStart(bobSession: Session, - aliceUserID: String?, - aliceDevice: String?, - tid: String, - protocols: List = SASDefaultVerificationTransaction.KNOWN_AGREEMENT_PROTOCOLS, - hashes: List = SASDefaultVerificationTransaction.KNOWN_HASHES, - mac: List = SASDefaultVerificationTransaction.KNOWN_MACS, - codes: List = SASDefaultVerificationTransaction.KNOWN_SHORT_CODES) { + private fun fakeBobStart( + bobSession: Session, + aliceUserID: String?, + aliceDevice: String?, + tid: String, + protocols: List = SASDefaultVerificationTransaction.KNOWN_AGREEMENT_PROTOCOLS, + hashes: List = SASDefaultVerificationTransaction.KNOWN_HASHES, + mac: List = SASDefaultVerificationTransaction.KNOWN_MACS, + codes: List = SASDefaultVerificationTransaction.KNOWN_SHORT_CODES + ) { val startMessage = KeyVerificationStart( fromDevice = bobSession.cryptoService().getMyDevice().deviceId, method = VerificationMethod.SAS.toValue(), @@ -412,7 +415,7 @@ class SASTest : InstrumentedTest { OutgoingSasVerificationTransaction.UxState.SHOW_SAS -> { aliceSASLatch.countDown() } - else -> Unit + else -> Unit } } } @@ -426,7 +429,7 @@ class SASTest : InstrumentedTest { IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT -> { tx.performAccept() } - else -> Unit + else -> Unit } if (uxState === IncomingSasVerificationTransaction.UxState.SHOW_SAS) { bobSASLatch.countDown() @@ -476,7 +479,7 @@ class SASTest : InstrumentedTest { aliceSASLatch.countDown() } } - else -> Unit + else -> Unit } } } @@ -496,16 +499,16 @@ class SASTest : InstrumentedTest { tx.performAccept() } } - IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { + IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { if (matchOnce) { matchOnce = false tx.userHasVerifiedShortCode() } } - IncomingSasVerificationTransaction.UxState.VERIFIED -> { + IncomingSasVerificationTransaction.UxState.VERIFIED -> { bobSASLatch.countDown() } - else -> Unit + else -> Unit } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 462f47cafc..3f22906965 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.internal.crypto.verification.qrcode import androidx.test.ext.junit.runners.AndroidJUnit4 import org.amshove.kluent.shouldBe import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -41,6 +42,7 @@ import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) +@Ignore class VerificationTest : InstrumentedTest { data class ExpectedResult( @@ -151,10 +153,12 @@ class VerificationTest : InstrumentedTest { // TODO Add tests without SAS - private fun doTest(aliceSupportedMethods: List, - bobSupportedMethods: List, - expectedResultForAlice: ExpectedResult, - expectedResultForBob: ExpectedResult) = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + private fun doTest( + aliceSupportedMethods: List, + bobSupportedMethods: List, + expectedResultForAlice: ExpectedResult, + expectedResultForBob: ExpectedResult + ) = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParserTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParserTest.kt index acb23bf723..0560cfec95 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParserTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParserTest.kt @@ -289,9 +289,11 @@ class MarkdownParserTest : InstrumentedTest { markdownParser.parse(text).expect(text, null) } - private fun testType(name: String, - markdownPattern: String, - htmlExpectedTag: String) { + private fun testType( + name: String, + markdownPattern: String, + htmlExpectedTag: String + ) { // Test simple case "$markdownPattern$name$markdownPattern" .let { @@ -376,10 +378,12 @@ class MarkdownParserTest : InstrumentedTest { } } - private fun testTypeNewLines(name: String, - markdownPattern: String, - htmlExpectedTag: String, - softBreak: String = "
") { + private fun testTypeNewLines( + name: String, + markdownPattern: String, + htmlExpectedTag: String, + softBreak: String = "
" + ) { // With new line inside the block "$markdownPattern$name\n$name$markdownPattern" .let { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/TestPermalinkService.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/TestPermalinkService.kt index 2f9a5e0a73..3a267ec694 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/TestPermalinkService.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/session/room/send/TestPermalinkService.kt @@ -44,7 +44,7 @@ class TestPermalinkService : PermalinkService { override fun createMentionSpanTemplate(type: PermalinkService.SpanTemplateType, forceMatrixTo: Boolean): String { return when (type) { - HTML -> "%2\$s" + HTML -> "%2\$s" MARKDOWN -> "[%2\$s](https://matrix.to/#/%1\$s)" } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt index 1ffcc2a3e6..45bd38870d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt @@ -83,7 +83,7 @@ class ThreadMessagingTest : InstrumentedTest { val timeline = aliceRoom.timelineService().createTimeline(null, TimelineSettings(30)) timeline.start() - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) run { val lock = CountDownLatch(1) val eventsListener = commonTestHelper.createEventListener(lock) { snapshot -> @@ -97,7 +97,7 @@ class ThreadMessagingTest : InstrumentedTest { timeline.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - aliceSession.stopSync() + aliceSession.syncService().stopSync() } @Test @@ -144,7 +144,7 @@ class ThreadMessagingTest : InstrumentedTest { val timeline = aliceRoom.timelineService().createTimeline(null, TimelineSettings(30)) timeline.start() - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) run { val lock = CountDownLatch(1) val eventsListener = commonTestHelper.createEventListener(lock) { snapshot -> @@ -156,9 +156,9 @@ class ThreadMessagingTest : InstrumentedTest { timeline.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - aliceSession.stopSync() + aliceSession.syncService().stopSync() - bobSession.startSync(true) + bobSession.syncService().startSync(true) run { val lock = CountDownLatch(1) val eventsListener = commonTestHelper.createEventListener(lock) { snapshot -> @@ -170,7 +170,7 @@ class ThreadMessagingTest : InstrumentedTest { timeline.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - bobSession.stopSync() + bobSession.syncService().stopSync() } @Test @@ -217,7 +217,7 @@ class ThreadMessagingTest : InstrumentedTest { val timeline = aliceRoom.timelineService().createTimeline(null, TimelineSettings(30)) timeline.start() - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) run { val lock = CountDownLatch(1) val eventsListener = commonTestHelper.createEventListener(lock) { snapshot -> @@ -233,7 +233,7 @@ class ThreadMessagingTest : InstrumentedTest { timeline.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - aliceSession.stopSync() + aliceSession.syncService().stopSync() } @Test @@ -314,7 +314,7 @@ class ThreadMessagingTest : InstrumentedTest { val timeline = aliceRoom.timelineService().createTimeline(null, TimelineSettings(30)) timeline.start() - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) run { val lock = CountDownLatch(1) val eventsListener = commonTestHelper.createEventListener(lock) { snapshot -> @@ -338,6 +338,6 @@ class ThreadMessagingTest : InstrumentedTest { timeline.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - aliceSession.stopSync() + aliceSession.syncService().stopSync() } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/ChunkEntityTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/ChunkEntityTest.kt index 94b2ba55a3..986d58741c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/ChunkEntityTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/ChunkEntityTest.kt @@ -154,9 +154,11 @@ internal class ChunkEntityTest : InstrumentedTest { } } - private fun ChunkEntity.addAll(roomId: String, - events: List, - direction: PaginationDirection) { + private fun ChunkEntity.addAll( + roomId: String, + events: List, + direction: PaginationDirection + ) { events.forEach { event -> val fakeEvent = event.toEntity(roomId, SendState.SYNCED, clock.epochMillis()).let { realm.copyToRealm(it) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/FakeTokenChunkEvent.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/FakeTokenChunkEvent.kt index 657f622c5b..2e9478ba7e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/FakeTokenChunkEvent.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/FakeTokenChunkEvent.kt @@ -19,8 +19,9 @@ package org.matrix.android.sdk.session.room.timeline import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.internal.session.room.timeline.TokenChunkEvent -internal data class FakeTokenChunkEvent(override val start: String?, - override val end: String?, - override val events: List = emptyList(), - override val stateEvents: List = emptyList() +internal data class FakeTokenChunkEvent( + override val start: String?, + override val end: String?, + override val events: List = emptyList(), + override val stateEvents: List = emptyList() ) : TokenChunkEvent diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt index 2b72ecc52a..a37d2ce015 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt @@ -57,7 +57,7 @@ class PollAggregationTest : InstrumentedTest { // Bob creates a poll roomFromBobPOV.sendService().sendPoll(PollType.DISCLOSED, pollQuestion, pollOptions) - aliceSession.startSync(true) + aliceSession.syncService().startSync(true) val aliceTimeline = roomFromAlicePOV.timelineService().createTimeline(null, TimelineSettings(30)) aliceTimeline.start() @@ -77,7 +77,7 @@ class PollAggregationTest : InstrumentedTest { } when (lock.count.toInt()) { - TOTAL_TEST_COUNT -> { + TOTAL_TEST_COUNT -> { // Poll has just been created. testInitialPollConditions(pollContent, pollSummary) lock.countDown() @@ -119,7 +119,7 @@ class PollAggregationTest : InstrumentedTest { testEndedPoll(pollSummary) lock.countDown() } - else -> { + else -> { fail("Lock count ${lock.count} didn't handled.") } } @@ -133,7 +133,7 @@ class PollAggregationTest : InstrumentedTest { aliceTimeline.removeAllListeners() - aliceSession.stopSync() + aliceSession.syncService().stopSync() aliceTimeline.dispose() } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/RoomDataHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/RoomDataHelper.kt index 8a4429db45..53585ae82a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/RoomDataHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/RoomDataHelper.kt @@ -41,11 +41,12 @@ object RoomDataHelper { } } - private fun createFakeEvent(type: String, - content: Content? = null, - prevContent: Content? = null, - sender: String = FAKE_TEST_SENDER, - stateKey: String? = null + private fun createFakeEvent( + type: String, + content: Content? = null, + prevContent: Content? = null, + sender: String = FAKE_TEST_SENDER, + stateKey: String? = null ): Event { return Event( type = type, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt index 3ff4572add..03ab6e6767 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt @@ -88,7 +88,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { } // Bob stop to sync - bobSession.stopSync() + bobSession.syncService().stopSync() val firstMessage = "First messages from Alice" // Alice sends 30 messages @@ -101,7 +101,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { .eventId // Bob start to sync - bobSession.startSync(true) + bobSession.syncService().startSync(true) run { val lock = CountDownLatch(1) @@ -125,7 +125,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { } // Bob stop to sync - bobSession.stopSync() + bobSession.syncService().stopSync() val secondMessage = "Second messages from Alice" // Alice sends again 30 messages @@ -136,7 +136,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { ) // Bob start to sync - bobSession.startSync(true) + bobSession.syncService().startSync(true) run { val lock = CountDownLatch(1) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 7ed0be927c..59b3b14532 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -20,6 +20,7 @@ import androidx.test.filters.LargeTest import kotlinx.coroutines.runBlocking import org.amshove.kluent.internal.assertEquals import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -38,6 +39,7 @@ import org.matrix.android.sdk.common.TestConstants @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest +@Ignore class TimelineSimpleBackPaginationTest : InstrumentedTest { @Test diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt index 87f404b0f1..27ea0e1c3c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt @@ -71,7 +71,7 @@ class TimelineWithManyMembersTest : InstrumentedTest { val timelineForCurrentMember = roomForCurrentMember.timelineService().createTimeline(null, TimelineSettings(30)) timelineForCurrentMember.start() - session.startSync(true) + session.syncService().startSync(true) run { val lock = CountDownLatch(1) @@ -92,7 +92,7 @@ class TimelineWithManyMembersTest : InstrumentedTest { timelineForCurrentMember.addListener(eventsListener) commonTestHelper.await(lock, 600_000) } - session.stopSync() + session.syncService().stopSync() } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index 0d8a9058a2..0cc0ef57c4 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -98,6 +99,7 @@ class SpaceCreationTest : InstrumentedTest { } @Test + @Ignore fun testJoinSimplePublicSpace() = runSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index f16cd91e36..5396251438 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -387,9 +387,10 @@ class SpaceHierarchyTest : InstrumentedTest { val roomIds: List ) - private fun createPublicSpace(session: Session, - spaceName: String, - childInfo: List> + private fun createPublicSpace( + session: Session, + spaceName: String, + childInfo: List> /** Name, auto-join, canonical*/ ): TestSpaceCreationResult { var spaceId = "" @@ -416,9 +417,10 @@ class SpaceHierarchyTest : InstrumentedTest { return TestSpaceCreationResult(spaceId, roomIds) } - private fun createPrivateSpace(session: Session, - spaceName: String, - childInfo: List> + private fun createPrivateSpace( + session: Session, + spaceName: String, + childInfo: List> /** Name, auto-join, canonical*/ ): TestSpaceCreationResult { var spaceId = "" diff --git a/matrix-sdk-android/src/main/java/org/commonmark/ext/maths/InlineMaths.kt b/matrix-sdk-android/src/main/java/org/commonmark/ext/maths/InlineMaths.kt index 3fe8d15696..556579942b 100644 --- a/matrix-sdk-android/src/main/java/org/commonmark/ext/maths/InlineMaths.kt +++ b/matrix-sdk-android/src/main/java/org/commonmark/ext/maths/InlineMaths.kt @@ -26,14 +26,14 @@ internal class InlineMaths(private val delimiter: InlineDelimiter) : CustomNode( override fun getOpeningDelimiter(): String { return when (delimiter) { - InlineDelimiter.SINGLE_DOLLAR -> "$" + InlineDelimiter.SINGLE_DOLLAR -> "$" InlineDelimiter.ROUND_BRACKET_ESCAPED -> "\\(" } } override fun getClosingDelimiter(): String { return when (delimiter) { - InlineDelimiter.SINGLE_DOLLAR -> "$" + InlineDelimiter.SINGLE_DOLLAR -> "$" InlineDelimiter.ROUND_BRACKET_ESCAPED -> "\\)" } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt index 629d947bb3..5ae70e1978 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt @@ -28,9 +28,11 @@ import org.matrix.android.sdk.api.session.Session * This interface defines methods to authenticate or to create an account to a matrix server. */ interface AuthenticationService { + /** * Request the supported login flows for this homeserver. - * This is the first method to call to be able to get a wizard to login or to create an account + * This is the first method to call to be able to get a wizard to login or to create an account. + * @param homeServerConnectionConfig contains the homeserver URL to login to, a wellKnown lookup will be attempted. */ suspend fun getLoginFlow(homeServerConnectionConfig: HomeServerConnectionConfig): LoginFlowResult @@ -93,14 +95,18 @@ interface AuthenticationService { /** * Create a session after a SSO successful login. */ - suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, - credentials: Credentials): Session + suspend fun createSessionFromSso( + homeServerConnectionConfig: HomeServerConnectionConfig, + credentials: Credentials + ): Session /** * Perform a wellknown request, using the domain from the matrixId. */ - suspend fun getWellKnownData(matrixId: String, - homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult + suspend fun getWellKnownData( + matrixId: String, + homeServerConnectionConfig: HomeServerConnectionConfig? + ): WellknownResult /** * Authenticate with a matrixId and a password. @@ -111,9 +117,11 @@ interface AuthenticationService { * @param initialDeviceName the initial device name * @param deviceId the device id, optional. If not provided or null, the server will generate one. */ - suspend fun directAuthentication(homeServerConnectionConfig: HomeServerConnectionConfig, - matrixId: String, - password: String, - initialDeviceName: String, - deviceId: String? = null): Session + suspend fun directAuthentication( + homeServerConnectionConfig: HomeServerConnectionConfig, + matrixId: String, + password: String, + initialDeviceName: String, + deviceId: String? = null + ): Session } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/converter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/converter.kt index 80630bc4e7..e2f16ceee8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/converter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/converter.kt @@ -41,8 +41,10 @@ import org.matrix.android.sdk.api.auth.registration.TermPolicies * @param userLanguage the user language * @param defaultLanguage the default language to use if the user language is not found for a policy in registrationFlowResponse */ -fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, - defaultLanguage: String = "en"): List { +fun TermPolicies.toLocalizedLoginTerms( + userLanguage: String, + defaultLanguage: String = "en" +): List { val result = ArrayList() val policies = get("policies") @@ -67,8 +69,8 @@ fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, // Search for language policy.keys.forEach { policyKey -> when (policyKey) { - "version" -> Unit // Ignore - userLanguage -> { + "version" -> Unit // Ignore + userLanguage -> { // We found the data for the user language userLanguageUrlAndName = extractUrlAndName(policy[policyKey]) } @@ -76,7 +78,7 @@ fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, // We found default language defaultLanguageUrlAndName = extractUrlAndName(policy[policyKey]) } - else -> { + else -> { if (firstUrlAndName == null) { // Get at least some data firstUrlAndName = extractUrlAndName(policy[policyKey]) @@ -87,7 +89,7 @@ fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, // Copy found language data by priority when { - userLanguageUrlAndName != null -> { + userLanguageUrlAndName != null -> { localizedFlowDataLoginTermsLocalizedUrl = userLanguageUrlAndName!!.url localizedFlowDataLoginTermsLocalizedName = userLanguageUrlAndName!!.name } @@ -95,7 +97,7 @@ fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, localizedFlowDataLoginTermsLocalizedUrl = defaultLanguageUrlAndName!!.url localizedFlowDataLoginTermsLocalizedName = defaultLanguageUrlAndName!!.name } - firstUrlAndName != null -> { + firstUrlAndName != null -> { localizedFlowDataLoginTermsLocalizedUrl = firstUrlAndName!!.url localizedFlowDataLoginTermsLocalizedName = firstUrlAndName!!.name } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SsoIdentityProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SsoIdentityProvider.kt index a0733dda97..773f5a8cc4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SsoIdentityProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SsoIdentityProvider.kt @@ -66,17 +66,17 @@ data class SsoIdentityProvider( private fun toPriority(): Int { return when (brand) { // We are on Android, so user is more likely to have a Google account - BRAND_GOOGLE -> 5 + BRAND_GOOGLE -> 5 // Facebook is also an important SSO provider BRAND_FACEBOOK -> 4 // Twitter is more for professionals - BRAND_TWITTER -> 3 + BRAND_TWITTER -> 3 // Here it's very for techie people BRAND_GITHUB, - BRAND_GITLAB -> 2 + BRAND_GITLAB -> 2 // And finally, if the account has been created with an iPhone... - BRAND_APPLE -> 1 - else -> 0 + BRAND_APPLE -> 1 + else -> 0 } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt index 3232025de3..5b8d2328c7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt @@ -39,10 +39,12 @@ interface LoginWizard { * @param deviceId the device id, optional. If not provided or null, the server will generate one. * @return a [Session] if the login is successful */ - suspend fun login(login: String, - password: String, - initialDeviceName: String, - deviceId: String? = null): Session + suspend fun login( + login: String, + password: String, + initialDeviceName: String, + deviceId: String? = null + ): Session /** * Exchange a login token to an access token. @@ -63,14 +65,14 @@ interface LoginWizard { * [resetPasswordMailConfirmed] is successfully called. * * @param email an email previously associated to the account the user wants the password to be reset. - * @param newPassword the desired new password */ - suspend fun resetPassword(email: String, - newPassword: String) + suspend fun resetPassword(email: String) /** * Confirm the new password, once the user has checked their email * When this method succeed, tha account password will be effectively modified. + * + * @param newPassword the desired new password */ - suspend fun resetPasswordMailConfirmed() + suspend fun resetPasswordMailConfirmed(newPassword: String) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt index 1252e93b84..98542d2086 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt @@ -88,15 +88,15 @@ fun RegistrationFlowResponse.toFlowResult(): FlowResult { val isMandatory = flows?.all { type in it.stages.orEmpty() } == true val stage = when (type) { - LoginFlowTypes.RECAPTCHA -> Stage.ReCaptcha( + LoginFlowTypes.RECAPTCHA -> Stage.ReCaptcha( isMandatory, ((params?.get(type) as? Map<*, *>)?.get("public_key") as? String) ?: "" ) - LoginFlowTypes.DUMMY -> Stage.Dummy(isMandatory) - LoginFlowTypes.TERMS -> Stage.Terms(isMandatory, params?.get(type) as? TermPolicies ?: emptyMap()) + LoginFlowTypes.DUMMY -> Stage.Dummy(isMandatory) + LoginFlowTypes.TERMS -> Stage.Terms(isMandatory, params?.get(type) as? TermPolicies ?: emptyMap()) LoginFlowTypes.EMAIL_IDENTITY -> Stage.Email(isMandatory) - LoginFlowTypes.MSISDN -> Stage.Msisdn(isMandatory) - else -> Stage.Other(isMandatory, type, (params?.get(type) as? Map<*, *>)) + LoginFlowTypes.MSISDN -> Stage.Msisdn(isMandatory) + else -> Stage.Other(isMandatory, type, (params?.get(type) as? Map<*, *>)) } if (type in completedStages.orEmpty()) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationWizard.kt index 14d26bf2b3..995fd27ace 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationWizard.kt @@ -54,9 +54,11 @@ interface RegistrationWizard { * @param password the desired password * @param initialDeviceDisplayName the device display name */ - suspend fun createAccount(userName: String?, - password: String?, - initialDeviceDisplayName: String?): RegistrationResult + suspend fun createAccount( + userName: String?, + password: String?, + initialDeviceDisplayName: String? + ): RegistrationResult /** * Perform the "m.login.recaptcha" stage. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/wellknown/WellknownResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/wellknown/WellknownResult.kt index 56257db79c..ea5570db1c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/wellknown/WellknownResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/wellknown/WellknownResult.kt @@ -26,9 +26,11 @@ sealed class WellknownResult { * Retrieve the specific piece of information from the user in a way which fits within the existing client user experience, * if the client is inclined to do so. Failure can take place instead if no good user experience for this is possible at this point. */ - data class Prompt(val homeServerUrl: String, - val identityServerUrl: String?, - val wellKnown: WellKnown) : WellknownResult() + data class Prompt( + val homeServerUrl: String, + val identityServerUrl: String?, + val wellKnown: WellKnown + ) : WellknownResult() /** * Stop the current auto-discovery mechanism. If no more auto-discovery mechanisms are available, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt index 5e1350e327..9f979098f8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.extensions fun CharSequence.ensurePrefix(prefix: CharSequence): CharSequence { return when { startsWith(prefix) -> this - else -> "$prefix$this" + else -> "$prefix$this" } } @@ -27,3 +27,8 @@ fun CharSequence.ensurePrefix(prefix: CharSequence): CharSequence { * Append a new line and then the provided string. */ fun StringBuilder.appendNl(str: String) = append("\n").append(str) + +/** + * Returns null if the string is empty. + */ +fun String.ensureNotEmpty() = ifEmpty { null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ssl/Fingerprint.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ssl/Fingerprint.kt index 93e93fd292..2fc04013f9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ssl/Fingerprint.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ssl/Fingerprint.kt @@ -36,7 +36,7 @@ data class Fingerprint( internal fun matchesCert(cert: X509Certificate): Boolean { val o: Fingerprint? = when (hashType) { HashType.SHA256 -> newSha256Fingerprint(cert) - HashType.SHA1 -> newSha1Fingerprint(cert) + HashType.SHA1 -> newSha1Fingerprint(cert) } return equals(o) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt index 2f1ae8cd87..b3a629094c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt @@ -17,8 +17,6 @@ package org.matrix.android.sdk.api.session import androidx.annotation.MainThread -import androidx.lifecycle.LiveData -import kotlinx.coroutines.flow.SharedFlow import okhttp3.OkHttpClient import org.matrix.android.sdk.api.MatrixCoroutineDispatchers import org.matrix.android.sdk.api.auth.data.SessionParams @@ -37,7 +35,6 @@ import org.matrix.android.sdk.api.session.file.FileService import org.matrix.android.sdk.api.session.group.GroupService import org.matrix.android.sdk.api.session.homeserver.HomeServerCapabilitiesService import org.matrix.android.sdk.api.session.identity.IdentityService -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.integrationmanager.IntegrationManagerService import org.matrix.android.sdk.api.session.media.MediaService import org.matrix.android.sdk.api.session.openid.OpenIdService @@ -55,8 +52,7 @@ import org.matrix.android.sdk.api.session.signout.SignOutService import org.matrix.android.sdk.api.session.space.SpaceService import org.matrix.android.sdk.api.session.statistics.StatisticsListener import org.matrix.android.sdk.api.session.sync.FilterService -import org.matrix.android.sdk.api.session.sync.SyncState -import org.matrix.android.sdk.api.session.sync.model.SyncResponse +import org.matrix.android.sdk.api.session.sync.SyncService import org.matrix.android.sdk.api.session.terms.TermsService import org.matrix.android.sdk.api.session.thirdparty.ThirdPartyService import org.matrix.android.sdk.api.session.typing.TypingUsersTracker @@ -98,59 +94,11 @@ interface Session { @MainThread fun open() - /** - * Requires a one time background sync. - */ - fun requireBackgroundSync() - - /** - * Launches infinite self rescheduling background syncs via the WorkManager. - * - * While dozing, syncs will only occur during maintenance windows. - * For reliability it's recommended to also start a long running foreground service - * along with disabling battery optimizations. - */ - fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) - - fun stopAnyBackgroundSync() - - /** - * This method start the sync thread. - */ - fun startSync(fromForeground: Boolean) - - /** - * This method stop the sync thread. - */ - fun stopSync() - /** * Clear cache of the session. */ suspend fun clearCache() - /** - * This method allows to listen the sync state. - * @return a [LiveData] of [SyncState]. - */ - fun getSyncStateLive(): LiveData - - /** - * This method returns the current sync state. - * @return the current [SyncState]. - */ - fun getSyncState(): SyncState - - /** - * This method returns a flow of SyncResponse. New value will be pushed through the sync thread. - */ - fun syncFlow(): SharedFlow - - /** - * This methods return true if an initial sync has been processed. - */ - fun hasAlreadySynced(): Boolean - /** * This method allow to close a session. It does stop some services. */ @@ -247,9 +195,9 @@ interface Session { fun termsService(): TermsService /** - * Returns the SyncStatusService associated with the session. + * Returns the SyncService associated with the session. */ - fun syncStatusService(): SyncStatusService + fun syncService(): SyncService /** * Returns the SecureStorageService associated with the session. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/account/AccountService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/account/AccountService.kt index 1f28dbd8af..e3d52adfc5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/account/AccountService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/account/AccountService.kt @@ -27,8 +27,10 @@ interface AccountService { * @param password Current password. * @param newPassword New password */ - suspend fun changePassword(password: String, - newPassword: String) + suspend fun changePassword( + password: String, + newPassword: String + ) /** * Deactivate the account. @@ -46,6 +48,8 @@ interface AccountService { * an incomplete view of conversations * @param userInteractiveAuthInterceptor see [UserInteractiveAuthInterceptor] */ - suspend fun deactivateAccount(eraseAllData: Boolean, - userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor) + suspend fun deactivateAccount( + eraseAllData: Boolean, + userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt index e13f7310e0..c87ac3c821 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt @@ -91,10 +91,12 @@ interface MxCall : MxCallDetail { * Send a m.call.replaces event to initiate call transfer. * See [org.matrix.android.sdk.api.session.room.model.call.CallReplacesContent] for documentation about the parameters */ - suspend fun transfer(targetUserId: String, - targetRoomId: String?, - createCallId: String?, - awaitCallId: String?) + suspend fun transfer( + targetUserId: String, + targetRoomId: String?, + createCallId: String?, + awaitCallId: String? + ) fun addListener(listener: StateListener) fun removeListener(listener: StateListener) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt index 35f3ab3162..9cc87b6f71 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt @@ -88,9 +88,11 @@ interface CryptoService { fun getDeviceTrackingStatus(userId: String): Int - suspend fun importRoomKeys(roomKeysAsArray: ByteArray, - password: String, - progressListener: ProgressListener?): ImportRoomKeysResult + suspend fun importRoomKeys( + roomKeysAsArray: ByteArray, + password: String, + progressListener: ProgressListener? + ): ImportRoomKeysResult suspend fun exportRoomKeys(password: String): ByteArray @@ -119,10 +121,12 @@ interface CryptoService { fun isRoomEncrypted(roomId: String): Boolean // TODO This could be removed from this interface - fun encryptEventContent(eventContent: Content, - eventType: String, - roomId: String, - callback: MatrixCallback) + fun encryptEventContent( + eventContent: Content, + eventType: String, + roomId: String, + callback: MatrixCallback + ) fun discardOutboundSession(roomId: String) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt index 0b5bbe3bbd..94ee7ba403 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt @@ -25,12 +25,14 @@ import org.matrix.olm.OlmException */ sealed class MXCryptoError : Throwable() { - data class Base(val errorType: ErrorType, - val technicalMessage: String, - /** - * Describe the error with more details. - */ - val detailedErrorDescription: String? = null) : MXCryptoError() + data class Base( + val errorType: ErrorType, + val technicalMessage: String, + /** + * Describe the error with more details. + */ + val detailedErrorDescription: String? = null + ) : MXCryptoError() data class OlmError(val olmException: OlmException) : MXCryptoError() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt index 855f17a34f..7202be7a21 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt @@ -26,7 +26,7 @@ data class RequestReply( ) sealed class RequestResult { - data class Success(val chainIndex: Int) : RequestResult() + data class Success(val chainIndex: Int) : RequestResult() data class Failure(val code: WithHeldCode) : RequestResult() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt index 5439389096..69f314f76f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt @@ -37,14 +37,18 @@ interface CrossSigningService { * Initialize cross signing for this user. * Users needs to enter credentials */ - fun initializeCrossSigning(uiaInterceptor: UserInteractiveAuthInterceptor?, - callback: MatrixCallback) + fun initializeCrossSigning( + uiaInterceptor: UserInteractiveAuthInterceptor?, + callback: MatrixCallback + ) fun isCrossSigningInitialized(): Boolean = getMyCrossSigningKeys() != null - fun checkTrustFromPrivateKeys(masterKeyPrivateKey: String?, - uskKeyPrivateKey: String?, - sskPrivateKey: String?): UserTrustResult + fun checkTrustFromPrivateKeys( + masterKeyPrivateKey: String?, + uskKeyPrivateKey: String?, + sskPrivateKey: String? + ): UserTrustResult fun getUserCrossSigningKeys(otherUserId: String): MXCrossSigningInfo? @@ -60,20 +64,26 @@ interface CrossSigningService { fun allPrivateKeysKnown(): Boolean - fun trustUser(otherUserId: String, - callback: MatrixCallback) + fun trustUser( + otherUserId: String, + callback: MatrixCallback + ) fun markMyMasterKeyAsTrusted() /** * Sign one of your devices and upload the signature. */ - fun trustDevice(deviceId: String, - callback: MatrixCallback) + fun trustDevice( + deviceId: String, + callback: MatrixCallback + ) - fun checkDeviceTrust(otherUserId: String, - otherDeviceId: String, - locallyTrusted: Boolean?): DeviceTrustResult + fun checkDeviceTrust( + otherUserId: String, + otherDeviceId: String, + locallyTrusted: Boolean? + ): DeviceTrustResult // FIXME Those method do not have to be in the service fun onSecretMSKGossip(mskPrivateKey: String) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupLastVersionResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupLastVersionResult.kt index a7e985cea9..92510bb52e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupLastVersionResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupLastVersionResult.kt @@ -24,5 +24,5 @@ sealed interface KeysBackupLastVersionResult { fun KeysBackupLastVersionResult.toKeysVersionResult(): KeysVersionResult? = when (this) { is KeysBackupLastVersionResult.KeysBackup -> keysVersionResult - KeysBackupLastVersionResult.NoKeysBackup -> null + KeysBackupLastVersionResult.NoKeysBackup -> null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt index dc8b03eaae..8745003f9f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt @@ -36,8 +36,10 @@ interface KeysBackupService { * @param keysBackupCreationInfo the info object from [prepareKeysBackupVersion]. * @param callback Asynchronous callback */ - fun createKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, - callback: MatrixCallback) + fun createKeysBackupVersion( + keysBackupCreationInfo: MegolmBackupCreationInfo, + callback: MatrixCallback + ) /** * Facility method to get the total number of locally stored keys. @@ -55,8 +57,10 @@ interface KeysBackupService { * @param progressListener the callback to follow the progress * @param callback the main callback */ - fun backupAllGroupSessions(progressListener: ProgressListener?, - callback: MatrixCallback?) + fun backupAllGroupSessions( + progressListener: ProgressListener?, + callback: MatrixCallback? + ) /** * Check trust on a key backup version. @@ -64,8 +68,10 @@ interface KeysBackupService { * @param keysBackupVersion the backup version to check. * @param callback block called when the operations completes. */ - fun getKeysBackupTrust(keysBackupVersion: KeysVersionResult, - callback: MatrixCallback) + fun getKeysBackupTrust( + keysBackupVersion: KeysVersionResult, + callback: MatrixCallback + ) /** * Return the current progress of the backup. @@ -79,8 +85,10 @@ interface KeysBackupService { * @param version the backup version * @param callback */ - fun getVersion(version: String, - callback: MatrixCallback) + fun getVersion( + version: String, + callback: MatrixCallback + ) /** * This method fetches the last backup version on the server, then compare to the currently backup version use. @@ -114,9 +122,11 @@ interface KeysBackupService { * @param progressListener a progress listener, as generating private key from password may take a while * @param callback Asynchronous callback */ - fun prepareKeysBackupVersion(password: String?, - progressListener: ProgressListener?, - callback: MatrixCallback) + fun prepareKeysBackupVersion( + password: String?, + progressListener: ProgressListener?, + callback: MatrixCallback + ) /** * Delete a keys backup version. It will delete all backed up keys on the server, and the backup itself. @@ -125,8 +135,10 @@ interface KeysBackupService { * @param version the backup version to delete. * @param callback Asynchronous callback */ - fun deleteBackup(version: String, - callback: MatrixCallback?) + fun deleteBackup( + version: String, + callback: MatrixCallback? + ) /** * Ask if the backup on the server contains keys that we may do not have locally. @@ -142,9 +154,11 @@ interface KeysBackupService { * @param trust the trust to set to the keys backup. * @param callback block called when the operations completes. */ - fun trustKeysBackupVersion(keysBackupVersion: KeysVersionResult, - trust: Boolean, - callback: MatrixCallback) + fun trustKeysBackupVersion( + keysBackupVersion: KeysVersionResult, + trust: Boolean, + callback: MatrixCallback + ) /** * Set trust on a keys backup version. @@ -153,9 +167,11 @@ interface KeysBackupService { * @param recoveryKey the recovery key to challenge with the key backup public key. * @param callback block called when the operations completes. */ - fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult, - recoveryKey: String, - callback: MatrixCallback) + fun trustKeysBackupVersionWithRecoveryKey( + keysBackupVersion: KeysVersionResult, + recoveryKey: String, + callback: MatrixCallback + ) /** * Set trust on a keys backup version. @@ -164,9 +180,11 @@ interface KeysBackupService { * @param password the pass phrase to challenge with the keyBackupVersion public key. * @param callback block called when the operations completes. */ - fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult, - password: String, - callback: MatrixCallback) + fun trustKeysBackupVersionWithPassphrase( + keysBackupVersion: KeysVersionResult, + password: String, + callback: MatrixCallback + ) /** * Restore a backup with a recovery key from a given backup version stored on the homeserver. @@ -178,11 +196,14 @@ interface KeysBackupService { * @param stepProgressListener the step progress listener * @param callback Callback. It provides the number of found keys and the number of successfully imported keys. */ - fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, - recoveryKey: String, roomId: String?, - sessionId: String?, - stepProgressListener: StepProgressListener?, - callback: MatrixCallback) + fun restoreKeysWithRecoveryKey( + keysVersionResult: KeysVersionResult, + recoveryKey: String, + roomId: String?, + sessionId: String?, + stepProgressListener: StepProgressListener?, + callback: MatrixCallback + ) /** * Restore a backup with a password from a given backup version stored on the homeserver. @@ -194,12 +215,14 @@ interface KeysBackupService { * @param stepProgressListener the step progress listener * @param callback Callback. It provides the number of found keys and the number of successfully imported keys. */ - fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, - password: String, - roomId: String?, - sessionId: String?, - stepProgressListener: StepProgressListener?, - callback: MatrixCallback) + fun restoreKeyBackupWithPassword( + keysBackupVersion: KeysVersionResult, + password: String, + roomId: String?, + sessionId: String?, + stepProgressListener: StepProgressListener?, + callback: MatrixCallback + ) val keysBackupVersion: KeysVersionResult? @@ -216,8 +239,10 @@ interface KeysBackupService { fun isValidRecoveryKeyForCurrentVersion(recoveryKey: String, callback: MatrixCallback) - fun computePrivateKey(passphrase: String, - privateKeySalt: String, - privateKeyIterations: Int, - progressListener: ProgressListener): ByteArray + fun computePrivateKey( + passphrase: String, + privateKeySalt: String, + privateKeyIterations: Int, + progressListener: ProgressListener + ): ByteArray } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt index 7127c8d3f4..afbf45ac70 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt @@ -40,7 +40,8 @@ sealed class KeysBackupVersionTrustSignature { /** * Flag to indicate the signature from this device is valid. */ - val valid: Boolean) : KeysBackupVersionTrustSignature() + val valid: Boolean + ) : KeysBackupVersionTrustSignature() data class UserSignature( val keyId: String?, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/EmojiRepresentation.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/EmojiRepresentation.kt index 2c1bf9ff4d..5402471e46 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/EmojiRepresentation.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/EmojiRepresentation.kt @@ -19,7 +19,8 @@ package org.matrix.android.sdk.api.session.crypto.verification import androidx.annotation.DrawableRes import androidx.annotation.StringRes -data class EmojiRepresentation(val emoji: String, - @StringRes val nameResId: Int, - @DrawableRes val drawableRes: Int? = null +data class EmojiRepresentation( + val emoji: String, + @StringRes val nameResId: Int, + @DrawableRes val drawableRes: Int? = null ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt index 321ec73094..ee93f14992 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt @@ -46,54 +46,68 @@ interface VerificationService { fun getExistingVerificationRequestInRoom(roomId: String, tid: String?): PendingVerificationRequest? - fun beginKeyVerification(method: VerificationMethod, - otherUserId: String, - otherDeviceId: String, - transactionId: String?): String? + fun beginKeyVerification( + method: VerificationMethod, + otherUserId: String, + otherDeviceId: String, + transactionId: String? + ): String? /** * Request key verification with another user via room events (instead of the to-device API). */ - fun requestKeyVerificationInDMs(methods: List, - otherUserId: String, - roomId: String, - localId: String? = LocalEcho.createLocalEchoId()): PendingVerificationRequest + fun requestKeyVerificationInDMs( + methods: List, + otherUserId: String, + roomId: String, + localId: String? = LocalEcho.createLocalEchoId() + ): PendingVerificationRequest fun cancelVerificationRequest(request: PendingVerificationRequest) /** * Request a key verification from another user using toDevice events. */ - fun requestKeyVerification(methods: List, - otherUserId: String, - otherDevices: List?): PendingVerificationRequest + fun requestKeyVerification( + methods: List, + otherUserId: String, + otherDevices: List? + ): PendingVerificationRequest - fun declineVerificationRequestInDMs(otherUserId: String, - transactionId: String, - roomId: String) + fun declineVerificationRequestInDMs( + otherUserId: String, + transactionId: String, + roomId: String + ) // Only SAS method is supported for the moment // TODO Parameter otherDeviceId should be removed in this case - fun beginKeyVerificationInDMs(method: VerificationMethod, - transactionId: String, - roomId: String, - otherUserId: String, - otherDeviceId: String): String + fun beginKeyVerificationInDMs( + method: VerificationMethod, + transactionId: String, + roomId: String, + otherUserId: String, + otherDeviceId: String + ): String /** * Returns false if the request is unknown. */ - fun readyPendingVerificationInDMs(methods: List, - otherUserId: String, - roomId: String, - transactionId: String): Boolean + fun readyPendingVerificationInDMs( + methods: List, + otherUserId: String, + roomId: String, + transactionId: String + ): Boolean /** * Returns false if the request is unknown. */ - fun readyPendingVerification(methods: List, - otherUserId: String, - transactionId: String): Boolean + fun readyPendingVerification( + methods: List, + otherUserId: String, + transactionId: String + ): Boolean interface Listener { /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/EventService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/EventService.kt index 297f277497..7f275bf952 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/EventService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/EventService.kt @@ -24,6 +24,8 @@ interface EventService { * Ask the homeserver for an event content. The SDK will try to decrypt it if it is possible * The result will not be stored into cache */ - suspend fun getEvent(roomId: String, - eventId: String): Event + suspend fun getEvent( + roomId: String, + eventId: String + ): Event } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt index 7124d8a1a3..7f9ab4c6dd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt @@ -212,13 +212,13 @@ data class Event( return when { isReplyRenderedInThread() || isQuote() -> ContentUtils.extractUsefulTextFromReply(text) - isFileMessage() -> "sent a file." - isAudioMessage() -> "sent an audio file." - isImageMessage() -> "sent an image." - isVideoMessage() -> "sent a video." - isSticker() -> "sent a sticker" - isPoll() -> getPollQuestion() ?: "created a poll." - else -> text + isFileMessage() -> "sent a file." + isAudioMessage() -> "sent an audio file." + isImageMessage() -> "sent an image." + isVideoMessage() -> "sent a video." + isSticker() -> "sent a sticker" + isPoll() -> getPollQuestion() ?: "created a poll." + else -> text } } @@ -318,35 +318,35 @@ fun Event.isTextMessage(): Boolean { MessageType.MSGTYPE_TEXT, MessageType.MSGTYPE_EMOTE, MessageType.MSGTYPE_NOTICE -> true - else -> false + else -> false } } fun Event.isImageMessage(): Boolean { return when (getMsgType()) { MessageType.MSGTYPE_IMAGE -> true - else -> false + else -> false } } fun Event.isVideoMessage(): Boolean { return when (getMsgType()) { MessageType.MSGTYPE_VIDEO -> true - else -> false + else -> false } } fun Event.isAudioMessage(): Boolean { return when (getMsgType()) { MessageType.MSGTYPE_AUDIO -> true - else -> false + else -> false } } fun Event.isFileMessage(): Boolean { return when (getMsgType()) { MessageType.MSGTYPE_FILE -> true - else -> false + else -> false } } @@ -356,14 +356,14 @@ fun Event.isAttachmentMessage(): Boolean { MessageType.MSGTYPE_AUDIO, MessageType.MSGTYPE_VIDEO, MessageType.MSGTYPE_FILE -> true - else -> false + else -> false } } fun Event.isLocationMessage(): Boolean { return when (getMsgType()) { MessageType.MSGTYPE_LOCATION -> true - else -> false + else -> false } } @@ -378,9 +378,9 @@ fun Event.getRelationContent(): RelationDefaultContent? { content.toModel()?.relatesTo ?: run { // Special cases when there is only a local msgtype for some event types when (getClearType()) { - EventType.STICKER -> getClearContent().toModel()?.relatesTo + EventType.STICKER -> getClearContent().toModel()?.relatesTo in EventType.BEACON_LOCATION_DATA -> getClearContent().toModel()?.relatesTo - else -> null + else -> null } } } @@ -427,3 +427,6 @@ fun Event.getPollContent(): MessagePollContent? { fun Event.supportsNotification() = this.getClearType() in EventType.MESSAGE + EventType.POLL_START + EventType.STATE_ROOM_BEACON_INFO + +fun Event.isContentReportable() = + this.getClearType() in EventType.MESSAGE + EventType.STATE_ROOM_BEACON_INFO diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt index d58c3614a7..fb8b65c4f2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt @@ -98,12 +98,12 @@ enum class WithHeldCode(val value: String) { companion object { fun fromCode(code: String?): WithHeldCode? { return when (code) { - BLACKLISTED.value -> BLACKLISTED - UNVERIFIED.value -> UNVERIFIED + BLACKLISTED.value -> BLACKLISTED + UNVERIFIED.value -> UNVERIFIED UNAUTHORISED.value -> UNAUTHORISED - UNAVAILABLE.value -> UNAVAILABLE - NO_OLM.value -> NO_OLM - else -> null + UNAVAILABLE.value -> UNAVAILABLE + NO_OLM.value -> NO_OLM + else -> null } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt index a7c81136e3..ca6c889cb8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt @@ -44,10 +44,12 @@ interface FileService { * Download a file if necessary and ensure that if the file is encrypted, the file is decrypted. * Result will be a decrypted file, stored in the cache folder. url parameter will be used to create unique filename to avoid name collision. */ - suspend fun downloadFile(fileName: String, - mimeType: String?, - url: String?, - elementToDecrypt: ElementToDecrypt?): File + suspend fun downloadFile( + fileName: String, + mimeType: String?, + url: String?, + elementToDecrypt: ElementToDecrypt? + ): File suspend fun downloadFile(messageContent: MessageWithAttachmentContent): File = downloadFile( @@ -57,10 +59,11 @@ interface FileService { elementToDecrypt = messageContent.encryptedFileInfo?.toElementToDecrypt() ) - fun isFileInCache(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt? + fun isFileInCache( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? ): Boolean fun isFileInCache(messageContent: MessageWithAttachmentContent) = @@ -75,10 +78,12 @@ interface FileService { * Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION * (if not other app won't be able to access it). */ - fun getTemporarySharableURI(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt?): Uri? + fun getTemporarySharableURI( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? + ): Uri? fun getTemporarySharableURI(messageContent: MessageWithAttachmentContent): Uri? = getTemporarySharableURI( @@ -92,10 +97,12 @@ interface FileService { * Get information on the given file. * Mimetype should be the same one as passed to downloadFile (limitation for now) */ - fun fileState(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt?): FileState + fun fileState( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? + ): FileState fun fileState(messageContent: MessageWithAttachmentContent): FileState = fileState( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt index 5b06fdacae..c78fb9cf79 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt @@ -81,13 +81,13 @@ data class HomeServerCapabilities( val versionCap = roomVersions.supportedVersion.firstOrNull { it.version == preferred } return when { - versionCap == null -> { + versionCap == null -> { RoomCapabilitySupport.UNKNOWN } versionCap.status == RoomVersionStatus.STABLE -> { RoomCapabilitySupport.SUPPORTED } - else -> { + else -> { RoomCapabilitySupport.SUPPORTED_UNSTABLE } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/ThreePid.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/ThreePid.kt index 42d777849b..6bcf576824 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/ThreePid.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/ThreePid.kt @@ -27,7 +27,7 @@ sealed class ThreePid(open val value: String) { internal fun ThreePid.toMedium(): String { return when (this) { - is ThreePid.Email -> ThirdPartyIdentifier.MEDIUM_EMAIL + is ThreePid.Email -> ThirdPartyIdentifier.MEDIUM_EMAIL is ThreePid.Msisdn -> ThirdPartyIdentifier.MEDIUM_MSISDN } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt deleted file mode 100644 index 7006e11751..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.matrix.android.sdk.api.session.initsync - -import androidx.lifecycle.LiveData - -interface SyncStatusService { - - fun getSyncStatusLive(): LiveData - - sealed class Status { - /** - * For initial sync. - */ - abstract class InitialSyncStatus : Status() - - object Idle : InitialSyncStatus() - data class InitialSyncProgressing( - val initSyncStep: InitSyncStep, - val percentProgress: Int = 0 - ) : InitialSyncStatus() - - /** - * For incremental sync. - */ - abstract class IncrementalSyncStatus : Status() - - object IncrementalSyncIdle : IncrementalSyncStatus() - data class IncrementalSyncParsing( - val rooms: Int, - val toDevice: Int - ) : IncrementalSyncStatus() - - object IncrementalSyncError : IncrementalSyncStatus() - object IncrementalSyncDone : IncrementalSyncStatus() - } -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixPermalinkSpan.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixPermalinkSpan.kt index 48b30dfa21..9c71c081be 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixPermalinkSpan.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixPermalinkSpan.kt @@ -25,8 +25,10 @@ import org.matrix.android.sdk.api.session.permalinks.MatrixPermalinkSpan.Callbac * @property url the permalink url tied to the span * @property callback the callback to use. */ -class MatrixPermalinkSpan(private val url: String, - private val callback: Callback? = null) : ClickableSpan() { +class MatrixPermalinkSpan( + private val url: String, + private val callback: Callback? = null +) : ClickableSpan() { interface Callback { fun onUrlClicked(url: String) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixToConverter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixToConverter.kt index a904e89681..c418b59df4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixToConverter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/MatrixToConverter.kt @@ -38,12 +38,12 @@ object MatrixToConverter { // URL is already a matrix.to uriString.startsWith(PermalinkService.MATRIX_TO_URL_BASE) -> uri // Web or client url - SUPPORTED_PATHS.any { it in uriString } -> { + SUPPORTED_PATHS.any { it in uriString } -> { val path = SUPPORTED_PATHS.first { it in uriString } Uri.parse(PermalinkService.MATRIX_TO_URL_BASE + uriString.substringAfter(path)) } // URL is not supported - else -> null + else -> null } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt index 9d078dc4b2..0168b7ac3a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt @@ -67,10 +67,10 @@ object PermalinkParser { val identifier = params.getOrNull(0) val extraParameter = params.getOrNull(1) return when { - identifier.isNullOrEmpty() -> PermalinkData.FallbackLink(uri) - MatrixPatterns.isUserId(identifier) -> PermalinkData.UserLink(userId = identifier) - MatrixPatterns.isGroupId(identifier) -> PermalinkData.GroupLink(groupId = identifier) - MatrixPatterns.isRoomId(identifier) -> { + identifier.isNullOrEmpty() -> PermalinkData.FallbackLink(uri) + MatrixPatterns.isUserId(identifier) -> PermalinkData.UserLink(userId = identifier) + MatrixPatterns.isGroupId(identifier) -> PermalinkData.GroupLink(groupId = identifier) + MatrixPatterns.isRoomId(identifier) -> { handleRoomIdCase(fragment, identifier, matrixToUri, extraParameter, viaQueryParameters) } MatrixPatterns.isRoomAlias(identifier) -> { @@ -81,7 +81,7 @@ object PermalinkParser { viaParameters = viaQueryParameters ) } - else -> PermalinkData.FallbackLink(uri) + else -> PermalinkData.FallbackLink(uri) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt index 095f2ef7c2..4c00c76459 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt @@ -107,8 +107,10 @@ interface ProfileService { /** * Finalize adding a 3Pids. Call this method once the user has validated that he owns the ThreePid. */ - suspend fun finalizeAddingThreePid(threePid: ThreePid, - userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor) + suspend fun finalizeAddingThreePid( + threePid: ThreePid, + userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor + ) /** * Cancel adding a threepid. It will remove locally stored data about this ThreePid. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt index 396f13ce46..d7958ea3cd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt @@ -58,12 +58,14 @@ interface PushersService { * email pushers since we don't want to stop other accounts notifying to the same email address. * @throws [InvalidParameterException] if a parameter is not correct */ - suspend fun addEmailPusher(email: String, - lang: String, - emailBranding: String, - appDisplayName: String, - deviceDisplayName: String, - append: Boolean = true) + suspend fun addEmailPusher( + email: String, + lang: String, + emailBranding: String, + appDisplayName: String, + deviceDisplayName: String, + append: Boolean = true + ) /** * Directly ask the push gateway to send a push to this device. @@ -75,10 +77,12 @@ interface PushersService { * @param pushkey the FCM token * @param eventId the eventId which will be sent in the Push message. Use a fake eventId. */ - suspend fun testPush(url: String, - appId: String, - pushkey: String, - eventId: String) + suspend fun testPush( + url: String, + appId: String, + pushkey: String, + eventId: String + ) /** * Remove a registered pusher. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt index 2b2930c1ba..6122aae972 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt @@ -71,15 +71,15 @@ sealed class Action { fun List.toJson(): List { return map { action -> when (action) { - is Action.Notify -> Action.ACTION_NOTIFY + is Action.Notify -> Action.ACTION_NOTIFY is Action.DoNotNotify -> Action.ACTION_DONT_NOTIFY - is Action.Sound -> { + is Action.Sound -> { mapOf( Action.ACTION_OBJECT_SET_TWEAK_KEY to Action.ACTION_OBJECT_SET_TWEAK_VALUE_SOUND, Action.ACTION_OBJECT_VALUE_KEY to action.sound ) } - is Action.Highlight -> { + is Action.Highlight -> { mapOf( Action.ACTION_OBJECT_SET_TWEAK_KEY to Action.ACTION_OBJECT_SET_TWEAK_VALUE_HIGHLIGHT, Action.ACTION_OBJECT_VALUE_KEY to action.highlight @@ -94,11 +94,11 @@ fun PushRule.getActions(): List { actions.forEach { actionStrOrObj -> when (actionStrOrObj) { - Action.ACTION_NOTIFY -> Action.Notify + Action.ACTION_NOTIFY -> Action.Notify Action.ACTION_DONT_NOTIFY -> Action.DoNotNotify - is Map<*, *> -> { + is Map<*, *> -> { when (actionStrOrObj[Action.ACTION_OBJECT_SET_TWEAK_KEY]) { - Action.ACTION_OBJECT_SET_TWEAK_VALUE_SOUND -> { + Action.ACTION_OBJECT_SET_TWEAK_VALUE_SOUND -> { (actionStrOrObj[Action.ACTION_OBJECT_VALUE_KEY] as? String)?.let { stringValue -> Action.Sound(stringValue) } @@ -112,13 +112,13 @@ fun PushRule.getActions(): List { // When the value is not there, default is true, says the spec ?: Action.Highlight(true) } - else -> { + else -> { Timber.w("Unsupported set_tweak value ${actionStrOrObj[Action.ACTION_OBJECT_SET_TWEAK_KEY]}") null } } } - else -> { + else -> { Timber.w("Unsupported action type $actionStrOrObj") null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ConditionResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ConditionResolver.kt index f8a930f987..d64ee5f777 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ConditionResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ConditionResolver.kt @@ -22,15 +22,23 @@ import org.matrix.android.sdk.api.session.events.model.Event * This class as all required context needed to evaluate rules */ interface ConditionResolver { - fun resolveEventMatchCondition(event: Event, - condition: EventMatchCondition): Boolean + fun resolveEventMatchCondition( + event: Event, + condition: EventMatchCondition + ): Boolean - fun resolveRoomMemberCountCondition(event: Event, - condition: RoomMemberCountCondition): Boolean + fun resolveRoomMemberCountCondition( + event: Event, + condition: RoomMemberCountCondition + ): Boolean - fun resolveSenderNotificationPermissionCondition(event: Event, - condition: SenderNotificationPermissionCondition): Boolean + fun resolveSenderNotificationPermissionCondition( + event: Event, + condition: SenderNotificationPermissionCondition + ): Boolean - fun resolveContainsDisplayNameCondition(event: Event, - condition: ContainsDisplayNameCondition): Boolean + fun resolveContainsDisplayNameCondition( + event: Event, + condition: ContainsDisplayNameCondition + ): Boolean } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ContainsDisplayNameCondition.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ContainsDisplayNameCondition.kt index 69dd14ddc2..0bf14345b9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ContainsDisplayNameCondition.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/ContainsDisplayNameCondition.kt @@ -39,7 +39,7 @@ class ContainsDisplayNameCondition : Condition { // EventType.ENCRYPTED -> { // event.root.getClearContent()?.toModel() // } - else -> null + else -> null } ?: return false return message.body.caseInsensitiveFind(displayName) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Kind.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Kind.kt index 463f3c2a73..bba6fe6026 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Kind.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Kind.kt @@ -27,11 +27,11 @@ enum class Kind(val value: String) { fun fromString(value: String): Kind { return when (value) { - "event_match" -> EventMatch - "contains_display_name" -> ContainsDisplayName - "room_member_count" -> RoomMemberCount + "event_match" -> EventMatch + "contains_display_name" -> ContainsDisplayName + "room_member_count" -> RoomMemberCount "sender_notification_permission" -> SenderNotificationPermission - else -> Unrecognised + else -> Unrecognised } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt index 7ffbc89559..8f9c25fd30 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt @@ -51,8 +51,10 @@ interface PushRuleService { // fun fulfilledBingRule(event: Event, rules: List): PushRule? - fun resolveSenderNotificationPermissionCondition(event: Event, - condition: SenderNotificationPermissionCondition): Boolean + fun resolveSenderNotificationPermissionCondition( + event: Event, + condition: SenderNotificationPermissionCondition + ): Boolean interface PushRuleListener { fun onEvents(pushEvents: PushEvents) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/RoomMemberCountCondition.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/RoomMemberCountCondition.kt index 6973ff1372..db097fd92c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/RoomMemberCountCondition.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/RoomMemberCountCondition.kt @@ -47,8 +47,8 @@ class RoomMemberCountCondition( val numMembers = room.membershipService().getNumberOfJoinedMembers() return when (prefix) { - "<" -> numMembers < count - ">" -> numMembers > count + "<" -> numMembers < count + ">" -> numMembers > count "<=" -> numMembers <= count ">=" -> numMembers >= count else -> numMembers == count diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushCondition.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushCondition.kt index 1fc8329535..ec0936e4c8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushCondition.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushCondition.kt @@ -61,7 +61,7 @@ data class PushCondition( fun asExecutableCondition(rule: PushRule): Condition? { return when (Kind.fromString(kind)) { - Kind.EventMatch -> { + Kind.EventMatch -> { if (key != null && pattern != null) { EventMatchCondition(key, pattern, rule.ruleId == RuleIds.RULE_ID_CONTAIN_USER_NAME) } else { @@ -69,10 +69,10 @@ data class PushCondition( null } } - Kind.ContainsDisplayName -> { + Kind.ContainsDisplayName -> { ContainsDisplayNameCondition() } - Kind.RoomMemberCount -> { + Kind.RoomMemberCount -> { if (iz.isNullOrEmpty()) { Timber.e("Malformed ROOM_MEMBER_COUNT condition") null @@ -88,7 +88,7 @@ data class PushCondition( SenderNotificationPermissionCondition(key) } } - Kind.Unrecognised -> { + Kind.Unrecognised -> { Timber.e("Unknown kind $kind") null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt index cb70603e66..77092c4811 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt @@ -28,8 +28,10 @@ interface RoomDirectoryService { /** * Get rooms from directory. */ - suspend fun getPublicRooms(server: String?, - publicRoomsParams: PublicRoomsParams): PublicRoomsResponse + suspend fun getPublicRooms( + server: String?, + publicRoomsParams: PublicRoomsParams + ): PublicRoomsResponse /** * Get the visibility of a room in the directory. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt index 1e022ef02a..5dfb8961e3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt @@ -60,9 +60,11 @@ interface RoomService { * @param reason optional reason for joining the room * @param viaServers the servers to attempt to join the room through. One of the servers must be participating in the room. */ - suspend fun joinRoom(roomIdOrAlias: String, - reason: String? = null, - viaServers: List = emptyList()) + suspend fun joinRoom( + roomIdOrAlias: String, + reason: String? = null, + viaServers: List = emptyList() + ) /** * @param roomId the roomId of the room to join @@ -107,15 +109,19 @@ interface RoomService { * Get a snapshot list of room summaries. * @return the immutable list of [RoomSummary] */ - fun getRoomSummaries(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): List + fun getRoomSummaries( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): List /** * Get a live list of room summaries. This list is refreshed as soon as the data changes. * @return the [LiveData] of List[RoomSummary] */ - fun getRoomSummariesLive(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData> + fun getRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY + ): LiveData> /** * Get a snapshot list of Breadcrumbs. @@ -145,8 +151,10 @@ interface RoomService { /** * Resolve a room alias to a room ID. */ - suspend fun getRoomIdByAlias(roomAlias: String, - searchOnServer: Boolean): Optional + suspend fun getRoomIdByAlias( + roomAlias: String, + searchOnServer: Boolean + ): Optional /** * Delete a room alias. @@ -211,9 +219,11 @@ interface RoomService { /** * TODO Doc. */ - fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, - pagedListConfig: PagedList.Config = defaultPagedListConfig, - sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData> + fun getPagedRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + pagedListConfig: PagedList.Config = defaultPagedListConfig, + sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY + ): LiveData> /** * Get's a live paged list from a filter that can be dynamically updated. @@ -255,8 +265,10 @@ interface RoomService { /** * Returns all the children of this space, as LiveData. */ - fun getFlattenRoomSummaryChildrenOfLive(spaceId: String?, - memberships: List = Membership.activeMemberships()): LiveData> + fun getFlattenRoomSummaryChildrenOfLive( + spaceId: String?, + memberships: List = Membership.activeMemberships() + ): LiveData> /** * Refreshes the RoomSummary LatestPreviewContent for the given @param roomId. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt index 8ef94b2896..0329828130 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt @@ -95,8 +95,8 @@ data class PowerLevelsContent( // the first implementation was a string value is String -> value.toInt() is Double -> value.toInt() - is Int -> value - else -> Role.Moderator.value + is Int -> value + else -> Role.Moderator.value } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt index ba274325bc..7dd853d75d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt @@ -30,9 +30,9 @@ data class RoomGuestAccessContent( @Json(name = "guest_access") val guestAccessStr: String? = null ) { val guestAccess: GuestAccess? = when (guestAccessStr) { - "can_join" -> GuestAccess.CanJoin + "can_join" -> GuestAccess.CanJoin "forbidden" -> GuestAccess.Forbidden - else -> { + else -> { Timber.w("Invalid value for GuestAccess: `$guestAccessStr`") null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt index da5c90ff05..39b4722c0c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt @@ -26,10 +26,10 @@ data class RoomHistoryVisibilityContent( ) { val historyVisibility: RoomHistoryVisibility? = when (historyVisibilityStr) { "world_readable" -> RoomHistoryVisibility.WORLD_READABLE - "shared" -> RoomHistoryVisibility.SHARED - "invited" -> RoomHistoryVisibility.INVITED - "joined" -> RoomHistoryVisibility.JOINED - else -> { + "shared" -> RoomHistoryVisibility.SHARED + "invited" -> RoomHistoryVisibility.INVITED + "joined" -> RoomHistoryVisibility.JOINED + else -> { Timber.w("Invalid value for RoomHistoryVisibility: `$historyVisibilityStr`") null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt index 3b338a36cd..dbe21b1633 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt @@ -36,12 +36,12 @@ data class RoomJoinRulesContent( @Json(name = "allow") val allowList: List? = null ) { val joinRules: RoomJoinRules? = when (joinRulesStr) { - "public" -> RoomJoinRules.PUBLIC - "invite" -> RoomJoinRules.INVITE - "knock" -> RoomJoinRules.KNOCK - "private" -> RoomJoinRules.PRIVATE + "public" -> RoomJoinRules.PUBLIC + "invite" -> RoomJoinRules.INVITE + "knock" -> RoomJoinRules.KNOCK + "private" -> RoomJoinRules.PRIVATE "restricted" -> RoomJoinRules.RESTRICTED - else -> { + else -> { Timber.w("Invalid value for RoomJoinRules: `$joinRulesStr`") null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationAcceptContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationAcceptContent.kt index 27619cf0a9..33f61648dc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationAcceptContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationAcceptContent.kt @@ -40,12 +40,14 @@ internal data class MessageVerificationAcceptContent( companion object : VerificationInfoAcceptFactory { - override fun create(tid: String, - keyAgreementProtocol: String, - hash: String, - commitment: String, - messageAuthenticationCode: String, - shortAuthenticationStrings: List): VerificationInfoAccept { + override fun create( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept { return MessageVerificationAcceptContent( hash, keyAgreementProtocol, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt index 02c597ee63..d34ea3c7d3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt @@ -58,16 +58,20 @@ interface RelationService { * @param targetEventId the id of the event being reacted * @param reaction the reaction (preferably emoji) */ - fun sendReaction(targetEventId: String, - reaction: String): Cancelable + fun sendReaction( + targetEventId: String, + reaction: String + ): Cancelable /** * Undo a reaction (emoji) to the targetedEvent. * @param targetEventId the id of the event being reacted * @param reaction the reaction (preferably emoji) */ - suspend fun undoReaction(targetEventId: String, - reaction: String): Cancelable + suspend fun undoReaction( + targetEventId: String, + reaction: String + ): Cancelable /** * Edit a poll. @@ -76,10 +80,12 @@ interface RelationService { * @param question The edited question * @param options The edited options */ - fun editPoll(targetEvent: TimelineEvent, - pollType: PollType, - question: String, - options: List): Cancelable + fun editPoll( + targetEvent: TimelineEvent, + pollType: PollType, + question: String, + options: List + ): Cancelable /** * Edit a text message body. Limited to "m.text" contentType. @@ -89,11 +95,13 @@ interface RelationService { * @param newBodyAutoMarkdown true to parse markdown on the new body * @param compatibilityBodyText The text that will appear on clients that don't support yet edition */ - fun editTextMessage(targetEvent: TimelineEvent, - msgType: String, - newBodyText: CharSequence, - newBodyAutoMarkdown: Boolean, - compatibilityBodyText: String = "* $newBodyText"): Cancelable + fun editTextMessage( + targetEvent: TimelineEvent, + msgType: String, + newBodyText: CharSequence, + newBodyAutoMarkdown: Boolean, + compatibilityBodyText: String = "* $newBodyText" + ): Cancelable /** * Edit a reply. This is a special case because replies contains fallback text as a prefix. @@ -103,10 +111,12 @@ interface RelationService { * @param newBodyText The edited body (stripped from in reply to content) * @param compatibilityBodyText The text that will appear on clients that don't support yet edition */ - fun editReply(replyToEdit: TimelineEvent, - originalTimelineEvent: TimelineEvent, - newBodyText: String, - compatibilityBodyText: String = "* $newBodyText"): Cancelable + fun editReply( + replyToEdit: TimelineEvent, + originalTimelineEvent: TimelineEvent, + newBodyText: String, + compatibilityBodyText: String = "* $newBodyText" + ): Cancelable /** * Get the edit history of the given event. @@ -127,11 +137,12 @@ interface RelationService { * @param showInThread If true, relation will be added to the reply in order to be visible from within threads * @param rootThreadEventId If show in thread is true then we need the rootThreadEventId to generate the relation */ - fun replyToMessage(eventReplied: TimelineEvent, - replyText: CharSequence, - autoMarkdown: Boolean = false, - showInThread: Boolean = false, - rootThreadEventId: String? = null + fun replyToMessage( + eventReplied: TimelineEvent, + replyText: CharSequence, + autoMarkdown: Boolean = false, + showInThread: Boolean = false, + rootThreadEventId: String? = null ): Cancelable? /** @@ -159,10 +170,12 @@ interface RelationService { * @param formattedText The formatted body using MessageType#FORMAT_MATRIX_HTML * @param eventReplied the event referenced by the reply within a thread */ - fun replyInThread(rootThreadEventId: String, - replyInThreadText: CharSequence, - msgType: String = MessageType.MSGTYPE_TEXT, - autoMarkdown: Boolean = false, - formattedText: String? = null, - eventReplied: TimelineEvent? = null): Cancelable? + fun replyInThread( + rootThreadEventId: String, + replyInThreadText: CharSequence, + msgType: String = MessageType.MSGTYPE_TEXT, + autoMarkdown: Boolean = false, + formattedText: String? = null, + eventReplied: TimelineEvent? = null + ): Cancelable? } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/Role.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/Role.kt index 5fe9bf6993..c5cc573458 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/Role.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/Role.kt @@ -32,11 +32,11 @@ sealed class Role(open val value: Int) : Comparable { // Order matters, default value should be checked after defined roles fun fromValue(value: Int, default: Int): Role { return when (value) { - Admin.value -> Admin + Admin.value -> Admin Moderator.value -> Moderator Default.value, - default -> Default - else -> Custom(value) + default -> Default + else -> Custom(value) } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt index c2e3ded2fa..661c3be5bd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt @@ -76,10 +76,12 @@ interface SendService { * @param rootThreadEventId when this param is not null, the Media will be sent in this specific thread * @return a [Cancelable] */ - fun sendMedia(attachment: ContentAttachmentData, - compressBeforeSending: Boolean, - roomIds: Set, - rootThreadEventId: String? = null): Cancelable + fun sendMedia( + attachment: ContentAttachmentData, + compressBeforeSending: Boolean, + roomIds: Set, + rootThreadEventId: String? = null + ): Cancelable /** * Method to send a list of media asynchronously. @@ -90,10 +92,12 @@ interface SendService { * @param rootThreadEventId when this param is not null, all the Media will be sent in this specific thread * @return a [Cancelable] */ - fun sendMedias(attachments: List, - compressBeforeSending: Boolean, - roomIds: Set, - rootThreadEventId: String? = null): Cancelable + fun sendMedias( + attachments: List, + compressBeforeSending: Boolean, + roomIds: Set, + rootThreadEventId: String? = null + ): Cancelable /** * Send a poll to the room. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt index 4ede1a66fc..e16405b3c0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt @@ -33,7 +33,7 @@ sealed interface UserDraft { fun isValid(): Boolean { return when (this) { is Regular -> content.isNotBlank() - else -> true + else -> true } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt index 4c308c355a..d629df8b16 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt @@ -29,9 +29,9 @@ data class SenderInfo( ) { val disambiguatedDisplayName: String get() = when { - displayName == null -> userId + displayName == null -> userId displayName.replaceSpaceChars().isBlank() -> "$displayName ($userId)" - isUniqueDisplayName -> displayName - else -> "$displayName ($userId)" + isUniqueDisplayName -> displayName + else -> "$displayName ($userId)" } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadEditions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadEditions.kt index c8353cf0de..dc9cc886e9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadEditions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadEditions.kt @@ -16,5 +16,7 @@ package org.matrix.android.sdk.api.session.room.threads.model -data class ThreadEditions(var rootThreadEdition: String? = null, - var latestThreadEdition: String? = null) +data class ThreadEditions( + var rootThreadEdition: String? = null, + var latestThreadEdition: String? = null +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt index 1ef972e889..0b1aea1966 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt @@ -22,12 +22,14 @@ import org.matrix.android.sdk.api.session.room.sender.SenderInfo /** * The main thread Summary model, mainly used to display the thread list. */ -data class ThreadSummary(val roomId: String, - val rootEvent: Event?, - val latestEvent: Event?, - val rootEventId: String, - val rootThreadSenderInfo: SenderInfo, - val latestThreadSenderInfo: SenderInfo, - val isUserParticipating: Boolean, - val numberOfThreads: Int, - val threadEditions: ThreadEditions = ThreadEditions()) +data class ThreadSummary( + val roomId: String, + val rootEvent: Event?, + val latestEvent: Event?, + val rootEventId: String, + val rootThreadSenderInfo: SenderInfo, + val latestThreadSenderInfo: SenderInfo, + val isUserParticipating: Boolean, + val numberOfThreads: Int, + val threadEditions: ThreadEditions = ThreadEditions() +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt index d4ade9b5b9..9d8c8a13bd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt @@ -139,11 +139,11 @@ fun TimelineEvent.getEditedEventId(): String? { */ fun TimelineEvent.getLastMessageContent(): MessageContent? { return when (root.getClearType()) { - EventType.STICKER -> root.getClearContent().toModel() - in EventType.POLL_START -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() + EventType.STICKER -> root.getClearContent().toModel() + in EventType.POLL_START -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() in EventType.STATE_ROOM_BEACON_INFO -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() - in EventType.BEACON_LOCATION_DATA -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() - else -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() + in EventType.BEACON_LOCATION_DATA -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() + else -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel() } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/search/SearchService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/search/SearchService.kt index bc1c9e5769..ffb8b1ca4d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/search/SearchService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/search/SearchService.kt @@ -33,12 +33,14 @@ interface SearchService { * @param afterLimit how many events after the result are returned. * @param includeProfile requests that the server returns the historic profile information for the users that sent the events that were returned. */ - suspend fun search(searchTerm: String, - roomId: String, - nextBatch: String?, - orderByRecent: Boolean, - limit: Int, - beforeLimit: Int, - afterLimit: Int, - includeProfile: Boolean): SearchResult + suspend fun search( + searchTerm: String, + roomId: String, + nextBatch: String?, + orderByRecent: Boolean, + limit: Int, + beforeLimit: Int, + afterLimit: Int, + includeProfile: Boolean + ): SearchResult } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt index 929463563f..bdbbd3ea84 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt @@ -44,10 +44,12 @@ interface SharedSecretStorageService { * * @return key creation info */ - suspend fun generateKey(keyId: String, - key: SsssKeySpec?, - keyName: String, - keySigner: KeySigner?): SsssKeyCreationInfo + suspend fun generateKey( + keyId: String, + key: SsssKeySpec?, + keyName: String, + keySigner: KeySigner? + ): SsssKeyCreationInfo /** * Generates a SSSS key using the given passphrase. @@ -61,11 +63,13 @@ interface SharedSecretStorageService { * * @return key creation info */ - suspend fun generateKeyWithPassphrase(keyId: String, - keyName: String, - passphrase: String, - keySigner: KeySigner, - progressListener: ProgressListener?): SsssKeyCreationInfo + suspend fun generateKeyWithPassphrase( + keyId: String, + keyName: String, + passphrase: String, + keySigner: KeySigner, + progressListener: ProgressListener? + ): SsssKeyCreationInfo fun getKey(keyId: String): KeyInfoResult diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt index c990388628..61c03e08fc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt @@ -31,11 +31,13 @@ interface Space { */ fun spaceSummary(): RoomSummary? - suspend fun addChildren(roomId: String, - viaServers: List?, - order: String?, + suspend fun addChildren( + roomId: String, + viaServers: List?, + order: String?, // autoJoin: Boolean = false, - suggested: Boolean? = false) + suggested: Boolean? = false + ) fun getChildInfo(roomId: String): SpaceChildContent? diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt index 38e55664d2..c7a6405014 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt @@ -37,11 +37,13 @@ interface SpaceService { /** * Just a shortcut for space creation for ease of use. */ - suspend fun createSpace(name: String, - topic: String?, - avatarUri: Uri?, - isPublic: Boolean, - roomAliasLocalPart: String? = null): String + suspend fun createSpace( + name: String, + topic: String?, + avatarUri: Uri?, + isPublic: Boolean, + roomAliasLocalPart: String? = null + ): String /** * Get a space from a spaceId. @@ -68,25 +70,33 @@ interface SpaceService { * then the parameters given for suggested_only and max_depth must be the same. * @param knownStateList when paginating, pass back the m.space.child state events */ - suspend fun querySpaceChildren(spaceId: String, - suggestedOnly: Boolean? = null, - limit: Int? = null, - from: String? = null, - knownStateList: List? = null): SpaceHierarchyData + suspend fun querySpaceChildren( + spaceId: String, + suggestedOnly: Boolean? = null, + limit: Int? = null, + from: String? = null, + knownStateList: List? = null + ): SpaceHierarchyData /** * Get a live list of space summaries. This list is refreshed as soon as the data changes. * @return the [LiveData] of List[SpaceSummary] */ - fun getSpaceSummariesLive(queryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): LiveData> + fun getSpaceSummariesLive( + queryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): LiveData> - fun getSpaceSummaries(spaceSummaryQueryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): List + fun getSpaceSummaries( + spaceSummaryQueryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): List - suspend fun joinSpace(spaceIdOrAlias: String, - reason: String? = null, - viaServers: List = emptyList()): JoinSpaceResult + suspend fun joinSpace( + spaceIdOrAlias: String, + reason: String? = null, + viaServers: List = emptyList() + ): JoinSpaceResult suspend fun rejectInvite(spaceId: String, reason: String?) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt index 76755517ce..d9c7772393 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt @@ -23,15 +23,19 @@ sealed interface StatisticEvent { /** * Initial sync request, response downloading, and treatment (parsing and storage) of response. */ - data class InitialSyncRequest(val requestDurationMs: Int, - val downloadDurationMs: Int, - val treatmentDurationMs: Int, - val nbOfJoinedRooms: Int) : StatisticEvent + data class InitialSyncRequest( + val requestDurationMs: Int, + val downloadDurationMs: Int, + val treatmentDurationMs: Int, + val nbOfJoinedRooms: Int + ) : StatisticEvent /** * Incremental sync event. */ - data class SyncTreatment(val durationMs: Int, - val afterPause: Boolean, - val nbOfJoinedRooms: Int) : StatisticEvent + data class SyncTreatment( + val durationMs: Int, + val afterPause: Boolean, + val nbOfJoinedRooms: Int + ) : StatisticEvent } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/InitSyncStep.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStep.kt similarity index 91% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/InitSyncStep.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStep.kt index 901c1b2ffb..407585b003 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/InitSyncStep.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStep.kt @@ -14,9 +14,9 @@ * limitations under the License. */ -package org.matrix.android.sdk.api.session.initsync +package org.matrix.android.sdk.api.session.sync -enum class InitSyncStep { +enum class InitialSyncStep { ServerComputing, Downloading, ImportingAccount, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncRequestState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncRequestState.kt new file mode 100644 index 0000000000..4e932d49de --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncRequestState.kt @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.api.session.sync + +sealed interface SyncRequestState { + /** + * For initial sync. + */ + interface InitialSyncRequestState : SyncRequestState + + object Idle : InitialSyncRequestState + data class InitialSyncProgressing( + val initialSyncStep: InitialSyncStep, + val percentProgress: Int = 0 + ) : InitialSyncRequestState + + /** + * For incremental sync. + */ + interface IncrementalSyncRequestState : SyncRequestState + + object IncrementalSyncIdle : IncrementalSyncRequestState + data class IncrementalSyncParsing( + val rooms: Int, + val toDevice: Int + ) : IncrementalSyncRequestState + + object IncrementalSyncError : IncrementalSyncRequestState + object IncrementalSyncDone : IncrementalSyncRequestState +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncService.kt new file mode 100644 index 0000000000..5b2bf651af --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/SyncService.kt @@ -0,0 +1,76 @@ +/* + * Copyright 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.api.session.sync + +import androidx.lifecycle.LiveData +import kotlinx.coroutines.flow.SharedFlow +import org.matrix.android.sdk.api.session.sync.model.SyncResponse + +interface SyncService { + /** + * This method start the sync thread. + */ + fun startSync(fromForeground: Boolean) + + /** + * This method stop the sync thread. + */ + fun stopSync() + + /** + * Requires a one time background sync. + */ + fun requireBackgroundSync() + + /** + * Launches infinite self rescheduling background syncs via the WorkManager. + * + * While dozing, syncs will only occur during maintenance windows. + * For reliability it's recommended to also start a long running foreground service + * along with disabling battery optimizations. + */ + fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) + + fun stopAnyBackgroundSync() + + /** + * This method returns the current sync state. + * @return the current [SyncState]. + */ + fun getSyncState(): SyncState + + /** + * This method allows to listen the sync state. + * @return a [LiveData] of [SyncState]. + */ + fun getSyncStateLive(): LiveData + + /** + * Get the [SyncRequestState] as a LiveData. + */ + fun getSyncRequestStateLive(): LiveData + + /** + * This method returns a flow of SyncResponse. New value will be pushed through the sync thread. + */ + fun syncFlow(): SharedFlow + + /** + * This methods return true if an initial sync has been processed. + */ + fun hasAlreadySynced(): Boolean +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncAndroidService.kt similarity index 97% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncService.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncAndroidService.kt index ac81be2174..8dee633b9c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/job/SyncAndroidService.kt @@ -46,7 +46,7 @@ import java.util.concurrent.atomic.AtomicBoolean * in order to be able to perform a sync even if the app is not running. * The and must be declared in the Manifest or the app using the SDK */ -abstract class SyncService : Service() { +abstract class SyncAndroidService : Service() { private var sessionId: String? = null private var mIsSelfDestroyed: Boolean = false @@ -84,7 +84,7 @@ abstract class SyncService : Service() { stopMe() } } - else -> { + else -> { val isInit = initialize(intent) onStart(isInitialSync) if (isInit) { @@ -158,9 +158,9 @@ abstract class SyncService : Service() { // never do that in foreground, let the syncThread work syncTask.execute(params) // Start sync if we were doing an initial sync and the syncThread is not launched yet - if (isInitialSync && session.getSyncState() == SyncState.Idle) { + if (isInitialSync && session.syncService().getSyncState() == SyncState.Idle) { val isForeground = !backgroundDetectionObserver.isInBackground - session.startSync(isForeground) + session.syncService().startSync(isForeground) } stopMe() } catch (throwable: Throwable) { @@ -210,7 +210,7 @@ abstract class SyncService : Service() { session = sessionComponent.session() sessionId = safeSessionId syncTask = sessionComponent.syncTask() - isInitialSync = !session.hasAlreadySynced() + isInitialSync = !session.syncService().hasAlreadySynced() networkConnectivityChecker = sessionComponent.networkConnectivityChecker() taskExecutor = sessionComponent.taskExecutor() coroutineDispatchers = sessionComponent.coroutineDispatchers() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncUnreadNotifications.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncUnreadNotifications.kt index 6618bceacd..09273f56e6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncUnreadNotifications.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncUnreadNotifications.kt @@ -38,4 +38,5 @@ data class RoomSyncUnreadNotifications( /** * The number of highlighted unread messages (subset of notifications). */ - @Json(name = "highlight_count") val highlightCount: Int? = null) + @Json(name = "highlight_count") val highlightCount: Int? = null +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsResponse.kt index 9a30b4d764..ae728326cc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsResponse.kt @@ -30,8 +30,10 @@ data class TermsResponse( val policies: JsonDict? = null ) { - fun getLocalizedTerms(userLanguage: String, - defaultLanguage: String = "en"): List { + fun getLocalizedTerms( + userLanguage: String, + defaultLanguage: String = "en" + ): List { return policies?.map { val tos = policies[it.key] as? Map<*, *> ?: return@map null ((tos[userLanguage] ?: tos[defaultLanguage]) as? Map<*, *>)?.let { termsMap -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsService.kt index 6c357b2224..1ddce763d1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/terms/TermsService.kt @@ -24,10 +24,12 @@ interface TermsService { suspend fun getTerms(serviceType: ServiceType, baseUrl: String): GetTermsResponse - suspend fun agreeToTerms(serviceType: ServiceType, - baseUrl: String, - agreedUrls: List, - token: String?) + suspend fun agreeToTerms( + serviceType: ServiceType, + baseUrl: String, + agreedUrls: List, + token: String? + ) /** * Get the homeserver terms, from the register API. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt index 8a29d00380..26dd31dc2d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt @@ -33,9 +33,11 @@ sealed class MatrixItem( open val displayName: String?, open val avatarUrl: String? ) { - data class UserItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class UserItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName?.removeSuffix(IRC_PATTERN), avatarUrl) { init { @@ -45,10 +47,12 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class EveryoneInRoomItem(override val id: String, - override val displayName: String = NOTIFY_EVERYONE, - override val avatarUrl: String? = null, - val roomDisplayName: String? = null) : + data class EveryoneInRoomItem( + override val id: String, + override val displayName: String = NOTIFY_EVERYONE, + override val avatarUrl: String? = null, + val roomDisplayName: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -57,9 +61,11 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class EventItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class EventItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -68,9 +74,11 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class RoomItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class RoomItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -79,9 +87,11 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class SpaceItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class SpaceItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -90,9 +100,11 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class RoomAliasItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class RoomAliasItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -101,9 +113,11 @@ sealed class MatrixItem( override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) } - data class GroupItem(override val id: String, - override val displayName: String? = null, - override val avatarUrl: String? = null) : + data class GroupItem( + override val id: String, + override val displayName: String? = null, + override val avatarUrl: String? = null + ) : MatrixItem(id, displayName, avatarUrl) { init { if (BuildConfig.DEBUG) checkId() @@ -124,20 +138,20 @@ sealed class MatrixItem( * Return the prefix as defined in the matrix spec (and not extracted from the id). */ private fun getIdPrefix() = when (this) { - is UserItem -> '@' - is EventItem -> '$' + is UserItem -> '@' + is EventItem -> '$' is SpaceItem, is RoomItem, is EveryoneInRoomItem -> '!' - is RoomAliasItem -> '#' - is GroupItem -> '+' + is RoomAliasItem -> '#' + is GroupItem -> '+' } fun firstLetterOfDisplayName(): String { val displayName = when (this) { // use the room display name for the notify everyone item is EveryoneInRoomItem -> roomDisplayName - else -> displayName + else -> displayName } return (displayName?.takeIf { it.isNotBlank() } ?: id) .let { dn -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/SessionManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/SessionManager.kt index 934d61de45..bd2dac9e3c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/SessionManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/SessionManager.kt @@ -27,8 +27,10 @@ import org.matrix.android.sdk.internal.session.SessionComponent import javax.inject.Inject @MatrixScope -internal class SessionManager @Inject constructor(private val matrixComponent: MatrixComponent, - private val sessionParamsStore: SessionParamsStore) { +internal class SessionManager @Inject constructor( + private val matrixComponent: MatrixComponent, + private val sessionParamsStore: SessionParamsStore +) { // SessionId -> SessionComponent private val sessionComponents = HashMap() @@ -53,7 +55,7 @@ internal class SessionManager @Inject constructor(private val matrixComponent: M fun stopSession(sessionId: String) { val sessionComponent = sessionComponents[sessionId] ?: throw RuntimeException("You don't have a session for id $sessionId") - sessionComponent.session().stopSync() + sessionComponent.session().syncService().stopSync() } fun getOrCreateSessionComponent(sessionParams: SessionParams): SessionComponent { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt index 46fa63334c..ea4502824e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt @@ -98,15 +98,19 @@ internal interface AuthAPI { * https://github.com/matrix-org/matrix-doc/pull/2290 */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register/{threePid}/requestToken") - suspend fun add3Pid(@Path("threePid") threePid: String, - @Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse + suspend fun add3Pid( + @Path("threePid") threePid: String, + @Body params: AddThreePidRegistrationParams + ): AddThreePidRegistrationResponse /** * Validate 3pid. */ @POST - suspend fun validate3Pid(@Url url: String, - @Body params: ValidationCodeBody): SuccessResult + suspend fun validate3Pid( + @Url url: String, + @Body params: ValidationCodeBody + ): SuccessResult /** * Get the supported login flow. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt index 298e116199..ddb70be906 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt @@ -46,9 +46,11 @@ internal abstract class AuthModule { @JvmStatic @Provides @AuthDatabase - fun providesRealmConfiguration(context: Context, - realmKeysUtils: RealmKeysUtils, - authRealmMigration: AuthRealmMigration): RealmConfiguration { + fun providesRealmConfiguration( + context: Context, + realmKeysUtils: RealmKeysUtils, + authRealmMigration: AuthRealmMigration + ): RealmConfiguration { val old = File(context.filesDir, "matrix-sdk-auth") if (old.exists()) { old.renameTo(File(context.filesDir, "matrix-sdk-auth.realm")) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt index fe78ccc75a..61a423669c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt @@ -130,16 +130,7 @@ internal class DefaultAuthenticationService @Inject constructor( ?.trim { it == '/' } } - /** - * This is the entry point of the authentication service. - * homeServerConnectionConfig contains a homeserver URL probably entered by the user, which can be a - * valid homeserver API url, the url of Element Web, or anything else. - */ override suspend fun getLoginFlow(homeServerConnectionConfig: HomeServerConnectionConfig): LoginFlowResult { - pendingSessionData = null - - pendingSessionStore.delete() - val result = runCatching { getLoginFlowInternal(homeServerConnectionConfig) } @@ -290,7 +281,7 @@ internal class DefaultAuthenticationService @Inject constructor( getLoginFlowResult(newAuthAPI, versions, wellknownResult.homeServerUrl) } - else -> throw Failure.OtherServerError("", HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) + else -> throw Failure.OtherServerError("", HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) } } @@ -367,13 +358,17 @@ internal class DefaultAuthenticationService @Inject constructor( pendingSessionStore.delete() } - override suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, - credentials: Credentials): Session { + override suspend fun createSessionFromSso( + homeServerConnectionConfig: HomeServerConnectionConfig, + credentials: Credentials + ): Session { return sessionCreator.createSession(credentials, homeServerConnectionConfig) } - override suspend fun getWellKnownData(matrixId: String, - homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult { + override suspend fun getWellKnownData( + matrixId: String, + homeServerConnectionConfig: HomeServerConnectionConfig? + ): WellknownResult { if (!MatrixPatterns.isUserId(matrixId)) { throw MatrixIdFailure.InvalidMatrixId } @@ -391,11 +386,13 @@ internal class DefaultAuthenticationService @Inject constructor( .withHomeServerUri("https://dummy.org") .build() - override suspend fun directAuthentication(homeServerConnectionConfig: HomeServerConnectionConfig, - matrixId: String, - password: String, - initialDeviceName: String, - deviceId: String?): Session { + override suspend fun directAuthentication( + homeServerConnectionConfig: HomeServerConnectionConfig, + matrixId: String, + password: String, + initialDeviceName: String, + deviceId: String? + ): Session { return directLoginTask.execute( DirectLoginTask.Params( homeServerConnectionConfig = homeServerConnectionConfig, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/PasswordLoginParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/PasswordLoginParams.kt index 5be480f633..5f0a2298cb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/PasswordLoginParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/PasswordLoginParams.kt @@ -31,7 +31,8 @@ internal data class PasswordLoginParams( @Json(name = "password") val password: String, @Json(name = "type") override val type: String, @Json(name = "initial_device_display_name") val deviceDisplayName: String?, - @Json(name = "device_id") val deviceId: String?) : LoginParams { + @Json(name = "device_id") val deviceId: String? +) : LoginParams { companion object { private const val IDENTIFIER_KEY_TYPE = "type" @@ -47,10 +48,12 @@ internal data class PasswordLoginParams( private const val IDENTIFIER_KEY_COUNTRY = "country" private const val IDENTIFIER_KEY_PHONE = "phone" - fun userIdentifier(user: String, - password: String, - deviceDisplayName: String?, - deviceId: String?): PasswordLoginParams { + fun userIdentifier( + user: String, + password: String, + deviceDisplayName: String?, + deviceId: String? + ): PasswordLoginParams { return PasswordLoginParams( identifier = mapOf( IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_USER, @@ -63,11 +66,13 @@ internal data class PasswordLoginParams( ) } - fun thirdPartyIdentifier(medium: String, - address: String, - password: String, - deviceDisplayName: String?, - deviceId: String?): PasswordLoginParams { + fun thirdPartyIdentifier( + medium: String, + address: String, + password: String, + deviceDisplayName: String?, + deviceId: String? + ): PasswordLoginParams { return PasswordLoginParams( identifier = mapOf( IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_THIRD_PARTY, @@ -81,11 +86,13 @@ internal data class PasswordLoginParams( ) } - fun phoneIdentifier(country: String, - phone: String, - password: String, - deviceDisplayName: String?, - deviceId: String?): PasswordLoginParams { + fun phoneIdentifier( + country: String, + phone: String, + password: String, + deviceDisplayName: String?, + deviceId: String? + ): PasswordLoginParams { return PasswordLoginParams( identifier = mapOf( IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_PHONE, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmPendingSessionStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmPendingSessionStore.kt index 13f26e321d..aae8ff8419 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmPendingSessionStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmPendingSessionStore.kt @@ -23,9 +23,10 @@ import org.matrix.android.sdk.internal.database.awaitTransaction import org.matrix.android.sdk.internal.di.AuthDatabase import javax.inject.Inject -internal class RealmPendingSessionStore @Inject constructor(private val mapper: PendingSessionMapper, - @AuthDatabase - private val realmConfiguration: RealmConfiguration +internal class RealmPendingSessionStore @Inject constructor( + private val mapper: PendingSessionMapper, + @AuthDatabase + private val realmConfiguration: RealmConfiguration ) : PendingSessionStore { override suspend fun savePendingSessionData(pendingSessionData: PendingSessionData) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmSessionParamsStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmSessionParamsStore.kt index 235ef6b709..4c3e3ca824 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmSessionParamsStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/RealmSessionParamsStore.kt @@ -28,9 +28,10 @@ import org.matrix.android.sdk.internal.di.AuthDatabase import timber.log.Timber import javax.inject.Inject -internal class RealmSessionParamsStore @Inject constructor(private val mapper: SessionParamsMapper, - @AuthDatabase - private val realmConfiguration: RealmConfiguration +internal class RealmSessionParamsStore @Inject constructor( + private val mapper: SessionParamsMapper, + @AuthDatabase + private val realmConfiguration: RealmConfiguration ) : SessionParamsStore { override fun getLast(): SessionParams? { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt index 0583951138..20b056f1c7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt @@ -52,10 +52,12 @@ internal class DefaultLoginWizard( return getProfileTask.execute(GetProfileTask.Params(matrixId)) } - override suspend fun login(login: String, - password: String, - initialDeviceName: String, - deviceId: String?): Session { + override suspend fun login( + login: String, + password: String, + initialDeviceName: String, + deviceId: String? + ): Session { val loginParams = if (Patterns.EMAIL_ADDRESS.matcher(login).matches()) { PasswordLoginParams.thirdPartyIdentifier( medium = ThreePidMedium.EMAIL, @@ -101,7 +103,7 @@ internal class DefaultLoginWizard( return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig) } - override suspend fun resetPassword(email: String, newPassword: String) { + override suspend fun resetPassword(email: String) { val param = RegisterAddThreePidTask.Params( RegisterThreePid.Email(email), pendingSessionData.clientSecret, @@ -115,18 +117,16 @@ internal class DefaultLoginWizard( authAPI.resetPassword(AddThreePidRegistrationParams.from(param)) } - pendingSessionData = pendingSessionData.copy(resetPasswordData = ResetPasswordData(newPassword, result)) + pendingSessionData = pendingSessionData.copy(resetPasswordData = ResetPasswordData(result)) .also { pendingSessionStore.savePendingSessionData(it) } } - override suspend fun resetPasswordMailConfirmed() { - val safeResetPasswordData = pendingSessionData.resetPasswordData - ?: throw IllegalStateException("developer error, no reset password in progress") - + override suspend fun resetPasswordMailConfirmed(newPassword: String) { + val resetPasswordData = pendingSessionData.resetPasswordData ?: throw IllegalStateException("Developer error - Must call resetPassword first") val param = ResetPasswordMailConfirmed.create( pendingSessionData.clientSecret, - safeResetPasswordData.addThreePidRegistrationResponse.sid, - safeResetPasswordData.newPassword + resetPasswordData.addThreePidRegistrationResponse.sid, + newPassword ) executeRequest(null) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt index 28706c7e80..c9311867c8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt @@ -73,7 +73,7 @@ internal class DefaultDirectLoginTask @Inject constructor( homeServerUrl, throwable.fingerprint ) - else -> throwable + else -> throwable } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt index a65ec38d6d..87a7b346dc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt @@ -24,6 +24,5 @@ import org.matrix.android.sdk.internal.auth.registration.AddThreePidRegistration */ @JsonClass(generateAdapter = true) internal data class ResetPasswordData( - val newPassword: String, val addThreePidRegistrationResponse: AddThreePidRegistrationResponse ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt index 2f05864d3b..f0cb6ebd6d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt @@ -84,7 +84,7 @@ internal data class AddThreePidRegistrationParams( companion object { fun from(params: RegisterAddThreePidTask.Params): AddThreePidRegistrationParams { return when (params.threePid) { - is RegisterThreePid.Email -> AddThreePidRegistrationParams( + is RegisterThreePid.Email -> AddThreePidRegistrationParams( email = params.threePid.email, clientSecret = params.clientSecret, sendAttempt = params.sendAttempt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index 345f4097db..d6ec0297b4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -51,12 +51,12 @@ internal class DefaultRegistrationWizard( override fun getCurrentThreePid(): String? { return when (val threePid = pendingSessionData.currentThreePidData?.threePid) { - is RegisterThreePid.Email -> threePid.email + is RegisterThreePid.Email -> threePid.email is RegisterThreePid.Msisdn -> { // Take formatted msisdn if provided by the server pendingSessionData.currentThreePidData?.addThreePidRegistrationResponse?.formattedMsisdn?.takeIf { it.isNotBlank() } ?: threePid.msisdn } - null -> null + null -> null } } @@ -67,9 +67,11 @@ internal class DefaultRegistrationWizard( return performRegistrationRequest(params) } - override suspend fun createAccount(userName: String?, - password: String?, - initialDeviceDisplayName: String?): RegistrationResult { + override suspend fun createAccount( + userName: String?, + password: String?, + initialDeviceDisplayName: String? + ): RegistrationResult { val params = RegistrationParams( username = userName, password = password, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/RegisterAddThreePidTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/RegisterAddThreePidTask.kt index 54a8ba0e6c..b84ed61361 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/RegisterAddThreePidTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/RegisterAddThreePidTask.kt @@ -41,7 +41,7 @@ internal class DefaultRegisterAddThreePidTask( private fun RegisterThreePid.toPath(): String { return when (this) { - is RegisterThreePid.Email -> "email" + is RegisterThreePid.Email -> "email" is RegisterThreePid.Msisdn -> "msisdn" } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt index c8f71af306..dde0a44ea0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt @@ -40,11 +40,13 @@ internal data class ThreePidData( } companion object { - fun from(threePid: RegisterThreePid, - addThreePidRegistrationResponse: AddThreePidRegistrationResponse, - registrationParams: RegistrationParams): ThreePidData { + fun from( + threePid: RegisterThreePid, + addThreePidRegistrationResponse: AddThreePidRegistrationResponse, + registrationParams: RegistrationParams + ): ThreePidData { return when (threePid) { - is RegisterThreePid.Email -> + is RegisterThreePid.Email -> ThreePidData(threePid.email, "", "", addThreePidRegistrationResponse, registrationParams) is RegisterThreePid.Msisdn -> ThreePidData("", threePid.msisdn, threePid.countryCode, addThreePidRegistrationResponse, registrationParams) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt index 9b135c347d..8118f9faff 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt @@ -35,9 +35,11 @@ import kotlin.coroutines.suspendCoroutine * @return UiaResult if UIA handled, failed or cancelled * */ -internal suspend fun handleUIA(failure: Throwable, - interceptor: UserInteractiveAuthInterceptor, - retryBlock: suspend (UIABaseAuth) -> Unit): UiaResult { +internal suspend fun handleUIA( + failure: Throwable, + interceptor: UserInteractiveAuthInterceptor, + retryBlock: suspend (UIABaseAuth) -> Unit +): UiaResult { Timber.d("## UIA: check error ${failure.message}") val flowResponse = failure.toRegistrationFlowResponse() ?: return UiaResult.FAILURE.also { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersion.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersion.kt index 815f8de2de..cd38b68a85 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersion.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersion.kt @@ -16,6 +16,8 @@ package org.matrix.android.sdk.internal.auth.version +import org.matrix.android.sdk.api.extensions.ensureNotEmpty + /** * Values will take the form "rX.Y.Z". * Ref: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-versions @@ -33,19 +35,19 @@ internal data class HomeServerVersion( minor < other.minor -> -1 patch > other.patch -> 1 patch < other.patch -> -1 - else -> 0 + else -> 0 } } companion object { - internal val pattern = Regex("""[r|v](\d+)\.(\d+)\.(\d+)""") + internal val pattern = Regex("""[r|v](\d+)\.(\d+)(?:\.(\d+))?""") internal fun parse(value: String): HomeServerVersion? { val result = pattern.matchEntire(value) ?: return null return HomeServerVersion( major = result.groupValues[1].toInt(), minor = result.groupValues[2].toInt(), - patch = result.groupValues[3].toInt() + patch = result.groupValues.getOrNull(index = 3)?.ensureNotEmpty()?.toInt() ?: 0 ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoModule.kt index 2265526484..c69a859016 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoModule.kt @@ -110,10 +110,12 @@ internal abstract class CryptoModule { @Provides @CryptoDatabase @SessionScope - fun providesRealmConfiguration(@SessionFilesDirectory directory: File, - @UserMd5 userMd5: String, - realmKeysUtils: RealmKeysUtils, - realmCryptoStoreMigration: RealmCryptoStoreMigration): RealmConfiguration { + fun providesRealmConfiguration( + @SessionFilesDirectory directory: File, + @UserMd5 userMd5: String, + realmKeysUtils: RealmKeysUtils, + realmCryptoStoreMigration: RealmCryptoStoreMigration + ): RealmConfiguration { return RealmConfiguration.Builder() .directory(directory) .apply { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt index 824478f1d3..719f366518 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt @@ -188,8 +188,8 @@ internal class DefaultCryptoService @Inject constructor( fun onStateEvent(roomId: String, event: Event) { when (event.type) { - EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) - EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event) + EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) + EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event) EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event) } } @@ -198,8 +198,8 @@ internal class DefaultCryptoService @Inject constructor( // handle state events if (event.isStateEvent()) { when (event.type) { - EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) - EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event) + EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) + EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event) EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event) } } @@ -592,10 +592,12 @@ internal class DefaultCryptoService @Inject constructor( * @param membersId list of members to start tracking their devices * @return true if the operation succeeds. */ - private suspend fun setEncryptionInRoom(roomId: String, - algorithm: String?, - inhibitDeviceQuery: Boolean, - membersId: List): Boolean { + private suspend fun setEncryptionInRoom( + roomId: String, + algorithm: String?, + inhibitDeviceQuery: Boolean, + membersId: List + ): Boolean { // If we already have encryption in this room, we should ignore this event // (for now at least. Maybe we should alert the user somehow?) val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId) @@ -618,8 +620,8 @@ internal class DefaultCryptoService @Inject constructor( val alg: IMXEncrypting? = when (algorithm) { MXCRYPTO_ALGORITHM_MEGOLM -> megolmEncryptionFactory.create(roomId) - MXCRYPTO_ALGORITHM_OLM -> olmEncryptionFactory.create(roomId) - else -> null + MXCRYPTO_ALGORITHM_OLM -> olmEncryptionFactory.create(roomId) + else -> null } if (alg != null) { @@ -691,10 +693,12 @@ internal class DefaultCryptoService @Inject constructor( * @param roomId the room identifier the event will be sent. * @param callback the asynchronous callback */ - override fun encryptEventContent(eventContent: Content, - eventType: String, - roomId: String, - callback: MatrixCallback) { + override fun encryptEventContent( + eventContent: Content, + eventType: String, + roomId: String, + callback: MatrixCallback + ) { // moved to crypto scope to have uptodate values cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { val userIds = getRoomUserIds(roomId) @@ -796,10 +800,10 @@ internal class DefaultCryptoService @Inject constructor( // Keys are imported directly, not waiting for end of sync onRoomKeyEvent(event) } - EventType.REQUEST_SECRET -> { + EventType.REQUEST_SECRET -> { secretShareManager.handleSecretRequest(event) } - EventType.ROOM_KEY_REQUEST -> { + EventType.ROOM_KEY_REQUEST -> { event.getClearContent().toModel()?.let { req -> // We'll always get these because we send room key requests to // '*' (ie. 'all devices') which includes the sending device, @@ -811,13 +815,13 @@ internal class DefaultCryptoService @Inject constructor( } } } - EventType.SEND_SECRET -> { + EventType.SEND_SECRET -> { onSecretSendReceived(event) } - EventType.ROOM_KEY_WITHHELD -> { + EventType.ROOM_KEY_WITHHELD -> { onKeyWithHeldReceived(event) } - else -> { + else -> { // ignore } } @@ -879,10 +883,12 @@ internal class DefaultCryptoService @Inject constructor( /** * Returns true if handled by SDK, otherwise should be sent to application layer. */ - private fun handleSDKLevelGossip(secretName: String?, - secretValue: String): Boolean { + private fun handleSDKLevelGossip( + secretName: String?, + secretValue: String + ): Boolean { return when (secretName) { - MASTER_KEY_SSSS_NAME -> { + MASTER_KEY_SSSS_NAME -> { crossSigningService.onSecretMSKGossip(secretValue) true } @@ -898,7 +904,7 @@ internal class DefaultCryptoService @Inject constructor( keysBackupService.onSecretKeyGossip(secretValue) true } - else -> false + else -> false } } @@ -1022,9 +1028,11 @@ internal class DefaultCryptoService @Inject constructor( * @param progressListener the progress listener * @return the result ImportRoomKeysResult */ - override suspend fun importRoomKeys(roomKeysAsArray: ByteArray, - password: String, - progressListener: ProgressListener?): ImportRoomKeysResult { + override suspend fun importRoomKeys( + roomKeysAsArray: ByteArray, + password: String, + progressListener: ProgressListener? + ): ImportRoomKeysResult { return withContext(coroutineDispatchers.crypto) { Timber.tag(loggerTag.value).v("importRoomKeys starts") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt index 18b815b3d8..4f3900adb9 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt @@ -231,8 +231,8 @@ internal class DeviceListManager @Inject constructor( for ((k, value) in failures) { val statusCode = when (val status = value["status"]) { is Double -> status.toInt() - is Int -> status.toInt() - else -> 0 + is Int -> status.toInt() + else -> 0 } if (statusCode == 503) { synchronized(notReadyToRetryHS) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/InboundGroupSessionStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/InboundGroupSessionStore.kt index 28ddf291b2..e4d322cadd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/InboundGroupSessionStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/InboundGroupSessionStore.kt @@ -44,7 +44,8 @@ private val loggerTag = LoggerTag("InboundGroupSessionStore", LoggerTag.CRYPTO) internal class InboundGroupSessionStore @Inject constructor( private val store: IMXCryptoStore, private val cryptoCoroutineScope: CoroutineScope, - private val coroutineDispatchers: MatrixCoroutineDispatchers) { + private val coroutineDispatchers: MatrixCoroutineDispatchers +) { private data class CacheKey( val sessionId: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt index 13f2fb861a..7f36224dae 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt @@ -135,7 +135,7 @@ internal class IncomingKeyRequestManager @Inject constructor( // just add to the buffer incomingRequestBuffer.add(validMegolmRequest) } - MegolmRequestAction.Cancel -> { + MegolmRequestAction.Cancel -> { // ignore, we can't cancel as it's not known (probably already processed) // still notify app layer if it was passed up previously IncomingRoomKeyRequest.fromRestRequest(senderId, request, clock)?.let { iReq -> @@ -159,7 +159,7 @@ internal class IncomingKeyRequestManager @Inject constructor( MegolmRequestAction.Request -> { // it's already in buffer, nop keep existing } - MegolmRequestAction.Cancel -> { + MegolmRequestAction.Cancel -> { // discard the request in buffer incomingRequestBuffer.remove(existing) outgoingRequestScope.launch(coroutineDispatchers.computation) { @@ -369,9 +369,11 @@ internal class IncomingKeyRequestManager @Inject constructor( shareMegolmKey(validReq, requestingDevice, null) } - private suspend fun shareMegolmKey(validRequest: ValidMegolmRequestBody, - requestingDevice: CryptoDeviceInfo, - chainIndex: Long?): Boolean { + private suspend fun shareMegolmKey( + validRequest: ValidMegolmRequestBody, + requestingDevice: CryptoDeviceInfo, + chainIndex: Long? + ): Boolean { Timber.tag(loggerTag.value) .d("try to re-share Megolm Key at index $chainIndex for ${validRequest.shortDbgString()}") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXCryptoAlgorithms.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXCryptoAlgorithms.kt index 5a5ee9e696..14b0e8e125 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXCryptoAlgorithms.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXCryptoAlgorithms.kt @@ -32,7 +32,7 @@ internal object MXCryptoAlgorithms { return when (algorithm) { MXCRYPTO_ALGORITHM_MEGOLM, MXCRYPTO_ALGORITHM_OLM -> true - else -> false + else -> false } } @@ -47,7 +47,7 @@ internal object MXCryptoAlgorithms { return when (algorithm) { MXCRYPTO_ALGORITHM_MEGOLM, MXCRYPTO_ALGORITHM_OLM -> true - else -> false + else -> false } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt index 1d25d82549..24b6fd166f 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt @@ -600,13 +600,15 @@ internal class MXOlmDevice @Inject constructor( * @param exportFormat true if the megolm keys are in export format * @return true if the operation succeeds. */ - fun addInboundGroupSession(sessionId: String, - sessionKey: String, - roomId: String, - senderKey: String, - forwardingCurve25519KeyChain: List, - keysClaimed: Map, - exportFormat: Boolean): AddSessionResult { + fun addInboundGroupSession( + sessionId: String, + sessionKey: String, + roomId: String, + senderKey: String, + forwardingCurve25519KeyChain: List, + keysClaimed: Map, + exportFormat: Boolean + ): AddSessionResult { val candidateSession = OlmInboundGroupSessionWrapper2(sessionKey, exportFormat) val existingSessionHolder = tryOrNull { getInboundGroupSession(sessionId, senderKey, roomId) } val existingSession = existingSessionHolder?.wrapper @@ -762,12 +764,14 @@ internal class MXOlmDevice @Inject constructor( * @return the decrypting result. Null if the sessionId is unknown. */ @Throws(MXCryptoError::class) - suspend fun decryptGroupMessage(body: String, - roomId: String, - timeline: String?, - eventId: String, - sessionId: String, - senderKey: String): OlmDecryptionResult { + suspend fun decryptGroupMessage( + body: String, + roomId: String, + timeline: String?, + eventId: String, + sessionId: String, + senderKey: String + ): OlmDecryptionResult { val sessionHolder = getInboundGroupSession(sessionId, senderKey, roomId) val wrapper = sessionHolder.wrapper val inboundGroupSession = wrapper.olmInboundGroupSession diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt index ab562d954a..3f4b633ea0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt @@ -19,8 +19,10 @@ package org.matrix.android.sdk.internal.crypto import org.matrix.android.sdk.api.auth.data.Credentials import javax.inject.Inject -internal class ObjectSigner @Inject constructor(private val credentials: Credentials, - private val olmDevice: MXOlmDevice) { +internal class ObjectSigner @Inject constructor( + private val credentials: Credentials, + private val olmDevice: MXOlmDevice +) { /** * Sign Object. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt index d7652d0771..6b22cc09d6 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt @@ -71,7 +71,8 @@ internal class OutgoingKeyRequestManager @Inject constructor( private val inboundGroupSessionStore: InboundGroupSessionStore, private val sendToDeviceTask: SendToDeviceTask, private val deviceListManager: DeviceListManager, - private val perSessionBackupQueryRateLimiter: PerSessionBackupQueryRateLimiter) { + private val perSessionBackupQueryRateLimiter: PerSessionBackupQueryRateLimiter +) { private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() private val outgoingRequestScope = CoroutineScope(SupervisorJob() + dispatcher) @@ -180,13 +181,15 @@ internal class OutgoingKeyRequestManager @Inject constructor( } } - fun onRoomKeyForwarded(sessionId: String, - algorithm: String, - roomId: String, - senderKey: String, - fromDevice: String?, - fromIndex: Int, - event: Event) { + fun onRoomKeyForwarded( + sessionId: String, + algorithm: String, + roomId: String, + senderKey: String, + fromDevice: String?, + fromIndex: Int, + event: Event + ) { Timber.tag(loggerTag.value).d("Key forwarded for $sessionId from ${event.senderId}|$fromDevice at index $fromIndex") outgoingRequestScope.launch { sequencer.post { @@ -208,12 +211,14 @@ internal class OutgoingKeyRequestManager @Inject constructor( } } - fun onRoomKeyWithHeld(sessionId: String, - algorithm: String, - roomId: String, - senderKey: String, - fromDevice: String?, - event: Event) { + fun onRoomKeyWithHeld( + sessionId: String, + algorithm: String, + roomId: String, + senderKey: String, + fromDevice: String?, + event: Event + ) { outgoingRequestScope.launch { sequencer.post { Timber.tag(loggerTag.value).d("Withheld received for $sessionId from ${event.senderId}|$fromDevice") @@ -294,19 +299,19 @@ internal class OutgoingKeyRequestManager @Inject constructor( } knownRequest.forEach { request -> when (request.state) { - OutgoingRoomKeyRequestState.UNSENT -> { + OutgoingRoomKeyRequestState.UNSENT -> { if (request.fromIndex >= localKnownChainIndex) { // we have a good index we can cancel cryptoStore.deleteOutgoingRoomKeyRequest(request.requestId) } } - OutgoingRoomKeyRequestState.SENT -> { + OutgoingRoomKeyRequestState.SENT -> { // It was already sent, and index satisfied we can cancel if (request.fromIndex >= localKnownChainIndex) { cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING) } } - OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> { + OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> { // It is already marked to be cancelled } OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> { @@ -315,7 +320,7 @@ internal class OutgoingKeyRequestManager @Inject constructor( cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING) } } - OutgoingRoomKeyRequestState.SENT_THEN_CANCELED -> { + OutgoingRoomKeyRequestState.SENT_THEN_CANCELED -> { // was already canceled // if we need a better index, should we resend? } @@ -346,14 +351,14 @@ internal class OutgoingKeyRequestManager @Inject constructor( val existing = cryptoStore.getOutgoingRoomKeyRequest(requestBody) Timber.tag(loggerTag.value).v("Queueing key request exiting is ${existing?.state}") when (existing?.state) { - null -> { + null -> { // create a new one cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients, fromIndex) } - OutgoingRoomKeyRequestState.UNSENT -> { + OutgoingRoomKeyRequestState.UNSENT -> { // nothing it's new or not yet handled } - OutgoingRoomKeyRequestState.SENT -> { + OutgoingRoomKeyRequestState.SENT -> { // it was already requested Timber.tag(loggerTag.value).d("The session ${requestBody.sessionId} is already requested") if (force) { @@ -366,7 +371,7 @@ internal class OutgoingKeyRequestManager @Inject constructor( } } } - OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> { + OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> { // request is canceled only if I got the keys so what to do here... if (force) { cryptoStore.updateOutgoingRoomKeyRequestState(existing.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND) @@ -375,7 +380,7 @@ internal class OutgoingKeyRequestManager @Inject constructor( OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> { // It's already going to resend } - OutgoingRoomKeyRequestState.SENT_THEN_CANCELED -> { + OutgoingRoomKeyRequestState.SENT_THEN_CANCELED -> { if (force) { cryptoStore.deleteOutgoingRoomKeyRequest(existing.requestId) cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients, fromIndex) @@ -396,11 +401,11 @@ internal class OutgoingKeyRequestManager @Inject constructor( measureTimeMillis { toProcess.forEach { when (it.state) { - OutgoingRoomKeyRequestState.UNSENT -> handleUnsentRequest(it) - OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> handleRequestToCancel(it) + OutgoingRoomKeyRequestState.UNSENT -> handleUnsentRequest(it) + OutgoingRoomKeyRequestState.CANCELLATION_PENDING -> handleRequestToCancel(it) OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> handleRequestToCancelWillResend(it) OutgoingRoomKeyRequestState.SENT_THEN_CANCELED, - OutgoingRoomKeyRequestState.SENT -> { + OutgoingRoomKeyRequestState.SENT -> { // these are filtered out } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt index a80bafbe79..d37e60d289 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt @@ -85,7 +85,7 @@ internal class RoomDecryptorProvider @Inject constructor( } } } - else -> olmDecryptionFactory.create() + else -> olmDecryptionFactory.create() } if (!roomId.isNullOrEmpty()) { synchronized(roomDecryptors) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt index 1a8c160d9c..9f6714cc45 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt @@ -49,8 +49,8 @@ internal class RoomEncryptorsStore @Inject constructor( } else { val alg: IMXEncrypting? = when (cryptoStore.getRoomAlgorithm(roomId)) { MXCRYPTO_ALGORITHM_MEGOLM -> megolmEncryptionFactory.create(roomId) - MXCRYPTO_ALGORITHM_OLM -> olmEncryptionFactory.create(roomId) - else -> null + MXCRYPTO_ALGORITHM_OLM -> olmEncryptionFactory.create(roomId) + else -> null } alg?.let { roomEncryptors.put(roomId, it) } return@synchronized alg diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt index 6fb6914206..a79e1a8901 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt @@ -150,14 +150,14 @@ internal class SecretShareManager @Inject constructor( // we can share the secret val secretValue = when (secretName) { - MASTER_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.master + MASTER_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.master SELF_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.selfSigned USER_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.user KEYBACKUP_SECRET_SSSS_NAME -> cryptoStore.getKeyBackupRecoveryKeyInfo()?.recoveryKey ?.let { extractCurveKeyFromRecoveryKey(it)?.toBase64NoPadding() } - else -> null + else -> null } if (secretValue == null) { Timber.tag(loggerTag.value) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt index c728f1b682..c263192fee 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt @@ -39,7 +39,8 @@ private val loggerTag = LoggerTag("EnsureOlmSessionsForDevicesAction", LoggerTag internal class EnsureOlmSessionsForDevicesAction @Inject constructor( private val olmDevice: MXOlmDevice, private val coroutineDispatchers: MatrixCoroutineDispatchers, - private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { + private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask +) { private val ensureMutex = Mutex() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForUsersAction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForUsersAction.kt index 4c5720daf2..da09524668 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForUsersAction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForUsersAction.kt @@ -23,9 +23,11 @@ import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore import timber.log.Timber import javax.inject.Inject -internal class EnsureOlmSessionsForUsersAction @Inject constructor(private val olmDevice: MXOlmDevice, - private val cryptoStore: IMXCryptoStore, - private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction) { +internal class EnsureOlmSessionsForUsersAction @Inject constructor( + private val olmDevice: MXOlmDevice, + private val cryptoStore: IMXCryptoStore, + private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction +) { /** * Try to make sure we have established olm sessions for the given users. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt index 67d73c21ed..f6ab96aee6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt @@ -33,11 +33,12 @@ import javax.inject.Inject private val loggerTag = LoggerTag("MegolmSessionDataImporter", LoggerTag.CRYPTO) -internal class MegolmSessionDataImporter @Inject constructor(private val olmDevice: MXOlmDevice, - private val roomDecryptorProvider: RoomDecryptorProvider, - private val outgoingKeyRequestManager: OutgoingKeyRequestManager, - private val cryptoStore: IMXCryptoStore, - private val clock: Clock, +internal class MegolmSessionDataImporter @Inject constructor( + private val olmDevice: MXOlmDevice, + private val roomDecryptorProvider: RoomDecryptorProvider, + private val outgoingKeyRequestManager: OutgoingKeyRequestManager, + private val cryptoStore: IMXCryptoStore, + private val clock: Clock, ) { /** @@ -50,9 +51,11 @@ internal class MegolmSessionDataImporter @Inject constructor(private val olmDevi * @return import room keys result */ @WorkerThread - fun handle(megolmSessionsData: List, - fromBackup: Boolean, - progressListener: ProgressListener?): ImportRoomKeysResult { + fun handle( + megolmSessionsData: List, + fromBackup: Boolean, + progressListener: ProgressListener? + ): ImportRoomKeysResult { val t0 = clock.epochMillis() val totalNumbersOfKeys = megolmSessionsData.size diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MessageEncrypter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MessageEncrypter.kt index 919e38c391..eff2132820 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MessageEncrypter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MessageEncrypter.kt @@ -36,7 +36,8 @@ internal class MessageEncrypter @Inject constructor( private val userId: String, @DeviceId private val deviceId: String?, - private val olmDevice: MXOlmDevice) { + private val olmDevice: MXOlmDevice +) { /** * Encrypt an event payload for a list of devices. * This method must be called from the getCryptoHandler() thread. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/SetDeviceVerificationAction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/SetDeviceVerificationAction.kt index 60181138fb..6028b1a5a2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/SetDeviceVerificationAction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/SetDeviceVerificationAction.kt @@ -26,7 +26,8 @@ import javax.inject.Inject internal class SetDeviceVerificationAction @Inject constructor( private val cryptoStore: IMXCryptoStore, @UserId private val userId: String, - private val defaultKeysBackupService: DefaultKeysBackupService) { + private val defaultKeysBackupService: DefaultKeysBackupService +) { fun handle(trustLevel: DeviceTrustLevel, userId: String, deviceId: String) { val device = cryptoStore.getUserDevice(userId, deviceId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXGroupEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXGroupEncryption.kt index 8cf01f1972..9ec78f37cf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXGroupEncryption.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXGroupEncryption.kt @@ -45,8 +45,10 @@ internal interface IMXGroupEncryption { * * @return true in case of success */ - suspend fun reshareKey(groupSessionId: String, - userId: String, - deviceId: String, - senderKey: String): Boolean + suspend fun reshareKey( + groupSessionId: String, + userId: String, + deviceId: String, + senderKey: String + ): Boolean } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 722462bf0e..141d6f74cd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -149,7 +149,8 @@ internal class MXMegolmDecryption( throw MXCryptoError.Base( MXCryptoError.ErrorType.KEYS_WITHHELD, withHeldInfo.code?.value ?: "", - withHeldInfo.reason) + withHeldInfo.reason + ) } if (requestKeysOnFail) { @@ -249,9 +250,9 @@ internal class MXMegolmDecryption( ) when (addSessionResult) { - is MXOlmDevice.AddSessionResult.Imported -> addSessionResult.ratchetIndex + is MXOlmDevice.AddSessionResult.Imported -> addSessionResult.ratchetIndex is MXOlmDevice.AddSessionResult.NotImportedHigherIndex -> addSessionResult.newIndex - else -> null + else -> null }?.let { index -> if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) { val fromDevice = (event.content?.get("sender_key") as? String)?.let { senderDeviceIdentityKey -> @@ -268,7 +269,8 @@ internal class MXMegolmDecryption( senderKey = senderKey, fromIndex = index, fromDevice = fromDevice, - event = event) + event = event + ) cryptoStore.saveIncomingForwardKeyAuditTrail( roomId = roomKeyContent.roomId, @@ -277,7 +279,8 @@ internal class MXMegolmDecryption( algorithm = roomKeyContent.algorithm ?: "", userId = event.senderId ?: "", deviceId = fromDevice ?: "", - chainIndex = index.toLong()) + chainIndex = index.toLong() + ) // The index is used to decide if we cancel sent request or if we wait for a better key outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(roomKeyContent.sessionId, roomKeyContent.roomId, senderKey, index) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt index 096773a959..81a6fb28c0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt @@ -35,6 +35,7 @@ internal class MXMegolmDecryptionFactory @Inject constructor( olmDevice, outgoingKeyRequestManager, cryptoStore, - eventsManager) + eventsManager + ) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index 8b4e9df607..7bfbae6edf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -84,9 +84,11 @@ internal class MXMegolmEncryption( private var sessionRotationPeriodMsgs: Int = 100 private var sessionRotationPeriodMs: Int = 7 * 24 * 3600 * 1000 - override suspend fun encryptEventContent(eventContent: Content, - eventType: String, - userIds: List): Content { + override suspend fun encryptEventContent( + eventContent: Content, + eventType: String, + userIds: List + ): Content { val ts = clock.epochMillis() Timber.tag(loggerTag.value).v("encryptEventContent : getDevicesInRoom") val devices = getDevicesInRoom(userIds) @@ -201,8 +203,10 @@ internal class MXMegolmEncryption( * @param session the session info * @param devicesByUsers the devices map */ - private suspend fun shareKey(session: MXOutboundSessionInfo, - devicesByUsers: Map>) { + private suspend fun shareKey( + session: MXOutboundSessionInfo, + devicesByUsers: Map> + ) { // nothing to send, the task is done if (devicesByUsers.isEmpty()) { Timber.tag(loggerTag.value).v("shareKey() : nothing more to do") @@ -230,8 +234,10 @@ internal class MXMegolmEncryption( * @param session the session info * @param devicesByUser the devices map */ - private suspend fun shareUserDevicesKey(session: MXOutboundSessionInfo, - devicesByUser: Map>) { + private suspend fun shareUserDevicesKey( + session: MXOutboundSessionInfo, + devicesByUser: Map> + ) { val sessionKey = olmDevice.getSessionKey(session.sessionId) val chainIndex = olmDevice.getMessageIndex(session.sessionId) @@ -321,10 +327,12 @@ internal class MXMegolmEncryption( } } - private suspend fun notifyKeyWithHeld(targets: List, - sessionId: String, - senderKey: String?, - code: WithHeldCode) { + private suspend fun notifyKeyWithHeld( + targets: List, + sessionId: String, + senderKey: String?, + code: WithHeldCode + ) { Timber.tag(loggerTag.value).d( "notifyKeyWithHeld() :sending withheld for session:$sessionId and code $code to" + " ${targets.joinToString { "${it.userId}|${it.deviceId}" }}" @@ -435,10 +443,12 @@ internal class MXMegolmEncryption( } } - override suspend fun reshareKey(groupSessionId: String, - userId: String, - deviceId: String, - senderKey: String): Boolean { + override suspend fun reshareKey( + groupSessionId: String, + userId: String, + deviceId: String, + senderKey: String + ): Boolean { Timber.tag(loggerTag.value).i("process reshareKey for $groupSessionId to $userId:$deviceId") val deviceInfo = cryptoStore.getUserDevice(userId, deviceId) ?: return false .also { Timber.tag(loggerTag.value).w("reshareKey: Device not found") } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/SharedWithHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/SharedWithHelper.kt index 61ad345c62..30fd403ce8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/SharedWithHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/SharedWithHelper.kt @@ -23,7 +23,8 @@ import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore internal class SharedWithHelper( private val roomId: String, private val sessionId: String, - private val cryptoStore: IMXCryptoStore) { + private val cryptoStore: IMXCryptoStore +) { fun sharedWithDevices(): MXUsersDevicesMap { return cryptoStore.getSharedWithInfo(roomId, sessionId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt index 23c8f0e905..219cadac46 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt @@ -38,7 +38,8 @@ internal class MXOlmDecryption( // The olm device interface private val olmDevice: MXOlmDevice, // the matrix userId - private val userId: String) : + private val userId: String +) : IMXDecrypting { @Throws(MXCryptoError::class) @@ -190,9 +191,9 @@ internal class MXOlmDecryption( val messageBody = message["body"] as? String ?: return null val messageType = when (val typeAsVoid = message["type"]) { is Double -> typeAsVoid.toInt() - is Int -> typeAsVoid - is Long -> typeAsVoid.toInt() - else -> return null + is Int -> typeAsVoid + is Long -> typeAsVoid.toInt() + else -> return null } // Try each session in turn diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryptionFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryptionFactory.kt index d5c5e85e41..a50ac8ca8a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryptionFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryptionFactory.kt @@ -20,8 +20,10 @@ import org.matrix.android.sdk.internal.crypto.MXOlmDevice import org.matrix.android.sdk.internal.di.UserId import javax.inject.Inject -internal class MXOlmDecryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice, - @UserId private val userId: String) { +internal class MXOlmDecryptionFactory @Inject constructor( + private val olmDevice: MXOlmDevice, + @UserId private val userId: String +) { fun create(): MXOlmDecryption { return MXOlmDecryption( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt index bde1d65093..fb70e23b03 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -32,7 +32,8 @@ internal class MXOlmEncryption( private val cryptoStore: IMXCryptoStore, private val messageEncrypter: MessageEncrypter, private val deviceListManager: DeviceListManager, - private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) : + private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction +) : IMXEncrypting { override suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryptionFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryptionFactory.kt index 44e55900e4..012886203e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryptionFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryptionFactory.kt @@ -24,12 +24,14 @@ import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore import javax.inject.Inject -internal class MXOlmEncryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice, - private val cryptoStore: IMXCryptoStore, - private val messageEncrypter: MessageEncrypter, - private val deviceListManager: DeviceListManager, - private val coroutineDispatchers: MatrixCoroutineDispatchers, - private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) { +internal class MXOlmEncryptionFactory @Inject constructor( + private val olmDevice: MXOlmDevice, + private val cryptoStore: IMXCryptoStore, + private val messageEncrypter: MessageEncrypter, + private val deviceListManager: DeviceListManager, + private val coroutineDispatchers: MatrixCoroutineDispatchers, + private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction +) { fun create(roomId: String): MXOlmEncryption { return MXOlmEncryption( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/api/CryptoApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/api/CryptoApi.kt index f5ead35933..d5a8bdfd7c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/api/CryptoApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/api/CryptoApi.kt @@ -117,9 +117,11 @@ internal interface CryptoApi { * @param body the body */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sendToDevice/{eventType}/{txnId}") - suspend fun sendToDevice(@Path("eventType") eventType: String, - @Path("txnId") transactionId: String, - @Body body: SendToDeviceBody) + suspend fun sendToDevice( + @Path("eventType") eventType: String, + @Path("txnId") transactionId: String, + @Body body: SendToDeviceBody + ) /** * Delete a device. @@ -129,8 +131,10 @@ internal interface CryptoApi { * @param params the deletion parameters */ @HTTP(path = NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}", method = "DELETE", hasBody = true) - suspend fun deleteDevice(@Path("device_id") deviceId: String, - @Body params: DeleteDeviceParams) + suspend fun deleteDevice( + @Path("device_id") deviceId: String, + @Body params: DeleteDeviceParams + ) /** * Update the device information. @@ -140,8 +144,10 @@ internal interface CryptoApi { * @param params the params */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}") - suspend fun updateDeviceInfo(@Path("device_id") deviceId: String, - @Body params: UpdateDeviceInfoBody) + suspend fun updateDeviceInfo( + @Path("device_id") deviceId: String, + @Body params: UpdateDeviceInfoBody + ) /** * Get the update devices list from two sync token. @@ -151,6 +157,8 @@ internal interface CryptoApi { * @param newToken the up-to token. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/changes") - suspend fun getKeyChanges(@Query("from") oldToken: String, - @Query("to") newToken: String): KeyChangesResponse + suspend fun getKeyChanges( + @Query("from") oldToken: String, + @Query("to") newToken: String + ): KeyChangesResponse } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt index 7ff08cd127..37c8e755ff 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt @@ -41,10 +41,12 @@ internal object MXEncryptedAttachments { private const val SECRET_KEY_SPEC_ALGORITHM = "AES" private const val MESSAGE_DIGEST_ALGORITHM = "SHA-256" - fun encrypt(clearStream: InputStream, - outputFile: File, - clock: Clock, - progress: ((current: Int, total: Int) -> Unit)): EncryptedFileInfo { + fun encrypt( + clearStream: InputStream, + outputFile: File, + clock: Clock, + progress: ((current: Int, total: Int) -> Unit) + ): EncryptedFileInfo { val t0 = clock.epochMillis() val secureRandom = SecureRandom() val initVectorBytes = ByteArray(16) { 0.toByte() } @@ -236,10 +238,11 @@ internal object MXEncryptedAttachments { * @param clock a clock to retrieve current time * @return true in case of success, false in case of error */ - fun decryptAttachment(attachmentStream: InputStream?, - elementToDecrypt: ElementToDecrypt?, - outputStream: OutputStream, - clock: Clock + fun decryptAttachment( + attachmentStream: InputStream?, + elementToDecrypt: ElementToDecrypt?, + outputStream: OutputStream, + clock: Clock ): Boolean { // sanity checks if (null == attachmentStream || elementToDecrypt == null) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt index 4fa355cd2a..3218b99948 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt @@ -53,13 +53,13 @@ internal class CrossSigningOlm @Inject constructor( fun signObject(type: KeyType, strToSign: String): Map { val myKeys = cryptoStore.getMyCrossSigningInfo() val pubKey = when (type) { - KeyType.SELF -> myKeys?.selfSigningKey() - KeyType.USER -> myKeys?.userKey() + KeyType.SELF -> myKeys?.selfSigningKey() + KeyType.USER -> myKeys?.userKey() KeyType.MASTER -> myKeys?.masterKey() }?.unpaddedBase64PublicKey val pkSigning = when (type) { - KeyType.SELF -> selfSigningPkSigning - KeyType.USER -> userPkSigning + KeyType.SELF -> selfSigningPkSigning + KeyType.USER -> userPkSigning KeyType.MASTER -> masterPkSigning } if (pubKey == null || pkSigning == null) { @@ -76,8 +76,8 @@ internal class CrossSigningOlm @Inject constructor( ?: throw NoSuchElementException("Cross Signing not configured") val myUserID = myKeys.userId val pubKey = when (type) { - KeyType.SELF -> myKeys.selfSigningKey() - KeyType.USER -> myKeys.userKey() + KeyType.SELF -> myKeys.selfSigningKey() + KeyType.USER -> myKeys.userKey() KeyType.MASTER -> myKeys.masterKey() }?.unpaddedBase64PublicKey ?: throw NoSuchElementException("Cross Signing not configured") val signaturesMadeByMyKey = signatures[myUserID] // Signatures made by me diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt index 6c198abc2e..e466def1a1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt @@ -261,9 +261,10 @@ internal class DefaultCrossSigningService @Inject constructor( } } - override fun checkTrustFromPrivateKeys(masterKeyPrivateKey: String?, - uskKeyPrivateKey: String?, - sskPrivateKey: String? + override fun checkTrustFromPrivateKeys( + masterKeyPrivateKey: String?, + uskKeyPrivateKey: String?, + sskPrivateKey: String? ): UserTrustResult { val mxCrossSigningInfo = getMyCrossSigningKeys() ?: return UserTrustResult.CrossSigningNotConfigured(userId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/UpdateTrustWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/UpdateTrustWorker.kt index 74f0f5745d..f1dc060e10 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/UpdateTrustWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/UpdateTrustWorker.kt @@ -149,7 +149,7 @@ internal class UpdateTrustWorker(context: Context, params: WorkerParameters, ses val trusts = otherInfos.mapValues { entry -> when (entry.key) { myUserId -> myTrustResult - else -> { + else -> { crossSigningService.checkOtherMSKTrusted(myCrossSigningInfo, entry.value).also { Timber.v("## CrossSigning - user:${entry.key} result:$it") } @@ -276,10 +276,12 @@ internal class UpdateTrustWorker(context: Context, params: WorkerParameters, ses } } - private fun computeRoomShield(myCrossSigningInfo: MXCrossSigningInfo?, - cryptoRealm: Realm, - activeMemberUserIds: List, - roomSummaryEntity: RoomSummaryEntity): RoomEncryptionTrustLevel { + private fun computeRoomShield( + myCrossSigningInfo: MXCrossSigningInfo?, + cryptoRealm: Realm, + activeMemberUserIds: List, + roomSummaryEntity: RoomSummaryEntity + ): RoomEncryptionTrustLevel { Timber.v("## CrossSigning - computeRoomShield ${roomSummaryEntity.roomId} -> ${activeMemberUserIds.logLimit()}") // The set of “all users” depends on the type of room: // For regular / topic rooms which have more than 2 members (including yourself) are considered when decorating a room diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt index efd3bca824..5eaa106af3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt @@ -151,9 +151,11 @@ internal class DefaultKeysBackupService @Inject constructor( keysBackupStateManager.removeListener(listener) } - override fun prepareKeysBackupVersion(password: String?, - progressListener: ProgressListener?, - callback: MatrixCallback) { + override fun prepareKeysBackupVersion( + password: String?, + progressListener: ProgressListener?, + callback: MatrixCallback + ) { cryptoCoroutineScope.launch(coroutineDispatchers.io) { try { val olmPkDecryption = OlmPkDecryption() @@ -227,8 +229,10 @@ internal class DefaultKeysBackupService @Inject constructor( } } - override fun createKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, - callback: MatrixCallback) { + override fun createKeysBackupVersion( + keysBackupCreationInfo: MegolmBackupCreationInfo, + callback: MatrixCallback + ) { @Suppress("UNCHECKED_CAST") val createKeysBackupVersionBody = CreateKeysBackupVersionBody( algorithm = keysBackupCreationInfo.algorithm, @@ -318,7 +322,7 @@ internal class DefaultKeysBackupService @Inject constructor( // val hashServer = keysBackupData?.backupLastServerHash return when { - totalNumberOfKeysLocally < totalNumberOfKeysServer -> { + totalNumberOfKeysLocally < totalNumberOfKeysServer -> { // Server contains more keys than this device true } @@ -327,7 +331,7 @@ internal class DefaultKeysBackupService @Inject constructor( // TODO We have not found any algorithm to determine if a restore is recommended here. Return false for the moment false } - else -> false + else -> false } } @@ -339,8 +343,10 @@ internal class DefaultKeysBackupService @Inject constructor( return cryptoStore.inboundGroupSessionsCount(true) } - override fun backupAllGroupSessions(progressListener: ProgressListener?, - callback: MatrixCallback?) { + override fun backupAllGroupSessions( + progressListener: ProgressListener?, + callback: MatrixCallback? + ) { if (!isEnabled() || backupOlmPkEncryption == null || keysBackupVersion == null) { callback?.onFailure(Throwable("Backup not enabled")) return @@ -391,8 +397,10 @@ internal class DefaultKeysBackupService @Inject constructor( }) } - override fun getKeysBackupTrust(keysBackupVersion: KeysVersionResult, - callback: MatrixCallback) { + override fun getKeysBackupTrust( + keysBackupVersion: KeysVersionResult, + callback: MatrixCallback + ) { // TODO Validate with François that this is correct object : Task { override suspend fun execute(params: KeysVersionResult): KeysBackupVersionTrust { @@ -499,9 +507,11 @@ internal class DefaultKeysBackupService @Inject constructor( ) } - override fun trustKeysBackupVersion(keysBackupVersion: KeysVersionResult, - trust: Boolean, - callback: MatrixCallback) { + override fun trustKeysBackupVersion( + keysBackupVersion: KeysVersionResult, + trust: Boolean, + callback: MatrixCallback + ) { Timber.v("trustKeyBackupVersion: $trust, version ${keysBackupVersion.version}") // Get auth data to update it @@ -583,9 +593,11 @@ internal class DefaultKeysBackupService @Inject constructor( } } - override fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult, - recoveryKey: String, - callback: MatrixCallback) { + override fun trustKeysBackupVersionWithRecoveryKey( + keysBackupVersion: KeysVersionResult, + recoveryKey: String, + callback: MatrixCallback + ) { Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}") cryptoCoroutineScope.launch(coroutineDispatchers.io) { @@ -602,9 +614,11 @@ internal class DefaultKeysBackupService @Inject constructor( } } - override fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult, - password: String, - callback: MatrixCallback) { + override fun trustKeysBackupVersionWithPassphrase( + keysBackupVersion: KeysVersionResult, + password: String, + callback: MatrixCallback + ) { Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}") cryptoCoroutineScope.launch(coroutineDispatchers.io) { @@ -701,12 +715,14 @@ internal class DefaultKeysBackupService @Inject constructor( progressListener.onProgress(backedUpKeys, total) } - override fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, - recoveryKey: String, - roomId: String?, - sessionId: String?, - stepProgressListener: StepProgressListener?, - callback: MatrixCallback) { + override fun restoreKeysWithRecoveryKey( + keysVersionResult: KeysVersionResult, + recoveryKey: String, + roomId: String?, + sessionId: String?, + stepProgressListener: StepProgressListener?, + callback: MatrixCallback + ) { Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}") cryptoCoroutineScope.launch(coroutineDispatchers.io) { @@ -800,12 +816,14 @@ internal class DefaultKeysBackupService @Inject constructor( } } - override fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, - password: String, - roomId: String?, - sessionId: String?, - stepProgressListener: StepProgressListener?, - callback: MatrixCallback) { + override fun restoreKeyBackupWithPassword( + keysBackupVersion: KeysVersionResult, + password: String, + roomId: String?, + sessionId: String?, + stepProgressListener: StepProgressListener?, + callback: MatrixCallback + ) { Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}") cryptoCoroutineScope.launch(coroutineDispatchers.io) { @@ -853,9 +871,11 @@ internal class DefaultKeysBackupService @Inject constructor( * Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable * parameters and always returns a KeysBackupData object through the Callback. */ - private suspend fun getKeys(sessionId: String?, - roomId: String?, - version: String): KeysBackupData { + private suspend fun getKeys( + sessionId: String?, + roomId: String?, + version: String + ): KeysBackupData { return if (roomId != null && sessionId != null) { // Get key for the room and for the session val data = getRoomSessionDataTask.execute(GetRoomSessionDataTask.Params(roomId, sessionId, version)) @@ -909,7 +929,7 @@ internal class DefaultKeysBackupService @Inject constructor( */ fun maybeBackupKeys() { when { - isStuck() -> { + isStuck() -> { // If not already done, or in error case, check for a valid backup version on the homeserver. // If there is one, maybeBackupKeys will be called again. checkAndStartKeysBackup() @@ -927,14 +947,16 @@ internal class DefaultKeysBackupService @Inject constructor( uiHandler.post { backupKeys() } } } - else -> { + else -> { Timber.v("maybeBackupKeys: Skip it because state: ${getState()}") } } } - override fun getVersion(version: String, - callback: MatrixCallback) { + override fun getVersion( + version: String, + callback: MatrixCallback + ) { getKeysBackupVersionTask .configureWith(version) { this.callback = object : MatrixCallback { @@ -970,7 +992,7 @@ internal class DefaultKeysBackupService @Inject constructor( override fun onSuccess(data: KeysBackupLastVersionResult) { val localBackupVersion = keysBackupVersion?.version when (data) { - KeysBackupLastVersionResult.NoKeysBackup -> { + KeysBackupLastVersionResult.NoKeysBackup -> { if (localBackupVersion == null) { // No backup on the server, and backup is not active callback.onSuccess(true) @@ -1173,10 +1195,12 @@ internal class DefaultKeysBackupService @Inject constructor( } } - override fun computePrivateKey(passphrase: String, - privateKeySalt: String, - privateKeyIterations: Int, - progressListener: ProgressListener): ByteArray { + override fun computePrivateKey( + passphrase: String, + privateKeySalt: String, + privateKeyIterations: Int, + progressListener: ProgressListener + ): ByteArray { return deriveKey(passphrase, privateKeySalt, privateKeyIterations, progressListener) } @@ -1354,7 +1378,7 @@ internal class DefaultKeysBackupService @Inject constructor( // Do not stay in KeysBackupState.WrongBackUpVersion but check what is available on the homeserver checkAndStartKeysBackup() } - else -> + else -> // Come back to the ready state so that we will retry on the next received key keysBackupStateManager.state = KeysBackupState.ReadyToBackUp } @@ -1476,8 +1500,10 @@ internal class DefaultKeysBackupService @Inject constructor( get() = cryptoStore @VisibleForTesting - fun createFakeKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, - callback: MatrixCallback) { + fun createFakeKeysBackupVersion( + keysBackupCreationInfo: MegolmBackupCreationInfo, + callback: MatrixCallback + ) { @Suppress("UNCHECKED_CAST") val createKeysBackupVersionBody = CreateKeysBackupVersionBody( algorithm = keysBackupCreationInfo.algorithm, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt index f821fdcf6d..8560eb5fc1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt @@ -49,8 +49,9 @@ internal data class GeneratePrivateKeyResult( * @return a {privateKey, salt, iterations} tuple. */ @WorkerThread -internal fun generatePrivateKeyWithPassword(password: String, - progressListener: ProgressListener? +internal fun generatePrivateKeyWithPassword( + password: String, + progressListener: ProgressListener? ): GeneratePrivateKeyResult { val salt = generateSalt() val iterations = DEFAULT_ITERATION @@ -70,10 +71,12 @@ internal fun generatePrivateKeyWithPassword(password: String, * @return a private key. */ @WorkerThread -internal fun retrievePrivateKeyWithPassword(password: String, - salt: String, - iterations: Int, - progressListener: ProgressListener? = null): ByteArray { +internal fun retrievePrivateKeyWithPassword( + password: String, + salt: String, + iterations: Int, + progressListener: ProgressListener? = null +): ByteArray { return deriveKey(password, salt, iterations, progressListener) } @@ -88,10 +91,12 @@ internal fun retrievePrivateKeyWithPassword(password: String, * @return a private key. */ @WorkerThread -internal fun deriveKey(password: String, - salt: String, - iterations: Int, - progressListener: ProgressListener?): ByteArray { +internal fun deriveKey( + password: String, + salt: String, + iterations: Int, + progressListener: ProgressListener? +): ByteArray { // Note: copied and adapted from MXMegolmExportEncryption // based on https://en.wikipedia.org/wiki/PBKDF2 algorithm // it is simpler than the generic algorithm because the expected key length is equal to the mac key length. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt index d9c63b46ab..48a735018a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt @@ -71,8 +71,10 @@ internal interface RoomKeysApi { * @param updateKeysBackupVersionBody the body */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}") - suspend fun updateKeysBackupVersion(@Path("version") version: String, - @Body updateKeysBackupVersionBody: UpdateKeysBackupVersionBody) + suspend fun updateKeysBackupVersion( + @Path("version") version: String, + @Body updateKeysBackupVersionBody: UpdateKeysBackupVersionBody + ) /* ========================================================================================== * Storing keys @@ -93,10 +95,12 @@ internal interface RoomKeysApi { * @param keyBackupData the data to send */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") - suspend fun storeRoomSessionData(@Path("roomId") roomId: String, - @Path("sessionId") sessionId: String, - @Query("version") version: String, - @Body keyBackupData: KeyBackupData): BackupKeysResult + suspend fun storeRoomSessionData( + @Path("roomId") roomId: String, + @Path("sessionId") sessionId: String, + @Query("version") version: String, + @Body keyBackupData: KeyBackupData + ): BackupKeysResult /** * Store several keys for the given room, using the given backup version. @@ -106,9 +110,11 @@ internal interface RoomKeysApi { * @param roomKeysBackupData the data to send */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") - suspend fun storeRoomSessionsData(@Path("roomId") roomId: String, - @Query("version") version: String, - @Body roomKeysBackupData: RoomKeysBackupData): BackupKeysResult + suspend fun storeRoomSessionsData( + @Path("roomId") roomId: String, + @Query("version") version: String, + @Body roomKeysBackupData: RoomKeysBackupData + ): BackupKeysResult /** * Store several keys, using the given backup version. @@ -117,8 +123,10 @@ internal interface RoomKeysApi { * @param keysBackupData the data to send */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys") - suspend fun storeSessionsData(@Query("version") version: String, - @Body keysBackupData: KeysBackupData): BackupKeysResult + suspend fun storeSessionsData( + @Query("version") version: String, + @Body keysBackupData: KeysBackupData + ): BackupKeysResult /* ========================================================================================== * Retrieving keys @@ -132,9 +140,11 @@ internal interface RoomKeysApi { * @param version the version of the backup, or empty String to retrieve the last version */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") - suspend fun getRoomSessionData(@Path("roomId") roomId: String, - @Path("sessionId") sessionId: String, - @Query("version") version: String): KeyBackupData + suspend fun getRoomSessionData( + @Path("roomId") roomId: String, + @Path("sessionId") sessionId: String, + @Query("version") version: String + ): KeyBackupData /** * Retrieve all the keys for the given room from the backup. @@ -143,8 +153,10 @@ internal interface RoomKeysApi { * @param version the version of the backup, or empty String to retrieve the last version */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") - suspend fun getRoomSessionsData(@Path("roomId") roomId: String, - @Query("version") version: String): RoomKeysBackupData + suspend fun getRoomSessionsData( + @Path("roomId") roomId: String, + @Query("version") version: String + ): RoomKeysBackupData /** * Retrieve all the keys from the backup. @@ -162,16 +174,20 @@ internal interface RoomKeysApi { * Deletes keys from the backup. */ @DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") - suspend fun deleteRoomSessionData(@Path("roomId") roomId: String, - @Path("sessionId") sessionId: String, - @Query("version") version: String) + suspend fun deleteRoomSessionData( + @Path("roomId") roomId: String, + @Path("sessionId") sessionId: String, + @Query("version") version: String + ) /** * Deletes keys from the backup. */ @DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") - suspend fun deleteRoomSessionsData(@Path("roomId") roomId: String, - @Query("version") version: String) + suspend fun deleteRoomSessionsData( + @Path("roomId") roomId: String, + @Query("version") version: String + ) /** * Deletes keys from the backup. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt index 9fdeda01c9..85ba1762d3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt @@ -69,12 +69,14 @@ internal data class KeyVerificationAccept( override fun toSendToDeviceObject() = this companion object : VerificationInfoAcceptFactory { - override fun create(tid: String, - keyAgreementProtocol: String, - hash: String, - commitment: String, - messageAuthenticationCode: String, - shortAuthenticationStrings: List): VerificationInfoAccept { + override fun create( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept { return KeyVerificationAccept( transactionId = tid, keyAgreementProtocol = keyAgreementProtocol, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/VerificationMethodValues.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/VerificationMethodValues.kt index c07434f586..afe6191bf7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/VerificationMethodValues.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/VerificationMethodValues.kt @@ -28,7 +28,7 @@ internal const val VERIFICATION_METHOD_RECIPROCATE = "m.reciprocate.v1" internal fun VerificationMethod.toValue(): String { return when (this) { - VerificationMethod.SAS -> VERIFICATION_METHOD_SAS + VerificationMethod.SAS -> VERIFICATION_METHOD_SAS VerificationMethod.QR_CODE_SCAN -> VERIFICATION_METHOD_QR_CODE_SCAN VerificationMethod.QR_CODE_SHOW -> VERIFICATION_METHOD_QR_CODE_SHOW } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt index 0daaec11a1..ddb048a912 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt @@ -63,10 +63,12 @@ internal class DefaultSharedSecretStorageService @Inject constructor( private val cryptoCoroutineScope: CoroutineScope ) : SharedSecretStorageService { - override suspend fun generateKey(keyId: String, - key: SsssKeySpec?, - keyName: String, - keySigner: KeySigner?): SsssKeyCreationInfo { + override suspend fun generateKey( + keyId: String, + key: SsssKeySpec?, + keyName: String, + keySigner: KeySigner? + ): SsssKeyCreationInfo { return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) { val bytes = (key as? RawBytesKeySpec)?.privateKey ?: ByteArray(32).also { @@ -95,11 +97,13 @@ internal class DefaultSharedSecretStorageService @Inject constructor( } } - override suspend fun generateKeyWithPassphrase(keyId: String, - keyName: String, - passphrase: String, - keySigner: KeySigner, - progressListener: ProgressListener?): SsssKeyCreationInfo { + override suspend fun generateKeyWithPassphrase( + keyId: String, + keyName: String, + passphrase: String, + keySigner: KeySigner, + progressListener: ProgressListener? + ): SsssKeyCreationInfo { return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) { val privatePart = generatePrivateKeyWithPassword(passphrase, progressListener) @@ -175,7 +179,7 @@ internal class DefaultSharedSecretStorageService @Inject constructor( throw SharedSecretStorageError.UnknownAlgorithm(key.keyInfo.content.algorithm ?: "") } } - is KeyInfoResult.Error -> throw key.error + is KeyInfoResult.Error -> throw key.error } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt index 9b1c785059..b18de34329 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt @@ -192,10 +192,12 @@ internal interface IMXCryptoStore { */ fun storeUserDevices(userId: String, devices: Map?) - fun storeUserCrossSigningKeys(userId: String, - masterKey: CryptoCrossSigningKey?, - selfSigningKey: CryptoCrossSigningKey?, - userSigningKey: CryptoCrossSigningKey?) + fun storeUserCrossSigningKeys( + userId: String, + masterKey: CryptoCrossSigningKey?, + selfSigningKey: CryptoCrossSigningKey?, + userSigningKey: CryptoCrossSigningKey? + ) /** * Retrieve the known devices for a user. @@ -392,7 +394,8 @@ internal interface IMXCryptoStore { algorithm: String, senderKey: String, fromDevice: String?, - event: Event) + event: Event + ) fun deleteOutgoingRoomKeyRequest(requestId: String) fun deleteOutgoingRoomKeyRequestInState(state: OutgoingRoomKeyRequestState) @@ -479,8 +482,14 @@ internal interface IMXCryptoStore { fun addWithHeldMegolmSession(withHeldContent: RoomKeyWithHeldContent) fun getWithHeldMegolmSession(roomId: String, sessionId: String): RoomKeyWithHeldContent? - fun markedSessionAsShared(roomId: String?, sessionId: String, userId: String, deviceId: String, - deviceIdentityKey: String, chainIndex: Int) + fun markedSessionAsShared( + roomId: String?, + sessionId: String, + userId: String, + deviceId: String, + deviceIdentityKey: String, + chainIndex: Int + ) /** * Query for information on this session sharing history. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt index 533ab70bba..c56e4d320b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt @@ -322,10 +322,12 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun storeUserCrossSigningKeys(userId: String, - masterKey: CryptoCrossSigningKey?, - selfSigningKey: CryptoCrossSigningKey?, - userSigningKey: CryptoCrossSigningKey?) { + override fun storeUserCrossSigningKeys( + userId: String, + masterKey: CryptoCrossSigningKey?, + selfSigningKey: CryptoCrossSigningKey?, + userSigningKey: CryptoCrossSigningKey? + ) { doRealmTransaction(realmConfiguration) { realm -> UserEntity.getOrCreate(realm, userId) .let { userEntity -> @@ -1154,9 +1156,11 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody, - recipients: Map>, - fromIndex: Int): OutgoingKeyRequest { + override fun getOrAddOutgoingRoomKeyRequest( + requestBody: RoomKeyRequestBody, + recipients: Map>, + fromIndex: Int + ): OutgoingKeyRequest { // Insert the request and return the one passed in parameter lateinit var request: OutgoingKeyRequest doRealmTransaction(realmConfiguration) { realm -> @@ -1220,12 +1224,14 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun updateOutgoingRoomKeyReply(roomId: String, - sessionId: String, - algorithm: String, - senderKey: String, - fromDevice: String?, - event: Event) { + override fun updateOutgoingRoomKeyReply( + roomId: String, + sessionId: String, + algorithm: String, + senderKey: String, + fromDevice: String?, + event: Event + ) { doRealmTransaction(realmConfiguration) { realm -> realm.where() .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, roomId) @@ -1266,7 +1272,8 @@ internal class RealmCryptoStore @Inject constructor( senderKey: String, algorithm: String, fromUser: String, - fromDevice: String) { + fromDevice: String + ) { monarchy.writeAsync { realm -> val now = clock.epochMillis() realm.createObject().apply { @@ -1288,13 +1295,15 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun saveWithheldAuditTrail(roomId: String, - sessionId: String, - senderKey: String, - algorithm: String, - code: WithHeldCode, - userId: String, - deviceId: String) { + override fun saveWithheldAuditTrail( + roomId: String, + sessionId: String, + senderKey: String, + algorithm: String, + code: WithHeldCode, + userId: String, + deviceId: String + ) { monarchy.writeAsync { realm -> val now = clock.epochMillis() realm.createObject().apply { @@ -1316,34 +1325,39 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun saveForwardKeyAuditTrail(roomId: String, - sessionId: String, - senderKey: String, - algorithm: String, - userId: String, - deviceId: String, - chainIndex: Long?) { + override fun saveForwardKeyAuditTrail( + roomId: String, + sessionId: String, + senderKey: String, + algorithm: String, + userId: String, + deviceId: String, + chainIndex: Long? + ) { saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, false) } - override fun saveIncomingForwardKeyAuditTrail(roomId: String, - sessionId: String, - senderKey: String, - algorithm: String, - userId: String, - deviceId: String, - chainIndex: Long?) { + override fun saveIncomingForwardKeyAuditTrail( + roomId: String, + sessionId: String, + senderKey: String, + algorithm: String, + userId: String, + deviceId: String, + chainIndex: Long? + ) { saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, true) } - private fun saveForwardKeyTrail(roomId: String, - sessionId: String, - senderKey: String, - algorithm: String, - userId: String, - deviceId: String, - chainIndex: Long?, - incoming: Boolean + private fun saveForwardKeyTrail( + roomId: String, + sessionId: String, + senderKey: String, + algorithm: String, + userId: String, + deviceId: String, + chainIndex: Long?, + incoming: Boolean ) { monarchy.writeAsync { realm -> val now = clock.epochMillis() @@ -1617,12 +1631,14 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun markedSessionAsShared(roomId: String?, - sessionId: String, - userId: String, - deviceId: String, - deviceIdentityKey: String, - chainIndex: Int) { + override fun markedSessionAsShared( + roomId: String?, + sessionId: String, + userId: String, + deviceId: String, + deviceIdentityKey: String, + chainIndex: Int + ) { doRealmTransaction(realmConfiguration) { realm -> SharedSessionEntity.create( realm = realm, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo004.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo004.kt index e5bdd2aa9b..0a986892d9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo004.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo004.kt @@ -104,10 +104,10 @@ internal class MigrateCryptoTo004(realm: DynamicRealm) : RealmMigrator(realm, 4) val trustLevel = realm.createObject("TrustLevelEntity") when (oldDevice.verified) { - MXDeviceInfo.DEVICE_VERIFICATION_UNKNOWN -> { + MXDeviceInfo.DEVICE_VERIFICATION_UNKNOWN -> { obj.setNull(DeviceInfoEntityFields.TRUST_LEVEL_ENTITY.`$`) } - MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED -> { + MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED -> { trustLevel.setNull(TrustLevelEntityFields.LOCALLY_VERIFIED) trustLevel.setNull(TrustLevelEntityFields.CROSS_SIGNED_VERIFIED) obj.setBoolean(DeviceInfoEntityFields.IS_BLOCKED, oldDevice.isBlocked) @@ -118,7 +118,7 @@ internal class MigrateCryptoTo004(realm: DynamicRealm) : RealmMigrator(realm, 4) trustLevel.setBoolean(TrustLevelEntityFields.CROSS_SIGNED_VERIFIED, false) obj.setObject(DeviceInfoEntityFields.TRUST_LEVEL_ENTITY.`$`, trustLevel) } - MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED -> { + MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED -> { trustLevel.setBoolean(TrustLevelEntityFields.LOCALLY_VERIFIED, true) trustLevel.setBoolean(TrustLevelEntityFields.CROSS_SIGNED_VERIFIED, false) obj.setObject(DeviceInfoEntityFields.TRUST_LEVEL_ENTITY.`$`, trustLevel) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt index 80ae4a8d0d..fe8e9f1db7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt @@ -30,7 +30,7 @@ internal object AuditTrailMapper { fun map(entity: AuditTrailEntity): AuditTrail? { val contentJson = entity.contentJson ?: return null return when (entity.type) { - TrailType.OutgoingKeyForward.name -> { + TrailType.OutgoingKeyForward.name -> { val info = tryOrNull { MoshiProvider.providesMoshi().adapter(ForwardInfo::class.java).fromJson(contentJson) } ?: return null @@ -50,7 +50,7 @@ internal object AuditTrailMapper { info = info ) } - TrailType.IncomingKeyRequest.name -> { + TrailType.IncomingKeyRequest.name -> { val info = tryOrNull { MoshiProvider.providesMoshi().adapter(IncomingKeyRequestInfo::class.java).fromJson(contentJson) } ?: return null @@ -60,7 +60,7 @@ internal object AuditTrailMapper { info = info ) } - TrailType.IncomingKeyForward.name -> { + TrailType.IncomingKeyForward.name -> { val info = tryOrNull { MoshiProvider.providesMoshi().adapter(ForwardInfo::class.java).fromJson(contentJson) } ?: return null @@ -70,7 +70,7 @@ internal object AuditTrailMapper { info = info ) } - else -> { + else -> { AuditTrail( ageLocalTs = entity.ageLocalTs ?: 0, type = TrailType.Unknown, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmInboundGroupSessionEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmInboundGroupSessionEntity.kt index 83671b28d9..a4f6c279ac 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmInboundGroupSessionEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmInboundGroupSessionEntity.kt @@ -33,7 +33,8 @@ internal open class OlmInboundGroupSessionEntity( // olmInboundGroupSessionData contains Json var olmInboundGroupSessionData: String? = null, // Indicate if the key has been backed up to the homeserver - var backedUp: Boolean = false) : + var backedUp: Boolean = false +) : RealmObject() { fun getInboundGroupSession(): OlmInboundGroupSessionWrapper2? { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmSessionEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmSessionEntity.kt index 1a637d76c4..9f010db288 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmSessionEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OlmSessionEntity.kt @@ -25,11 +25,13 @@ import org.matrix.olm.OlmSession internal fun OlmSessionEntity.Companion.createPrimaryKey(sessionId: String, deviceKey: String) = "$sessionId|$deviceKey" // olmSessionData is a serialized OlmSession -internal open class OlmSessionEntity(@PrimaryKey var primaryKey: String = "", - var sessionId: String? = null, - var deviceKey: String? = null, - var olmSessionData: String? = null, - var lastReceivedMessageTs: Long = 0) : +internal open class OlmSessionEntity( + @PrimaryKey var primaryKey: String = "", + var sessionId: String? = null, + var deviceKey: String? = null, + var olmSessionData: String? = null, + var lastReceivedMessageTs: Long = 0 +) : RealmObject() { fun getOlmSession(): OlmSession? { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt index 7a8ba18809..854d148b76 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt @@ -117,7 +117,7 @@ internal open class OutgoingKeyRequestEntity( private fun eventToResult(event: Event): RequestResult? { return when (event.getClearType()) { - EventType.ROOM_KEY_WITHHELD -> { + EventType.ROOM_KEY_WITHHELD -> { event.content.toModel()?.code?.let { RequestResult.Failure(it) } @@ -125,7 +125,7 @@ internal open class OutgoingKeyRequestEntity( EventType.FORWARDED_ROOM_KEY -> { RequestResult.Success((event.content?.get("chain_index") as? Number)?.toInt() ?: 0) } - else -> null + else -> null } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/SharedSessionQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/SharedSessionQueries.kt index 8bf9794375..85dd50c88e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/SharedSessionQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/SharedSessionQueries.kt @@ -24,12 +24,14 @@ import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntity import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntityFields -internal fun SharedSessionEntity.Companion.get(realm: Realm, - roomId: String?, - sessionId: String, - userId: String, - deviceId: String, - deviceIdentityKey: String?): SharedSessionEntity? { +internal fun SharedSessionEntity.Companion.get( + realm: Realm, + roomId: String?, + sessionId: String, + userId: String, + deviceId: String, + deviceIdentityKey: String? +): SharedSessionEntity? { return realm.where() .equalTo(SharedSessionEntityFields.ROOM_ID, roomId) .equalTo(SharedSessionEntityFields.SESSION_ID, sessionId) @@ -48,12 +50,15 @@ internal fun SharedSessionEntity.Companion.get(realm: Realm, roomId: String?, se .findAll() } -internal fun SharedSessionEntity.Companion.create(realm: Realm, roomId: String?, - sessionId: String, - userId: String, - deviceId: String, - deviceIdentityKey: String, - chainIndex: Int): SharedSessionEntity { +internal fun SharedSessionEntity.Companion.create( + realm: Realm, + roomId: String?, + sessionId: String, + userId: String, + deviceId: String, + deviceIdentityKey: String, + chainIndex: Int +): SharedSessionEntity { return realm.createObject().apply { this.roomId = roomId this.algorithm = MXCRYPTO_ALGORITHM_MEGOLM diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt index 394c618968..a4b4cd0761 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt @@ -31,10 +31,11 @@ import org.matrix.android.sdk.internal.task.Task import javax.inject.Inject internal interface EncryptEventTask : Task { - data class Params(val roomId: String, - val event: Event, - /**Do not encrypt these keys, keep them as is in encrypted content (e.g. m.relates_to)*/ - val keepKeys: List? = null + data class Params( + val roomId: String, + val event: Event, + /**Do not encrypt these keys, keep them as is in encrypted content (e.g. m.relates_to)*/ + val keepKeys: List? = null ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/RedactEventTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/RedactEventTask.kt index d6a7f3c6a0..56bdc8cae8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/RedactEventTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/RedactEventTask.kt @@ -32,7 +32,8 @@ internal interface RedactEventTask : Task { internal class DefaultRedactEventTask @Inject constructor( private val roomAPI: RoomAPI, - private val globalErrorReceiver: GlobalErrorReceiver) : RedactEventTask { + private val globalErrorReceiver: GlobalErrorReceiver +) : RedactEventTask { override suspend fun execute(params: RedactEventTask.Params): String { val response = executeRequest(globalErrorReceiver) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt index 50efe51bc1..fbd9d245d9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt @@ -39,7 +39,8 @@ internal class DefaultSendEventTask @Inject constructor( private val encryptEventTask: EncryptEventTask, private val loadRoomMembersTask: LoadRoomMembersTask, private val roomAPI: RoomAPI, - private val globalErrorReceiver: GlobalErrorReceiver) : SendEventTask { + private val globalErrorReceiver: GlobalErrorReceiver +) : SendEventTask { override suspend fun execute(params: SendEventTask.Params): String { try { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt index 7c52c62d92..944f41d488 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt @@ -37,7 +37,8 @@ internal class DefaultSendVerificationMessageTask @Inject constructor( private val encryptEventTask: EncryptEventTask, private val roomAPI: RoomAPI, private val cryptoSessionInfoProvider: CryptoSessionInfoProvider, - private val globalErrorReceiver: GlobalErrorReceiver) : SendVerificationMessageTask { + private val globalErrorReceiver: GlobalErrorReceiver +) : SendVerificationMessageTask { override suspend fun execute(params: SendVerificationMessageTask.Params): String { val event = handleEncryption(params) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt index a9d5cf1191..6b3bb1e641 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt @@ -60,26 +60,26 @@ internal class DefaultIncomingSASDefaultVerificationTransaction( override val uxState: IncomingSasVerificationTransaction.UxState get() { return when (val immutableState = state) { - is VerificationTxState.OnStarted -> IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT + is VerificationTxState.OnStarted -> IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT is VerificationTxState.SendingAccept, is VerificationTxState.Accepted, is VerificationTxState.OnKeyReceived, is VerificationTxState.SendingKey, - is VerificationTxState.KeySent -> IncomingSasVerificationTransaction.UxState.WAIT_FOR_KEY_AGREEMENT + is VerificationTxState.KeySent -> IncomingSasVerificationTransaction.UxState.WAIT_FOR_KEY_AGREEMENT is VerificationTxState.ShortCodeReady -> IncomingSasVerificationTransaction.UxState.SHOW_SAS is VerificationTxState.ShortCodeAccepted, is VerificationTxState.SendingMac, is VerificationTxState.MacSent, - is VerificationTxState.Verifying -> IncomingSasVerificationTransaction.UxState.WAIT_FOR_VERIFICATION - is VerificationTxState.Verified -> IncomingSasVerificationTransaction.UxState.VERIFIED - is VerificationTxState.Cancelled -> { + is VerificationTxState.Verifying -> IncomingSasVerificationTransaction.UxState.WAIT_FOR_VERIFICATION + is VerificationTxState.Verified -> IncomingSasVerificationTransaction.UxState.VERIFIED + is VerificationTxState.Cancelled -> { if (immutableState.byMe) { IncomingSasVerificationTransaction.UxState.CANCELLED_BY_ME } else { IncomingSasVerificationTransaction.UxState.CANCELLED_BY_OTHER } } - else -> IncomingSasVerificationTransaction.UxState.UNKNOWN + else -> IncomingSasVerificationTransaction.UxState.UNKNOWN } } @@ -232,7 +232,7 @@ internal class DefaultIncomingSASDefaultVerificationTransaction( val sasInfo = "MATRIX_KEY_VERIFICATION_SAS|$otherUserId|$otherDeviceId|$otherKey|$userId|$deviceId|${getSAS().publicKey}|$transactionId" return getSAS().generateShortCode(sasInfo, 6) } - else -> { + else -> { // Protocol has been checked earlier throw IllegalArgumentException() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt index ddb8ed232b..f1cf1b7547 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt @@ -57,27 +57,27 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction( override val uxState: OutgoingSasVerificationTransaction.UxState get() { return when (val immutableState = state) { - is VerificationTxState.None -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_START + is VerificationTxState.None -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_START is VerificationTxState.SendingStart, is VerificationTxState.Started, is VerificationTxState.OnAccepted, is VerificationTxState.SendingKey, is VerificationTxState.KeySent, - is VerificationTxState.OnKeyReceived -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_KEY_AGREEMENT + is VerificationTxState.OnKeyReceived -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_KEY_AGREEMENT is VerificationTxState.ShortCodeReady -> OutgoingSasVerificationTransaction.UxState.SHOW_SAS is VerificationTxState.ShortCodeAccepted, is VerificationTxState.SendingMac, is VerificationTxState.MacSent, - is VerificationTxState.Verifying -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_VERIFICATION - is VerificationTxState.Verified -> OutgoingSasVerificationTransaction.UxState.VERIFIED - is VerificationTxState.Cancelled -> { + is VerificationTxState.Verifying -> OutgoingSasVerificationTransaction.UxState.WAIT_FOR_VERIFICATION + is VerificationTxState.Verified -> OutgoingSasVerificationTransaction.UxState.VERIFIED + is VerificationTxState.Cancelled -> { if (immutableState.byMe) { OutgoingSasVerificationTransaction.UxState.CANCELLED_BY_OTHER } else { OutgoingSasVerificationTransaction.UxState.CANCELLED_BY_ME } } - else -> OutgoingSasVerificationTransaction.UxState.UNKNOWN + else -> OutgoingSasVerificationTransaction.UxState.UNKNOWN } } @@ -224,7 +224,7 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction( val sasInfo = "MATRIX_KEY_VERIFICATION_SAS|$userId|$deviceId|${getSAS().publicKey}|$otherUserId|$otherDeviceId|$otherKey|$transactionId" return getSAS().generateShortCode(sasInfo, 6) } - else -> { + else -> { // Protocol has been checked earlier throw IllegalArgumentException() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt index af48283767..1a04ee0302 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt @@ -129,31 +129,31 @@ internal class DefaultVerificationService @Inject constructor( Timber.d("## SAS onToDeviceEvent ${event.getClearType()}") cryptoCoroutineScope.launch(coroutineDispatchers.dmVerif) { when (event.getClearType()) { - EventType.KEY_VERIFICATION_START -> { + EventType.KEY_VERIFICATION_START -> { onStartRequestReceived(event) } - EventType.KEY_VERIFICATION_CANCEL -> { + EventType.KEY_VERIFICATION_CANCEL -> { onCancelReceived(event) } - EventType.KEY_VERIFICATION_ACCEPT -> { + EventType.KEY_VERIFICATION_ACCEPT -> { onAcceptReceived(event) } - EventType.KEY_VERIFICATION_KEY -> { + EventType.KEY_VERIFICATION_KEY -> { onKeyReceived(event) } - EventType.KEY_VERIFICATION_MAC -> { + EventType.KEY_VERIFICATION_MAC -> { onMacReceived(event) } - EventType.KEY_VERIFICATION_READY -> { + EventType.KEY_VERIFICATION_READY -> { onReadyReceived(event) } - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { onDoneReceived(event) } MessageType.MSGTYPE_VERIFICATION_REQUEST -> { onRequestReceived(event) } - else -> { + else -> { // ignore } } @@ -163,7 +163,7 @@ internal class DefaultVerificationService @Inject constructor( fun onRoomEvent(event: Event) { cryptoCoroutineScope.launch(coroutineDispatchers.dmVerif) { when (event.getClearType()) { - EventType.KEY_VERIFICATION_START -> { + EventType.KEY_VERIFICATION_START -> { onRoomStartRequestReceived(event) } EventType.KEY_VERIFICATION_CANCEL -> { @@ -173,24 +173,24 @@ internal class DefaultVerificationService @Inject constructor( EventType.KEY_VERIFICATION_ACCEPT -> { onRoomAcceptReceived(event) } - EventType.KEY_VERIFICATION_KEY -> { + EventType.KEY_VERIFICATION_KEY -> { onRoomKeyRequestReceived(event) } - EventType.KEY_VERIFICATION_MAC -> { + EventType.KEY_VERIFICATION_MAC -> { onRoomMacReceived(event) } - EventType.KEY_VERIFICATION_READY -> { + EventType.KEY_VERIFICATION_READY -> { onRoomReadyReceived(event) } - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { onRoomDoneReceived(event) } - EventType.MESSAGE -> { + EventType.MESSAGE -> { if (MessageType.MSGTYPE_VERIFICATION_REQUEST == event.getClearContent().toModel()?.msgType) { onRoomRequestReceived(event) } } - else -> { + else -> { // ignore } } @@ -472,9 +472,11 @@ internal class DefaultVerificationService @Inject constructor( /** * Return a CancelCode to make the caller cancel the verification. Else return null */ - private suspend fun handleStart(otherUserId: String?, - startReq: ValidVerificationInfoStart, - txConfigure: (DefaultVerificationTransaction) -> Unit): CancelCode? { + private suspend fun handleStart( + otherUserId: String?, + startReq: ValidVerificationInfoStart, + txConfigure: (DefaultVerificationTransaction) -> Unit + ): CancelCode? { Timber.d("## SAS onStartRequestReceived $startReq") if (otherUserId?.let { checkKeysAreDownloaded(it, startReq.fromDevice) } != null) { val tid = startReq.transactionId @@ -505,9 +507,9 @@ internal class DefaultVerificationService @Inject constructor( } when (startReq) { - is ValidVerificationInfoStart.SasVerificationInfoStart -> { + is ValidVerificationInfoStart.SasVerificationInfoStart -> { when (existing) { - is SasVerificationTransaction -> { + is SasVerificationTransaction -> { // should cancel both! Timber.v("## SAS onStartRequestReceived - Request exist with same id ${startReq.transactionId}") existing.cancel(CancelCode.UnexpectedMessage) @@ -517,7 +519,7 @@ internal class DefaultVerificationService @Inject constructor( is QrCodeVerificationTransaction -> { // Nothing to do? } - null -> { + null -> { getExistingTransactionsForUser(otherUserId) ?.filterIsInstance(SasVerificationTransaction::class.java) ?.takeIf { it.isNotEmpty() } @@ -589,8 +591,10 @@ internal class DefaultVerificationService @Inject constructor( } // TODO Refacto: It could just return a boolean - private suspend fun checkKeysAreDownloaded(otherUserId: String, - otherDeviceId: String): MXUsersDevicesMap? { + private suspend fun checkKeysAreDownloaded( + otherUserId: String, + otherDeviceId: String + ): MXUsersDevicesMap? { return try { var keys = deviceListManager.downloadKeys(listOf(otherUserId), false) if (keys.getUserDeviceIds(otherUserId)?.contains(otherDeviceId) == true) { @@ -899,9 +903,11 @@ internal class DefaultVerificationService @Inject constructor( } } - private fun handleReadyReceived(senderId: String, - readyReq: ValidVerificationInfoReady, - transportCreator: (DefaultVerificationTransaction) -> VerificationTransport) { + private fun handleReadyReceived( + senderId: String, + readyReq: ValidVerificationInfoReady, + transportCreator: (DefaultVerificationTransaction) -> VerificationTransport + ) { val existingRequest = getExistingVerificationRequests(senderId).find { it.transactionId == readyReq.transactionId } if (existingRequest == null) { Timber.e("## SAS Received Ready for unknown request txId:${readyReq.transactionId} fromDevice ${readyReq.fromDevice}") @@ -939,7 +945,7 @@ internal class DefaultVerificationService @Inject constructor( updatePendingRequest( existingRequest.copy( - readyInfo = readyReq + readyInfo = readyReq ) ) @@ -967,12 +973,12 @@ internal class DefaultVerificationService @Inject constructor( } return when { - userId != otherUserId -> + userId != otherUserId -> createQrCodeDataForDistinctUser(requestId, otherUserId) crossSigningService.isCrossSigningVerified() -> // This is a self verification and I am the old device (Osborne2) createQrCodeDataForVerifiedDevice(requestId, otherDeviceId) - else -> + else -> // This is a self verification and I am the new device (Dynabook) createQrCodeDataForUnVerifiedDevice(requestId) } @@ -1158,10 +1164,12 @@ internal class DefaultVerificationService @Inject constructor( } } - override fun requestKeyVerificationInDMs(methods: List, - otherUserId: String, - roomId: String, - localId: String?): PendingVerificationRequest { + override fun requestKeyVerificationInDMs( + methods: List, + otherUserId: String, + roomId: String, + localId: String? + ): PendingVerificationRequest { Timber.i("## SAS Requesting verification to user: $otherUserId in room $roomId") val requestsForUser = pendingRequests.getOrPut(otherUserId) { mutableListOf() } @@ -1328,11 +1336,13 @@ internal class DefaultVerificationService @Inject constructor( dispatchRequestUpdated(updated) } - override fun beginKeyVerificationInDMs(method: VerificationMethod, - transactionId: String, - roomId: String, - otherUserId: String, - otherDeviceId: String): String { + override fun beginKeyVerificationInDMs( + method: VerificationMethod, + transactionId: String, + roomId: String, + otherUserId: String, + otherDeviceId: String + ): String { if (method == VerificationMethod.SAS) { val tx = DefaultOutgoingSASDefaultVerificationTransaction( setDeviceVerificationAction, @@ -1357,10 +1367,12 @@ internal class DefaultVerificationService @Inject constructor( } } - override fun readyPendingVerificationInDMs(methods: List, - otherUserId: String, - roomId: String, - transactionId: String): Boolean { + override fun readyPendingVerificationInDMs( + methods: List, + otherUserId: String, + roomId: String, + transactionId: String + ): Boolean { Timber.v("## SAS readyPendingVerificationInDMs $otherUserId room:$roomId tx:$transactionId") // Let's find the related request val existingRequest = getExistingVerificationRequest(otherUserId, transactionId) @@ -1399,9 +1411,11 @@ internal class DefaultVerificationService @Inject constructor( } } - override fun readyPendingVerification(methods: List, - otherUserId: String, - transactionId: String): Boolean { + override fun readyPendingVerification( + methods: List, + otherUserId: String, + transactionId: String + ): Boolean { Timber.v("## SAS readyPendingVerification $otherUserId tx:$transactionId") // Let's find the related request val existingRequest = getExistingVerificationRequest(otherUserId, transactionId) @@ -1445,7 +1459,8 @@ internal class DefaultVerificationService @Inject constructor( otherDeviceId: String, otherUserMethods: List?, methods: List, - transportCreator: (DefaultVerificationTransaction) -> VerificationTransport): List { + transportCreator: (DefaultVerificationTransaction) -> VerificationTransport + ): List { if (otherUserMethods.isNullOrEmpty()) { return emptyList() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt index 27bc764395..9d19fd137e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt @@ -37,7 +37,8 @@ internal abstract class DefaultVerificationTransaction( override val transactionId: String, override val otherUserId: String, override var otherDeviceId: String? = null, - override val isIncoming: Boolean) : VerificationTransaction { + override val isIncoming: Boolean +) : VerificationTransaction { lateinit var transport: VerificationTransport @@ -55,9 +56,12 @@ internal abstract class DefaultVerificationTransaction( listeners.remove(listener) } - protected fun trust(canTrustOtherUserMasterKey: Boolean, - toVerifyDeviceIds: List, - eventuallyMarkMyMasterKeyAsTrusted: Boolean, autoDone: Boolean = true) { + protected fun trust( + canTrustOtherUserMasterKey: Boolean, + toVerifyDeviceIds: List, + eventuallyMarkMyMasterKeyAsTrusted: Boolean, + autoDone: Boolean = true + ) { Timber.d("## Verification: trust ($otherUserId,$otherDeviceId) , verifiedDevices:$toVerifyDeviceIds") Timber.d("## Verification: trust Mark myMSK trusted $eventuallyMarkMyMasterKeyAsTrusted") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt index 68dd57478e..1cbaff059a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt @@ -314,11 +314,13 @@ internal abstract class SASDefaultVerificationTransaction( transport.cancelTransaction(transactionId, otherUserId, otherDeviceId ?: "", code) } - protected fun sendToOther(type: String, - keyToDevice: VerificationInfo, - nextState: VerificationTxState, - onErrorReason: CancelCode, - onDone: (() -> Unit)?) { + protected fun sendToOther( + type: String, + keyToDevice: VerificationInfo, + nextState: VerificationTxState, + onErrorReason: CancelCode, + onDone: (() -> Unit)? + ) { transport.sendToOther(type, keyToDevice, nextState, onErrorReason, onDone) } @@ -331,11 +333,11 @@ internal abstract class SASDefaultVerificationTransaction( if (shortCodeBytes!!.size < 5) return null return getDecimalCodeRepresentation(shortCodeBytes!!) } - SasMode.EMOJI -> { + SasMode.EMOJI -> { if (shortCodeBytes!!.size < 6) return null return getEmojiCodeRepresentation(shortCodeBytes!!).joinToString(" ") { it.emoji } } - else -> return null + else -> return null } } @@ -360,8 +362,8 @@ internal abstract class SASDefaultVerificationTransaction( private fun macUsingAgreedMethod(message: String, info: String): String? { return when (accepted?.messageAuthenticationCode?.lowercase(Locale.ROOT)) { SAS_MAC_SHA256_LONGKDF -> getSAS().calculateMacLongKdf(message, info) - SAS_MAC_SHA256 -> getSAS().calculateMac(message, info) - else -> null + SAS_MAC_SHA256 -> getSAS().calculateMac(message, info) + else -> null } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationEmoji.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationEmoji.kt index eb1819fe6a..cff3591771 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationEmoji.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationEmoji.kt @@ -20,69 +20,69 @@ import org.matrix.android.sdk.api.session.crypto.verification.EmojiRepresentatio internal fun getEmojiForCode(code: Int): EmojiRepresentation { return when (code % 64) { - 0 -> EmojiRepresentation("🐶", R.string.verification_emoji_dog, R.drawable.ic_verification_dog) - 1 -> EmojiRepresentation("🐱", R.string.verification_emoji_cat, R.drawable.ic_verification_cat) - 2 -> EmojiRepresentation("🦁", R.string.verification_emoji_lion, R.drawable.ic_verification_lion) - 3 -> EmojiRepresentation("🐎", R.string.verification_emoji_horse, R.drawable.ic_verification_horse) - 4 -> EmojiRepresentation("🦄", R.string.verification_emoji_unicorn, R.drawable.ic_verification_unicorn) - 5 -> EmojiRepresentation("🐷", R.string.verification_emoji_pig, R.drawable.ic_verification_pig) - 6 -> EmojiRepresentation("🐘", R.string.verification_emoji_elephant, R.drawable.ic_verification_elephant) - 7 -> EmojiRepresentation("🐰", R.string.verification_emoji_rabbit, R.drawable.ic_verification_rabbit) - 8 -> EmojiRepresentation("🐼", R.string.verification_emoji_panda, R.drawable.ic_verification_panda) - 9 -> EmojiRepresentation("🐓", R.string.verification_emoji_rooster, R.drawable.ic_verification_rooster) - 10 -> EmojiRepresentation("🐧", R.string.verification_emoji_penguin, R.drawable.ic_verification_penguin) - 11 -> EmojiRepresentation("🐢", R.string.verification_emoji_turtle, R.drawable.ic_verification_turtle) - 12 -> EmojiRepresentation("🐟", R.string.verification_emoji_fish, R.drawable.ic_verification_fish) - 13 -> EmojiRepresentation("🐙", R.string.verification_emoji_octopus, R.drawable.ic_verification_octopus) - 14 -> EmojiRepresentation("🦋", R.string.verification_emoji_butterfly, R.drawable.ic_verification_butterfly) - 15 -> EmojiRepresentation("🌷", R.string.verification_emoji_flower, R.drawable.ic_verification_flower) - 16 -> EmojiRepresentation("🌳", R.string.verification_emoji_tree, R.drawable.ic_verification_tree) - 17 -> EmojiRepresentation("🌵", R.string.verification_emoji_cactus, R.drawable.ic_verification_cactus) - 18 -> EmojiRepresentation("🍄", R.string.verification_emoji_mushroom, R.drawable.ic_verification_mushroom) - 19 -> EmojiRepresentation("🌏", R.string.verification_emoji_globe, R.drawable.ic_verification_globe) - 20 -> EmojiRepresentation("🌙", R.string.verification_emoji_moon, R.drawable.ic_verification_moon) - 21 -> EmojiRepresentation("☁️", R.string.verification_emoji_cloud, R.drawable.ic_verification_cloud) - 22 -> EmojiRepresentation("🔥", R.string.verification_emoji_fire, R.drawable.ic_verification_fire) - 23 -> EmojiRepresentation("🍌", R.string.verification_emoji_banana, R.drawable.ic_verification_banana) - 24 -> EmojiRepresentation("🍎", R.string.verification_emoji_apple, R.drawable.ic_verification_apple) - 25 -> EmojiRepresentation("🍓", R.string.verification_emoji_strawberry, R.drawable.ic_verification_strawberry) - 26 -> EmojiRepresentation("🌽", R.string.verification_emoji_corn, R.drawable.ic_verification_corn) - 27 -> EmojiRepresentation("🍕", R.string.verification_emoji_pizza, R.drawable.ic_verification_pizza) - 28 -> EmojiRepresentation("🎂", R.string.verification_emoji_cake, R.drawable.ic_verification_cake) - 29 -> EmojiRepresentation("❤️", R.string.verification_emoji_heart, R.drawable.ic_verification_heart) - 30 -> EmojiRepresentation("🙂", R.string.verification_emoji_smiley, R.drawable.ic_verification_smiley) - 31 -> EmojiRepresentation("🤖", R.string.verification_emoji_robot, R.drawable.ic_verification_robot) - 32 -> EmojiRepresentation("🎩", R.string.verification_emoji_hat, R.drawable.ic_verification_hat) - 33 -> EmojiRepresentation("👓", R.string.verification_emoji_glasses, R.drawable.ic_verification_glasses) - 34 -> EmojiRepresentation("🔧", R.string.verification_emoji_spanner, R.drawable.ic_verification_spanner) - 35 -> EmojiRepresentation("🎅", R.string.verification_emoji_santa, R.drawable.ic_verification_santa) - 36 -> EmojiRepresentation("👍", R.string.verification_emoji_thumbs_up, R.drawable.ic_verification_thumbs_up) - 37 -> EmojiRepresentation("☂️", R.string.verification_emoji_umbrella, R.drawable.ic_verification_umbrella) - 38 -> EmojiRepresentation("⌛", R.string.verification_emoji_hourglass, R.drawable.ic_verification_hourglass) - 39 -> EmojiRepresentation("⏰", R.string.verification_emoji_clock, R.drawable.ic_verification_clock) - 40 -> EmojiRepresentation("🎁", R.string.verification_emoji_gift, R.drawable.ic_verification_gift) - 41 -> EmojiRepresentation("💡", R.string.verification_emoji_light_bulb, R.drawable.ic_verification_light_bulb) - 42 -> EmojiRepresentation("📕", R.string.verification_emoji_book, R.drawable.ic_verification_book) - 43 -> EmojiRepresentation("✏️", R.string.verification_emoji_pencil, R.drawable.ic_verification_pencil) - 44 -> EmojiRepresentation("📎", R.string.verification_emoji_paperclip, R.drawable.ic_verification_paperclip) - 45 -> EmojiRepresentation("✂️", R.string.verification_emoji_scissors, R.drawable.ic_verification_scissors) - 46 -> EmojiRepresentation("🔒", R.string.verification_emoji_lock, R.drawable.ic_verification_lock) - 47 -> EmojiRepresentation("🔑", R.string.verification_emoji_key, R.drawable.ic_verification_key) - 48 -> EmojiRepresentation("🔨", R.string.verification_emoji_hammer, R.drawable.ic_verification_hammer) - 49 -> EmojiRepresentation("☎️", R.string.verification_emoji_telephone, R.drawable.ic_verification_phone) - 50 -> EmojiRepresentation("🏁", R.string.verification_emoji_flag, R.drawable.ic_verification_flag) - 51 -> EmojiRepresentation("🚂", R.string.verification_emoji_train, R.drawable.ic_verification_train) - 52 -> EmojiRepresentation("🚲", R.string.verification_emoji_bicycle, R.drawable.ic_verification_bicycle) - 53 -> EmojiRepresentation("✈️", R.string.verification_emoji_aeroplane, R.drawable.ic_verification_aeroplane) - 54 -> EmojiRepresentation("🚀", R.string.verification_emoji_rocket, R.drawable.ic_verification_rocket) - 55 -> EmojiRepresentation("🏆", R.string.verification_emoji_trophy, R.drawable.ic_verification_trophy) - 56 -> EmojiRepresentation("⚽", R.string.verification_emoji_ball, R.drawable.ic_verification_ball) - 57 -> EmojiRepresentation("🎸", R.string.verification_emoji_guitar, R.drawable.ic_verification_guitar) - 58 -> EmojiRepresentation("🎺", R.string.verification_emoji_trumpet, R.drawable.ic_verification_trumpet) - 59 -> EmojiRepresentation("🔔", R.string.verification_emoji_bell, R.drawable.ic_verification_bell) - 60 -> EmojiRepresentation("⚓", R.string.verification_emoji_anchor, R.drawable.ic_verification_anchor) - 61 -> EmojiRepresentation("🎧", R.string.verification_emoji_headphones, R.drawable.ic_verification_headphones) - 62 -> EmojiRepresentation("📁", R.string.verification_emoji_folder, R.drawable.ic_verification_folder) + 0 -> EmojiRepresentation("🐶", R.string.verification_emoji_dog, R.drawable.ic_verification_dog) + 1 -> EmojiRepresentation("🐱", R.string.verification_emoji_cat, R.drawable.ic_verification_cat) + 2 -> EmojiRepresentation("🦁", R.string.verification_emoji_lion, R.drawable.ic_verification_lion) + 3 -> EmojiRepresentation("🐎", R.string.verification_emoji_horse, R.drawable.ic_verification_horse) + 4 -> EmojiRepresentation("🦄", R.string.verification_emoji_unicorn, R.drawable.ic_verification_unicorn) + 5 -> EmojiRepresentation("🐷", R.string.verification_emoji_pig, R.drawable.ic_verification_pig) + 6 -> EmojiRepresentation("🐘", R.string.verification_emoji_elephant, R.drawable.ic_verification_elephant) + 7 -> EmojiRepresentation("🐰", R.string.verification_emoji_rabbit, R.drawable.ic_verification_rabbit) + 8 -> EmojiRepresentation("🐼", R.string.verification_emoji_panda, R.drawable.ic_verification_panda) + 9 -> EmojiRepresentation("🐓", R.string.verification_emoji_rooster, R.drawable.ic_verification_rooster) + 10 -> EmojiRepresentation("🐧", R.string.verification_emoji_penguin, R.drawable.ic_verification_penguin) + 11 -> EmojiRepresentation("🐢", R.string.verification_emoji_turtle, R.drawable.ic_verification_turtle) + 12 -> EmojiRepresentation("🐟", R.string.verification_emoji_fish, R.drawable.ic_verification_fish) + 13 -> EmojiRepresentation("🐙", R.string.verification_emoji_octopus, R.drawable.ic_verification_octopus) + 14 -> EmojiRepresentation("🦋", R.string.verification_emoji_butterfly, R.drawable.ic_verification_butterfly) + 15 -> EmojiRepresentation("🌷", R.string.verification_emoji_flower, R.drawable.ic_verification_flower) + 16 -> EmojiRepresentation("🌳", R.string.verification_emoji_tree, R.drawable.ic_verification_tree) + 17 -> EmojiRepresentation("🌵", R.string.verification_emoji_cactus, R.drawable.ic_verification_cactus) + 18 -> EmojiRepresentation("🍄", R.string.verification_emoji_mushroom, R.drawable.ic_verification_mushroom) + 19 -> EmojiRepresentation("🌏", R.string.verification_emoji_globe, R.drawable.ic_verification_globe) + 20 -> EmojiRepresentation("🌙", R.string.verification_emoji_moon, R.drawable.ic_verification_moon) + 21 -> EmojiRepresentation("☁️", R.string.verification_emoji_cloud, R.drawable.ic_verification_cloud) + 22 -> EmojiRepresentation("🔥", R.string.verification_emoji_fire, R.drawable.ic_verification_fire) + 23 -> EmojiRepresentation("🍌", R.string.verification_emoji_banana, R.drawable.ic_verification_banana) + 24 -> EmojiRepresentation("🍎", R.string.verification_emoji_apple, R.drawable.ic_verification_apple) + 25 -> EmojiRepresentation("🍓", R.string.verification_emoji_strawberry, R.drawable.ic_verification_strawberry) + 26 -> EmojiRepresentation("🌽", R.string.verification_emoji_corn, R.drawable.ic_verification_corn) + 27 -> EmojiRepresentation("🍕", R.string.verification_emoji_pizza, R.drawable.ic_verification_pizza) + 28 -> EmojiRepresentation("🎂", R.string.verification_emoji_cake, R.drawable.ic_verification_cake) + 29 -> EmojiRepresentation("❤️", R.string.verification_emoji_heart, R.drawable.ic_verification_heart) + 30 -> EmojiRepresentation("🙂", R.string.verification_emoji_smiley, R.drawable.ic_verification_smiley) + 31 -> EmojiRepresentation("🤖", R.string.verification_emoji_robot, R.drawable.ic_verification_robot) + 32 -> EmojiRepresentation("🎩", R.string.verification_emoji_hat, R.drawable.ic_verification_hat) + 33 -> EmojiRepresentation("👓", R.string.verification_emoji_glasses, R.drawable.ic_verification_glasses) + 34 -> EmojiRepresentation("🔧", R.string.verification_emoji_spanner, R.drawable.ic_verification_spanner) + 35 -> EmojiRepresentation("🎅", R.string.verification_emoji_santa, R.drawable.ic_verification_santa) + 36 -> EmojiRepresentation("👍", R.string.verification_emoji_thumbs_up, R.drawable.ic_verification_thumbs_up) + 37 -> EmojiRepresentation("☂️", R.string.verification_emoji_umbrella, R.drawable.ic_verification_umbrella) + 38 -> EmojiRepresentation("⌛", R.string.verification_emoji_hourglass, R.drawable.ic_verification_hourglass) + 39 -> EmojiRepresentation("⏰", R.string.verification_emoji_clock, R.drawable.ic_verification_clock) + 40 -> EmojiRepresentation("🎁", R.string.verification_emoji_gift, R.drawable.ic_verification_gift) + 41 -> EmojiRepresentation("💡", R.string.verification_emoji_light_bulb, R.drawable.ic_verification_light_bulb) + 42 -> EmojiRepresentation("📕", R.string.verification_emoji_book, R.drawable.ic_verification_book) + 43 -> EmojiRepresentation("✏️", R.string.verification_emoji_pencil, R.drawable.ic_verification_pencil) + 44 -> EmojiRepresentation("📎", R.string.verification_emoji_paperclip, R.drawable.ic_verification_paperclip) + 45 -> EmojiRepresentation("✂️", R.string.verification_emoji_scissors, R.drawable.ic_verification_scissors) + 46 -> EmojiRepresentation("🔒", R.string.verification_emoji_lock, R.drawable.ic_verification_lock) + 47 -> EmojiRepresentation("🔑", R.string.verification_emoji_key, R.drawable.ic_verification_key) + 48 -> EmojiRepresentation("🔨", R.string.verification_emoji_hammer, R.drawable.ic_verification_hammer) + 49 -> EmojiRepresentation("☎️", R.string.verification_emoji_telephone, R.drawable.ic_verification_phone) + 50 -> EmojiRepresentation("🏁", R.string.verification_emoji_flag, R.drawable.ic_verification_flag) + 51 -> EmojiRepresentation("🚂", R.string.verification_emoji_train, R.drawable.ic_verification_train) + 52 -> EmojiRepresentation("🚲", R.string.verification_emoji_bicycle, R.drawable.ic_verification_bicycle) + 53 -> EmojiRepresentation("✈️", R.string.verification_emoji_aeroplane, R.drawable.ic_verification_aeroplane) + 54 -> EmojiRepresentation("🚀", R.string.verification_emoji_rocket, R.drawable.ic_verification_rocket) + 55 -> EmojiRepresentation("🏆", R.string.verification_emoji_trophy, R.drawable.ic_verification_trophy) + 56 -> EmojiRepresentation("⚽", R.string.verification_emoji_ball, R.drawable.ic_verification_ball) + 57 -> EmojiRepresentation("🎸", R.string.verification_emoji_guitar, R.drawable.ic_verification_guitar) + 58 -> EmojiRepresentation("🎺", R.string.verification_emoji_trumpet, R.drawable.ic_verification_trumpet) + 59 -> EmojiRepresentation("🔔", R.string.verification_emoji_bell, R.drawable.ic_verification_bell) + 60 -> EmojiRepresentation("⚓", R.string.verification_emoji_anchor, R.drawable.ic_verification_anchor) + 61 -> EmojiRepresentation("🎧", R.string.verification_emoji_headphones, R.drawable.ic_verification_headphones) + 62 -> EmojiRepresentation("📁", R.string.verification_emoji_folder, R.drawable.ic_verification_folder) /* 63 */ else -> EmojiRepresentation("📌", R.string.verification_emoji_pin, R.drawable.ic_verification_pin) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt index 3ddb0ca758..0b9287cb05 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt @@ -63,12 +63,14 @@ internal interface VerificationInfoAccept : VerificationInfo): VerificationInfoAccept + fun create( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept } internal data class ValidVerificationInfoAccept( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt index d71bd7359e..66591fe00f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt @@ -68,7 +68,7 @@ internal interface VerificationInfoStart : VerificationInfo { + VERIFICATION_METHOD_SAS -> { val validKeyAgreementProtocols = keyAgreementProtocols?.takeIf { it.isNotEmpty() } ?: return null val validHashes = hashes?.takeIf { it.contains("sha256") } ?: return null val validMessageAuthenticationCodes = messageAuthenticationCodes @@ -98,14 +98,15 @@ internal interface VerificationInfoStart : VerificationInfo null + else -> null } } } internal sealed class ValidVerificationInfoStart( open val transactionId: String, - open val fromDevice: String) { + open val fromDevice: String +) { data class SasVerificationInfoStart( override val transactionId: String, override val fromDevice: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt index 303b6c5839..9f123f0c08 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt @@ -131,7 +131,7 @@ internal class VerificationMessageProcessor @Inject constructor( EventType.KEY_VERIFICATION_DONE -> { verificationService.onRoomEvent(event) } - EventType.MESSAGE -> { + EventType.MESSAGE -> { if (MessageType.MSGTYPE_VERIFICATION_REQUEST == event.getClearContent().toModel()?.msgType) { verificationService.onRoomRequestReceived(event) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt index 69dec12ef3..5314c23870 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt @@ -28,11 +28,13 @@ internal interface VerificationTransport { /** * Sends a message. */ - fun sendToOther(type: String, - verificationInfo: VerificationInfo, - nextState: VerificationTxState, - onErrorReason: CancelCode, - onDone: (() -> Unit)?) + fun sendToOther( + type: String, + verificationInfo: VerificationInfo, + nextState: VerificationTxState, + onErrorReason: CancelCode, + onDone: (() -> Unit)? + ) /** * @param supportedMethods list of supported method by this client @@ -42,65 +44,85 @@ internal interface VerificationTransport { * @param toDevices list of device Ids * @param callback will be called with eventId and ValidVerificationInfoRequest in case of success */ - fun sendVerificationRequest(supportedMethods: List, - localId: String, - otherUserId: String, - roomId: String?, - toDevices: List?, - callback: (String?, ValidVerificationInfoRequest?) -> Unit) + fun sendVerificationRequest( + supportedMethods: List, + localId: String, + otherUserId: String, + roomId: String?, + toDevices: List?, + callback: (String?, ValidVerificationInfoRequest?) -> Unit + ) - fun cancelTransaction(transactionId: String, - otherUserId: String, - otherUserDeviceId: String?, - code: CancelCode) + fun cancelTransaction( + transactionId: String, + otherUserId: String, + otherUserDeviceId: String?, + code: CancelCode + ) - fun cancelTransaction(transactionId: String, - otherUserId: String, - otherUserDeviceIds: List, - code: CancelCode) + fun cancelTransaction( + transactionId: String, + otherUserId: String, + otherUserDeviceIds: List, + code: CancelCode + ) - fun done(transactionId: String, - onDone: (() -> Unit)?) + fun done( + transactionId: String, + onDone: (() -> Unit)? + ) /** * Creates an accept message suitable for this transport. */ - fun createAccept(tid: String, - keyAgreementProtocol: String, - hash: String, - commitment: String, - messageAuthenticationCode: String, - shortAuthenticationStrings: List): VerificationInfoAccept + fun createAccept( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept - fun createKey(tid: String, - pubKey: String): VerificationInfoKey + fun createKey( + tid: String, + pubKey: String + ): VerificationInfoKey /** * Create start for SAS verification. */ - fun createStartForSas(fromDevice: String, - transactionId: String, - keyAgreementProtocols: List, - hashes: List, - messageAuthenticationCodes: List, - shortAuthenticationStrings: List): VerificationInfoStart + fun createStartForSas( + fromDevice: String, + transactionId: String, + keyAgreementProtocols: List, + hashes: List, + messageAuthenticationCodes: List, + shortAuthenticationStrings: List + ): VerificationInfoStart /** * Create start for QR code verification. */ - fun createStartForQrCode(fromDevice: String, - transactionId: String, - sharedSecret: String): VerificationInfoStart + fun createStartForQrCode( + fromDevice: String, + transactionId: String, + sharedSecret: String + ): VerificationInfoStart fun createMac(tid: String, mac: Map, keys: String): VerificationInfoMac - fun createReady(tid: String, - fromDevice: String, - methods: List): VerificationInfoReady + fun createReady( + tid: String, + fromDevice: String, + methods: List + ): VerificationInfoReady // TODO Refactor - fun sendVerificationReady(keyReq: VerificationInfoReady, - otherUserId: String, - otherDeviceId: String?, - callback: (() -> Unit)?) + fun sendVerificationReady( + keyReq: VerificationInfoReady, + otherUserId: String, + otherDeviceId: String?, + callback: (() -> Unit)? + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt index 03df849d22..f38a604890 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt @@ -61,11 +61,13 @@ internal class VerificationTransportRoomMessage( private val verificationSenderScope = CoroutineScope(cryptoCoroutineScope.coroutineContext + dispatcher) private val sequencer = SemaphoreCoroutineSequencer() - override fun sendToOther(type: String, - verificationInfo: VerificationInfo, - nextState: VerificationTxState, - onErrorReason: CancelCode, - onDone: (() -> Unit)?) { + override fun sendToOther( + type: String, + verificationInfo: VerificationInfo, + nextState: VerificationTxState, + onErrorReason: CancelCode, + onDone: (() -> Unit)? + ) { Timber.d("## SAS sending msg type $type") Timber.v("## SAS sending msg info $verificationInfo") val event = createEventAndLocalEcho( @@ -92,12 +94,14 @@ internal class VerificationTransportRoomMessage( } } - override fun sendVerificationRequest(supportedMethods: List, - localId: String, - otherUserId: String, - roomId: String?, - toDevices: List?, - callback: (String?, ValidVerificationInfoRequest?) -> Unit) { + override fun sendVerificationRequest( + supportedMethods: List, + localId: String, + otherUserId: String, + roomId: String?, + toDevices: List?, + callback: (String?, ValidVerificationInfoRequest?) -> Unit + ) { Timber.d("## SAS sending verification request with supported methods: $supportedMethods") // This transport requires a room requireNotNull(roomId) @@ -160,11 +164,17 @@ internal class VerificationTransportRoomMessage( } } - override fun cancelTransaction(transactionId: String, otherUserId: String, otherUserDeviceIds: List, code: CancelCode) = - cancelTransaction(transactionId, otherUserId, null, code) + override fun cancelTransaction( + transactionId: String, + otherUserId: String, + otherUserDeviceIds: List, + code: CancelCode + ) = cancelTransaction(transactionId, otherUserId, null, code) - override fun done(transactionId: String, - onDone: (() -> Unit)?) { + override fun done( + transactionId: String, + onDone: (() -> Unit)? + ) { Timber.d("## SAS sending done for $transactionId") val event = createEventAndLocalEcho( type = EventType.KEY_VERIFICATION_DONE, @@ -191,12 +201,14 @@ internal class VerificationTransportRoomMessage( } } - override fun createAccept(tid: String, - keyAgreementProtocol: String, - hash: String, - commitment: String, - messageAuthenticationCode: String, - shortAuthenticationStrings: List): VerificationInfoAccept = + override fun createAccept( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept = MessageVerificationAcceptContent.create( tid, keyAgreementProtocol, @@ -210,12 +222,14 @@ internal class VerificationTransportRoomMessage( override fun createMac(tid: String, mac: Map, keys: String) = MessageVerificationMacContent.create(tid, mac, keys) - override fun createStartForSas(fromDevice: String, - transactionId: String, - keyAgreementProtocols: List, - hashes: List, - messageAuthenticationCodes: List, - shortAuthenticationStrings: List): VerificationInfoStart { + override fun createStartForSas( + fromDevice: String, + transactionId: String, + keyAgreementProtocols: List, + hashes: List, + messageAuthenticationCodes: List, + shortAuthenticationStrings: List + ): VerificationInfoStart { return MessageVerificationStartContent( fromDevice, hashes, @@ -231,9 +245,11 @@ internal class VerificationTransportRoomMessage( ) } - override fun createStartForQrCode(fromDevice: String, - transactionId: String, - sharedSecret: String): VerificationInfoStart { + override fun createStartForQrCode( + fromDevice: String, + transactionId: String, + sharedSecret: String + ): VerificationInfoStart { return MessageVerificationStartContent( fromDevice, null, @@ -274,10 +290,12 @@ internal class VerificationTransportRoomMessage( } } - override fun sendVerificationReady(keyReq: VerificationInfoReady, - otherUserId: String, - otherDeviceId: String?, - callback: (() -> Unit)?) { + override fun sendVerificationReady( + keyReq: VerificationInfoReady, + otherUserId: String, + otherDeviceId: String?, + callback: (() -> Unit)? + ) { // Not applicable (send event is called directly) Timber.w("## SAS ignored verification ready with methods: ${keyReq.methods}") } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt index 974adf3888..861a7a3a77 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt @@ -47,12 +47,14 @@ internal class VerificationTransportToDevice( private val clock: Clock, ) : VerificationTransport { - override fun sendVerificationRequest(supportedMethods: List, - localId: String, - otherUserId: String, - roomId: String?, - toDevices: List?, - callback: (String?, ValidVerificationInfoRequest?) -> Unit) { + override fun sendVerificationRequest( + supportedMethods: List, + localId: String, + otherUserId: String, + roomId: String?, + toDevices: List?, + callback: (String?, ValidVerificationInfoRequest?) -> Unit + ) { Timber.d("## SAS sending verification request with supported methods: $supportedMethods") val contentMap = MXUsersDevicesMap() val validKeyReq = ValidVerificationInfoRequest( @@ -86,10 +88,12 @@ internal class VerificationTransportToDevice( .executeBy(taskExecutor) } - override fun sendVerificationReady(keyReq: VerificationInfoReady, - otherUserId: String, - otherDeviceId: String?, - callback: (() -> Unit)?) { + override fun sendVerificationReady( + keyReq: VerificationInfoReady, + otherUserId: String, + otherDeviceId: String?, + callback: (() -> Unit)? + ) { Timber.d("## SAS sending verification ready with methods: ${keyReq.methods}") val contentMap = MXUsersDevicesMap() @@ -111,11 +115,13 @@ internal class VerificationTransportToDevice( .executeBy(taskExecutor) } - override fun sendToOther(type: String, - verificationInfo: VerificationInfo, - nextState: VerificationTxState, - onErrorReason: CancelCode, - onDone: (() -> Unit)?) { + override fun sendToOther( + type: String, + verificationInfo: VerificationInfo, + nextState: VerificationTxState, + onErrorReason: CancelCode, + onDone: (() -> Unit)? + ) { Timber.d("## SAS sending msg type $type") Timber.v("## SAS sending msg info $verificationInfo") val stateBeforeCall = tx?.state @@ -214,12 +220,14 @@ internal class VerificationTransportToDevice( .executeBy(taskExecutor) } - override fun createAccept(tid: String, - keyAgreementProtocol: String, - hash: String, - commitment: String, - messageAuthenticationCode: String, - shortAuthenticationStrings: List): VerificationInfoAccept = KeyVerificationAccept.create( + override fun createAccept( + tid: String, + keyAgreementProtocol: String, + hash: String, + commitment: String, + messageAuthenticationCode: String, + shortAuthenticationStrings: List + ): VerificationInfoAccept = KeyVerificationAccept.create( tid, keyAgreementProtocol, hash, @@ -232,12 +240,14 @@ internal class VerificationTransportToDevice( override fun createMac(tid: String, mac: Map, keys: String) = KeyVerificationMac.create(tid, mac, keys) - override fun createStartForSas(fromDevice: String, - transactionId: String, - keyAgreementProtocols: List, - hashes: List, - messageAuthenticationCodes: List, - shortAuthenticationStrings: List): VerificationInfoStart { + override fun createStartForSas( + fromDevice: String, + transactionId: String, + keyAgreementProtocols: List, + hashes: List, + messageAuthenticationCodes: List, + shortAuthenticationStrings: List + ): VerificationInfoStart { return KeyVerificationStart( fromDevice, VERIFICATION_METHOD_SAS, @@ -250,9 +260,11 @@ internal class VerificationTransportToDevice( ) } - override fun createStartForQrCode(fromDevice: String, - transactionId: String, - sharedSecret: String): VerificationInfoStart { + override fun createStartForQrCode( + fromDevice: String, + transactionId: String, + sharedSecret: String + ): VerificationInfoStart { return KeyVerificationStart( fromDevice, VERIFICATION_METHOD_RECIPROCATE, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt index b1ad4d87b6..690ac12268 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt @@ -94,7 +94,7 @@ internal class DefaultQrCodeVerificationTransaction( // Check the other device view of my MSK when (otherQrCodeData) { - is QrCodeData.VerifyingAnotherUser -> { + is QrCodeData.VerifyingAnotherUser -> { // key2 (aka otherUserMasterCrossSigningPublicKey) is what the one displaying the QR code (other user) think my MSK is. // Let's check that it's correct // If not -> Cancel @@ -104,7 +104,7 @@ internal class DefaultQrCodeVerificationTransaction( return } else Unit } - is QrCodeData.SelfVerifyingMasterKeyTrusted -> { + is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // key1 (aka userMasterCrossSigningPublicKey) is the session displaying the QR code view of our MSK. // Let's check that I see the same MSK // If not -> Cancel @@ -135,7 +135,7 @@ internal class DefaultQrCodeVerificationTransaction( // Let's now check the other user/device key material when (otherQrCodeData) { - is QrCodeData.VerifyingAnotherUser -> { + is QrCodeData.VerifyingAnotherUser -> { // key1(aka userMasterCrossSigningPublicKey) is the MSK of the one displaying the QR code (i.e other user) // Let's check that it matches what I think it should be if (otherQrCodeData.userMasterCrossSigningPublicKey @@ -149,7 +149,7 @@ internal class DefaultQrCodeVerificationTransaction( Unit } } - is QrCodeData.SelfVerifyingMasterKeyTrusted -> { + is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // key2 (aka otherDeviceKey) is my current device key in POV of the one displaying the QR code (i.e other device) // Let's check that it's correct if (otherQrCodeData.otherDeviceKey @@ -259,11 +259,11 @@ internal class DefaultQrCodeVerificationTransaction( override fun otherUserScannedMyQrCode() { when (qrCodeData) { - is QrCodeData.VerifyingAnotherUser -> { + is QrCodeData.VerifyingAnotherUser -> { // Alice telling Bob that the code was scanned successfully is sufficient for Bob to trust Alice's key, trust(true, emptyList(), false) } - is QrCodeData.SelfVerifyingMasterKeyTrusted -> { + is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // I now know that I have the correct device key for other session, // and can sign it with the self-signing key and upload the signature trust(false, listOf(otherDeviceId ?: ""), false) @@ -272,7 +272,7 @@ internal class DefaultQrCodeVerificationTransaction( // I now know that i can trust my MSK trust(true, emptyList(), true) } - null -> Unit + null -> Unit } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/Extensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/Extensions.kt index b80c29c244..a0202485d6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/Extensions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/Extensions.kt @@ -36,8 +36,8 @@ internal fun QrCodeData.toEncodedString(): String { // Mode result += when (this) { - is QrCodeData.VerifyingAnotherUser -> 0 - is QrCodeData.SelfVerifyingMasterKeyTrusted -> 1 + is QrCodeData.VerifyingAnotherUser -> 0 + is QrCodeData.SelfVerifyingMasterKeyTrusted -> 1 is QrCodeData.SelfVerifyingMasterKeyNotTrusted -> 2 }.toByte() @@ -119,9 +119,9 @@ internal fun String.toQrCodeData(): QrCodeData? { val secret = byteArray.copyOfRange(cursor, byteArray.size).toBase64NoPadding() return when (mode) { - 0 -> QrCodeData.VerifyingAnotherUser(transactionId, key1, key2, secret) - 1 -> QrCodeData.SelfVerifyingMasterKeyTrusted(transactionId, key1, key2, secret) - 2 -> QrCodeData.SelfVerifyingMasterKeyNotTrusted(transactionId, key1, key2, secret) + 0 -> QrCodeData.VerifyingAnotherUser(transactionId, key1, key2, secret) + 1 -> QrCodeData.SelfVerifyingMasterKeyTrusted(transactionId, key1, key2, secret) + 2 -> QrCodeData.SelfVerifyingMasterKeyNotTrusted(transactionId, key1, key2, secret) else -> null } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/EventInsertLiveObserver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/EventInsertLiveObserver.kt index 6ccd4ae03e..d1ca4f48a6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/EventInsertLiveObserver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/EventInsertLiveObserver.kt @@ -32,8 +32,10 @@ import org.matrix.android.sdk.internal.session.EventInsertLiveProcessor import timber.log.Timber import javax.inject.Inject -internal class EventInsertLiveObserver @Inject constructor(@SessionDatabase realmConfiguration: RealmConfiguration, - private val processors: Set<@JvmSuppressWildcards EventInsertLiveProcessor>) : +internal class EventInsertLiveObserver @Inject constructor( + @SessionDatabase realmConfiguration: RealmConfiguration, + private val processors: Set<@JvmSuppressWildcards EventInsertLiveProcessor> +) : RealmLiveEntityObserver(realmConfiguration) { private val lock = Mutex() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt index 392c1a7185..b3a039d119 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt @@ -38,8 +38,10 @@ import javax.inject.Inject * then we generate a random secret key. The database key is encrypted with the secret key; The secret * key is encrypted with the public RSA key and stored with the encrypted key in the shared pref */ -internal class RealmKeysUtils @Inject constructor(context: Context, - private val secretStoringUtils: SecretStoringUtils) { +internal class RealmKeysUtils @Inject constructor( + context: Context, + private val secretStoringUtils: SecretStoringUtils +) { private val rng = SecureRandom() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmQueryLatch.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmQueryLatch.kt index c9c797304a..c5ca861e9b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmQueryLatch.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmQueryLatch.kt @@ -27,9 +27,11 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout -internal suspend fun awaitNotEmptyResult(realmConfiguration: RealmConfiguration, - timeoutMillis: Long, - builder: (Realm) -> RealmQuery) { +internal suspend fun awaitNotEmptyResult( + realmConfiguration: RealmConfiguration, + timeoutMillis: Long, + builder: (Realm) -> RealmQuery +) { withTimeout(timeoutMillis) { // Confine Realm interaction to a single thread with Looper. withContext(Dispatchers.Main) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/SessionRealmConfigurationFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/SessionRealmConfigurationFactory.kt index 08d55b5647..949dd5daa1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/SessionRealmConfigurationFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/SessionRealmConfigurationFactory.kt @@ -44,7 +44,8 @@ internal class SessionRealmConfigurationFactory @Inject constructor( @SessionFilesDirectory val directory: File, @SessionId val sessionId: String, @UserMd5 val userMd5: String, - context: Context) { + context: Context +) { // Keep legacy preferences name for compatibility reason private val sharedPreferences = context.getSharedPreferences("im.vector.matrix.android.realm", Context.MODE_PRIVATE) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt index caaf6b8110..ee9e2403d6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt @@ -79,11 +79,13 @@ internal fun ChunkEntity.addStateEvent(roomId: String, stateEvent: EventEntity, } } -internal fun ChunkEntity.addTimelineEvent(roomId: String, - eventEntity: EventEntity, - direction: PaginationDirection, - ownedByThreadChunk: Boolean = false, - roomMemberContentsByUser: Map? = null): TimelineEventEntity? { +internal fun ChunkEntity.addTimelineEvent( + roomId: String, + eventEntity: EventEntity, + direction: PaginationDirection, + ownedByThreadChunk: Boolean = false, + roomMemberContentsByUser: Map? = null +): TimelineEventEntity? { val eventId = eventEntity.eventId if (timelineEvents.find(eventId) != null) { return null @@ -199,7 +201,7 @@ private fun handleReadReceipts(realm: Realm, roomId: String, eventEntity: EventE internal fun ChunkEntity.nextDisplayIndex(direction: PaginationDirection): Int { return when (direction) { - PaginationDirection.FORWARDS -> { + PaginationDirection.FORWARDS -> { (timelineEvents.where().max(TimelineEventEntityFields.DISPLAY_INDEX)?.toInt() ?: 0) + 1 } PaginationDirection.BACKWARDS -> { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt index 5db859bce2..dfac7f6708 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt @@ -47,9 +47,11 @@ private typealias Summary = Pair? */ internal fun Map.updateThreadSummaryIfNeeded( roomId: String, - realm: Realm, currentUserId: String, + realm: Realm, + currentUserId: String, chunkEntity: ChunkEntity? = null, - shouldUpdateNotifications: Boolean = true) { + shouldUpdateNotifications: Boolean = true +) { for ((rootThreadEventId, eventEntity) in this) { eventEntity.threadSummaryInThread(eventEntity.realm, rootThreadEventId, chunkEntity)?.let { threadSummary -> @@ -87,7 +89,8 @@ internal fun EventEntity.findRootThreadEvent(): EventEntity? = */ internal fun EventEntity.markEventAsRoot( inThreadMessages: Int, - latestMessageTimelineEventEntity: TimelineEventEntity?) { + latestMessageTimelineEventEntity: TimelineEventEntity? +) { isRootThread = true numberOfThreads = inThreadMessages threadSummaryLatestMessage = latestMessageTimelineEventEntity diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt index 5b4fe287cb..79a99cdfac 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt @@ -54,7 +54,8 @@ internal fun ThreadSummaryEntity.updateThreadSummary( numberOfThreads: Int?, latestThreadEventEntity: EventEntity?, isUserParticipating: Boolean, - roomMemberContentsByUser: HashMap) { + roomMemberContentsByUser: HashMap +) { updateThreadSummaryRootEvent(rootThreadEventEntity, roomMemberContentsByUser) updateThreadSummaryLatestEvent(latestThreadEventEntity, roomMemberContentsByUser) this.isUserParticipating = isUserParticipating @@ -180,7 +181,7 @@ internal fun ThreadSummaryEntity.Companion.createOrUpdate( roomEntity.addIfNecessary(threadSummary) } - ThreadSummaryUpdateType.ADD -> { + ThreadSummaryUpdateType.ADD -> { val rootThreadEventId = threadEventEntity?.rootThreadEventId ?: return Timber.i("###THREADS ThreadSummaryHelper ADD for root eventId:$rootThreadEventId") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt index a00a2a8ee1..4cf2ef6723 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt @@ -27,21 +27,21 @@ internal object DraftMapper { fun map(entity: DraftEntity): UserDraft { return when (entity.draftMode) { DraftEntity.MODE_REGULAR -> UserDraft.Regular(entity.content) - DraftEntity.MODE_EDIT -> UserDraft.Edit(entity.linkedEventId, entity.content) - DraftEntity.MODE_QUOTE -> UserDraft.Quote(entity.linkedEventId, entity.content) - DraftEntity.MODE_REPLY -> UserDraft.Reply(entity.linkedEventId, entity.content) - DraftEntity.MODE_VOICE -> UserDraft.Voice(entity.content) - else -> null + DraftEntity.MODE_EDIT -> UserDraft.Edit(entity.linkedEventId, entity.content) + DraftEntity.MODE_QUOTE -> UserDraft.Quote(entity.linkedEventId, entity.content) + DraftEntity.MODE_REPLY -> UserDraft.Reply(entity.linkedEventId, entity.content) + DraftEntity.MODE_VOICE -> UserDraft.Voice(entity.content) + else -> null } ?: UserDraft.Regular("") } fun map(domain: UserDraft): DraftEntity { return when (domain) { is UserDraft.Regular -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_REGULAR, linkedEventId = "") - is UserDraft.Edit -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_EDIT, linkedEventId = domain.linkedEventId) - is UserDraft.Quote -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_QUOTE, linkedEventId = domain.linkedEventId) - is UserDraft.Reply -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_REPLY, linkedEventId = domain.linkedEventId) - is UserDraft.Voice -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_VOICE, linkedEventId = "") + is UserDraft.Edit -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_EDIT, linkedEventId = domain.linkedEventId) + is UserDraft.Quote -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_QUOTE, linkedEventId = domain.linkedEventId) + is UserDraft.Reply -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_REPLY, linkedEventId = domain.linkedEventId) + is UserDraft.Voice -> DraftEntity(content = domain.content, draftMode = DraftEntity.MODE_VOICE, linkedEventId = "") } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/EventMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/EventMapper.kt index bc7d40bf6f..5b60c53642 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/EventMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/EventMapper.kt @@ -127,10 +127,12 @@ internal fun EventEntity.asDomain(castJsonNumbers: Boolean = false): Event { return EventMapper.map(this, castJsonNumbers) } -internal fun Event.toEntity(roomId: String, - sendState: SendState, - ageLocalTs: Long?, - contentToInject: String? = null): EventEntity { +internal fun Event.toEntity( + roomId: String, + sendState: SendState, + ageLocalTs: Long?, + contentToInject: String? = null +): EventEntity { return EventMapper.map(this, roomId).apply { this.sendState = sendState this.ageLocalTs = ageLocalTs diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/IsUselessResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/IsUselessResolver.kt index d704ecac8e..1a4821e80c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/IsUselessResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/IsUselessResolver.kt @@ -32,7 +32,7 @@ internal object IsUselessResolver { event.content != null && event.content.toContent() == event.resolvedPrevContent()?.toContent() } - else -> false + else -> false } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/RoomSummaryMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/RoomSummaryMapper.kt index 41faf30a82..735cfe411c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/RoomSummaryMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/RoomSummaryMapper.kt @@ -29,8 +29,10 @@ import org.matrix.android.sdk.internal.database.model.RoomSummaryEntity import org.matrix.android.sdk.internal.database.model.presence.toUserPresence import javax.inject.Inject -internal class RoomSummaryMapper @Inject constructor(private val timelineEventMapper: TimelineEventMapper, - private val typingUsersTracker: TypingUsersTracker) { +internal class RoomSummaryMapper @Inject constructor( + private val timelineEventMapper: TimelineEventMapper, + private val typingUsersTracker: TypingUsersTracker +) { fun map(roomSummaryEntity: RoomSummaryEntity): RoomSummary { val tags = roomSummaryEntity.tags().map { @@ -109,7 +111,7 @@ internal class RoomSummaryMapper @Inject constructor(private val timelineEventMa // I should probably use #hasEncryptorClassForAlgorithm but it says it supports // OLM which is some legacy? Now only megolm allowed in rooms MXCRYPTO_ALGORITHM_MEGOLM -> RoomEncryptionAlgorithm.Megolm - else -> RoomEncryptionAlgorithm.UnsupportedAlgorithm(alg) + else -> RoomEncryptionAlgorithm.UnsupportedAlgorithm(alg) } ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo019.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo019.kt index 754a66bb4b..38de70cc7c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo019.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo019.kt @@ -21,8 +21,10 @@ import org.matrix.android.sdk.internal.database.model.RoomSummaryEntityFields import org.matrix.android.sdk.internal.util.Normalizer import org.matrix.android.sdk.internal.util.database.RealmMigrator -internal class MigrateSessionTo019(realm: DynamicRealm, - private val normalizer: Normalizer) : RealmMigrator(realm, 19) { +internal class MigrateSessionTo019( + realm: DynamicRealm, + private val normalizer: Normalizer +) : RealmMigrator(realm, 19) { override fun doMigrate(realm: DynamicRealm) { realm.schema.get("RoomSummaryEntity") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt index 8399d82d5d..e5360ce0b6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt @@ -53,7 +53,8 @@ internal open class ChunkEntity( internal fun ChunkEntity.deleteOnCascade( deleteStateEvents: Boolean, - canDeleteRoot: Boolean) { + canDeleteRoot: Boolean +) { assertIsManaged() if (deleteStateEvents) { stateEvents.deleteAllFromRealm() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/CurrentStateEventEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/CurrentStateEventEntity.kt index 251b057722..9deef69dab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/CurrentStateEventEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/CurrentStateEventEntity.kt @@ -20,11 +20,12 @@ package org.matrix.android.sdk.internal.database.model import io.realm.RealmObject import io.realm.annotations.Index -internal open class CurrentStateEventEntity(var eventId: String = "", - var root: EventEntity? = null, - @Index var roomId: String = "", - @Index var type: String = "", - @Index var stateKey: String = "" +internal open class CurrentStateEventEntity( + var eventId: String = "", + var root: EventEntity? = null, + @Index var roomId: String = "", + @Index var type: String = "", + @Index var stateKey: String = "" ) : RealmObject() { companion object } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/DraftEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/DraftEntity.kt index fd09da4448..3c19d4d443 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/DraftEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/DraftEntity.kt @@ -18,9 +18,10 @@ package org.matrix.android.sdk.internal.database.model import io.realm.RealmObject -internal open class DraftEntity(var content: String = "", - var draftMode: String = MODE_REGULAR, - var linkedEventId: String = "" +internal open class DraftEntity( + var content: String = "", + var draftMode: String = MODE_REGULAR, + var linkedEventId: String = "" ) : RealmObject() { companion object { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventEntity.kt index ba80cc8302..8b5a211fba 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventEntity.kt @@ -25,28 +25,29 @@ import org.matrix.android.sdk.api.session.threads.ThreadNotificationState import org.matrix.android.sdk.internal.di.MoshiProvider import org.matrix.android.sdk.internal.extensions.assertIsManaged -internal open class EventEntity(@Index var eventId: String = "", - @Index var roomId: String = "", - @Index var type: String = "", - var content: String? = null, - var prevContent: String? = null, - var isUseless: Boolean = false, - @Index var stateKey: String? = null, - var originServerTs: Long? = null, - @Index var sender: String? = null, +internal open class EventEntity( + @Index var eventId: String = "", + @Index var roomId: String = "", + @Index var type: String = "", + var content: String? = null, + var prevContent: String? = null, + var isUseless: Boolean = false, + @Index var stateKey: String? = null, + var originServerTs: Long? = null, + @Index var sender: String? = null, // Can contain a serialized MatrixError - var sendStateDetails: String? = null, - var age: Long? = 0, - var unsignedData: String? = null, - var redacts: String? = null, - var decryptionResultJson: String? = null, - var ageLocalTs: Long? = null, + var sendStateDetails: String? = null, + var age: Long? = 0, + var unsignedData: String? = null, + var redacts: String? = null, + var decryptionResultJson: String? = null, + var ageLocalTs: Long? = null, // Thread related, no need to create a new Entity for performance - @Index var isRootThread: Boolean = false, - @Index var rootThreadEventId: String? = null, + @Index var isRootThread: Boolean = false, + @Index var rootThreadEventId: String? = null, // Number messages within the thread - var numberOfThreads: Int = 0, - var threadSummaryLatestMessage: TimelineEventEntity? = null + var numberOfThreads: Int = 0, + var threadSummaryLatestMessage: TimelineEventEntity? = null ) : RealmObject() { private var sendStateStr: String = SendState.UNKNOWN.name diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventInsertEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventInsertEntity.kt index 5cfd306d2f..eff332dc3a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventInsertEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventInsertEntity.kt @@ -22,13 +22,14 @@ import io.realm.RealmObject * This class is used to get notification on new events being inserted. It's to avoid realm getting slow when listening to insert * in EventEntity table. */ -internal open class EventInsertEntity(var eventId: String = "", - var eventType: String = "", - /** - * This flag will be used to filter EventInsertEntity in EventInsertLiveObserver. - * Currently it's set to false when the event content is encrypted. - */ - var canBeProcessed: Boolean = true +internal open class EventInsertEntity( + var eventId: String = "", + var eventType: String = "", + /** + * This flag will be used to filter EventInsertEntity in EventInsertLiveObserver. + * Currently it's set to false when the event content is encrypted. + */ + var canBeProcessed: Boolean = true ) : RealmObject() { private var insertTypeStr: String = EventInsertType.INCREMENTAL_SYNC.name diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/GroupSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/GroupSummaryEntity.kt index 4ba45dcda2..d965148559 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/GroupSummaryEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/GroupSummaryEntity.kt @@ -21,12 +21,13 @@ import io.realm.RealmObject import io.realm.annotations.PrimaryKey import org.matrix.android.sdk.api.session.room.model.Membership -internal open class GroupSummaryEntity(@PrimaryKey var groupId: String = "", - var displayName: String = "", - var shortDescription: String = "", - var avatarUrl: String = "", - var roomIds: RealmList = RealmList(), - var userIds: RealmList = RealmList() +internal open class GroupSummaryEntity( + @PrimaryKey var groupId: String = "", + var displayName: String = "", + var shortDescription: String = "", + var avatarUrl: String = "", + var roomIds: RealmList = RealmList(), + var userIds: RealmList = RealmList() ) : RealmObject() { private var membershipStr: String = Membership.NONE.name diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ReadReceiptEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ReadReceiptEntity.kt index e01d849cc2..9623c95359 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ReadReceiptEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ReadReceiptEntity.kt @@ -21,11 +21,12 @@ import io.realm.RealmResults import io.realm.annotations.LinkingObjects import io.realm.annotations.PrimaryKey -internal open class ReadReceiptEntity(@PrimaryKey var primaryKey: String = "", - var eventId: String = "", - var roomId: String = "", - var userId: String = "", - var originServerTs: Double = 0.0 +internal open class ReadReceiptEntity( + @PrimaryKey var primaryKey: String = "", + var eventId: String = "", + var roomId: String = "", + var userId: String = "", + var originServerTs: Double = 0.0 ) : RealmObject() { companion object diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomEntity.kt index d8e6b8af0f..d2116fa9b8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomEntity.kt @@ -24,11 +24,12 @@ import org.matrix.android.sdk.internal.database.model.threads.ThreadSummaryEntit import org.matrix.android.sdk.internal.database.query.findRootOrLatest import org.matrix.android.sdk.internal.extensions.assertIsManaged -internal open class RoomEntity(@PrimaryKey var roomId: String = "", - var chunks: RealmList = RealmList(), - var sendingTimelineEvents: RealmList = RealmList(), - var threadSummaries: RealmList = RealmList(), - var accountData: RealmList = RealmList() +internal open class RoomEntity( + @PrimaryKey var roomId: String = "", + var chunks: RealmList = RealmList(), + var sendingTimelineEvents: RealmList = RealmList(), + var threadSummaries: RealmList = RealmList(), + var accountData: RealmList = RealmList() ) : RealmObject() { private var membershipStr: String = Membership.NONE.name diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomMemberSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomMemberSummaryEntity.kt index a8a76d1681..6fb9324fcd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomMemberSummaryEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/RoomMemberSummaryEntity.kt @@ -23,13 +23,14 @@ import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.util.MatrixItem import org.matrix.android.sdk.internal.database.model.presence.UserPresenceEntity -internal open class RoomMemberSummaryEntity(@PrimaryKey var primaryKey: String = "", - @Index var userId: String = "", - @Index var roomId: String = "", - @Index var displayName: String? = null, - var avatarUrl: String? = null, - var reason: String? = null, - var isDirect: Boolean = false +internal open class RoomMemberSummaryEntity( + @PrimaryKey var primaryKey: String = "", + @Index var userId: String = "", + @Index var roomId: String = "", + @Index var displayName: String? = null, + var avatarUrl: String? = null, + var reason: String? = null, + var isDirect: Boolean = false ) : RealmObject() { private var membershipStr: String = Membership.NONE.name diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SyncEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SyncEntity.kt index a82ec41456..ff261b80c1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SyncEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SyncEntity.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.internal.database.model import io.realm.RealmObject import io.realm.annotations.PrimaryKey -internal open class SyncEntity(var nextBatch: String? = null, - @PrimaryKey var id: Long = 0 +internal open class SyncEntity( + var nextBatch: String? = null, + @PrimaryKey var id: Long = 0 ) : RealmObject() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/TimelineEventEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/TimelineEventEntity.kt index 477c04fe51..c8f22dc2cc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/TimelineEventEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/TimelineEventEntity.kt @@ -22,20 +22,21 @@ import io.realm.annotations.Index import io.realm.annotations.LinkingObjects import org.matrix.android.sdk.internal.extensions.assertIsManaged -internal open class TimelineEventEntity(var localId: Long = 0, - @Index var eventId: String = "", - @Index var roomId: String = "", - @Index var displayIndex: Int = 0, - var root: EventEntity? = null, - var annotations: EventAnnotationsSummaryEntity? = null, - var senderName: String? = null, - var isUniqueDisplayName: Boolean = false, - var senderAvatar: String? = null, - var senderMembershipEventId: String? = null, +internal open class TimelineEventEntity( + var localId: Long = 0, + @Index var eventId: String = "", + @Index var roomId: String = "", + @Index var displayIndex: Int = 0, + var root: EventEntity? = null, + var annotations: EventAnnotationsSummaryEntity? = null, + var senderName: String? = null, + var isUniqueDisplayName: Boolean = false, + var senderAvatar: String? = null, + var senderMembershipEventId: String? = null, // ownedByThreadChunk indicates that the current TimelineEventEntity belongs // to a thread chunk and is a temporarily event. - var ownedByThreadChunk: Boolean = false, - var readReceipts: ReadReceiptsSummaryEntity? = null + var ownedByThreadChunk: Boolean = false, + var readReceipts: ReadReceiptsSummaryEntity? = null ) : RealmObject() { @LinkingObjects("timelineEvents") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt index 2c778f9797..7ccfc6b104 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt @@ -24,7 +24,8 @@ import io.realm.annotations.LinkingObjects /** * Create a specific table to be able to do direct query on it and keep the draft ordered. */ -internal open class UserDraftsEntity(var userDrafts: RealmList = RealmList() +internal open class UserDraftsEntity( + var userDrafts: RealmList = RealmList() ) : RealmObject() { // Link to RoomSummaryEntity diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserEntity.kt index bd6e73582d..3644d12ac9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserEntity.kt @@ -19,9 +19,10 @@ package org.matrix.android.sdk.internal.database.model import io.realm.RealmObject import io.realm.annotations.PrimaryKey -internal open class UserEntity(@PrimaryKey var userId: String = "", - var displayName: String = "", - var avatarUrl: String = "" +internal open class UserEntity( + @PrimaryKey var userId: String = "", + var displayName: String = "", + var avatarUrl: String = "" ) : RealmObject() { companion object diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/presence/UserPresenceEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/presence/UserPresenceEntity.kt index 5713337ec5..8d808417c2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/presence/UserPresenceEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/presence/UserPresenceEntity.kt @@ -21,12 +21,13 @@ import io.realm.annotations.PrimaryKey import org.matrix.android.sdk.api.session.presence.model.PresenceEnum import org.matrix.android.sdk.api.session.presence.model.UserPresence -internal open class UserPresenceEntity(@PrimaryKey var userId: String = "", - var lastActiveAgo: Long? = null, - var statusMessage: String? = null, - var isCurrentlyActive: Boolean? = null, - var avatarUrl: String? = null, - var displayName: String? = null +internal open class UserPresenceEntity( + @PrimaryKey var userId: String = "", + var lastActiveAgo: Long? = null, + var statusMessage: String? = null, + var isCurrentlyActive: Boolean? = null, + var avatarUrl: String? = null, + var displayName: String? = null ) : RealmObject() { var presence: PresenceEnum diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/threads/ThreadSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/threads/ThreadSummaryEntity.kt index ab9d66548e..45f9e3aa20 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/threads/ThreadSummaryEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/threads/ThreadSummaryEntity.kt @@ -23,17 +23,18 @@ import io.realm.annotations.LinkingObjects import org.matrix.android.sdk.internal.database.model.EventEntity import org.matrix.android.sdk.internal.database.model.RoomEntity -internal open class ThreadSummaryEntity(@Index var rootThreadEventId: String? = "", - var rootThreadEventEntity: EventEntity? = null, - var latestThreadEventEntity: EventEntity? = null, - var rootThreadSenderName: String? = null, - var latestThreadSenderName: String? = null, - var rootThreadSenderAvatar: String? = null, - var latestThreadSenderAvatar: String? = null, - var rootThreadIsUniqueDisplayName: Boolean = false, - var isUserParticipating: Boolean = false, - var latestThreadIsUniqueDisplayName: Boolean = false, - var numberOfThreads: Int = 0 +internal open class ThreadSummaryEntity( + @Index var rootThreadEventId: String? = "", + var rootThreadEventEntity: EventEntity? = null, + var latestThreadEventEntity: EventEntity? = null, + var rootThreadSenderName: String? = null, + var latestThreadSenderName: String? = null, + var rootThreadSenderAvatar: String? = null, + var latestThreadSenderAvatar: String? = null, + var rootThreadIsUniqueDisplayName: Boolean = false, + var isUserParticipating: Boolean = false, + var latestThreadIsUniqueDisplayName: Boolean = false, + var numberOfThreads: Int = 0 ) : RealmObject() { @LinkingObjects("threadSummaries") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt index 716783f2ba..e0dbf2eee8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt @@ -23,40 +23,50 @@ import io.realm.kotlin.createObject import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntity import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntityFields -internal fun CurrentStateEventEntity.Companion.whereType(realm: Realm, - roomId: String, - type: String): RealmQuery { +internal fun CurrentStateEventEntity.Companion.whereType( + realm: Realm, + roomId: String, + type: String +): RealmQuery { return realm.where(CurrentStateEventEntity::class.java) .equalTo(CurrentStateEventEntityFields.ROOM_ID, roomId) .equalTo(CurrentStateEventEntityFields.TYPE, type) } -internal fun CurrentStateEventEntity.Companion.whereStateKey(realm: Realm, - roomId: String, - type: String, - stateKey: String): RealmQuery { +internal fun CurrentStateEventEntity.Companion.whereStateKey( + realm: Realm, + roomId: String, + type: String, + stateKey: String +): RealmQuery { return whereType(realm = realm, roomId = roomId, type = type) .equalTo(CurrentStateEventEntityFields.STATE_KEY, stateKey) } -internal fun CurrentStateEventEntity.Companion.getOrNull(realm: Realm, - roomId: String, - stateKey: String, - type: String): CurrentStateEventEntity? { +internal fun CurrentStateEventEntity.Companion.getOrNull( + realm: Realm, + roomId: String, + stateKey: String, + type: String +): CurrentStateEventEntity? { return whereStateKey(realm = realm, roomId = roomId, type = type, stateKey = stateKey).findFirst() } -internal fun CurrentStateEventEntity.Companion.getOrCreate(realm: Realm, - roomId: String, - stateKey: String, - type: String): CurrentStateEventEntity { +internal fun CurrentStateEventEntity.Companion.getOrCreate( + realm: Realm, + roomId: String, + stateKey: String, + type: String +): CurrentStateEventEntity { return getOrNull(realm = realm, roomId = roomId, stateKey = stateKey, type = type) ?: create(realm, roomId, stateKey, type) } -private fun create(realm: Realm, - roomId: String, - stateKey: String, - type: String): CurrentStateEventEntity { +private fun create( + realm: Realm, + roomId: String, + stateKey: String, + type: String +): CurrentStateEventEntity { return realm.createObject().apply { this.type = type this.roomId = roomId diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/EventEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/EventEntityQueries.kt index f7fa1037ba..0f1c226044 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/EventEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/EventEntityQueries.kt @@ -59,9 +59,10 @@ internal fun EventEntity.Companion.where(realm: Realm, eventIds: List): .`in`(EventEntityFields.EVENT_ID, eventIds.toTypedArray()) } -internal fun EventEntity.Companion.whereType(realm: Realm, - type: String, - roomId: String? = null +internal fun EventEntity.Companion.whereType( + realm: Realm, + type: String, + roomId: String? = null ): RealmQuery { val query = realm.where() if (roomId != null) { @@ -70,9 +71,11 @@ internal fun EventEntity.Companion.whereType(realm: Realm, return query.equalTo(EventEntityFields.TYPE, type) } -internal fun EventEntity.Companion.whereTypes(realm: Realm, - typeList: List = emptyList(), - roomId: String? = null): RealmQuery { +internal fun EventEntity.Companion.whereTypes( + realm: Realm, + typeList: List = emptyList(), + roomId: String? = null +): RealmQuery { val query = realm.where() query.`in`(EventEntityFields.TYPE, typeList.toTypedArray()) if (roomId != null) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/LiveLocationShareAggregatedSummaryEntityQuery.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/LiveLocationShareAggregatedSummaryEntityQuery.kt index 0cc41413f6..7dfeb6884a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/LiveLocationShareAggregatedSummaryEntityQuery.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/LiveLocationShareAggregatedSummaryEntityQuery.kt @@ -33,8 +33,10 @@ internal fun LiveLocationShareAggregatedSummaryEntity.Companion.where( .equalTo(LiveLocationShareAggregatedSummaryEntityFields.EVENT_ID, eventId) } -internal fun LiveLocationShareAggregatedSummaryEntity.Companion.whereRoomId(realm: Realm, - roomId: String): RealmQuery { +internal fun LiveLocationShareAggregatedSummaryEntity.Companion.whereRoomId( + realm: Realm, + roomId: String +): RealmQuery { return realm.where() .equalTo(LiveLocationShareAggregatedSummaryEntityFields.ROOM_ID, roomId) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PushersQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PushersQueries.kt index 3cea19a690..67fd8296d5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PushersQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PushersQueries.kt @@ -26,8 +26,10 @@ import org.matrix.android.sdk.internal.database.model.PushRulesEntityFields import org.matrix.android.sdk.internal.database.model.PusherEntity import org.matrix.android.sdk.internal.database.model.PusherEntityFields -internal fun PusherEntity.Companion.where(realm: Realm, - pushKey: String? = null): RealmQuery { +internal fun PusherEntity.Companion.where( + realm: Realm, + pushKey: String? = null +): RealmQuery { return realm.where() .apply { if (pushKey != null) { @@ -36,17 +38,21 @@ internal fun PusherEntity.Companion.where(realm: Realm, } } -internal fun PushRulesEntity.Companion.where(realm: Realm, - scope: String, - kind: RuleKind): RealmQuery { +internal fun PushRulesEntity.Companion.where( + realm: Realm, + scope: String, + kind: RuleKind +): RealmQuery { return realm.where() .equalTo(PushRulesEntityFields.SCOPE, scope) .equalTo(PushRulesEntityFields.KIND_STR, kind.name) } -internal fun PushRuleEntity.Companion.where(realm: Realm, - scope: String, - ruleId: String): RealmQuery { +internal fun PushRuleEntity.Companion.where( + realm: Realm, + scope: String, + ruleId: String +): RealmQuery { return realm.where() .equalTo(PushRuleEntityFields.PARENT.SCOPE, scope) .equalTo(PushRuleEntityFields.RULE_ID, ruleId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt index 1a832a29bb..0b0f01a67d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt @@ -24,10 +24,12 @@ import org.matrix.android.sdk.internal.database.model.ReadMarkerEntity import org.matrix.android.sdk.internal.database.model.ReadReceiptEntity import org.matrix.android.sdk.internal.database.model.TimelineEventEntity -internal fun isEventRead(realmConfiguration: RealmConfiguration, - userId: String?, - roomId: String?, - eventId: String?): Boolean { +internal fun isEventRead( + realmConfiguration: RealmConfiguration, + userId: String?, + roomId: String?, + eventId: String? +): Boolean { if (userId.isNullOrBlank() || roomId.isNullOrBlank() || eventId.isNullOrBlank()) { return false } @@ -39,12 +41,12 @@ internal fun isEventRead(realmConfiguration: RealmConfiguration, val eventToCheck = TimelineEventEntity.where(realm, roomId, eventId).findFirst() when { // The event doesn't exist locally, let's assume it hasn't been read - eventToCheck == null -> false - eventToCheck.root?.sender == userId -> true + eventToCheck == null -> false + eventToCheck.root?.sender == userId -> true // If new event exists and the latest event is from ourselves we can infer the event is read - latestEventIsFromSelf(realm, roomId, userId) -> true + latestEventIsFromSelf(realm, roomId, userId) -> true eventToCheck.isBeforeLatestReadReceipt(realm, roomId, userId) -> true - else -> false + else -> false } } } @@ -77,9 +79,11 @@ private fun Realm.hasReadReceiptInLatestChunk(latestChunkEntity: ChunkEntity, ro } != null } -internal fun isReadMarkerMoreRecent(realmConfiguration: RealmConfiguration, - roomId: String?, - eventId: String?): Boolean { +internal fun isReadMarkerMoreRecent( + realmConfiguration: RealmConfiguration, + roomId: String?, + eventId: String? +): Boolean { if (roomId.isNullOrBlank() || eventId.isNullOrBlank()) { return false } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RoomSummaryEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RoomSummaryEntityQueries.kt index 8993c36a30..3c8d61432a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RoomSummaryEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RoomSummaryEntityQueries.kt @@ -53,8 +53,10 @@ internal fun RoomSummaryEntity.Companion.getOrNull(realm: Realm, roomId: String) return where(realm, roomId).findFirst() } -internal fun RoomSummaryEntity.Companion.getDirectRooms(realm: Realm, - excludeRoomIds: Set? = null): RealmResults { +internal fun RoomSummaryEntity.Companion.getDirectRooms( + realm: Realm, + excludeRoomIds: Set? = null +): RealmResults { return RoomSummaryEntity.where(realm) .equalTo(RoomSummaryEntityFields.IS_DIRECT, true) .apply { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt index 1654a33806..30010f90fd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt @@ -33,39 +33,49 @@ internal fun TimelineEventEntity.Companion.where(realm: Realm): RealmQuery { +internal fun TimelineEventEntity.Companion.where( + realm: Realm, + roomId: String, + eventId: String +): RealmQuery { return where(realm) .equalTo(TimelineEventEntityFields.ROOM_ID, roomId) .equalTo(TimelineEventEntityFields.EVENT_ID, eventId) } -internal fun TimelineEventEntity.Companion.where(realm: Realm, - roomId: String, - eventIds: List): RealmQuery { +internal fun TimelineEventEntity.Companion.where( + realm: Realm, + roomId: String, + eventIds: List +): RealmQuery { return where(realm) .equalTo(TimelineEventEntityFields.ROOM_ID, roomId) .`in`(TimelineEventEntityFields.EVENT_ID, eventIds.toTypedArray()) } -internal fun TimelineEventEntity.Companion.whereRoomId(realm: Realm, - roomId: String): RealmQuery { +internal fun TimelineEventEntity.Companion.whereRoomId( + realm: Realm, + roomId: String +): RealmQuery { return where(realm) .equalTo(TimelineEventEntityFields.ROOM_ID, roomId) } -internal fun TimelineEventEntity.Companion.findWithSenderMembershipEvent(realm: Realm, - senderMembershipEventId: String): List { +internal fun TimelineEventEntity.Companion.findWithSenderMembershipEvent( + realm: Realm, + senderMembershipEventId: String +): List { return where(realm) .equalTo(TimelineEventEntityFields.SENDER_MEMBERSHIP_EVENT_ID, senderMembershipEventId) .findAll() } -internal fun TimelineEventEntity.Companion.latestEvent(realm: Realm, - roomId: String, - includesSending: Boolean, - filters: TimelineEventFilters = TimelineEventFilters()): TimelineEventEntity? { +internal fun TimelineEventEntity.Companion.latestEvent( + realm: Realm, + roomId: String, + includesSending: Boolean, + filters: TimelineEventFilters = TimelineEventFilters() +): TimelineEventEntity? { val roomEntity = RoomEntity.where(realm, roomId).findFirst() ?: return null val sendingTimelineEvents = roomEntity.sendingTimelineEvents.where().filterEvents(filters) @@ -129,9 +139,11 @@ internal fun RealmList.find(eventId: String): TimelineEvent .findFirst() } -internal fun TimelineEventEntity.Companion.findAllInRoomWithSendStates(realm: Realm, - roomId: String, - sendStates: List): RealmResults { +internal fun TimelineEventEntity.Companion.findAllInRoomWithSendStates( + realm: Realm, + roomId: String, + sendStates: List +): RealmResults { return whereRoomId(realm, roomId) .filterSendStates(sendStates) .findAll() @@ -145,8 +157,10 @@ internal fun RealmQuery.filterSendStates(sendStates: List): RealmResults { +internal fun TimelineEventEntity.Companion.findAllFrom( + realm: Realm, + senderIds: Collection +): RealmResults { return where(realm) .`in`(TimelineEventEntityFields.ROOT.SENDER, senderIds.toTypedArray()) .isNull(TimelineEventEntityFields.ROOT.STATE_KEY) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixComponent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixComponent.kt index dbc6aac6b5..095916643c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixComponent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixComponent.kt @@ -100,7 +100,9 @@ internal interface MatrixComponent { @Component.Factory interface Factory { - fun create(@BindsInstance context: Context, - @BindsInstance matrixConfiguration: MatrixConfiguration): MatrixComponent + fun create( + @BindsInstance context: Context, + @BindsInstance matrixConfiguration: MatrixConfiguration + ): MatrixComponent } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/NetworkModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/NetworkModule.kt index 0cbbe1210d..862cf463b2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/NetworkModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/NetworkModule.kt @@ -62,13 +62,15 @@ internal object NetworkModule { @Provides @JvmStatic @Unauthenticated - fun providesOkHttpClient(matrixConfiguration: MatrixConfiguration, - stethoInterceptor: StethoInterceptor, - timeoutInterceptor: TimeOutInterceptor, - userAgentInterceptor: UserAgentInterceptor, - httpLoggingInterceptor: HttpLoggingInterceptor, - curlLoggingInterceptor: CurlLoggingInterceptor, - apiInterceptor: ApiInterceptor): OkHttpClient { + fun providesOkHttpClient( + matrixConfiguration: MatrixConfiguration, + stethoInterceptor: StethoInterceptor, + timeoutInterceptor: TimeOutInterceptor, + userAgentInterceptor: UserAgentInterceptor, + httpLoggingInterceptor: HttpLoggingInterceptor, + curlLoggingInterceptor: CurlLoggingInterceptor, + apiInterceptor: ApiInterceptor + ): OkHttpClient { val spec = ConnectionSpec.Builder(matrixConfiguration.connectionSpec).build() return OkHttpClient.Builder() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt index c59936af94..ad28286a84 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt @@ -59,8 +59,10 @@ internal class WorkManagerProvider @Inject constructor( /** * Create a PeriodicWorkRequestBuilder, with the Matrix SDK tag. */ - inline fun matrixPeriodicWorkRequestBuilder(repeatInterval: Long, - repeatIntervalTimeUnit: TimeUnit) = + inline fun matrixPeriodicWorkRequestBuilder( + repeatInterval: Long, + repeatIntervalTimeUnit: TimeUnit + ) = PeriodicWorkRequestBuilder(repeatInterval, repeatIntervalTimeUnit) .addTag(tag) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/federation/FederationModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/federation/FederationModule.kt index a4eef80c58..bbb29b6255 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/federation/FederationModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/federation/FederationModule.kt @@ -34,9 +34,11 @@ internal abstract class FederationModule { companion object { @Provides @JvmStatic - fun providesFederationAPI(@Unauthenticated okHttpClient: Lazy, - sessionParams: SessionParams, - retrofitFactory: RetrofitFactory): FederationAPI { + fun providesFederationAPI( + @Unauthenticated okHttpClient: Lazy, + sessionParams: SessionParams, + retrofitFactory: RetrofitFactory + ): FederationAPI { return retrofitFactory.create(okHttpClient, sessionParams.homeServerUrlBase) .create(FederationAPI::class.java) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt index 0a76fb2eef..56d9cc2143 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt @@ -132,7 +132,7 @@ internal class DefaultLegacySessionImporter @Inject constructor( bytes = it.bytes, hashType = when (it.type) { LegacyFingerprint.HashType.SHA1, - null -> Fingerprint.HashType.SHA1 + null -> Fingerprint.HashType.SHA1 LegacyFingerprint.HashType.SHA256 -> Fingerprint.HashType.SHA256 } ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkCallbackStrategy.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkCallbackStrategy.kt index 8e18d2d850..f75fb01746 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkCallbackStrategy.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkCallbackStrategy.kt @@ -31,8 +31,10 @@ internal interface NetworkCallbackStrategy { fun unregister() } -internal class FallbackNetworkCallbackStrategy @Inject constructor(private val context: Context, - private val networkInfoReceiver: NetworkInfoReceiver) : NetworkCallbackStrategy { +internal class FallbackNetworkCallbackStrategy @Inject constructor( + private val context: Context, + private val networkInfoReceiver: NetworkInfoReceiver +) : NetworkCallbackStrategy { @Suppress("DEPRECATION") val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt index 65bf3fcadf..c54227a786 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt @@ -41,9 +41,11 @@ internal interface NetworkConnectivityChecker { } @SessionScope -internal class DefaultNetworkConnectivityChecker @Inject constructor(private val homeServerPinger: HomeServerPinger, - private val backgroundDetectionObserver: BackgroundDetectionObserver, - private val networkCallbackStrategy: NetworkCallbackStrategy) : +internal class DefaultNetworkConnectivityChecker @Inject constructor( + private val homeServerPinger: HomeServerPinger, + private val backgroundDetectionObserver: BackgroundDetectionObserver, + private val networkCallbackStrategy: NetworkCallbackStrategy +) : NetworkConnectivityChecker { private val hasInternetAccess = AtomicBoolean(true) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ProgressRequestBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ProgressRequestBody.kt index 818d7d6af3..6e4d064a0f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ProgressRequestBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ProgressRequestBody.kt @@ -26,8 +26,10 @@ import okio.buffer import org.matrix.android.sdk.api.extensions.tryOrNull import java.io.IOException -internal class ProgressRequestBody(private val delegate: RequestBody, - private val listener: Listener) : RequestBody() { +internal class ProgressRequestBody( + private val delegate: RequestBody, + private val listener: Listener +) : RequestBody() { private lateinit var countingSink: CountingSink diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/Request.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/Request.kt index 87a98e03f6..fefb7fb5e3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/Request.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/Request.kt @@ -40,11 +40,13 @@ import java.io.IOException * @param maxRetriesCount the max number of retries * @param requestBlock a suspend lambda to perform the network request */ -internal suspend inline fun executeRequest(globalErrorReceiver: GlobalErrorReceiver?, - canRetry: Boolean = false, - maxDelayBeforeRetry: Long = 32_000L, - maxRetriesCount: Int = 4, - noinline requestBlock: suspend () -> DATA): DATA { +internal suspend inline fun executeRequest( + globalErrorReceiver: GlobalErrorReceiver?, + canRetry: Boolean = false, + maxDelayBeforeRetry: Long = 32_000L, + maxRetriesCount: Int = 4, + noinline requestBlock: suspend () -> DATA +): DATA { var currentRetryCount = 0 var currentDelay = 1_000L @@ -54,8 +56,8 @@ internal suspend inline fun executeRequest(globalErrorReceiver: GlobalErr } catch (throwable: Throwable) { val exception = when (throwable) { is KotlinNullPointerException -> IllegalStateException("The request returned a null body") - is HttpException -> throwable.toFailure(globalErrorReceiver) - else -> throwable + is HttpException -> throwable.toFailure(globalErrorReceiver) + else -> throwable } // Log some details about the request which has failed. @@ -92,11 +94,11 @@ internal suspend inline fun executeRequest(globalErrorReceiver: GlobalErr // Try again (loop) } else { throw when (exception) { - is IOException -> Failure.NetworkConnection(exception) + is IOException -> Failure.NetworkConnection(exception) is Failure.ServerError, is Failure.OtherServerError, is CancellationException -> exception - else -> Failure.Unknown(exception) + else -> Failure.Unknown(exception) } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RequestExecutor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RequestExecutor.kt index 71df7c08be..2e8b2bc771 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RequestExecutor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RequestExecutor.kt @@ -19,19 +19,23 @@ package org.matrix.android.sdk.internal.network import org.matrix.android.sdk.internal.network.executeRequest as internalExecuteRequest internal interface RequestExecutor { - suspend fun executeRequest(globalErrorReceiver: GlobalErrorReceiver?, - canRetry: Boolean = false, - maxDelayBeforeRetry: Long = 32_000L, - maxRetriesCount: Int = 4, - requestBlock: suspend () -> DATA): DATA + suspend fun executeRequest( + globalErrorReceiver: GlobalErrorReceiver?, + canRetry: Boolean = false, + maxDelayBeforeRetry: Long = 32_000L, + maxRetriesCount: Int = 4, + requestBlock: suspend () -> DATA + ): DATA } internal object DefaultRequestExecutor : RequestExecutor { - override suspend fun executeRequest(globalErrorReceiver: GlobalErrorReceiver?, - canRetry: Boolean, - maxDelayBeforeRetry: Long, - maxRetriesCount: Int, - requestBlock: suspend () -> DATA): DATA { + override suspend fun executeRequest( + globalErrorReceiver: GlobalErrorReceiver?, + canRetry: Boolean, + maxDelayBeforeRetry: Long, + maxRetriesCount: Int, + requestBlock: suspend () -> DATA + ): DATA { return internalExecuteRequest(globalErrorReceiver, canRetry, maxDelayBeforeRetry, maxRetriesCount, requestBlock) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt index 5268ea851d..30f7cdd65b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt @@ -92,10 +92,10 @@ private fun toFailure(errorBody: ResponseBody?, httpCode: Int, globalErrorReceiv globalErrorReceiver?.handleGlobalError(GlobalError.ConsentNotGivenError(matrixError.consentUri)) } httpCode == HttpURLConnection.HTTP_UNAUTHORIZED && /* 401 */ - matrixError.code == MatrixError.M_UNKNOWN_TOKEN -> { + matrixError.code == MatrixError.M_UNKNOWN_TOKEN -> { globalErrorReceiver?.handleGlobalError(GlobalError.InvalidToken(matrixError.isSoftLogout.orFalse())) } - matrixError.code == MatrixError.ORG_MATRIX_EXPIRED_ACCOUNT -> { + matrixError.code == MatrixError.ORG_MATRIX_EXPIRED_ACCOUNT -> { globalErrorReceiver?.handleGlobalError(GlobalError.ExpiredAccount) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UnitConverterFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UnitConverterFactory.kt index f2571ab73f..8dcff59cba 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UnitConverterFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UnitConverterFactory.kt @@ -22,8 +22,10 @@ import retrofit2.Retrofit import java.lang.reflect.Type internal object UnitConverterFactory : Converter.Factory() { - override fun responseBodyConverter(type: Type, annotations: Array, - retrofit: Retrofit): Converter? { + override fun responseBodyConverter( + type: Type, annotations: Array, + retrofit: Retrofit + ): Converter? { return if (type == Unit::class.java) UnitConverter else null } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UserAgentHolder.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UserAgentHolder.kt index 00e15c283e..28d96dfce7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UserAgentHolder.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/UserAgentHolder.kt @@ -24,8 +24,10 @@ import timber.log.Timber import javax.inject.Inject @MatrixScope -internal class UserAgentHolder @Inject constructor(private val context: Context, - matrixConfiguration: MatrixConfiguration) { +internal class UserAgentHolder @Inject constructor( + private val context: Context, + matrixConfiguration: MatrixConfiguration +) { var userAgent: String = "" private set diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/ForceToBoolean.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/ForceToBoolean.kt index 628486bb5f..b4925429d0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/ForceToBoolean.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/ForceToBoolean.kt @@ -37,9 +37,9 @@ internal class ForceToBooleanJsonAdapter { @ForceToBoolean fun fromJson(reader: JsonReader): Boolean { return when (val token = reader.peek()) { - JsonReader.Token.NUMBER -> reader.nextInt() != 0 + JsonReader.Token.NUMBER -> reader.nextInt() != 0 JsonReader.Token.BOOLEAN -> reader.nextBoolean() - else -> { + else -> { Timber.e("Expecting a boolean or a int but get: $token") reader.skipValue() false diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/RuntimeJsonAdapterFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/RuntimeJsonAdapterFactory.kt index dd41b9f6fc..7cf3603cc5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/RuntimeJsonAdapterFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/RuntimeJsonAdapterFactory.kt @@ -70,11 +70,13 @@ internal class RuntimeJsonAdapterFactory( } @Suppress("UNCHECKED_CAST") - internal class RuntimeJsonAdapter(val labelKey: String, - val labelToAdapter: Map>, - val typeToLabel: Map, - val objectJsonAdapter: JsonAdapter, - val fallbackAdapter: JsonAdapter) : JsonAdapter() { + internal class RuntimeJsonAdapter( + val labelKey: String, + val labelToAdapter: Map>, + val typeToLabel: Map, + val objectJsonAdapter: JsonAdapter, + val fallbackAdapter: JsonAdapter + ) : JsonAdapter() { @Throws(IOException::class) override fun fromJson(reader: JsonReader): Any? { val peekedToken = reader.peek() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManager.kt index 539570cdd9..1b957c3855 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManager.kt @@ -29,8 +29,10 @@ import javax.net.ssl.X509TrustManager * @property defaultTrustManager Optional trust manager to fall back on if cert does not match * any of the fingerprints. Can be null. */ -internal class PinnedTrustManager(private val fingerprints: List, - private val defaultTrustManager: X509TrustManager?) : X509TrustManager { +internal class PinnedTrustManager( + private val fingerprints: List, + private val defaultTrustManager: X509TrustManager? +) : X509TrustManager { @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array, s: String) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerApi24.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerApi24.kt index 191bb90a67..ef703f3b61 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerApi24.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerApi24.kt @@ -34,8 +34,10 @@ import javax.net.ssl.X509ExtendedTrustManager * any of the fingerprints. Can be null. */ @RequiresApi(Build.VERSION_CODES.N) -internal class PinnedTrustManagerApi24(private val fingerprints: List, - private val defaultTrustManager: X509ExtendedTrustManager?) : X509ExtendedTrustManager() { +internal class PinnedTrustManagerApi24( + private val fingerprints: List, + private val defaultTrustManager: X509ExtendedTrustManager? +) : X509ExtendedTrustManager() { @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array, authType: String, engine: SSLEngine?) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerProvider.kt index f01ee7af24..bfdc4e537e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/PinnedTrustManagerProvider.kt @@ -25,8 +25,10 @@ internal object PinnedTrustManagerProvider { // Set to false to perform some tests private const val USE_DEFAULT_TRUST_MANAGER = true - fun provide(fingerprints: List?, - defaultTrustManager: X509TrustManager?): X509TrustManager { + fun provide( + fingerprints: List?, + defaultTrustManager: X509TrustManager? + ): X509TrustManager { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && defaultTrustManager is X509ExtendedTrustManager) { PinnedTrustManagerApi24( fingerprints.orEmpty(), diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryRoomOrderProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryRoomOrderProcessor.kt index c5ea2d48ad..8df0482993 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryRoomOrderProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryRoomOrderProcessor.kt @@ -24,10 +24,10 @@ import org.matrix.android.sdk.internal.database.model.RoomSummaryEntityFields internal fun RealmQuery.process(sortOrder: RoomSortOrder): RealmQuery { when (sortOrder) { - RoomSortOrder.NAME -> { + RoomSortOrder.NAME -> { sort(RoomSummaryEntityFields.DISPLAY_NAME, Sort.ASCENDING) } - RoomSortOrder.ACTIVITY -> { + RoomSortOrder.ACTIVITY -> { sort(RoomSummaryEntityFields.LAST_ACTIVITY_TIME, Sort.DESCENDING) } RoomSortOrder.PRIORITY_AND_ACTIVITY -> { @@ -40,7 +40,7 @@ internal fun RealmQuery.process(sortOrder: RoomSortOrder): Re arrayOf(Sort.DESCENDING, Sort.ASCENDING, Sort.DESCENDING) ) } - RoomSortOrder.NONE -> { + RoomSortOrder.NONE -> { } } return this diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryStringValueProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryStringValueProcessor.kt index ba4d05e747..b2ab9879df 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryStringValueProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/query/QueryStringValueProcessor.kt @@ -31,12 +31,12 @@ internal class QueryStringValueProcessor @Inject constructor( fun RealmQuery.process(field: String, queryStringValue: QueryStringValue): RealmQuery { return when (queryStringValue) { is QueryStringValue.NoCondition -> this - is QueryStringValue.IsNotNull -> isNotNull(field) - is QueryStringValue.IsNull -> isNull(field) - is QueryStringValue.IsEmpty -> isEmpty(field) - is QueryStringValue.IsNotEmpty -> isNotEmpty(field) - is ContentQueryStringValue -> when (queryStringValue) { - is QueryStringValue.Equals -> equalTo(field, queryStringValue.toRealmValue(), queryStringValue.case.toRealmCase()) + is QueryStringValue.IsNotNull -> isNotNull(field) + is QueryStringValue.IsNull -> isNull(field) + is QueryStringValue.IsEmpty -> isEmpty(field) + is QueryStringValue.IsNotEmpty -> isNotEmpty(field) + is ContentQueryStringValue -> when (queryStringValue) { + is QueryStringValue.Equals -> equalTo(field, queryStringValue.toRealmValue(), queryStringValue.case.toRealmCase()) is QueryStringValue.Contains -> contains(field, queryStringValue.toRealmValue(), queryStringValue.case.toRealmCase()) } } @@ -44,7 +44,7 @@ internal class QueryStringValueProcessor @Inject constructor( private fun ContentQueryStringValue.toRealmValue(): String { return when (case) { - QueryStringValue.Case.NORMALIZED -> normalizer.normalize(string) + QueryStringValue.Case.NORMALIZED -> normalizer.normalize(string) QueryStringValue.Case.SENSITIVE, QueryStringValue.Case.INSENSITIVE -> string } @@ -55,6 +55,6 @@ private fun QueryStringValue.Case.toRealmCase(): Case { return when (this) { QueryStringValue.Case.INSENSITIVE -> Case.INSENSITIVE QueryStringValue.Case.SENSITIVE, - QueryStringValue.Case.NORMALIZED -> Case.SENSITIVE + QueryStringValue.Case.NORMALIZED -> Case.SENSITIVE } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GetUrlTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GetUrlTask.kt index d0e2534e7a..87adad9063 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GetUrlTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GetUrlTask.kt @@ -42,8 +42,8 @@ internal class DefaultGetUrlTask @Inject constructor( override suspend fun execute(params: GetUrlTask.Params): String { return when (params.cacheStrategy) { - CacheStrategy.NoCache -> doRequest(params.url) - is CacheStrategy.TtlCache -> doRequestWithCache( + CacheStrategy.NoCache -> doRequest(params.url) + is CacheStrategy.TtlCache -> doRequestWithCache( params.url, params.cacheStrategy.validityDurationInMillis, params.cacheStrategy.strict diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/RawModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/RawModule.kt index a830976671..4b643f1fef 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/RawModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/RawModule.kt @@ -51,8 +51,10 @@ internal abstract class RawModule { @Provides @GlobalDatabase @MatrixScope - fun providesRealmConfiguration(realmKeysUtils: RealmKeysUtils, - globalRealmMigration: GlobalRealmMigration): RealmConfiguration { + fun providesRealmConfiguration( + realmKeysUtils: RealmKeysUtils, + globalRealmMigration: GlobalRealmMigration + ): RealmConfiguration { return RealmConfiguration.Builder() .apply { realmKeysUtils.configureEncryption(this, DB_ALIAS) @@ -67,8 +69,10 @@ internal abstract class RawModule { @Provides @JvmStatic - fun providesRawAPI(@Unauthenticated okHttpClient: Lazy, - retrofitFactory: RetrofitFactory): RawAPI { + fun providesRawAPI( + @Unauthenticated okHttpClient: Lazy, + retrofitFactory: RetrofitFactory + ): RawAPI { return retrofitFactory.create(okHttpClient, "https://example.org").create(RawAPI::class.java) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt index 760aa41081..bbf260a3f1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt @@ -80,10 +80,12 @@ internal class DefaultFileService @Inject constructor( * Download file in the cache folder, and eventually decrypt it. * TODO looks like files are copied 3 times */ - override suspend fun downloadFile(fileName: String, - mimeType: String?, - url: String?, - elementToDecrypt: ElementToDecrypt?): File { + override suspend fun downloadFile( + fileName: String, + mimeType: String?, + url: String?, + elementToDecrypt: ElementToDecrypt? + ): File { url ?: throw IllegalArgumentException("url is null") Timber.v("## FileService downloadFile $url") @@ -125,7 +127,7 @@ internal class DefaultFileService @Inject constructor( val resolvedUrl = contentUrlResolver.resolveForDownload(url, elementToDecrypt) ?: throw IllegalArgumentException("url is null") val request = when (resolvedUrl) { - is ContentUrlResolver.ResolvedMethod.GET -> { + is ContentUrlResolver.ResolvedMethod.GET -> { Request.Builder() .url(resolvedUrl.url) .header(DOWNLOAD_PROGRESS_INTERCEPTOR_HEADER, url) @@ -218,11 +220,13 @@ internal class DefaultFileService @Inject constructor( return result.getOrThrow() } - fun storeDataFor(mxcUrl: String, - filename: String?, - mimeType: String?, - originalFile: File, - encryptedFile: File?) { + fun storeDataFor( + mxcUrl: String, + filename: String?, + mimeType: String?, + originalFile: File, + encryptedFile: File? + ) { val files = getFiles(mxcUrl, filename, mimeType, encryptedFile != null) if (encryptedFile != null) { // We switch the two files here, original file it the decrypted file @@ -256,10 +260,12 @@ internal class DefaultFileService @Inject constructor( } } - override fun isFileInCache(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt?): Boolean { + override fun isFileInCache( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? + ): Boolean { return fileState(mxcUrl, fileName, mimeType, elementToDecrypt) is FileService.FileState.InCache } @@ -272,10 +278,12 @@ internal class DefaultFileService @Inject constructor( fun getClearFile(): File = decryptedFile ?: file } - private fun getFiles(mxcUrl: String, - fileName: String?, - mimeType: String?, - isEncrypted: Boolean): CachedFiles { + private fun getFiles( + mxcUrl: String, + fileName: String?, + mimeType: String?, + isEncrypted: Boolean + ): CachedFiles { val hashFolder = mxcUrl.md5() val safeFileName = safeFileName(fileName, mimeType) return if (isEncrypted) { @@ -293,10 +301,12 @@ internal class DefaultFileService @Inject constructor( } } - override fun fileState(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt?): FileService.FileState { + override fun fileState( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? + ): FileService.FileState { mxcUrl ?: return FileService.FileState.Unknown val files = getFiles(mxcUrl, fileName, mimeType, elementToDecrypt != null) if (files.file.exists()) { @@ -314,10 +324,12 @@ internal class DefaultFileService @Inject constructor( * Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION * (if not other app won't be able to access it). */ - override fun getTemporarySharableURI(mxcUrl: String?, - fileName: String, - mimeType: String?, - elementToDecrypt: ElementToDecrypt?): Uri? { + override fun getTemporarySharableURI( + mxcUrl: String?, + fileName: String, + mimeType: String?, + elementToDecrypt: ElementToDecrypt? + ): Uri? { mxcUrl ?: return null // this string could be extracted no? val authority = "${context.packageName}.mx-sdk.fileprovider" diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultSession.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultSession.kt index 5f77cfb23a..32269c9afd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultSession.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultSession.kt @@ -44,7 +44,6 @@ import org.matrix.android.sdk.api.session.file.FileService import org.matrix.android.sdk.api.session.group.GroupService import org.matrix.android.sdk.api.session.homeserver.HomeServerCapabilitiesService import org.matrix.android.sdk.api.session.identity.IdentityService -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.integrationmanager.IntegrationManagerService import org.matrix.android.sdk.api.session.media.MediaService import org.matrix.android.sdk.api.session.openid.OpenIdService @@ -61,6 +60,7 @@ import org.matrix.android.sdk.api.session.securestorage.SharedSecretStorageServi import org.matrix.android.sdk.api.session.signout.SignOutService import org.matrix.android.sdk.api.session.space.SpaceService import org.matrix.android.sdk.api.session.sync.FilterService +import org.matrix.android.sdk.api.session.sync.SyncService import org.matrix.android.sdk.api.session.terms.TermsService import org.matrix.android.sdk.api.session.thirdparty.ThirdPartyService import org.matrix.android.sdk.api.session.typing.TypingUsersTracker @@ -76,13 +76,8 @@ import org.matrix.android.sdk.internal.di.SessionId import org.matrix.android.sdk.internal.di.UnauthenticatedWithCertificate import org.matrix.android.sdk.internal.di.WorkManagerProvider import org.matrix.android.sdk.internal.network.GlobalErrorHandler -import org.matrix.android.sdk.internal.session.sync.SyncTokenStore -import org.matrix.android.sdk.internal.session.sync.job.SyncThread -import org.matrix.android.sdk.internal.session.sync.job.SyncWorker import org.matrix.android.sdk.internal.util.createUIHandler -import timber.log.Timber import javax.inject.Inject -import javax.inject.Provider @SessionScope internal class DefaultSession @Inject constructor( @@ -112,16 +107,14 @@ internal class DefaultSession @Inject constructor( private val permalinkService: Lazy, private val secureStorageService: Lazy, private val profileService: Lazy, + private val syncService: Lazy, private val mediaService: Lazy, private val widgetService: Lazy, - private val syncThreadProvider: Provider, private val contentUrlResolver: ContentUrlResolver, - private val syncTokenStore: SyncTokenStore, private val sessionParamsStore: SessionParamsStore, private val contentUploadProgressTracker: ContentUploadStateTracker, private val typingUsersTracker: TypingUsersTracker, private val contentDownloadStateTracker: ContentDownloadStateTracker, - private val syncStatusService: Lazy, private val homeServerCapabilitiesService: Lazy, private val accountDataService: Lazy, private val sharedSecretStorageService: Lazy, @@ -138,14 +131,11 @@ internal class DefaultSession @Inject constructor( private val toDeviceService: Lazy, private val eventStreamService: Lazy, @UnauthenticatedWithCertificate - private val unauthenticatedWithCertificateOkHttpClient: Lazy + private val unauthenticatedWithCertificateOkHttpClient: Lazy, + private val sessionState: SessionState, ) : Session, GlobalErrorHandler.Listener { - private var isOpen = false - - private var syncThread: SyncThread? = null - private val uiHandler = createUIHandler() override val isOpenable: Boolean @@ -153,8 +143,7 @@ internal class DefaultSession @Inject constructor( @MainThread override fun open() { - assert(!isOpen) - isOpen = true + sessionState.setIsOpen(true) globalErrorHandler.listener = this cryptoService.get().ensureDevice() uiHandler.post { @@ -167,40 +156,9 @@ internal class DefaultSession @Inject constructor( } } - override fun requireBackgroundSync() { - SyncWorker.requireBackgroundSync(workManagerProvider, sessionId) - } - - override fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) { - SyncWorker.automaticallyBackgroundSync(workManagerProvider, sessionId, timeOutInSeconds, repeatDelayInSeconds) - } - - override fun stopAnyBackgroundSync() { - SyncWorker.stopAnyBackgroundSync(workManagerProvider) - } - - override fun startSync(fromForeground: Boolean) { - Timber.i("Starting sync thread") - assert(isOpen) - val localSyncThread = getSyncThread() - localSyncThread.setInitialForeground(fromForeground) - if (!localSyncThread.isAlive) { - localSyncThread.start() - } else { - localSyncThread.restart() - Timber.w("Attempt to start an already started thread") - } - } - - override fun stopSync() { - assert(isOpen) - syncThread?.kill() - syncThread = null - } - override fun close() { - assert(isOpen) - stopSync() + assert(sessionState.isOpen) + syncService.get().stopSync() // timelineEventDecryptor.destroy() uiHandler.post { lifecycleObservers.forEach { it.onSessionStopped(this) } @@ -210,28 +168,12 @@ internal class DefaultSession @Inject constructor( } cryptoService.get().close() globalErrorHandler.listener = null - isOpen = false - } - - override fun getSyncStateLive() = getSyncThread().liveState() - - override fun syncFlow() = getSyncThread().syncFlow() - - override fun getSyncState() = getSyncThread().currentState() - - override fun hasAlreadySynced(): Boolean { - return syncTokenStore.getLastToken() != null - } - - private fun getSyncThread(): SyncThread { - return syncThread ?: syncThreadProvider.get().also { - syncThread = it - } + sessionState.setIsOpen(false) } override suspend fun clearCache() { - stopSync() - stopAnyBackgroundSync() + syncService.get().stopSync() + syncService.get().stopAnyBackgroundSync() uiHandler.post { lifecycleObservers.forEach { it.onClearCache(this) @@ -271,7 +213,7 @@ internal class DefaultSession @Inject constructor( override fun pushersService(): PushersService = pushersService.get() override fun eventService(): EventService = eventService.get() override fun termsService(): TermsService = termsService.get() - override fun syncStatusService(): SyncStatusService = syncStatusService.get() + override fun syncService(): SyncService = syncService.get() override fun secureStorageService(): SecureStorageService = secureStorageService.get() override fun profileService(): ProfileService = profileService.get() override fun presenceService(): PresenceService = presenceService.get() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt index 1e3566f49e..f01451b688 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt @@ -138,6 +138,7 @@ internal interface SessionComponent { interface Factory { fun create( matrixComponent: MatrixComponent, - @BindsInstance sessionParams: SessionParams): SessionComponent + @BindsInstance sessionParams: SessionParams + ): SessionComponent } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt index 9208ff219b..2c2317de0d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt @@ -39,7 +39,6 @@ import org.matrix.android.sdk.api.session.ToDeviceService import org.matrix.android.sdk.api.session.accountdata.SessionAccountDataService import org.matrix.android.sdk.api.session.events.EventService import org.matrix.android.sdk.api.session.homeserver.HomeServerCapabilitiesService -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.openid.OpenIdService import org.matrix.android.sdk.api.session.permalinks.PermalinkService import org.matrix.android.sdk.api.session.securestorage.SecureStorageService @@ -82,7 +81,6 @@ import org.matrix.android.sdk.internal.session.download.DownloadProgressIntercep import org.matrix.android.sdk.internal.session.events.DefaultEventService import org.matrix.android.sdk.internal.session.homeserver.DefaultHomeServerCapabilitiesService import org.matrix.android.sdk.internal.session.identity.DefaultIdentityService -import org.matrix.android.sdk.internal.session.initsync.DefaultSyncStatusService import org.matrix.android.sdk.internal.session.integrationmanager.IntegrationManager import org.matrix.android.sdk.internal.session.openid.DefaultOpenIdService import org.matrix.android.sdk.internal.session.permalinks.DefaultPermalinkService @@ -166,9 +164,11 @@ internal abstract class SessionModule { @Provides @SessionFilesDirectory @SessionScope - fun providesFilesDir(@UserMd5 userMd5: String, - @SessionId sessionId: String, - context: Context): File { + fun providesFilesDir( + @UserMd5 userMd5: String, + @SessionId sessionId: String, + context: Context + ): File { // Temporary code for migration val old = File(context.filesDir, userMd5) if (old.exists()) { @@ -181,8 +181,10 @@ internal abstract class SessionModule { @JvmStatic @Provides @SessionDownloadsDirectory - fun providesDownloadsCacheDir(@SessionId sessionId: String, - @CacheDirectory cacheFile: File): File { + fun providesDownloadsCacheDir( + @SessionId sessionId: String, + @CacheDirectory cacheFile: File + ): File { return File(cacheFile, "downloads/$sessionId") } @@ -208,8 +210,10 @@ internal abstract class SessionModule { @Provides @SessionScope @UnauthenticatedWithCertificate - fun providesOkHttpClientWithCertificate(@Unauthenticated okHttpClient: OkHttpClient, - homeServerConnectionConfig: HomeServerConnectionConfig): OkHttpClient { + fun providesOkHttpClientWithCertificate( + @Unauthenticated okHttpClient: OkHttpClient, + homeServerConnectionConfig: HomeServerConnectionConfig + ): OkHttpClient { return okHttpClient .newBuilder() .addSocketFactory(homeServerConnectionConfig) @@ -220,10 +224,12 @@ internal abstract class SessionModule { @Provides @SessionScope @Authenticated - fun providesOkHttpClient(@UnauthenticatedWithCertificate okHttpClient: OkHttpClient, - @Authenticated accessTokenProvider: AccessTokenProvider, - @SessionId sessionId: String, - @MockHttpInterceptor testInterceptor: TestInterceptor?): OkHttpClient { + fun providesOkHttpClient( + @UnauthenticatedWithCertificate okHttpClient: OkHttpClient, + @Authenticated accessTokenProvider: AccessTokenProvider, + @SessionId sessionId: String, + @MockHttpInterceptor testInterceptor: TestInterceptor? + ): OkHttpClient { return okHttpClient .newBuilder() .addAccessTokenInterceptor(accessTokenProvider) @@ -240,8 +246,10 @@ internal abstract class SessionModule { @Provides @SessionScope @UnauthenticatedWithCertificateWithProgress - fun providesProgressOkHttpClient(@UnauthenticatedWithCertificate okHttpClient: OkHttpClient, - downloadProgressInterceptor: DownloadProgressInterceptor): OkHttpClient { + fun providesProgressOkHttpClient( + @UnauthenticatedWithCertificate okHttpClient: OkHttpClient, + downloadProgressInterceptor: DownloadProgressInterceptor + ): OkHttpClient { return okHttpClient.newBuilder() .apply { // Remove the previous CurlLoggingInterceptor, to add it after the accessTokenInterceptor @@ -260,9 +268,11 @@ internal abstract class SessionModule { @JvmStatic @Provides @SessionScope - fun providesRetrofit(@Authenticated okHttpClient: Lazy, - sessionParams: SessionParams, - retrofitFactory: RetrofitFactory): Retrofit { + fun providesRetrofit( + @Authenticated okHttpClient: Lazy, + sessionParams: SessionParams, + retrofitFactory: RetrofitFactory + ): Retrofit { return retrofitFactory .create(okHttpClient, sessionParams.homeServerConnectionConfig.homeServerUriBase.toString()) } @@ -270,8 +280,9 @@ internal abstract class SessionModule { @JvmStatic @Provides @SessionScope - fun providesNetworkCallbackStrategy(fallbackNetworkCallbackStrategy: Provider, - preferredNetworkCallbackStrategy: Provider + fun providesNetworkCallbackStrategy( + fallbackNetworkCallbackStrategy: Provider, + preferredNetworkCallbackStrategy: Provider ): NetworkCallbackStrategy { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { preferredNetworkCallbackStrategy.get() @@ -349,9 +360,6 @@ internal abstract class SessionModule { @IntoSet abstract fun bindEventSenderProcessorAsSessionLifecycleObserver(processor: EventSenderProcessorCoroutine): SessionLifecycleObserver - @Binds - abstract fun bindSyncStatusService(service: DefaultSyncStatusService): SyncStatusService - @Binds abstract fun bindSecureStorageService(service: DefaultSecureStorageService): SecureStorageService diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionState.kt new file mode 100644 index 0000000000..b109a9aa60 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionState.kt @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session + +import javax.inject.Inject + +@SessionScope +internal class SessionState @Inject constructor() { + var isOpen = false + private set + + /** + * Set the new state. Throw if already in the new state. + */ + fun setIsOpen(newState: Boolean) { + assert(newState != isOpen) + isOpen = newState + } +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DeactivateAccountTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DeactivateAccountTask.kt index 9f3f1f649e..5f4d3d5fbc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DeactivateAccountTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DeactivateAccountTask.kt @@ -60,10 +60,10 @@ internal class DefaultDeactivateAccountTask @Inject constructor( execute(params.copy(userAuthParam = authUpdate)) } )) { - UiaResult.SUCCESS -> { + UiaResult.SUCCESS -> { false } - UiaResult.FAILURE -> { + UiaResult.FAILURE -> { Timber.d("## UIA: propagate failure") throw throwable } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DefaultAccountService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DefaultAccountService.kt index dc77d7bffb..bb830a5e41 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DefaultAccountService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/DefaultAccountService.kt @@ -20,8 +20,10 @@ import org.matrix.android.sdk.api.auth.UserInteractiveAuthInterceptor import org.matrix.android.sdk.api.session.account.AccountService import javax.inject.Inject -internal class DefaultAccountService @Inject constructor(private val changePasswordTask: ChangePasswordTask, - private val deactivateAccountTask: DeactivateAccountTask) : AccountService { +internal class DefaultAccountService @Inject constructor( + private val changePasswordTask: ChangePasswordTask, + private val deactivateAccountTask: DeactivateAccountTask +) : AccountService { override suspend fun changePassword(password: String, newPassword: String) { changePasswordTask.execute(ChangePasswordTask.Params(password, newPassword)) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/CallSignalingHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/CallSignalingHandler.kt index c4f711a9e6..48a9dfd3da 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/CallSignalingHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/CallSignalingHandler.kt @@ -63,25 +63,25 @@ internal class CallSignalingHandler @Inject constructor( fun onCallEvent(event: Event) { when (event.getClearType()) { - EventType.CALL_ANSWER -> { + EventType.CALL_ANSWER -> { handleCallAnswerEvent(event) } - EventType.CALL_INVITE -> { + EventType.CALL_INVITE -> { handleCallInviteEvent(event) } - EventType.CALL_HANGUP -> { + EventType.CALL_HANGUP -> { handleCallHangupEvent(event) } - EventType.CALL_REJECT -> { + EventType.CALL_REJECT -> { handleCallRejectEvent(event) } - EventType.CALL_CANDIDATES -> { + EventType.CALL_CANDIDATES -> { handleCallCandidatesEvent(event) } - EventType.CALL_SELECT_ANSWER -> { + EventType.CALL_SELECT_ANSWER -> { handleCallSelectAnswerEvent(event) } - EventType.CALL_NEGOTIATE -> { + EventType.CALL_NEGOTIATE -> { handleCallNegotiateEvent(event) } EventType.CALL_ASSERTED_IDENTITY, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/MxCallFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/MxCallFactory.kt index 9ec892b65d..5b4100f276 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/MxCallFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/MxCallFactory.kt @@ -79,10 +79,12 @@ internal class MxCallFactory @Inject constructor( } } - fun updateOutgoingCallWithOpponentData(call: MxCall, - userId: String, - content: CallSignalingContent, - callCapabilities: CallCapabilities?) { + fun updateOutgoingCallWithOpponentData( + call: MxCall, + userId: String, + content: CallSignalingContent, + callCapabilities: CallCapabilities? + ) { (call as? MxCallImpl)?.updateOpponentData(userId, content, callCapabilities) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/model/MxCallImpl.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/model/MxCallImpl.kt index 796e83311f..13a77e55e1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/model/MxCallImpl.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/model/MxCallImpl.kt @@ -220,10 +220,12 @@ internal class MxCallImpl( .also { eventSenderProcessor.postEvent(it) } } - override suspend fun transfer(targetUserId: String, - targetRoomId: String?, - createCallId: String?, - awaitCallId: String?) { + override suspend fun transfer( + targetUserId: String, + targetRoomId: String?, + createCallId: String?, + awaitCallId: String? + ) { val profileInfoParams = GetProfileInfoTask.Params(targetUserId) val profileInfo = try { getProfileInfoTask.execute(profileInfoParams) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/DefaultContentUrlResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/DefaultContentUrlResolver.kt index 5d77424482..ad2b9d0905 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/DefaultContentUrlResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/DefaultContentUrlResolver.kt @@ -80,9 +80,11 @@ internal class DefaultContentUrlResolver @Inject constructor( } } - private fun resolve(contentUrl: String, - toThumbnail: Boolean, - params: String = ""): String { + private fun resolve( + contentUrl: String, + toThumbnail: Boolean, + params: String = "" + ): String { var serverAndMediaId = contentUrl.removeMxcPrefix() val apiPath = if (scannerService.isScannerEnabled()) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/FileUploader.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/FileUploader.kt index f96a019fe2..c023646c7f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/FileUploader.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/FileUploader.kt @@ -62,10 +62,12 @@ internal class FileUploader @Inject constructor( private val uploadUrl = contentUrlResolver.uploadUrl private val responseAdapter = moshi.adapter(ContentUploadResponse::class.java) - suspend fun uploadFile(file: File, - filename: String?, - mimeType: String?, - progressListener: ProgressRequestBody.Listener? = null): ContentUploadResponse { + suspend fun uploadFile( + file: File, + filename: String?, + mimeType: String?, + progressListener: ProgressRequestBody.Listener? = null + ): ContentUploadResponse { // Check size limit val maxUploadFileSize = homeServerCapabilitiesService.getHomeServerCapabilities().maxUploadFileSize @@ -99,18 +101,22 @@ internal class FileUploader @Inject constructor( return upload(uploadBody, filename, progressListener) } - suspend fun uploadByteArray(byteArray: ByteArray, - filename: String?, - mimeType: String?, - progressListener: ProgressRequestBody.Listener? = null): ContentUploadResponse { + suspend fun uploadByteArray( + byteArray: ByteArray, + filename: String?, + mimeType: String?, + progressListener: ProgressRequestBody.Listener? = null + ): ContentUploadResponse { val uploadBody = byteArray.toRequestBody(mimeType?.toMediaTypeOrNull()) return upload(uploadBody, filename, progressListener) } - suspend fun uploadFromUri(uri: Uri, - filename: String?, - mimeType: String?, - progressListener: ProgressRequestBody.Listener? = null): ContentUploadResponse { + suspend fun uploadFromUri( + uri: Uri, + filename: String?, + mimeType: String?, + progressListener: ProgressRequestBody.Listener? = null + ): ContentUploadResponse { val workingFile = context.copyUriToTempFile(uri) return uploadFile(workingFile, filename, mimeType, progressListener).also { tryOrNull { workingFile.delete() } @@ -128,9 +134,11 @@ internal class FileUploader @Inject constructor( } } - private suspend fun upload(uploadBody: RequestBody, - filename: String?, - progressListener: ProgressRequestBody.Listener?): ContentUploadResponse { + private suspend fun upload( + uploadBody: RequestBody, + filename: String?, + progressListener: ProgressRequestBody.Listener? + ): ContentUploadResponse { val urlBuilder = uploadUrl.toHttpUrlOrNull()?.newBuilder() ?: throw RuntimeException() val httpUrl = urlBuilder diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageCompressor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageCompressor.kt index c5aa6cd5e7..bc04cac35a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageCompressor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageCompressor.kt @@ -35,7 +35,8 @@ internal class ImageCompressor @Inject constructor( imageFile: File, desiredWidth: Int, desiredHeight: Int, - desiredQuality: Int = 80): File { + desiredQuality: Int = 80 + ): File { return withContext(coroutineDispatchers.io) { val compressedBitmap = BitmapFactory.Options().run { inJustDecodeBounds = true @@ -68,20 +69,20 @@ internal class ImageCompressor @Inject constructor( val orientation = exifInfo.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) val matrix = Matrix() when (orientation) { - ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f) - ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f) - ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f) + ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f) + ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f) + ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f) ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.preScale(-1f, 1f) - ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f) - ExifInterface.ORIENTATION_TRANSPOSE -> { + ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f) + ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.preRotate(-90f) matrix.preScale(-1f, 1f) } - ExifInterface.ORIENTATION_TRANSVERSE -> { + ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.preRotate(90f) matrix.preScale(-1f, 1f) } - else -> return bitmap + else -> return bitmap } return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt index 5a00c4b5b4..1e62b5d7f5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt @@ -192,7 +192,7 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter }) .let { videoCompressionResult -> when (videoCompressionResult) { - is VideoCompressionResult.Success -> { + is VideoCompressionResult.Success -> { val compressedFile = videoCompressionResult.compressedFile var compressedWidth: Int? = null var compressedHeight: Int? = null @@ -375,12 +375,14 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter ) } - private suspend fun handleSuccess(params: Params, - attachmentUrl: String, - encryptedFileInfo: EncryptedFileInfo?, - thumbnailUrl: String?, - thumbnailEncryptedFileInfo: EncryptedFileInfo?, - newAttachmentAttributes: NewAttachmentAttributes): Result { + private suspend fun handleSuccess( + params: Params, + attachmentUrl: String, + encryptedFileInfo: EncryptedFileInfo?, + thumbnailUrl: String?, + thumbnailEncryptedFileInfo: EncryptedFileInfo?, + newAttachmentAttributes: NewAttachmentAttributes + ): Result { notifyTracker(params) { contentUploadStateTracker.setSuccess(it) } params.localEchoIds.forEach { updateEvent(it.eventId, attachmentUrl, encryptedFileInfo, thumbnailUrl, thumbnailEncryptedFileInfo, newAttachmentAttributes) @@ -396,20 +398,22 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter } } - private suspend fun updateEvent(eventId: String, - url: String, - encryptedFileInfo: EncryptedFileInfo?, - thumbnailUrl: String? = null, - thumbnailEncryptedFileInfo: EncryptedFileInfo?, - newAttachmentAttributes: NewAttachmentAttributes) { + private suspend fun updateEvent( + eventId: String, + url: String, + encryptedFileInfo: EncryptedFileInfo?, + thumbnailUrl: String? = null, + thumbnailEncryptedFileInfo: EncryptedFileInfo?, + newAttachmentAttributes: NewAttachmentAttributes + ) { localEchoRepository.updateEcho(eventId) { _, event -> val messageContent: MessageContent? = event.asDomain().content.toModel() val updatedContent = when (messageContent) { is MessageImageContent -> messageContent.update(url, encryptedFileInfo, newAttachmentAttributes) is MessageVideoContent -> messageContent.update(url, encryptedFileInfo, thumbnailUrl, thumbnailEncryptedFileInfo, newAttachmentAttributes) - is MessageFileContent -> messageContent.update(url, encryptedFileInfo, newAttachmentAttributes.newFileSize) + is MessageFileContent -> messageContent.update(url, encryptedFileInfo, newAttachmentAttributes.newFileSize) is MessageAudioContent -> messageContent.update(url, encryptedFileInfo, newAttachmentAttributes.newFileSize) - else -> messageContent + else -> messageContent } event.content = ContentMapper.map(updatedContent.toContent()) } @@ -419,9 +423,11 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter params.localEchoIds.forEach { function.invoke(it.eventId) } } - private fun MessageImageContent.update(url: String, - encryptedFileInfo: EncryptedFileInfo?, - newAttachmentAttributes: NewAttachmentAttributes?): MessageImageContent { + private fun MessageImageContent.update( + url: String, + encryptedFileInfo: EncryptedFileInfo?, + newAttachmentAttributes: NewAttachmentAttributes? + ): MessageImageContent { return copy( url = if (encryptedFileInfo == null) url else null, encryptedFileInfo = encryptedFileInfo?.copy(url = url), @@ -433,11 +439,13 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter ) } - private fun MessageVideoContent.update(url: String, - encryptedFileInfo: EncryptedFileInfo?, - thumbnailUrl: String?, - thumbnailEncryptedFileInfo: EncryptedFileInfo?, - newAttachmentAttributes: NewAttachmentAttributes?): MessageVideoContent { + private fun MessageVideoContent.update( + url: String, + encryptedFileInfo: EncryptedFileInfo?, + thumbnailUrl: String?, + thumbnailEncryptedFileInfo: EncryptedFileInfo?, + newAttachmentAttributes: NewAttachmentAttributes? + ): MessageVideoContent { return copy( url = if (encryptedFileInfo == null) url else null, encryptedFileInfo = encryptedFileInfo?.copy(url = url), @@ -451,9 +459,11 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter ) } - private fun MessageFileContent.update(url: String, - encryptedFileInfo: EncryptedFileInfo?, - size: Long): MessageFileContent { + private fun MessageFileContent.update( + url: String, + encryptedFileInfo: EncryptedFileInfo?, + size: Long + ): MessageFileContent { return copy( url = if (encryptedFileInfo == null) url else null, encryptedFileInfo = encryptedFileInfo?.copy(url = url), @@ -461,9 +471,11 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter ) } - private fun MessageAudioContent.update(url: String, - encryptedFileInfo: EncryptedFileInfo?, - size: Long): MessageAudioContent { + private fun MessageAudioContent.update( + url: String, + encryptedFileInfo: EncryptedFileInfo?, + size: Long + ): MessageAudioContent { return copy( url = if (encryptedFileInfo == null) url else null, encryptedFileInfo = encryptedFileInfo?.copy(url = url), diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/VideoCompressor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/VideoCompressor.kt index a43f8abf33..5c00927e23 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/VideoCompressor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/VideoCompressor.kt @@ -32,8 +32,10 @@ internal class VideoCompressor @Inject constructor( private val temporaryFileCreator: TemporaryFileCreator ) { - suspend fun compress(videoFile: File, - progressListener: ProgressListener?): VideoCompressionResult { + suspend fun compress( + videoFile: File, + progressListener: ProgressListener? + ): VideoCompressionResult { val destinationFile = temporaryFileCreator.create() val job = Job() @@ -111,7 +113,7 @@ internal class VideoCompressor @Inject constructor( deleteFile(destinationFile) VideoCompressionResult.CompressionNotNeeded } - else -> { + else -> { // Should not happen... // Delete now the temporary file deleteFile(destinationFile) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/ContentScannerModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/ContentScannerModule.kt index 7ea74225cd..89b5c44ef0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/ContentScannerModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/ContentScannerModule.kt @@ -49,9 +49,11 @@ internal abstract class ContentScannerModule { @Provides @ContentScannerDatabase @SessionScope - fun providesContentScannerRealmConfiguration(realmKeysUtils: RealmKeysUtils, - @SessionFilesDirectory directory: File, - @UserMd5 userMd5: String): RealmConfiguration { + fun providesContentScannerRealmConfiguration( + realmKeysUtils: RealmKeysUtils, + @SessionFilesDirectory directory: File, + @UserMd5 userMd5: String + ): RealmConfiguration { return RealmConfiguration.Builder() .directory(directory) .name("matrix-sdk-content-scanning.realm") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerEntityQueries.kt index e4b64a1a0e..bb3051bc96 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerEntityQueries.kt @@ -31,10 +31,12 @@ internal fun ContentScanResultEntity.Companion.get(realm: Realm, attachmentUrl: .findFirst() } -internal fun ContentScanResultEntity.Companion.getOrCreate(realm: Realm, - attachmentUrl: String, - contentScannerUrl: String?, - currentTimeMillis: Long): ContentScanResultEntity { +internal fun ContentScanResultEntity.Companion.getOrCreate( + realm: Realm, + attachmentUrl: String, + contentScannerUrl: String?, + currentTimeMillis: Long +): ContentScanResultEntity { return ContentScanResultEntity.get(realm, attachmentUrl, contentScannerUrl) ?: realm.createObject().also { it.mediaUrl = attachmentUrl diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/RealmContentScannerStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/RealmContentScannerStore.kt index 27729d38c7..72dc15c1bd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/RealmContentScannerStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/RealmContentScannerStore.kt @@ -106,7 +106,7 @@ internal class RealmContentScannerStore @Inject constructor( ScanState.IN_PROGRESS, ScanState.TRUSTED, ScanState.INFECTED -> true - else -> false + else -> false } } return isKnown diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt index 0db6812609..488c61206b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt @@ -49,8 +49,10 @@ internal interface DirectoryAPI { * @param body the body containing the new directory visibility */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/list/room/{roomId}") - suspend fun setRoomDirectoryVisibility(@Path("roomId") roomId: String, - @Body body: RoomDirectoryVisibilityJson) + suspend fun setRoomDirectoryVisibility( + @Path("roomId") roomId: String, + @Body body: RoomDirectoryVisibilityJson + ) /** * Add alias to the room. @@ -58,8 +60,10 @@ internal interface DirectoryAPI { * @param body the Json body */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/room/{roomAlias}") - suspend fun addRoomAlias(@Path("roomAlias") roomAlias: String, - @Body body: AddRoomAliasBody) + suspend fun addRoomAlias( + @Path("roomAlias") roomAlias: String, + @Body body: AddRoomAliasBody + ) /** * Delete a room alias. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/download/ProgressResponseBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/download/ProgressResponseBody.kt index 4fd4fda7d1..4e0096b7dd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/download/ProgressResponseBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/download/ProgressResponseBody.kt @@ -27,7 +27,8 @@ import okio.buffer internal class ProgressResponseBody( private val responseBody: ResponseBody, private val chainUrl: String, - private val progressListener: ProgressListener) : ResponseBody() { + private val progressListener: ProgressListener +) : ResponseBody() { private var bufferedSource: BufferedSource? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/DefaultFilterService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/DefaultFilterService.kt index 9a16b8fd4a..2e68d02d8c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/DefaultFilterService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/DefaultFilterService.kt @@ -21,8 +21,10 @@ import org.matrix.android.sdk.internal.task.TaskExecutor import org.matrix.android.sdk.internal.task.configureWith import javax.inject.Inject -internal class DefaultFilterService @Inject constructor(private val saveFilterTask: SaveFilterTask, - private val taskExecutor: TaskExecutor) : FilterService { +internal class DefaultFilterService @Inject constructor( + private val saveFilterTask: SaveFilterTask, + private val taskExecutor: TaskExecutor +) : FilterService { // TODO Pass a list of support events instead override fun setFilter(filterPreset: FilterService.FilterPreset) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt index d1df77d14a..ac1e9a654c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt @@ -31,8 +31,10 @@ internal interface FilterApi { * @param body the Json representation of a FilterBody object */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/filter") - suspend fun uploadFilter(@Path("userId") userId: String, - @Body body: Filter): FilterResponse + suspend fun uploadFilter( + @Path("userId") userId: String, + @Body body: Filter + ): FilterResponse /** * Gets a filter with a given filterId from the homeserver. @@ -42,6 +44,8 @@ internal interface FilterApi { * @return Filter */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/filter/{filterId}") - suspend fun getFilterById(@Path("userId") userId: String, - @Path("filterId") filterId: String): Filter + suspend fun getFilterById( + @Path("userId") userId: String, + @Path("filterId") filterId: String + ): Filter } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt index e9d5b876a8..63afa1bbbc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt @@ -45,7 +45,7 @@ internal class DefaultSaveFilterTask @Inject constructor( FilterService.FilterPreset.ElementFilter -> { FilterFactory.createElementFilter() } - FilterService.FilterPreset.NoFilter -> { + FilterService.FilterPreset.NoFilter -> { FilterFactory.createDefaultFilter() } } @@ -53,7 +53,7 @@ internal class DefaultSaveFilterTask @Inject constructor( FilterService.FilterPreset.ElementFilter -> { FilterFactory.createElementRoomFilter() } - FilterService.FilterPreset.NoFilter -> { + FilterService.FilterPreset.NoFilter -> { FilterFactory.createDefaultRoomFilter() } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/DefaultGroup.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/DefaultGroup.kt index 4f610fd81b..9c37d4db6c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/DefaultGroup.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/DefaultGroup.kt @@ -18,8 +18,10 @@ package org.matrix.android.sdk.internal.session.group import org.matrix.android.sdk.api.session.group.Group -internal class DefaultGroup(override val groupId: String, - private val getGroupDataTask: GetGroupDataTask) : Group { +internal class DefaultGroup( + override val groupId: String, + private val getGroupDataTask: GetGroupDataTask +) : Group { override suspend fun fetchGroupData() { val params = GetGroupDataTask.Params.FetchWithIds(listOf(groupId)) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataTask.kt index 4e0ee3422b..235291d061 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataTask.kt @@ -58,7 +58,7 @@ internal class DefaultGetGroupDataTask @Inject constructor( is GetGroupDataTask.Params.FetchAllActive -> { getActiveGroupIds() } - is GetGroupDataTask.Params.FetchWithIds -> { + is GetGroupDataTask.Params.FetchWithIds -> { params.groupIds } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt index b1a518724c..d22da8f6f2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt @@ -109,10 +109,12 @@ internal class DefaultGetHomeServerCapabilitiesTask @Inject constructor( insertInDb(capabilities, mediaConfig, versions, wellknownResult) } - private suspend fun insertInDb(getCapabilitiesResult: GetCapabilitiesResult?, - getMediaConfigResult: GetMediaConfigResult?, - getVersionResult: Versions?, - getWellknownResult: WellknownResult?) { + private suspend fun insertInDb( + getCapabilitiesResult: GetCapabilitiesResult?, + getMediaConfigResult: GetMediaConfigResult?, + getVersionResult: Versions?, + getWellknownResult: WellknownResult? + ) { monarchy.awaitTransaction { realm -> val homeServerCapabilitiesEntity = HomeServerCapabilitiesEntity.getOrCreate(realm) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/HomeServerPinger.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/HomeServerPinger.kt index 70e1e551aa..a3d6b7fa49 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/HomeServerPinger.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/HomeServerPinger.kt @@ -22,8 +22,10 @@ import org.matrix.android.sdk.internal.network.executeRequest import org.matrix.android.sdk.internal.task.TaskExecutor import javax.inject.Inject -internal class HomeServerPinger @Inject constructor(private val taskExecutor: TaskExecutor, - private val capabilitiesAPI: CapabilitiesAPI) { +internal class HomeServerPinger @Inject constructor( + private val taskExecutor: TaskExecutor, + private val capabilitiesAPI: CapabilitiesAPI +) { fun canReachHomeServer(callback: (Boolean) -> Unit) { taskExecutor.executorScope.launch { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/DefaultIdentityService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/DefaultIdentityService.kt index 74838afc65..30c7773a8e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/DefaultIdentityService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/DefaultIdentityService.kt @@ -283,8 +283,8 @@ internal class DefaultIdentityService @Inject constructor( identityStore.setToken(null) lookUpInternal(false, threePids) } - throwable.isTermsNotSigned() -> throw IdentityServiceError.TermsNotSignedException - else -> throw throwable + throwable.isTermsNotSigned() -> throw IdentityServiceError.TermsNotSignedException + else -> throw throwable } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt index aef86ed08e..7b04bc52b0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt @@ -95,8 +95,10 @@ internal interface IdentityAPI { * - https://matrix.org/docs/spec/identity_service/latest#post-matrix-identity-v2-validate-email-submittoken */ @POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "validate/{medium}/submitToken") - suspend fun submitToken(@Path("medium") medium: String, - @Body body: IdentityRequestOwnershipParams): SuccessResult + suspend fun submitToken( + @Path("medium") medium: String, + @Body body: IdentityRequestOwnershipParams + ): SuccessResult /** * https://matrix.org/docs/spec/identity_service/r0.3.0#post-matrix-identity-v2-sign-ed25519. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityBulkLookupTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityBulkLookupTask.kt index f642ed4cf2..21b59cca9d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityBulkLookupTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityBulkLookupTask.kt @@ -75,10 +75,12 @@ internal class DefaultIdentityBulkLookupTask @Inject constructor( val identityLookUpResponse: IdentityLookUpResponse ) - private suspend fun lookUpInternal(identityAPI: IdentityAPI, - threePids: List, - hashDetailResponse: IdentityHashDetailResponse, - canRetry: Boolean): LookUpData { + private suspend fun lookUpInternal( + identityAPI: IdentityAPI, + threePids: List, + hashDetailResponse: IdentityHashDetailResponse, + canRetry: Boolean + ): LookUpData { val hashedAddresses = getHashedAddresses(threePids, hashDetailResponse.pepper) return try { LookUpData(hashedAddresses, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityModule.kt index 4e9d7dc7f7..464ae96e3a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityModule.kt @@ -47,8 +47,10 @@ internal abstract class IdentityModule { @Provides @SessionScope @AuthenticatedIdentity - fun providesOkHttpClient(@UnauthenticatedWithCertificate okHttpClient: OkHttpClient, - @AuthenticatedIdentity accessTokenProvider: AccessTokenProvider): OkHttpClient { + fun providesOkHttpClient( + @UnauthenticatedWithCertificate okHttpClient: OkHttpClient, + @AuthenticatedIdentity accessTokenProvider: AccessTokenProvider + ): OkHttpClient { return okHttpClient .newBuilder() .addAccessTokenInterceptor(accessTokenProvider) @@ -59,10 +61,12 @@ internal abstract class IdentityModule { @Provides @IdentityDatabase @SessionScope - fun providesIdentityRealmConfiguration(realmKeysUtils: RealmKeysUtils, - realmIdentityStoreMigration: RealmIdentityStoreMigration, - @SessionFilesDirectory directory: File, - @UserMd5 userMd5: String): RealmConfiguration { + fun providesIdentityRealmConfiguration( + realmKeysUtils: RealmKeysUtils, + realmIdentityStoreMigration: RealmIdentityStoreMigration, + @SessionFilesDirectory directory: File, + @UserMd5 userMd5: String + ): RealmConfiguration { return RealmConfiguration.Builder() .directory(directory) .name("matrix-sdk-identity.realm") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityRequestTokenForBindingTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityRequestTokenForBindingTask.kt index fe12309650..02462387fa 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityRequestTokenForBindingTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityRequestTokenForBindingTask.kt @@ -57,7 +57,7 @@ internal class DefaultIdentityRequestTokenForBindingTask @Inject constructor( val tokenResponse = executeRequest(null) { when (params.threePid) { - is ThreePid.Email -> identityAPI.requestTokenToBindEmail( + is ThreePid.Email -> identityAPI.requestTokenToBindEmail( IdentityRequestTokenForEmailBody( clientSecret = clientSecret, sendAttempt = sendAttempt, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt index aecf21678c..08e5b43977 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt @@ -32,8 +32,10 @@ private fun IdentityDataEntity.Companion.getOrCreate(realm: Realm): IdentityData return get(realm) ?: realm.createObject() } -internal fun IdentityDataEntity.Companion.setUrl(realm: Realm, - url: String?) { +internal fun IdentityDataEntity.Companion.setUrl( + realm: Realm, + url: String? +) { realm.where().findAll().deleteAllFromRealm() // Delete all pending binding if any IdentityPendingBindingEntity.deleteAll(realm) @@ -45,23 +47,29 @@ internal fun IdentityDataEntity.Companion.setUrl(realm: Realm, } } -internal fun IdentityDataEntity.Companion.setToken(realm: Realm, - newToken: String?) { +internal fun IdentityDataEntity.Companion.setToken( + realm: Realm, + newToken: String? +) { get(realm)?.apply { token = newToken } } -internal fun IdentityDataEntity.Companion.setUserConsent(realm: Realm, - newConsent: Boolean) { +internal fun IdentityDataEntity.Companion.setUserConsent( + realm: Realm, + newConsent: Boolean +) { get(realm)?.apply { userConsent = newConsent } } -internal fun IdentityDataEntity.Companion.setHashDetails(realm: Realm, - pepper: String, - algorithms: List) { +internal fun IdentityDataEntity.Companion.setHashDetails( + realm: Realm, + pepper: String, + algorithms: List +) { get(realm)?.apply { hashLookupPepper = pepper hashLookupAlgorithm = RealmList().apply { addAll(algorithms) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/Extensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/Extensions.kt deleted file mode 100644 index b40b1a56bf..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/Extensions.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2021 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.session.initsync - -import org.matrix.android.sdk.api.session.initsync.InitSyncStep - -internal inline fun reportSubtask(reporter: ProgressReporter?, - initSyncStep: InitSyncStep, - totalProgress: Int, - parentWeight: Float, - block: () -> T): T { - reporter?.startTask(initSyncStep, totalProgress, parentWeight) - return block().also { - reporter?.endTask() - } -} - -internal inline fun Map.mapWithProgress(reporter: ProgressReporter?, - initSyncStep: InitSyncStep, - parentWeight: Float, - transform: (Map.Entry) -> R): List { - var current = 0F - reporter?.startTask(initSyncStep, count() + 1, parentWeight) - return map { - reporter?.reportProgress(current) - current++ - transform.invoke(it) - }.also { - reporter?.endTask() - } -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt index 8034e5b974..7588037b46 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt @@ -54,11 +54,13 @@ import javax.inject.Inject * */ @SessionScope -internal class IntegrationManager @Inject constructor(matrixConfiguration: MatrixConfiguration, - @SessionDatabase private val monarchy: Monarchy, - private val updateUserAccountDataTask: UpdateUserAccountDataTask, - private val accountDataDataSource: UserAccountDataDataSource, - private val widgetFactory: WidgetFactory) : +internal class IntegrationManager @Inject constructor( + matrixConfiguration: MatrixConfiguration, + @SessionDatabase private val monarchy: Monarchy, + private val updateUserAccountDataTask: UpdateUserAccountDataTask, + private val accountDataDataSource: UserAccountDataDataSource, + private val widgetFactory: WidgetFactory +) : SessionLifecycleObserver { private val currentConfigs = ArrayList() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/GetPreviewUrlTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/GetPreviewUrlTask.kt index 32bcf3f7ca..a31f0d6065 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/GetPreviewUrlTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/GetPreviewUrlTask.kt @@ -48,8 +48,8 @@ internal class DefaultGetPreviewUrlTask @Inject constructor( override suspend fun execute(params: GetPreviewUrlTask.Params): PreviewUrlData { return when (params.cacheStrategy) { - CacheStrategy.NoCache -> doRequest(params.url, params.timestamp) - is CacheStrategy.TtlCache -> doRequestWithCache( + CacheStrategy.NoCache -> doRequest(params.url, params.timestamp) + is CacheStrategy.TtlCache -> doRequestWithCache( params.url, params.timestamp, params.cacheStrategy.validityDurationInMillis, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/GetOpenIdTokenTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/GetOpenIdTokenTask.kt index a6ad025b8d..5ab6aca88c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/GetOpenIdTokenTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/GetOpenIdTokenTask.kt @@ -28,7 +28,8 @@ internal interface GetOpenIdTokenTask : Task internal class DefaultGetOpenIdTokenTask @Inject constructor( @UserId private val userId: String, private val openIdAPI: OpenIdAPI, - private val globalErrorReceiver: GlobalErrorReceiver) : GetOpenIdTokenTask { + private val globalErrorReceiver: GlobalErrorReceiver +) : GetOpenIdTokenTask { override suspend fun execute(params: Unit): OpenIdToken { return executeRequest(globalErrorReceiver) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/OpenIdAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/OpenIdAPI.kt index c3caaefdec..180ecbb1a3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/OpenIdAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/openid/OpenIdAPI.kt @@ -35,6 +35,8 @@ internal interface OpenIdAPI { * @param body an empty json body */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/openid/request_token") - suspend fun openIdToken(@Path("userId") userId: String, - @Body body: JsonDict = emptyMap()): OpenIdToken + suspend fun openIdToken( + @Path("userId") userId: String, + @Body body: JsonDict = emptyMap() + ): OpenIdToken } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt index f9da7b66f6..8e20199135 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt @@ -44,15 +44,15 @@ internal class PermalinkFactory @Inject constructor( fun createPermalink(id: String, forceMatrixTo: Boolean): String? { return when { - id.isEmpty() -> null + id.isEmpty() -> null !useClientFormat(forceMatrixTo) -> MATRIX_TO_URL_BASE + escape(id) - else -> { + else -> { buildString { append(matrixConfiguration.clientPermalinkBaseUrl) when { MatrixPatterns.isRoomId(id) || MatrixPatterns.isRoomAlias(id) -> append(ROOM_PATH) - MatrixPatterns.isUserId(id) -> append(USER_PATH) - MatrixPatterns.isGroupId(id) -> append(GROUP_PATH) + MatrixPatterns.isUserId(id) -> append(USER_PATH) + MatrixPatterns.isGroupId(id) -> append(GROUP_PATH) } append(escape(id)) } @@ -94,16 +94,16 @@ internal class PermalinkFactory @Inject constructor( fun getLinkedId(url: String): String? { val clientBaseUrl = matrixConfiguration.clientPermalinkBaseUrl return when { - url.startsWith(MATRIX_TO_URL_BASE) -> url.substring(MATRIX_TO_URL_BASE.length) + url.startsWith(MATRIX_TO_URL_BASE) -> url.substring(MATRIX_TO_URL_BASE.length) clientBaseUrl != null && url.startsWith(clientBaseUrl) -> { when (PermalinkParser.parse(url)) { is PermalinkData.GroupLink -> url.substring(clientBaseUrl.length + GROUP_PATH.length) - is PermalinkData.RoomLink -> url.substring(clientBaseUrl.length + ROOM_PATH.length) - is PermalinkData.UserLink -> url.substring(clientBaseUrl.length + USER_PATH.length) - else -> null + is PermalinkData.RoomLink -> url.substring(clientBaseUrl.length + ROOM_PATH.length) + is PermalinkData.UserLink -> url.substring(clientBaseUrl.length + USER_PATH.length) + else -> null } } - else -> null + else -> null } ?.substringBeforeLast("?") } @@ -111,7 +111,7 @@ internal class PermalinkFactory @Inject constructor( fun createMentionSpanTemplate(type: PermalinkService.SpanTemplateType, forceMatrixTo: Boolean): String { return buildString { when (type) { - HTML -> append(MENTION_SPAN_TO_HTML_TEMPLATE_BEGIN) + HTML -> append(MENTION_SPAN_TO_HTML_TEMPLATE_BEGIN) MARKDOWN -> append(MENTION_SPAN_TO_MD_TEMPLATE_BEGIN) } append(baseUrl(forceMatrixTo)) @@ -119,7 +119,7 @@ internal class PermalinkFactory @Inject constructor( append(USER_PATH) } when (type) { - HTML -> append(MENTION_SPAN_TO_HTML_TEMPLATE_END) + HTML -> append(MENTION_SPAN_TO_HTML_TEMPLATE_END) MARKDOWN -> append(MENTION_SPAN_TO_MD_TEMPLATE_END) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/PresenceAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/PresenceAPI.kt index 53d0d5e963..4af0307cb5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/PresenceAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/PresenceAPI.kt @@ -31,8 +31,10 @@ internal interface PresenceAPI { * Ref: https://matrix.org/docs/spec/client_server/latest#put-matrix-client-r0-presence-userid-status */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "presence/{userId}/status") - suspend fun setPresence(@Path("userId") userId: String, - @Body body: SetPresenceBody) + suspend fun setPresence( + @Path("userId") userId: String, + @Body body: SetPresenceBody + ) /** * Get the given user's presence state. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AddThreePidTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AddThreePidTask.kt index 678d399428..4a6cb6c019 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AddThreePidTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AddThreePidTask.kt @@ -37,11 +37,12 @@ internal class DefaultAddThreePidTask @Inject constructor( private val profileAPI: ProfileAPI, @SessionDatabase private val monarchy: Monarchy, private val pendingThreePidMapper: PendingThreePidMapper, - private val globalErrorReceiver: GlobalErrorReceiver) : AddThreePidTask() { + private val globalErrorReceiver: GlobalErrorReceiver +) : AddThreePidTask() { override suspend fun execute(params: Params) { when (params.threePid) { - is ThreePid.Email -> addEmail(params.threePid) + is ThreePid.Email -> addEmail(params.threePid) is ThreePid.Msisdn -> addMsisdn(params.threePid) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/BindThreePidsTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/BindThreePidsTask.kt index f630c2c225..5e892b32c3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/BindThreePidsTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/BindThreePidsTask.kt @@ -33,11 +33,12 @@ internal abstract class BindThreePidsTask : Task ) } -internal class DefaultBindThreePidsTask @Inject constructor(private val profileAPI: ProfileAPI, - private val identityStore: IdentityStore, - @AuthenticatedIdentity - private val accessTokenProvider: AccessTokenProvider, - private val globalErrorReceiver: GlobalErrorReceiver) : BindThreePidsTask() { +internal class DefaultBindThreePidsTask @Inject constructor( + private val profileAPI: ProfileAPI, + private val identityStore: IdentityStore, + @AuthenticatedIdentity private val accessTokenProvider: AccessTokenProvider, + private val globalErrorReceiver: GlobalErrorReceiver +) : BindThreePidsTask() { override suspend fun execute(params: Params) { val identityServerUrlWithoutProtocol = identityStore.getIdentityServerUrlWithoutProtocol() ?: throw IdentityServiceError.NoIdentityServerConfigured val identityServerAccessToken = accessTokenProvider.getToken() ?: throw IdentityServiceError.NoIdentityServerConfigured diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DefaultProfileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DefaultProfileService.kt index 5e64a6af0e..0776569661 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DefaultProfileService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DefaultProfileService.kt @@ -38,20 +38,22 @@ import org.matrix.android.sdk.internal.task.TaskExecutor import org.matrix.android.sdk.internal.task.configureWith import javax.inject.Inject -internal class DefaultProfileService @Inject constructor(private val taskExecutor: TaskExecutor, - @SessionDatabase private val monarchy: Monarchy, - private val coroutineDispatchers: MatrixCoroutineDispatchers, - private val refreshUserThreePidsTask: RefreshUserThreePidsTask, - private val getProfileInfoTask: GetProfileInfoTask, - private val setDisplayNameTask: SetDisplayNameTask, - private val setAvatarUrlTask: SetAvatarUrlTask, - private val addThreePidTask: AddThreePidTask, - private val validateSmsCodeTask: ValidateSmsCodeTask, - private val finalizeAddingThreePidTask: FinalizeAddingThreePidTask, - private val deleteThreePidTask: DeleteThreePidTask, - private val pendingThreePidMapper: PendingThreePidMapper, - private val userStore: UserStore, - private val fileUploader: FileUploader) : ProfileService { +internal class DefaultProfileService @Inject constructor( + private val taskExecutor: TaskExecutor, + @SessionDatabase private val monarchy: Monarchy, + private val coroutineDispatchers: MatrixCoroutineDispatchers, + private val refreshUserThreePidsTask: RefreshUserThreePidsTask, + private val getProfileInfoTask: GetProfileInfoTask, + private val setDisplayNameTask: SetDisplayNameTask, + private val setAvatarUrlTask: SetAvatarUrlTask, + private val addThreePidTask: AddThreePidTask, + private val validateSmsCodeTask: ValidateSmsCodeTask, + private val finalizeAddingThreePidTask: FinalizeAddingThreePidTask, + private val deleteThreePidTask: DeleteThreePidTask, + private val pendingThreePidMapper: PendingThreePidMapper, + private val userStore: UserStore, + private val fileUploader: FileUploader +) : ProfileService { override suspend fun getDisplayName(userId: String): Optional { val params = GetProfileInfoTask.Params(userId) @@ -132,8 +134,10 @@ internal class DefaultProfileService @Inject constructor(private val taskExecuto validateSmsCodeTask.execute(ValidateSmsCodeTask.Params(threePid, code)) } - override suspend fun finalizeAddingThreePid(threePid: ThreePid, - userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor) { + override suspend fun finalizeAddingThreePid( + threePid: ThreePid, + userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor + ) { finalizeAddingThreePidTask .execute( FinalizeAddingThreePidTask.Params( @@ -165,8 +169,8 @@ internal class DefaultProfileService @Inject constructor(private val taskExecuto private fun UserThreePidEntity.asDomain(): ThreePid { return when (medium) { - ThirdPartyIdentifier.MEDIUM_EMAIL -> ThreePid.Email(address) + ThirdPartyIdentifier.MEDIUM_EMAIL -> ThreePid.Email(address) ThirdPartyIdentifier.MEDIUM_MSISDN -> ThreePid.Msisdn(address) - else -> error("Invalid medium type") + else -> error("Invalid medium type") } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DeleteThreePidTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DeleteThreePidTask.kt index 7b7617aa80..a8047a0118 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DeleteThreePidTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/DeleteThreePidTask.kt @@ -31,7 +31,8 @@ internal abstract class DeleteThreePidTask : Task -internal class DefaultRefreshUserThreePidsTask @Inject constructor(private val profileAPI: ProfileAPI, - @SessionDatabase private val monarchy: Monarchy, - private val globalErrorReceiver: GlobalErrorReceiver) : RefreshUserThreePidsTask() { +internal class DefaultRefreshUserThreePidsTask @Inject constructor( + private val profileAPI: ProfileAPI, + @SessionDatabase private val monarchy: Monarchy, + private val globalErrorReceiver: GlobalErrorReceiver +) : RefreshUserThreePidsTask() { override suspend fun execute(params: Unit) { val accountThreePidsResponse = executeRequest(globalErrorReceiver) { @@ -55,9 +57,9 @@ internal class DefaultRefreshUserThreePidsTask @Inject constructor(private val p private fun Any?.toLong(): Long { return when (this) { - null -> 0L - is Long -> this + null -> 0L + is Long -> this is Double -> this.toLong() - else -> 0L + else -> 0L } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetAvatarUrlTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetAvatarUrlTask.kt index a7d116d919..80282a894b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetAvatarUrlTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetAvatarUrlTask.kt @@ -30,7 +30,8 @@ internal abstract class SetAvatarUrlTask : Task { internal class DefaultSetAvatarUrlTask @Inject constructor( private val profileAPI: ProfileAPI, - private val globalErrorReceiver: GlobalErrorReceiver) : SetAvatarUrlTask() { + private val globalErrorReceiver: GlobalErrorReceiver +) : SetAvatarUrlTask() { override suspend fun execute(params: Params) { val body = SetAvatarUrlBody( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetDisplayNameTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetDisplayNameTask.kt index 61d3042310..e3f04792b6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetDisplayNameTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/SetDisplayNameTask.kt @@ -30,7 +30,8 @@ internal abstract class SetDisplayNameTask : Task Result.retry() - else -> Result.failure() + else -> Result.failure() } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultConditionResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultConditionResolver.kt index 67fba390d0..ace5ee0b9a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultConditionResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultConditionResolver.kt @@ -34,18 +34,24 @@ internal class DefaultConditionResolver @Inject constructor( @UserId private val userId: String ) : ConditionResolver { - override fun resolveEventMatchCondition(event: Event, - condition: EventMatchCondition): Boolean { + override fun resolveEventMatchCondition( + event: Event, + condition: EventMatchCondition + ): Boolean { return condition.isSatisfied(event) } - override fun resolveRoomMemberCountCondition(event: Event, - condition: RoomMemberCountCondition): Boolean { + override fun resolveRoomMemberCountCondition( + event: Event, + condition: RoomMemberCountCondition + ): Boolean { return condition.isSatisfied(event, roomGetter) } - override fun resolveSenderNotificationPermissionCondition(event: Event, - condition: SenderNotificationPermissionCondition): Boolean { + override fun resolveSenderNotificationPermissionCondition( + event: Event, + condition: SenderNotificationPermissionCondition + ): Boolean { val roomId = event.roomId ?: return false val room = roomGetter.getRoom(roomId) ?: return false @@ -57,8 +63,10 @@ internal class DefaultConditionResolver @Inject constructor( return condition.isSatisfied(event, powerLevelsContent) } - override fun resolveContainsDisplayNameCondition(event: Event, - condition: ContainsDisplayNameCondition): Boolean { + override fun resolveContainsDisplayNameCondition( + event: Event, + condition: ContainsDisplayNameCondition + ): Boolean { val roomId = event.roomId ?: return false val room = roomGetter.getRoom(roomId) ?: return false val myDisplayName = room.membershipService().getRoomMember(userId)?.displayName ?: return false diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultPushersService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultPushersService.kt index 9437550d7a..e912d9ccf8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultPushersService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/DefaultPushersService.kt @@ -46,10 +46,12 @@ internal class DefaultPushersService @Inject constructor( private val taskExecutor: TaskExecutor ) : PushersService { - override suspend fun testPush(url: String, - appId: String, - pushkey: String, - eventId: String) { + override suspend fun testPush( + url: String, + appId: String, + pushkey: String, + eventId: String + ) { pushGatewayNotifyTask.execute(PushGatewayNotifyTask.Params(url, appId, pushkey, eventId)) } @@ -79,12 +81,14 @@ internal class DefaultPushersService @Inject constructor( append = append ) - override suspend fun addEmailPusher(email: String, - lang: String, - emailBranding: String, - appDisplayName: String, - deviceDisplayName: String, - append: Boolean) { + override suspend fun addEmailPusher( + email: String, + lang: String, + emailBranding: String, + appDisplayName: String, + deviceDisplayName: String, + append: Boolean + ) { addPusherTask.execute( AddPusherTask.Params( JsonPusher( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt index fbae04a1f1..1b316c7872 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt @@ -38,9 +38,11 @@ internal interface PushRulesApi { * @param enabledBody the new enable status */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}/enabled") - suspend fun updateEnableRuleStatus(@Path("kind") kind: String, - @Path("ruleId") ruleId: String, - @Body enabledBody: EnabledBody) + suspend fun updateEnableRuleStatus( + @Path("kind") kind: String, + @Path("ruleId") ruleId: String, + @Body enabledBody: EnabledBody + ) /** * Update the ruleID action. @@ -51,9 +53,11 @@ internal interface PushRulesApi { * @param actions the actions */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}/actions") - suspend fun updateRuleActions(@Path("kind") kind: String, - @Path("ruleId") ruleId: String, - @Body actions: Any) + suspend fun updateRuleActions( + @Path("kind") kind: String, + @Path("ruleId") ruleId: String, + @Body actions: Any + ) /** * Delete a rule. @@ -62,8 +66,10 @@ internal interface PushRulesApi { * @param ruleId the ruleId */ @DELETE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}") - suspend fun deleteRule(@Path("kind") kind: String, - @Path("ruleId") ruleId: String) + suspend fun deleteRule( + @Path("kind") kind: String, + @Path("ruleId") ruleId: String + ) /** * Add the ruleID enable status. @@ -73,7 +79,9 @@ internal interface PushRulesApi { * @param rule the rule to add. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}") - suspend fun addRule(@Path("kind") kind: String, - @Path("ruleId") ruleId: String, - @Body rule: PushRule) + suspend fun addRule( + @Path("kind") kind: String, + @Path("ruleId") ruleId: String, + @Body rule: PushRule + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/RemovePusherTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/RemovePusherTask.kt index 057c309078..86ba33cb98 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/RemovePusherTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/RemovePusherTask.kt @@ -30,8 +30,10 @@ import org.matrix.android.sdk.internal.util.awaitTransaction import javax.inject.Inject internal interface RemovePusherTask : Task { - data class Params(val pushKey: String, - val pushAppId: String) + data class Params( + val pushKey: String, + val pushAppId: String + ) } internal class DefaultRemovePusherTask @Inject constructor( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/UpdatePushRuleEnableStatusTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/UpdatePushRuleEnableStatusTask.kt index 815661a1ce..a923f1932b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/UpdatePushRuleEnableStatusTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/UpdatePushRuleEnableStatusTask.kt @@ -23,9 +23,11 @@ import org.matrix.android.sdk.internal.task.Task import javax.inject.Inject internal interface UpdatePushRuleEnableStatusTask : Task { - data class Params(val kind: RuleKind, - val pushRule: PushRule, - val enabled: Boolean) + data class Params( + val kind: RuleKind, + val pushRule: PushRule, + val enabled: Boolean + ) } internal class DefaultUpdatePushRuleEnableStatusTask @Inject constructor( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushrules/ProcessEventForPushTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushrules/ProcessEventForPushTask.kt index 60c1194708..09d7d50ecb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushrules/ProcessEventForPushTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushrules/ProcessEventForPushTask.kt @@ -62,7 +62,7 @@ internal class DefaultProcessEventForPushTask @Inject constructor( EventType.REDACTION, EventType.ENCRYPTED, EventType.STATE_ROOM_MEMBER -> true - else -> false + else -> false } }.filter { it.senderId != userId diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomDirectoryService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomDirectoryService.kt index 7330c91c20..1edc4c1e66 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomDirectoryService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomDirectoryService.kt @@ -35,8 +35,10 @@ internal class DefaultRoomDirectoryService @Inject constructor( private val roomAliasAvailabilityChecker: RoomAliasAvailabilityChecker ) : RoomDirectoryService { - override suspend fun getPublicRooms(server: String?, - publicRoomsParams: PublicRoomsParams): PublicRoomsResponse { + override suspend fun getPublicRooms( + server: String?, + publicRoomsParams: PublicRoomsParams + ): PublicRoomsResponse { return getPublicRoomTask.execute(GetPublicRoomTask.Params(server, publicRoomsParams)) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt index 2edd8cc488..5e6d052443 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt @@ -94,8 +94,10 @@ internal class DefaultRoomService @Inject constructor( return roomSummaryDataSource.getRoomSummaryLive(roomId) } - override fun getRoomSummaries(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder): List { + override fun getRoomSummaries( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder + ): List { return roomSummaryDataSource.getRoomSummaries(queryParams, sortOrder) } @@ -119,14 +121,18 @@ internal class DefaultRoomService @Inject constructor( } } - override fun getRoomSummariesLive(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder): LiveData> { + override fun getRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder + ): LiveData> { return roomSummaryDataSource.getRoomSummariesLive(queryParams, sortOrder) } - override fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, - pagedListConfig: PagedList.Config, - sortOrder: RoomSortOrder): LiveData> { + override fun getPagedRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + pagedListConfig: PagedList.Config, + sortOrder: RoomSortOrder + ): LiveData> { return roomSummaryDataSource.getSortedPagedRoomSummariesLive(queryParams, pagedListConfig, sortOrder) } @@ -163,9 +169,11 @@ internal class DefaultRoomService @Inject constructor( joinRoomTask.execute(JoinRoomTask.Params(roomIdOrAlias, reason, viaServers)) } - override suspend fun joinRoom(roomId: String, - reason: String?, - thirdPartySigned: SignInvitationResult) { + override suspend fun joinRoom( + roomId: String, + reason: String?, + thirdPartySigned: SignInvitationResult + ) { joinRoomTask.execute(JoinRoomTask.Params(roomId, reason, thirdPartySigned = thirdPartySigned)) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt index 3efeef7688..bb43d90328 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt @@ -103,12 +103,12 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } val isLocalEcho = LocalEcho.isLocalEchoId(event.eventId ?: "") when (event.type) { - EventType.REACTION -> { + EventType.REACTION -> { // we got a reaction!! Timber.v("###REACTION in room $roomId , reaction eventID ${event.eventId}") handleReaction(realm, event, roomId, isLocalEcho) } - EventType.MESSAGE -> { + EventType.MESSAGE -> { if (event.unsignedData?.relations?.annotations != null) { Timber.v("###REACTION Aggregation in room $roomId for event ${event.eventId}") handleInitialAggregatedRelations(realm, event, roomId, event.unsignedData.relations.annotations) @@ -134,7 +134,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( EventType.KEY_VERIFICATION_START, EventType.KEY_VERIFICATION_MAC, EventType.KEY_VERIFICATION_READY, - EventType.KEY_VERIFICATION_KEY -> { + EventType.KEY_VERIFICATION_KEY -> { Timber.v("## SAS REF in room $roomId for event ${event.eventId}") event.content.toModel()?.relatesTo?.let { if (it.type == RelationType.REFERENCE && it.eventId != null) { @@ -143,7 +143,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } } - EventType.ENCRYPTED -> { + EventType.ENCRYPTED -> { // Relation type is in clear val encryptedEventContent = event.content.toModel() if (encryptedEventContent?.relatesTo?.type == RelationType.REPLACE || @@ -168,20 +168,20 @@ internal class EventRelationsAggregationProcessor @Inject constructor( EventType.KEY_VERIFICATION_START, EventType.KEY_VERIFICATION_MAC, EventType.KEY_VERIFICATION_READY, - EventType.KEY_VERIFICATION_KEY -> { + EventType.KEY_VERIFICATION_KEY -> { Timber.v("## SAS REF in room $roomId for event ${event.eventId}") encryptedEventContent.relatesTo.eventId?.let { handleVerification(realm, event, roomId, isLocalEcho, it) } } - in EventType.POLL_RESPONSE -> { + in EventType.POLL_RESPONSE -> { event.getClearContent().toModel(catchError = true)?.let { sessionManager.getSessionComponent(sessionId)?.session()?.let { session -> pollAggregationProcessor.handlePollResponseEvent(session, realm, event) } } } - in EventType.POLL_END -> { + in EventType.POLL_END -> { sessionManager.getSessionComponent(sessionId)?.session()?.let { session -> getPowerLevelsHelper(event.roomId)?.let { pollAggregationProcessor.handlePollEndEvent(session, it, realm, event) @@ -211,11 +211,11 @@ internal class EventRelationsAggregationProcessor @Inject constructor( // } // } } - EventType.REDACTION -> { + EventType.REDACTION -> { val eventToPrune = event.redacts?.let { EventEntity.where(realm, eventId = it).findFirst() } ?: return when (eventToPrune.type) { - EventType.MESSAGE -> { + EventType.MESSAGE -> { Timber.d("REDACTION for message ${eventToPrune.eventId}") // val unsignedData = EventMapper.map(eventToPrune).unsignedData // ?: UnsignedData(null, null) @@ -231,7 +231,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } } } - in EventType.POLL_START -> { + in EventType.POLL_START -> { val content: MessagePollContent? = event.content.toModel() if (content?.relatesTo?.type == RelationType.REPLACE) { Timber.v("###REPLACE in room $roomId for event ${event.eventId}") @@ -239,14 +239,14 @@ internal class EventRelationsAggregationProcessor @Inject constructor( handleReplace(realm, event, content, roomId, isLocalEcho) } } - in EventType.POLL_RESPONSE -> { + in EventType.POLL_RESPONSE -> { event.content.toModel(catchError = true)?.let { sessionManager.getSessionComponent(sessionId)?.session()?.let { session -> pollAggregationProcessor.handlePollResponseEvent(session, realm, event) } } } - in EventType.POLL_END -> { + in EventType.POLL_END -> { sessionManager.getSessionComponent(sessionId)?.session()?.let { session -> getPowerLevelsHelper(event.roomId)?.let { pollAggregationProcessor.handlePollEndEvent(session, it, realm, event) @@ -261,7 +261,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( in EventType.BEACON_LOCATION_DATA -> { handleBeaconLocationData(event, realm, roomId, isLocalEcho) } - else -> Timber.v("UnHandled event ${event.eventId}") + else -> Timber.v("UnHandled event ${event.eventId}") } } catch (t: Throwable) { Timber.e(t, "## Should not happen ") @@ -271,12 +271,14 @@ internal class EventRelationsAggregationProcessor @Inject constructor( // OPT OUT serer aggregation until API mature enough private val SHOULD_HANDLE_SERVER_AGREGGATION = false // should be true to work with e2e - private fun handleReplace(realm: Realm, - event: Event, - content: MessageContent, - roomId: String, - isLocalEcho: Boolean, - relatedEventId: String? = null) { + private fun handleReplace( + realm: Realm, + event: Event, + content: MessageContent, + roomId: String, + isLocalEcho: Boolean, + relatedEventId: String? = null + ) { val eventId = event.eventId ?: return val targetEventId = relatedEventId ?: content.relatesTo?.eventId ?: return val newContent = content.newContent ?: return @@ -366,9 +368,11 @@ internal class EventRelationsAggregationProcessor @Inject constructor( * @param replaceEvent The new event * @param editions list of edition of event */ - private fun handleThreadSummaryEdition(editedEvent: EventEntity?, - replaceEvent: TimelineEventEntity?, - editions: List?) { + private fun handleThreadSummaryEdition( + editedEvent: EventEntity?, + replaceEvent: TimelineEventEntity?, + editions: List? + ) { replaceEvent ?: return editedEvent ?: return editedEvent.findRootThreadEvent()?.apply { @@ -387,10 +391,12 @@ internal class EventRelationsAggregationProcessor @Inject constructor( ?.let { PowerLevelsHelper(it) } } - private fun handleInitialAggregatedRelations(realm: Realm, - event: Event, - roomId: String, - aggregation: AggregatedAnnotation) { + private fun handleInitialAggregatedRelations( + realm: Realm, + event: Event, + roomId: String, + aggregation: AggregatedAnnotation + ) { if (SHOULD_HANDLE_SERVER_AGREGGATION) { aggregation.chunk?.forEach { if (it.type == EventType.REACTION) { @@ -412,10 +418,12 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } } - private fun handleReaction(realm: Realm, - event: Event, - roomId: String, - isLocalEcho: Boolean) { + private fun handleReaction( + realm: Realm, + event: Event, + roomId: String, + isLocalEcho: Boolean + ) { val content = event.content.toModel() if (content == null) { Timber.e("Malformed reaction content ${event.content}") @@ -480,9 +488,11 @@ internal class EventRelationsAggregationProcessor @Inject constructor( /** * Called when an event is deleted. */ - private fun handleRedactionOfReplace(realm: Realm, - redacted: EventEntity, - relatedEventId: String) { + private fun handleRedactionOfReplace( + realm: Realm, + redacted: EventEntity, + relatedEventId: String + ) { Timber.d("Handle redaction of m.replace") val eventSummary = EventAnnotationsSummaryEntity.where(realm, redacted.roomId, relatedEventId).findFirst() if (eventSummary == null) { @@ -498,8 +508,10 @@ internal class EventRelationsAggregationProcessor @Inject constructor( sourceToDiscard.deleteFromRealm() } - private fun handleReactionRedact(realm: Realm, - eventToPrune: EventEntity) { + private fun handleReactionRedact( + realm: Realm, + eventToPrune: EventEntity + ) { Timber.v("REDACTION of reaction ${eventToPrune.eventId}") // delete a reaction, need to update the annotation summary if any val reactionContent: ReactionContent = EventMapper.map(eventToPrune).content.toModel() ?: return @@ -560,7 +572,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( EventType.KEY_VERIFICATION_ACCEPT, EventType.KEY_VERIFICATION_READY, EventType.KEY_VERIFICATION_KEY, - EventType.KEY_VERIFICATION_MAC -> currentState.toState(VerificationState.WAITING) + EventType.KEY_VERIFICATION_MAC -> currentState.toState(VerificationState.WAITING) EventType.KEY_VERIFICATION_CANCEL -> currentState.toState( if (event.senderId == userId) { VerificationState.CANCELED_BY_ME @@ -568,8 +580,8 @@ internal class EventRelationsAggregationProcessor @Inject constructor( VerificationState.CANCELED_BY_OTHER } ) - EventType.KEY_VERIFICATION_DONE -> currentState.toState(VerificationState.DONE) - else -> VerificationState.REQUEST + EventType.KEY_VERIFICATION_DONE -> currentState.toState(VerificationState.DONE) + else -> VerificationState.REQUEST } data = data.copy(verificationState = newState) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt index ba7f4cf5ad..ac2880de69 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt @@ -58,8 +58,9 @@ internal interface RoomAPI { * Ref: https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-publicrooms */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "publicRooms") - suspend fun publicRooms(@Query("server") server: String?, - @Body publicRoomsParams: PublicRoomsParams + suspend fun publicRooms( + @Query("server") server: String?, + @Body publicRoomsParams: PublicRoomsParams ): PublicRoomsResponse /** @@ -84,11 +85,12 @@ internal interface RoomAPI { * @param filter A JSON RoomEventFilter to filter returned events with. Optional. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/messages") - suspend fun getRoomMessagesFrom(@Path("roomId") roomId: String, - @Query("from") from: String, - @Query("dir") dir: String, - @Query("limit") limit: Int?, - @Query("filter") filter: String? + suspend fun getRoomMessagesFrom( + @Path("roomId") roomId: String, + @Query("from") from: String, + @Query("dir") dir: String, + @Query("limit") limit: Int?, + @Query("filter") filter: String? ): PaginationResponse /** @@ -100,10 +102,11 @@ internal interface RoomAPI { * @param notMembership to exclude one type of membership (optional) */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/members") - suspend fun getMembers(@Path("roomId") roomId: String, - @Query("at") syncToken: String?, - @Query("membership") membership: Membership?, - @Query("not_membership") notMembership: Membership? + suspend fun getMembers( + @Path("roomId") roomId: String, + @Query("at") syncToken: String?, + @Query("membership") membership: Membership?, + @Query("not_membership") notMembership: Membership? ): RoomMembersResponse /** @@ -115,10 +118,11 @@ internal interface RoomAPI { * @param content the event content */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/send/{eventType}/{txId}") - suspend fun send(@Path("txId") txId: String, - @Path("roomId") roomId: String, - @Path("eventType") eventType: String, - @Body content: Content? + suspend fun send( + @Path("txId") txId: String, + @Path("roomId") roomId: String, + @Path("eventType") eventType: String, + @Body content: Content? ): SendResponse /** @@ -130,10 +134,12 @@ internal interface RoomAPI { * @param filter A JSON RoomEventFilter to filter returned events with. Optional. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/context/{eventId}") - suspend fun getContextOfEvent(@Path("roomId") roomId: String, - @Path("eventId") eventId: String, - @Query("limit") limit: Int, - @Query("filter") filter: String? = null): EventContextResponse + suspend fun getContextOfEvent( + @Path("roomId") roomId: String, + @Path("eventId") eventId: String, + @Query("limit") limit: Int, + @Query("filter") filter: String? = null + ): EventContextResponse /** * Retrieve an event from its room id / events id. @@ -142,8 +148,10 @@ internal interface RoomAPI { * @param eventId the event Id */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/event/{eventId}") - suspend fun getEvent(@Path("roomId") roomId: String, - @Path("eventId") eventId: String): Event + suspend fun getEvent( + @Path("roomId") roomId: String, + @Path("eventId") eventId: String + ): Event /** * Send read markers. @@ -152,17 +160,21 @@ internal interface RoomAPI { * @param markers the read markers */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/read_markers") - suspend fun sendReadMarker(@Path("roomId") roomId: String, - @Body markers: Map) + suspend fun sendReadMarker( + @Path("roomId") roomId: String, + @Body markers: Map + ) /** * Send receipt to a room. */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/receipt/{receiptType}/{eventId}") - suspend fun sendReceipt(@Path("roomId") roomId: String, - @Path("receiptType") receiptType: String, - @Path("eventId") eventId: String, - @Body body: JsonDict = emptyMap()) + suspend fun sendReceipt( + @Path("roomId") roomId: String, + @Path("receiptType") receiptType: String, + @Path("eventId") eventId: String, + @Body body: JsonDict = emptyMap() + ) /** * Invite a user to the given room. @@ -172,8 +184,10 @@ internal interface RoomAPI { * @param body a object that just contains a user id */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/invite") - suspend fun invite(@Path("roomId") roomId: String, - @Body body: InviteBody) + suspend fun invite( + @Path("roomId") roomId: String, + @Body body: InviteBody + ) /** * Invite a user to a room, using a ThreePid @@ -182,8 +196,10 @@ internal interface RoomAPI { * @param body the Json body */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/invite") - suspend fun invite3pid(@Path("roomId") roomId: String, - @Body body: ThreePidInviteBody) + suspend fun invite3pid( + @Path("roomId") roomId: String, + @Body body: ThreePidInviteBody + ) /** * Send a generic state event. @@ -193,9 +209,10 @@ internal interface RoomAPI { * @param params the request parameters */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/state/{state_event_type}") - suspend fun sendStateEvent(@Path("roomId") roomId: String, - @Path("state_event_type") stateEventType: String, - @Body params: JsonDict + suspend fun sendStateEvent( + @Path("roomId") roomId: String, + @Path("state_event_type") stateEventType: String, + @Body params: JsonDict ): SendResponse /** @@ -207,10 +224,11 @@ internal interface RoomAPI { * @param params the request parameters */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/state/{state_event_type}/{state_key}") - suspend fun sendStateEvent(@Path("roomId") roomId: String, - @Path("state_event_type") stateEventType: String, - @Path("state_key") stateKey: String, - @Body params: JsonDict + suspend fun sendStateEvent( + @Path("roomId") roomId: String, + @Path("state_event_type") stateEventType: String, + @Path("state_key") stateKey: String, + @Body params: JsonDict ): SendResponse /** @@ -231,13 +249,14 @@ internal interface RoomAPI { * @param limit max number of Event to retrieve */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "rooms/{roomId}/relations/{eventId}/{relationType}/{eventType}") - suspend fun getRelations(@Path("roomId") roomId: String, - @Path("eventId") eventId: String, - @Path("relationType") relationType: String, - @Path("eventType") eventType: String, - @Query("from") from: String? = null, - @Query("to") to: String? = null, - @Query("limit") limit: Int? = null + suspend fun getRelations( + @Path("roomId") roomId: String, + @Path("eventId") eventId: String, + @Path("relationType") relationType: String, + @Path("eventType") eventType: String, + @Query("from") from: String? = null, + @Query("to") to: String? = null, + @Query("limit") limit: Int? = null ): RelationsResponse /** @@ -251,12 +270,13 @@ internal interface RoomAPI { * @param limit max number of Event to retrieve */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "rooms/{roomId}/relations/{eventId}/{relationType}") - suspend fun getThreadsRelations(@Path("roomId") roomId: String, - @Path("eventId") eventId: String, - @Path("relationType") relationType: String = RelationType.THREAD, - @Query("from") from: String? = null, - @Query("to") to: String? = null, - @Query("limit") limit: Int? = null + suspend fun getThreadsRelations( + @Path("roomId") roomId: String, + @Path("eventId") eventId: String, + @Path("relationType") relationType: String = RelationType.THREAD, + @Query("from") from: String? = null, + @Query("to") to: String? = null, + @Query("limit") limit: Int? = null ): RelationsResponse /** @@ -267,9 +287,11 @@ internal interface RoomAPI { * @param params the request body */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "join/{roomIdOrAlias}") - suspend fun join(@Path("roomIdOrAlias") roomIdOrAlias: String, - @Query("server_name") viaServers: List, - @Body params: JsonDict): JoinRoomResponse + suspend fun join( + @Path("roomIdOrAlias") roomIdOrAlias: String, + @Query("server_name") viaServers: List, + @Body params: JsonDict + ): JoinRoomResponse /** * Leave the given room. @@ -278,8 +300,10 @@ internal interface RoomAPI { * @param params the request body */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/leave") - suspend fun leave(@Path("roomId") roomId: String, - @Body params: Map) + suspend fun leave( + @Path("roomId") roomId: String, + @Body params: Map + ) /** * Ban a user from the given room. @@ -288,8 +312,10 @@ internal interface RoomAPI { * @param userIdAndReason the banned user object (userId and reason for ban) */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/ban") - suspend fun ban(@Path("roomId") roomId: String, - @Body userIdAndReason: UserIdAndReason) + suspend fun ban( + @Path("roomId") roomId: String, + @Body userIdAndReason: UserIdAndReason + ) /** * unban a user from the given room. @@ -298,8 +324,10 @@ internal interface RoomAPI { * @param userIdAndReason the unbanned user object (userId and reason for unban) */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/unban") - suspend fun unban(@Path("roomId") roomId: String, - @Body userIdAndReason: UserIdAndReason) + suspend fun unban( + @Path("roomId") roomId: String, + @Body userIdAndReason: UserIdAndReason + ) /** * Kick a user from the given room. @@ -308,8 +336,10 @@ internal interface RoomAPI { * @param userIdAndReason the kicked user object (userId and reason for kicking) */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/kick") - suspend fun kick(@Path("roomId") roomId: String, - @Body userIdAndReason: UserIdAndReason) + suspend fun kick( + @Path("roomId") roomId: String, + @Body userIdAndReason: UserIdAndReason + ) /** * Strips all information out of an event which isn't critical to the integrity of the server-side representation of the room. @@ -337,9 +367,11 @@ internal interface RoomAPI { * @param body body containing score and reason */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/report/{eventId}") - suspend fun reportContent(@Path("roomId") roomId: String, - @Path("eventId") eventId: String, - @Body body: ReportContentBody) + suspend fun reportContent( + @Path("roomId") roomId: String, + @Path("eventId") eventId: String, + @Body body: ReportContentBody + ) /** * Get a list of aliases maintained by the local server for the given room. @@ -352,9 +384,11 @@ internal interface RoomAPI { * Inform that the user is starting to type or has stopped typing. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/typing/{userId}") - suspend fun sendTypingState(@Path("roomId") roomId: String, - @Path("userId") userId: String, - @Body body: TypingBody) + suspend fun sendTypingState( + @Path("roomId") roomId: String, + @Path("userId") userId: String, + @Body body: TypingBody + ) /* * Room tagging @@ -364,27 +398,33 @@ internal interface RoomAPI { * Add a tag to a room. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/rooms/{roomId}/tags/{tag}") - suspend fun putTag(@Path("userId") userId: String, - @Path("roomId") roomId: String, - @Path("tag") tag: String, - @Body body: TagBody) + suspend fun putTag( + @Path("userId") userId: String, + @Path("roomId") roomId: String, + @Path("tag") tag: String, + @Body body: TagBody + ) /** * Delete a tag from a room. */ @DELETE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/rooms/{roomId}/tags/{tag}") - suspend fun deleteTag(@Path("userId") userId: String, - @Path("roomId") roomId: String, - @Path("tag") tag: String) + suspend fun deleteTag( + @Path("userId") userId: String, + @Path("roomId") roomId: String, + @Path("tag") tag: String + ) /** * Set an AccountData event to the room. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/rooms/{roomId}/account_data/{type}") - suspend fun setRoomAccountData(@Path("userId") userId: String, - @Path("roomId") roomId: String, - @Path("type") type: String, - @Body content: JsonDict) + suspend fun setRoomAccountData( + @Path("userId") userId: String, + @Path("roomId") roomId: String, + @Path("type") type: String, + @Body content: JsonDict + ) /** * Upgrades the given room to a particular room version. @@ -394,8 +434,10 @@ internal interface RoomAPI { * 403: The user is not permitted to upgrade the room.(M_FORBIDDEN) */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/upgrade") - suspend fun upgradeRoom(@Path("roomId") roomId: String, - @Body body: RoomUpgradeBody): RoomUpgradeResponse + suspend fun upgradeRoom( + @Path("roomId") roomId: String, + @Body body: RoomUpgradeBody + ): RoomUpgradeResponse /** * The API returns the summary of the specified room, if the room could be found and the client should be able to view @@ -404,6 +446,8 @@ internal interface RoomAPI { * https://github.com/deepbluev7/matrix-doc/blob/room-summaries/proposals/3266-room-summary.md */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "im.nheko.summary/rooms/{roomIdOrAlias}/summary") - suspend fun getRoomSummary(@Path("roomIdOrAlias") roomidOrAlias: String, - @Query("via") viaServers: List?): RoomStrippedState + suspend fun getRoomSummary( + @Path("roomIdOrAlias") roomidOrAlias: String, + @Query("via") viaServers: List? + ): RoomStrippedState } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/DefaultRoomAccountDataService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/DefaultRoomAccountDataService.kt index caeeb3bf53..aea786b46b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/DefaultRoomAccountDataService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/DefaultRoomAccountDataService.kt @@ -25,9 +25,10 @@ import org.matrix.android.sdk.api.session.room.accountdata.RoomAccountDataEvent import org.matrix.android.sdk.api.session.room.accountdata.RoomAccountDataService import org.matrix.android.sdk.api.util.Optional -internal class DefaultRoomAccountDataService @AssistedInject constructor(@Assisted private val roomId: String, - private val dataSource: RoomAccountDataDataSource, - private val updateRoomAccountDataTask: UpdateRoomAccountDataTask +internal class DefaultRoomAccountDataService @AssistedInject constructor( + @Assisted private val roomId: String, + private val dataSource: RoomAccountDataDataSource, + private val updateRoomAccountDataTask: UpdateRoomAccountDataTask ) : RoomAccountDataService { @AssistedFactory diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/RoomAccountDataDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/RoomAccountDataDataSource.kt index d5a110dfc2..5196f004ea 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/RoomAccountDataDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/accountdata/RoomAccountDataDataSource.kt @@ -33,9 +33,11 @@ import org.matrix.android.sdk.internal.database.model.RoomEntityFields import org.matrix.android.sdk.internal.di.SessionDatabase import javax.inject.Inject -internal class RoomAccountDataDataSource @Inject constructor(@SessionDatabase private val monarchy: Monarchy, - private val realmSessionProvider: RealmSessionProvider, - private val accountDataMapper: AccountDataMapper) { +internal class RoomAccountDataDataSource @Inject constructor( + @SessionDatabase private val monarchy: Monarchy, + private val realmSessionProvider: RealmSessionProvider, + private val accountDataMapper: AccountDataMapper +) { fun getAccountDataEvent(roomId: String, type: String): RoomAccountDataEvent? { return getAccountDataEvents(roomId, setOf(type)).firstOrNull() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DeactivateLiveLocationShareWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DeactivateLiveLocationShareWorker.kt index 2b83c8028b..b17753b25a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DeactivateLiveLocationShareWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DeactivateLiveLocationShareWorker.kt @@ -75,6 +75,7 @@ internal class DeactivateLiveLocationShareWorker(context: Context, params: Worke private suspend fun deactivateLiveLocationShare(params: Params) { awaitTransaction(realmConfiguration) { realm -> + Timber.d("deactivating live with id=${params.eventId}") val aggregatedSummary = LiveLocationShareAggregatedSummaryEntity.get( realm = realm, roomId = params.roomId, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt index 8f4682a9d5..05bde8f83f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt @@ -67,16 +67,18 @@ internal class LiveLocationAggregationProcessor @Inject constructor( eventId = targetEventId ) - Timber.d("updating summary of id=$targetEventId with isLive=${content.isLive}") - + // remote event can stay with isLive == true while the local summary is no more active + val isActive = aggregatedSummary.isActive.orTrue() && isLive val endOfLiveTimestampMillis = content.getBestTimestampMillis()?.let { it + (content.timeout ?: 0) } + Timber.d("updating summary of id=$targetEventId with isActive=$isActive and endTimestamp=$endOfLiveTimestampMillis") + aggregatedSummary.endOfLiveTimestampMillis = endOfLiveTimestampMillis - aggregatedSummary.isActive = isLive + aggregatedSummary.isActive = isActive aggregatedSummary.userId = event.senderId deactivateAllPreviousBeacons(realm, roomId, event.senderId, targetEventId) - if (isLive) { + if (isActive) { scheduleDeactivationAfterTimeout(targetEventId, roomId, endOfLiveTimestampMillis) } else { cancelDeactivationAfterTimeout(targetEventId, roomId) @@ -90,6 +92,7 @@ internal class LiveLocationAggregationProcessor @Inject constructor( val workData = WorkerParamsFactory.toData(workParams) val workName = DeactivateLiveLocationShareWorker.getWorkName(eventId = eventId, roomId = roomId) val workDelayMillis = (endOfLiveTimestampMillis - clock.epochMillis()).coerceAtLeast(0) + Timber.d("scheduling deactivation of $eventId after $workDelayMillis millis") val workRequest = workManagerProvider.matrixOneTimeWorkRequestBuilder() .setInitialDelay(workDelayMillis, TimeUnit.MILLISECONDS) .setInputData(workData) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/poll/DefaultPollAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/poll/DefaultPollAggregationProcessor.kt index d4b414aaea..90d8e02c39 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/poll/DefaultPollAggregationProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/poll/DefaultPollAggregationProcessor.kt @@ -193,8 +193,10 @@ class DefaultPollAggregationProcessor @Inject constructor() : PollAggregationPro ?: EventAnnotationsSummaryEntity.create(realm, roomId, eventId) } - private fun getAggregatedPollSummaryEntity(realm: Realm, - eventAnnotationsSummaryEntity: EventAnnotationsSummaryEntity): PollResponseAggregatedSummaryEntity { + private fun getAggregatedPollSummaryEntity( + realm: Realm, + eventAnnotationsSummaryEntity: EventAnnotationsSummaryEntity + ): PollResponseAggregatedSummaryEntity { return eventAnnotationsSummaryEntity.pollResponseSummary ?: realm.createObject(PollResponseAggregatedSummaryEntity::class.java).also { eventAnnotationsSummaryEntity.pollResponseSummary = it diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/crypto/DefaultRoomCryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/crypto/DefaultRoomCryptoService.kt index 2546c58cc7..4f0228e6a8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/crypto/DefaultRoomCryptoService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/crypto/DefaultRoomCryptoService.kt @@ -61,10 +61,10 @@ internal class DefaultRoomCryptoService @AssistedInject constructor( (!force && isEncrypted() && encryptionAlgorithm() == MXCRYPTO_ALGORITHM_MEGOLM) -> { throw IllegalStateException("Encryption is already enabled for this room") } - (!force && algorithm != MXCRYPTO_ALGORITHM_MEGOLM) -> { + (!force && algorithm != MXCRYPTO_ALGORITHM_MEGOLM) -> { throw InvalidParameterException("Only MXCRYPTO_ALGORITHM_MEGOLM algorithm is supported") } - else -> { + else -> { val params = SendStateTask.Params( roomId = roomId, stateKey = "", diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DefaultDraftService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DefaultDraftService.kt index 3867e0dc8d..1ea8addb20 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DefaultDraftService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DefaultDraftService.kt @@ -26,9 +26,10 @@ import org.matrix.android.sdk.api.session.room.send.DraftService import org.matrix.android.sdk.api.session.room.send.UserDraft import org.matrix.android.sdk.api.util.Optional -internal class DefaultDraftService @AssistedInject constructor(@Assisted private val roomId: String, - private val draftRepository: DraftRepository, - private val coroutineDispatchers: MatrixCoroutineDispatchers +internal class DefaultDraftService @AssistedInject constructor( + @Assisted private val roomId: String, + private val draftRepository: DraftRepository, + private val coroutineDispatchers: MatrixCoroutineDispatchers ) : DraftService { @AssistedFactory diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DraftRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DraftRepository.kt index c8c52c4b23..b672ef7e46 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DraftRepository.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/draft/DraftRepository.kt @@ -35,8 +35,10 @@ import org.matrix.android.sdk.internal.util.awaitTransaction import timber.log.Timber import javax.inject.Inject -internal class DraftRepository @Inject constructor(@SessionDatabase private val monarchy: Monarchy, - private val realmSessionProvider: RealmSessionProvider) { +internal class DraftRepository @Inject constructor( + @SessionDatabase private val monarchy: Monarchy, + private val realmSessionProvider: RealmSessionProvider +) { suspend fun saveDraft(roomId: String, userDraft: UserDraft) { monarchy.awaitTransaction { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/LoadRoomMembersTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/LoadRoomMembersTask.kt index d3d1cb856a..15d0889255 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/LoadRoomMembersTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/LoadRoomMembersTask.kt @@ -68,9 +68,9 @@ internal class DefaultLoadRoomMembersTask @Inject constructor( override suspend fun execute(params: LoadRoomMembersTask.Params) { when (getRoomMembersLoadStatus(params.roomId)) { - RoomMembersLoadStatusType.NONE -> doRequest(params) + RoomMembersLoadStatusType.NONE -> doRequest(params) RoomMembersLoadStatusType.LOADING -> waitPreviousRequestToFinish(params) - RoomMembersLoadStatusType.LOADED -> Unit + RoomMembersLoadStatusType.LOADED -> Unit } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomChangeMembershipStateDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomChangeMembershipStateDataSource.kt index 35d8cb08af..c61625b2b1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomChangeMembershipStateDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomChangeMembershipStateDataSource.kt @@ -61,8 +61,8 @@ internal class RoomChangeMembershipStateDataSource @Inject constructor() { private fun Membership.toMembershipChangeState(): ChangeMembershipState { return when { this == Membership.JOIN -> ChangeMembershipState.Joined - this.isLeft() -> ChangeMembershipState.Left - else -> ChangeMembershipState.Unknown + this.isLeft() -> ChangeMembershipState.Left + else -> ChangeMembershipState.Unknown } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt index 9e672dcc5c..4645bb05ab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt @@ -110,32 +110,32 @@ internal class RoomDisplayNameResolver @Inject constructor( } val otherMembersCount = otherMembersSubset.count() name = when (otherMembersCount) { - 0 -> { + 0 -> { // Get left members if any val leftMembersNames = roomMembers.queryLeftRoomMembersEvent() .findAll() .map { displayNameResolver.getBestName(it.toMatrixItem()) } roomDisplayNameFallbackProvider.getNameForEmptyRoom(roomSummary?.isDirect.orFalse(), leftMembersNames) } - 1 -> { + 1 -> { roomDisplayNameFallbackProvider.getNameFor1member( resolveRoomMemberName(otherMembersSubset[0], roomMembers) ) } - 2 -> { + 2 -> { roomDisplayNameFallbackProvider.getNameFor2members( resolveRoomMemberName(otherMembersSubset[0], roomMembers), resolveRoomMemberName(otherMembersSubset[1], roomMembers) ) } - 3 -> { + 3 -> { roomDisplayNameFallbackProvider.getNameFor3members( resolveRoomMemberName(otherMembersSubset[0], roomMembers), resolveRoomMemberName(otherMembersSubset[1], roomMembers), resolveRoomMemberName(otherMembersSubset[2], roomMembers) ) } - 4 -> { + 4 -> { roomDisplayNameFallbackProvider.getNameFor4members( resolveRoomMemberName(otherMembersSubset[0], roomMembers), resolveRoomMemberName(otherMembersSubset[1], roomMembers), @@ -158,8 +158,10 @@ internal class RoomDisplayNameResolver @Inject constructor( } /** See [org.matrix.android.sdk.api.session.room.sender.SenderInfo.disambiguatedDisplayName]. */ - private fun resolveRoomMemberName(roomMemberSummary: RoomMemberSummaryEntity, - roomMemberHelper: RoomMemberHelper): String { + private fun resolveRoomMemberName( + roomMemberSummary: RoomMemberSummaryEntity, + roomMemberHelper: RoomMemberHelper + ): String { val isUnique = roomMemberHelper.isUniqueDisplayName(roomMemberSummary.displayName) return if (isUnique) { displayNameResolver.getBestName(roomMemberSummary.toMatrixItem()) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberEventHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberEventHandler.kt index a1b30a0be5..1e36e9c6da 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberEventHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberEventHandler.kt @@ -34,11 +34,13 @@ internal class RoomMemberEventHandler @Inject constructor( @UserId private val myUserId: String ) { - fun handle(realm: Realm, - roomId: String, - event: Event, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator? = null): Boolean { + fun handle( + realm: Realm, + roomId: String, + event: Event, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator? = null + ): Boolean { if (event.type != EventType.STATE_ROOM_MEMBER) { return false } @@ -59,12 +61,14 @@ internal class RoomMemberEventHandler @Inject constructor( } } - private fun handleInitialSync(realm: Realm, - roomId: String, - currentUserId: String, - eventUserId: String, - roomMember: RoomMemberContent, - aggregator: SyncResponsePostTreatmentAggregator?): Boolean { + private fun handleInitialSync( + realm: Realm, + roomId: String, + currentUserId: String, + eventUserId: String, + roomMember: RoomMemberContent, + aggregator: SyncResponsePostTreatmentAggregator? + ): Boolean { if (currentUserId != eventUserId) { saveUserEntityLocallyIfNecessary(realm, eventUserId, roomMember) } @@ -73,10 +77,12 @@ internal class RoomMemberEventHandler @Inject constructor( return true } - private fun saveRoomMemberEntityLocally(realm: Realm, - roomId: String, - userId: String, - roomMember: RoomMemberContent) { + private fun saveRoomMemberEntityLocally( + realm: Realm, + roomId: String, + userId: String, + roomMember: RoomMemberContent + ) { val roomMemberEntity = RoomMemberEntityFactory.create( roomId, userId, @@ -96,9 +102,11 @@ internal class RoomMemberEventHandler @Inject constructor( return RoomMemberSummaryEntity.where(realm, roomId, userId).findFirst()?.userPresenceEntity } - private fun saveUserEntityLocallyIfNecessary(realm: Realm, - userId: String, - roomMember: RoomMemberContent) { + private fun saveUserEntityLocallyIfNecessary( + realm: Realm, + userId: String, + roomMember: RoomMemberContent + ) { if (roomMember.membership.isActive()) { saveUserLocally(realm, userId, roomMember) } @@ -109,9 +117,11 @@ internal class RoomMemberEventHandler @Inject constructor( realm.insertOrUpdate(userEntity) } - private fun updateDirectChatsIfNecessary(roomId: String, - roomMember: RoomMemberContent, - aggregator: SyncResponsePostTreatmentAggregator?) { + private fun updateDirectChatsIfNecessary( + roomId: String, + roomMember: RoomMemberContent, + aggregator: SyncResponsePostTreatmentAggregator? + ) { // check whether this new room member event may be used to update the directs dictionary in account data // this is required to handle correctly invite by email in DM val mxId = roomMember.thirdPartyInvite?.signed?.mxid @@ -120,12 +130,14 @@ internal class RoomMemberEventHandler @Inject constructor( } } - private fun handleIncrementalSync(realm: Realm, - roomId: String, - eventUserId: String, - roomMember: RoomMemberContent, - prevContent: Content?, - aggregator: SyncResponsePostTreatmentAggregator?): Boolean { + private fun handleIncrementalSync( + realm: Realm, + roomId: String, + eventUserId: String, + roomMember: RoomMemberContent, + prevContent: Content?, + aggregator: SyncResponsePostTreatmentAggregator? + ): Boolean { if (aggregator != null) { val previousDisplayName = prevContent?.get("displayname") as? String val previousAvatar = prevContent?.get("avatar_url") as? String diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt index 40228fe8c9..7da12a75de 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt @@ -33,8 +33,9 @@ import org.matrix.android.sdk.internal.database.query.where * It allows to get the live membership of a user. */ -internal class RoomMemberHelper(private val realm: Realm, - private val roomId: String +internal class RoomMemberHelper( + private val realm: Realm, + private val roomId: String ) { private val roomSummary: RoomSummaryEntity? by lazy { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/admin/MembershipAdminTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/admin/MembershipAdminTask.kt index d2c21f3520..b07a77a18f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/admin/MembershipAdminTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/admin/MembershipAdminTask.kt @@ -43,9 +43,9 @@ internal class DefaultMembershipAdminTask @Inject constructor(private val roomAP val userIdAndReason = UserIdAndReason(params.userId, params.reason) executeRequest(null) { when (params.type) { - MembershipAdminTask.Type.BAN -> roomAPI.ban(params.roomId, userIdAndReason) + MembershipAdminTask.Type.BAN -> roomAPI.ban(params.roomId, userIdAndReason) MembershipAdminTask.Type.UNBAN -> roomAPI.unban(params.roomId, userIdAndReason) - MembershipAdminTask.Type.KICK -> roomAPI.kick(params.roomId, userIdAndReason) + MembershipAdminTask.Type.KICK -> roomAPI.kick(params.roomId, userIdAndReason) } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/DefaultRoomPushRuleService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/DefaultRoomPushRuleService.kt index 85f53e1346..d46100a3a8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/DefaultRoomPushRuleService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/DefaultRoomPushRuleService.kt @@ -29,9 +29,11 @@ import org.matrix.android.sdk.internal.database.model.PushRuleEntity import org.matrix.android.sdk.internal.database.query.where import org.matrix.android.sdk.internal.di.SessionDatabase -internal class DefaultRoomPushRuleService @AssistedInject constructor(@Assisted private val roomId: String, - private val setRoomNotificationStateTask: SetRoomNotificationStateTask, - @SessionDatabase private val monarchy: Monarchy) : +internal class DefaultRoomPushRuleService @AssistedInject constructor( + @Assisted private val roomId: String, + private val setRoomNotificationStateTask: SetRoomNotificationStateTask, + @SessionDatabase private val monarchy: Monarchy +) : RoomPushRuleService { @AssistedFactory diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/RoomPushRuleMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/RoomPushRuleMapper.kt index a5a5ab58ba..42b069f8fa 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/RoomPushRuleMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/RoomPushRuleMapper.kt @@ -33,10 +33,10 @@ internal fun PushRuleEntity.toRoomPushRule(): RoomPushRule? { RuleSetKey.OVERRIDE -> { PushRulesMapper.map(this) } - RuleSetKey.ROOM -> { + RuleSetKey.ROOM -> { PushRulesMapper.mapRoomRule(this) } - else -> null + else -> null } return if (pushRule == null || kind == null) { null @@ -47,7 +47,7 @@ internal fun PushRuleEntity.toRoomPushRule(): RoomPushRule? { internal fun RoomNotificationState.toRoomPushRule(roomId: String): RoomPushRule? { return when { - this == RoomNotificationState.ALL_MESSAGES -> null + this == RoomNotificationState.ALL_MESSAGES -> null this == RoomNotificationState.ALL_MESSAGES_NOISY -> { val rule = PushRule( actions = listOf(Action.Notify, Action.Sound()).toJson(), @@ -56,7 +56,7 @@ internal fun RoomNotificationState.toRoomPushRule(roomId: String): RoomPushRule? ) return RoomPushRule(RuleSetKey.ROOM, rule) } - else -> { + else -> { val condition = PushCondition( kind = Kind.EventMatch.value, key = "room_id", diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/SetRoomNotificationStateTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/SetRoomNotificationStateTask.kt index 021d7dbefb..3d51d19cba 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/SetRoomNotificationStateTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/notification/SetRoomNotificationStateTask.kt @@ -35,9 +35,11 @@ internal interface SetRoomNotificationStateTask : Task { + else -> { // RoomDirectoryVisibility.PRIVATE or null // We cannot resolve this room :/ null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/prune/RedactionEventProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/prune/RedactionEventProcessor.kt index e926d6a785..e33fbb56b1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/prune/RedactionEventProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/prune/RedactionEventProcessor.kt @@ -145,10 +145,10 @@ internal class RedactionEventProcessor @Inject constructor() : EventInsertLivePr private fun computeAllowedKeys(type: String): List { // Add filtered content, allowed keys in content depends on the event type return when (type) { - EventType.STATE_ROOM_MEMBER -> listOf("membership") - EventType.STATE_ROOM_CREATE -> listOf("creator") - EventType.STATE_ROOM_JOIN_RULES -> listOf("join_rule") - EventType.STATE_ROOM_POWER_LEVELS -> listOf( + EventType.STATE_ROOM_MEMBER -> listOf("membership") + EventType.STATE_ROOM_CREATE -> listOf("creator") + EventType.STATE_ROOM_JOIN_RULES -> listOf("join_rule") + EventType.STATE_ROOM_POWER_LEVELS -> listOf( "users", "users_default", "events", @@ -159,10 +159,10 @@ internal class RedactionEventProcessor @Inject constructor() : EventInsertLivePr "redact", "invite" ) - EventType.STATE_ROOM_ALIASES -> listOf("aliases") + EventType.STATE_ROOM_ALIASES -> listOf("aliases") EventType.STATE_ROOM_CANONICAL_ALIAS -> listOf("alias") - EventType.FEEDBACK -> listOf("type", "target_event_id") - else -> emptyList() + EventType.FEEDBACK -> listOf("type", "target_event_id") + else -> emptyList() } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/DefaultRelationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/DefaultRelationService.kt index 7b68e2a74c..9839a44427 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/DefaultRelationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/DefaultRelationService.kt @@ -92,25 +92,31 @@ internal class DefaultRelationService @AssistedInject constructor( } } - override fun editPoll(targetEvent: TimelineEvent, - pollType: PollType, - question: String, - options: List): Cancelable { + override fun editPoll( + targetEvent: TimelineEvent, + pollType: PollType, + question: String, + options: List + ): Cancelable { return eventEditor.editPoll(targetEvent, pollType, question, options) } - override fun editTextMessage(targetEvent: TimelineEvent, - msgType: String, - newBodyText: CharSequence, - newBodyAutoMarkdown: Boolean, - compatibilityBodyText: String): Cancelable { + override fun editTextMessage( + targetEvent: TimelineEvent, + msgType: String, + newBodyText: CharSequence, + newBodyAutoMarkdown: Boolean, + compatibilityBodyText: String + ): Cancelable { return eventEditor.editTextMessage(targetEvent, msgType, newBodyText, newBodyAutoMarkdown, compatibilityBodyText) } - override fun editReply(replyToEdit: TimelineEvent, - originalTimelineEvent: TimelineEvent, - newBodyText: String, - compatibilityBodyText: String): Cancelable { + override fun editReply( + replyToEdit: TimelineEvent, + originalTimelineEvent: TimelineEvent, + newBodyText: String, + compatibilityBodyText: String + ): Cancelable { return eventEditor.editReply(replyToEdit, originalTimelineEvent, newBodyText, compatibilityBodyText) } @@ -164,7 +170,8 @@ internal class DefaultRelationService @AssistedInject constructor( msgType: String, autoMarkdown: Boolean, formattedText: String?, - eventReplied: TimelineEvent?): Cancelable? { + eventReplied: TimelineEvent? + ): Cancelable? { val event = if (eventReplied != null) { // Reply within a thread eventFactory.createReplyTextEvent( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/EventEditor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/EventEditor.kt index 7bf7d6b587..795e9003ce 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/EventEditor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/EventEditor.kt @@ -38,11 +38,13 @@ internal class EventEditor @Inject constructor( private val clock: Clock, ) { - fun editTextMessage(targetEvent: TimelineEvent, - msgType: String, - newBodyText: CharSequence, - newBodyAutoMarkdown: Boolean, - compatibilityBodyText: String): Cancelable { + fun editTextMessage( + targetEvent: TimelineEvent, + msgType: String, + newBodyText: CharSequence, + newBodyAutoMarkdown: Boolean, + compatibilityBodyText: String + ): Cancelable { val roomId = targetEvent.roomId if (targetEvent.root.sendState.hasFailed()) { // We create a new in memory event for the EventSenderProcessor but we keep the eventId of the failed event. @@ -61,10 +63,12 @@ internal class EventEditor @Inject constructor( } } - fun editPoll(targetEvent: TimelineEvent, - pollType: PollType, - question: String, - options: List): Cancelable { + fun editPoll( + targetEvent: TimelineEvent, + pollType: PollType, + question: String, + options: List + ): Cancelable { val roomId = targetEvent.roomId if (targetEvent.root.sendState.hasFailed()) { val editedEvent = eventFactory.createPollEvent(roomId, pollType, question, options).copy( @@ -92,10 +96,12 @@ internal class EventEditor @Inject constructor( return eventSenderProcessor.postEvent(editedEvent) } - fun editReply(replyToEdit: TimelineEvent, - originalTimelineEvent: TimelineEvent, - newBodyText: String, - compatibilityBodyText: String): Cancelable { + fun editReply( + replyToEdit: TimelineEvent, + originalTimelineEvent: TimelineEvent, + newBodyText: String, + compatibilityBodyText: String + ): Cancelable { val roomId = replyToEdit.roomId if (replyToEdit.root.sendState.hasFailed()) { // We create a new in memory event for the EventSenderProcessor but we keep the eventId of the failed event. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/FindReactionEventForUndoTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/FindReactionEventForUndoTask.kt index f7cfa3489d..585f896f32 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/FindReactionEventForUndoTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/FindReactionEventForUndoTask.kt @@ -41,7 +41,8 @@ internal interface FindReactionEventForUndoTask : Task diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/UpdateQuickReactionTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/UpdateQuickReactionTask.kt index d0ab430dad..24e8ba7f9e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/UpdateQuickReactionTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/UpdateQuickReactionTask.kt @@ -41,8 +41,10 @@ internal interface UpdateQuickReactionTask : Task?>? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadSummariesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadSummariesTask.kt index c5f9bd13fd..254dee4295 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadSummariesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadSummariesTask.kt @@ -77,8 +77,10 @@ internal class DefaultFetchThreadSummariesTask @Inject constructor( return handleResponse(response, params) } - private suspend fun handleResponse(response: PaginationResponse, - params: FetchThreadSummariesTask.Params): Result { + private suspend fun handleResponse( + response: PaginationResponse, + params: FetchThreadSummariesTask.Params + ): Result { val rootThreadList = response.events monarchy.awaitTransaction { realm -> val roomEntity = RoomEntity.where(realm, roomId = params.roomId).findFirst() ?: return@awaitTransaction diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt index dabdd04f60..bad734173e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt @@ -109,8 +109,10 @@ internal class DefaultFetchThreadTimelineTask @Inject constructor( return handleRelationsResponse(response, params) } - private suspend fun handleRelationsResponse(response: RelationsResponse, - params: FetchThreadTimelineTask.Params): Result { + private suspend fun handleRelationsResponse( + response: RelationsResponse, + params: FetchThreadTimelineTask.Params + ): Result { val threadList = response.chunks val threadRootEvent = response.originalEvent val hasReachEnd = response.nextBatch == null @@ -232,9 +234,11 @@ internal class DefaultFetchThreadTimelineTask @Inject constructor( } } - private fun handleReaction(realm: Realm, - event: Event, - roomId: String) { + private fun handleReaction( + realm: Realm, + event: Event, + roomId: String + ) { val unsignedData = event.unsignedData ?: return val relatedEventId = event.eventId ?: return diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/reporting/DefaultReportingService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/reporting/DefaultReportingService.kt index c961f718ef..1e32bf5e16 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/reporting/DefaultReportingService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/reporting/DefaultReportingService.kt @@ -21,8 +21,9 @@ import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import org.matrix.android.sdk.api.session.room.reporting.ReportingService -internal class DefaultReportingService @AssistedInject constructor(@Assisted private val roomId: String, - private val reportContentTask: ReportContentTask +internal class DefaultReportingService @AssistedInject constructor( + @Assisted private val roomId: String, + private val reportContentTask: ReportContentTask ) : ReportingService { @AssistedFactory diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt index 8529365858..fc78abcfd9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt @@ -198,7 +198,7 @@ internal class DefaultSendService @AssistedInject constructor( localEchoRepository.updateSendState(localEcho.eventId, roomId, SendState.UNSENT) internalSendMedia(listOf(localEcho.root), attachmentData, true) } - is MessageFileContent -> { + is MessageFileContent -> { val attachmentData = ContentAttachmentData( size = messageContent.info!!.size, mimeType = messageContent.mimeType, @@ -222,7 +222,7 @@ internal class DefaultSendService @AssistedInject constructor( localEchoRepository.updateSendState(localEcho.eventId, roomId, SendState.UNSENT) internalSendMedia(listOf(localEcho.root), attachmentData, true) } - else -> NoOpCancellable + else -> NoOpCancellable } } return NoOpCancellable @@ -265,10 +265,11 @@ internal class DefaultSendService @AssistedInject constructor( } } - override fun sendMedias(attachments: List, - compressBeforeSending: Boolean, - roomIds: Set, - rootThreadEventId: String? + override fun sendMedias( + attachments: List, + compressBeforeSending: Boolean, + roomIds: Set, + rootThreadEventId: String? ): Cancelable { return attachments.mapTo(CancelableBag()) { sendMedia( @@ -280,10 +281,11 @@ internal class DefaultSendService @AssistedInject constructor( } } - override fun sendMedia(attachment: ContentAttachmentData, - compressBeforeSending: Boolean, - roomIds: Set, - rootThreadEventId: String? + override fun sendMedia( + attachment: ContentAttachmentData, + compressBeforeSending: Boolean, + roomIds: Set, + rootThreadEventId: String? ): Cancelable { // Ensure that the event will not be send in a thread if we are a different flow. // Like sending files to multiple rooms @@ -354,10 +356,12 @@ internal class DefaultSendService @AssistedInject constructor( return "${roomId}_$identifier" } - private fun createUploadMediaWork(allLocalEchos: List, - attachment: ContentAttachmentData, - isRoomEncrypted: Boolean, - compressBeforeSending: Boolean): OneTimeWorkRequest { + private fun createUploadMediaWork( + allLocalEchos: List, + attachment: ContentAttachmentData, + isRoomEncrypted: Boolean, + compressBeforeSending: Boolean + ): OneTimeWorkRequest { val localEchoIds = allLocalEchos.map { LocalEchoIdentifiers(it.roomId!!, it.eventId!!) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt index d39088bd6d..3b9ca44d18 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt @@ -119,12 +119,14 @@ internal class LocalEchoEventFactory @Inject constructor( return createMessageEvent(roomId, textContent.toMessageTextContent(msgType)) } - fun createReplaceTextEvent(roomId: String, - targetEventId: String, - newBodyText: CharSequence, - newBodyAutoMarkdown: Boolean, - msgType: String, - compatibilityText: String): Event { + fun createReplaceTextEvent( + roomId: String, + targetEventId: String, + newBodyText: CharSequence, + newBodyAutoMarkdown: Boolean, + msgType: String, + compatibilityText: String + ): Event { return createMessageEvent( roomId, MessageTextContent( @@ -138,9 +140,11 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - private fun createPollContent(question: String, - options: List, - pollType: PollType): MessagePollContent { + private fun createPollContent( + question: String, + options: List, + pollType: PollType + ): MessagePollContent { return MessagePollContent( unstablePollCreationInfo = PollCreationInfo( question = PollQuestion(unstableQuestion = question), @@ -152,11 +156,13 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createPollReplaceEvent(roomId: String, - pollType: PollType, - targetEventId: String, - question: String, - options: List): Event { + fun createPollReplaceEvent( + roomId: String, + pollType: PollType, + targetEventId: String, + question: String, + options: List + ): Event { val newContent = MessagePollContent( relatesTo = RelationDefaultContent(RelationType.REPLACE, targetEventId), newContent = createPollContent(question, options, pollType).toContent() @@ -172,9 +178,11 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createPollReplyEvent(roomId: String, - pollEventId: String, - answerId: String): Event { + fun createPollReplyEvent( + roomId: String, + pollEventId: String, + answerId: String + ): Event { val content = MessagePollResponseContent( body = answerId, relatesTo = RelationDefaultContent( @@ -195,10 +203,12 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createPollEvent(roomId: String, - pollType: PollType, - question: String, - options: List): Event { + fun createPollEvent( + roomId: String, + pollType: PollType, + question: String, + options: List + ): Event { val content = createPollContent(question, options, pollType) val localId = LocalEcho.createLocalEchoId() return Event( @@ -212,8 +222,10 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createEndPollEvent(roomId: String, - eventId: String): Event { + fun createEndPollEvent( + roomId: String, + eventId: String + ): Event { val content = MessageEndPollContent( relatesTo = RelationDefaultContent( type = RelationType.REFERENCE, @@ -232,11 +244,13 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createLocationEvent(roomId: String, - latitude: Double, - longitude: Double, - uncertainty: Double?, - isUserLocation: Boolean): Event { + fun createLocationEvent( + roomId: String, + latitude: Double, + longitude: Double, + uncertainty: Double?, + isUserLocation: Boolean + ): Event { val geoUri = buildGeoUri(latitude, longitude, uncertainty) val assetType = if (isUserLocation) LocationAssetType.SELF else LocationAssetType.PIN val content = MessageLocationContent( @@ -250,11 +264,13 @@ internal class LocalEchoEventFactory @Inject constructor( return createMessageEvent(roomId, content) } - fun createLiveLocationEvent(beaconInfoEventId: String, - roomId: String, - latitude: Double, - longitude: Double, - uncertainty: Double?): Event { + fun createLiveLocationEvent( + beaconInfoEventId: String, + roomId: String, + latitude: Double, + longitude: Double, + uncertainty: Double? + ): Event { val geoUri = buildGeoUri(latitude, longitude, uncertainty) val content = MessageBeaconLocationDataContent( body = geoUri, @@ -277,13 +293,15 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createReplaceTextOfReply(roomId: String, - eventReplaced: TimelineEvent, - originalEvent: TimelineEvent, - newBodyText: String, - autoMarkdown: Boolean, - msgType: String, - compatibilityText: String): Event { + fun createReplaceTextOfReply( + roomId: String, + eventReplaced: TimelineEvent, + originalEvent: TimelineEvent, + newBodyText: String, + autoMarkdown: Boolean, + msgType: String, + compatibilityText: String + ): Event { val permalink = permalinkFactory.createPermalink(roomId, originalEvent.root.eventId ?: "", false) val userLink = originalEvent.root.senderId?.let { permalinkFactory.createPermalink(it, false) } ?: "" @@ -321,16 +339,17 @@ internal class LocalEchoEventFactory @Inject constructor( ) } - fun createMediaEvent(roomId: String, - attachment: ContentAttachmentData, - rootThreadEventId: String? + fun createMediaEvent( + roomId: String, + attachment: ContentAttachmentData, + rootThreadEventId: String? ): Event { return when (attachment.type) { - ContentAttachmentData.Type.IMAGE -> createImageEvent(roomId, attachment, rootThreadEventId) - ContentAttachmentData.Type.VIDEO -> createVideoEvent(roomId, attachment, rootThreadEventId) - ContentAttachmentData.Type.AUDIO -> createAudioEvent(roomId, attachment, isVoiceMessage = false, rootThreadEventId = rootThreadEventId) + ContentAttachmentData.Type.IMAGE -> createImageEvent(roomId, attachment, rootThreadEventId) + ContentAttachmentData.Type.VIDEO -> createVideoEvent(roomId, attachment, rootThreadEventId) + ContentAttachmentData.Type.AUDIO -> createAudioEvent(roomId, attachment, isVoiceMessage = false, rootThreadEventId = rootThreadEventId) ContentAttachmentData.Type.VOICE_MESSAGE -> createAudioEvent(roomId, attachment, isVoiceMessage = true, rootThreadEventId = rootThreadEventId) - ContentAttachmentData.Type.FILE -> createFileEvent(roomId, attachment, rootThreadEventId) + ContentAttachmentData.Type.FILE -> createFileEvent(roomId, attachment, rootThreadEventId) } } @@ -435,10 +454,11 @@ internal class LocalEchoEventFactory @Inject constructor( return createMessageEvent(roomId, content) } - private fun createAudioEvent(roomId: String, - attachment: ContentAttachmentData, - isVoiceMessage: Boolean, - rootThreadEventId: String? + private fun createAudioEvent( + roomId: String, + attachment: ContentAttachmentData, + isVoiceMessage: Boolean, + rootThreadEventId: String? ): Event { val content = MessageAudioContent( msgType = MessageType.MSGTYPE_AUDIO, @@ -534,7 +554,8 @@ internal class LocalEchoEventFactory @Inject constructor( text: CharSequence, msgType: String, autoMarkdown: Boolean, - formattedText: String?): Event { + formattedText: String? + ): Event { val content = formattedText?.let { TextContent(text.toString(), it) } ?: createTextContent(text, autoMarkdown) return createEvent( roomId, @@ -555,12 +576,14 @@ internal class LocalEchoEventFactory @Inject constructor( /** * Creates a reply to a regular timeline Event or a thread Event if needed. */ - fun createReplyTextEvent(roomId: String, - eventReplied: TimelineEvent, - replyText: CharSequence, - autoMarkdown: Boolean, - rootThreadEventId: String? = null, - showInThread: Boolean): Event? { + fun createReplyTextEvent( + roomId: String, + eventReplied: TimelineEvent, + replyText: CharSequence, + autoMarkdown: Boolean, + rootThreadEventId: String? = null, + showInThread: Boolean + ): Event? { // Fallbacks and event representation // TODO Add error/warning logs when any of this is null val permalink = permalinkFactory.createPermalink(eventReplied.root, false) ?: return null @@ -662,7 +685,7 @@ internal class LocalEchoEventFactory @Inject constructor( when (content?.msgType) { MessageType.MSGTYPE_EMOTE, MessageType.MSGTYPE_TEXT, - MessageType.MSGTYPE_NOTICE -> { + MessageType.MSGTYPE_NOTICE -> { var formattedText: String? = null if (content is MessageContentWithFormattedBody) { formattedText = content.matrixFormattedBody @@ -673,14 +696,14 @@ internal class LocalEchoEventFactory @Inject constructor( TextContent(content.body, formattedText) } } - MessageType.MSGTYPE_FILE -> return TextContent("sent a file.") - MessageType.MSGTYPE_AUDIO -> return TextContent("sent an audio file.") - MessageType.MSGTYPE_IMAGE -> return TextContent("sent an image.") - MessageType.MSGTYPE_VIDEO -> return TextContent("sent a video.") + MessageType.MSGTYPE_FILE -> return TextContent("sent a file.") + MessageType.MSGTYPE_AUDIO -> return TextContent("sent an audio file.") + MessageType.MSGTYPE_IMAGE -> return TextContent("sent an image.") + MessageType.MSGTYPE_VIDEO -> return TextContent("sent a video.") MessageType.MSGTYPE_POLL_START -> { return TextContent((content as? MessagePollContent)?.getBestPollCreationInfo()?.question?.getBestQuestion() ?: "") } - else -> return TextContent(content?.body ?: "") + else -> return TextContent(content?.body ?: "") } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt index bed590fd09..394cb8944f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt @@ -201,7 +201,7 @@ internal class LocalEchoRepository @Inject constructor( // need to resend the attachment true } - else -> { + else -> { Timber.e("Cannot resend message ${event.root.getClearType()} / ${content.msgType}") false } @@ -211,7 +211,7 @@ internal class LocalEchoRepository @Inject constructor( false } } - else -> { + else -> { Timber.e("Unsupported message to resend ${event.root.getClearType()}") false } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt index 1c0da4839a..765c282b65 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt @@ -71,7 +71,7 @@ internal class RedactEventWorker(context: Context, params: WorkerParameters, ses { when (it) { is Failure.NetworkConnection -> Result.retry() - else -> { + else -> { // TODO mark as failed to send? // always return success, or the chain will be stuck for ever! Result.success( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/TextContentExtension.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/TextContentExtension.kt index 49bc05f40c..c5728ba527 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/TextContentExtension.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/TextContentExtension.kt @@ -43,7 +43,8 @@ internal fun TextContent.toMessageTextContent(msgType: String = MessageType.MSGT internal fun TextContent.toThreadTextContent( rootThreadEventId: String, latestThreadEventId: String, - msgType: String = MessageType.MSGTYPE_TEXT): MessageTextContent { + msgType: String = MessageType.MSGTYPE_TEXT +): MessageTextContent { return MessageTextContent( msgType = msgType, format = MessageFormat.FORMAT_MATRIX_HTML.takeIf { formattedText != null }, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/WaveFormSanitizer.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/WaveFormSanitizer.kt index 78a03f3775..c7ca2e770f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/WaveFormSanitizer.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/WaveFormSanitizer.kt @@ -58,7 +58,7 @@ internal class WaveFormSanitizer @Inject constructor() { } } } - else -> { + else -> { sizeInRangeList.addAll(waveForm) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/MentionLinkSpecComparator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/MentionLinkSpecComparator.kt index 3d235ec4d6..db5eec7e7e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/MentionLinkSpecComparator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/MentionLinkSpecComparator.kt @@ -24,9 +24,9 @@ internal class MentionLinkSpecComparator @Inject constructor() : Comparator -1 o1.start > o2.start -> 1 - o1.end < o2.end -> 1 - o1.end > o2.end -> -1 - else -> 0 + o1.end < o2.end -> 1 + o1.end > o2.end -> -1 + else -> 0 } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/TextPillsUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/TextPillsUtils.kt index fa2e0052ab..38bddae951 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/TextPillsUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/pills/TextPillsUtils.kt @@ -90,7 +90,7 @@ internal class TextPillsUtils @Inject constructor( // test if there is an overlap if (b.start in a.start until a.end) { when { - b.end <= a.end -> + b.end <= a.end -> // b is inside a -> b should be removed remove = i + 1 a.end - a.start > b.end - b.start -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt index 8ef631ad36..2c7eea1e54 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt @@ -150,13 +150,13 @@ internal class EventSenderProcessorCoroutine @Inject constructor( canReachServer.set(false) task.markAsFailedOrRetry(exception, 0) } - (exception.isLimitExceededError()) -> { + (exception.isLimitExceededError()) -> { task.markAsFailedOrRetry(exception, exception.getRetryDelay(3_000)) } - exception is CancellationException -> { + exception is CancellationException -> { Timber.v("## $task has been cancelled, try next task") } - else -> { + else -> { Timber.v("## un-retryable error for $task, try next task") // this task is in error, check next one? task.onTaskFailed() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorThread.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorThread.kt index 301f8cb9d6..c5b13043d7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorThread.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorThread.kt @@ -180,7 +180,7 @@ internal class EventSenderProcessorThread @Inject constructor( waitForNetwork() } } - (exception.isLimitExceededError()) -> { + (exception.isLimitExceededError()) -> { if (task.retryCount.getAndIncrement() >= 3) task.onTaskFailed() Timber.v("## SendThread retryLoop retryable error for $task reason: ${exception.localizedMessage}") // wait a bit @@ -188,17 +188,17 @@ internal class EventSenderProcessorThread @Inject constructor( sleep(3_000) continue@retryLoop } - exception.isTokenError() -> { + exception.isTokenError() -> { Timber.v("## SendThread retryLoop retryable TOKEN error, interrupt") // we can exit the loop task.onTaskFailed() throw InterruptedException() } - exception is CancellationException -> { + exception is CancellationException -> { Timber.v("## SendThread task has been cancelled") break@retryLoop } - else -> { + else -> { Timber.v("## SendThread retryLoop Un-Retryable error, try next task") // this task is in error, check next one? task.onTaskFailed() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/QueueMemento.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/QueueMemento.kt index 545fc41737..0eedd4bd4d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/QueueMemento.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/QueueMemento.kt @@ -35,11 +35,13 @@ import javax.inject.Inject private const val PERSISTENCE_KEY = "ManagedBySender" -internal class QueueMemento @Inject constructor(context: Context, - @SessionId sessionId: String, - private val queuedTaskFactory: QueuedTaskFactory, - private val localEchoRepository: LocalEchoRepository, - private val cryptoService: CryptoService) { +internal class QueueMemento @Inject constructor( + context: Context, + @SessionId sessionId: String, + private val queuedTaskFactory: QueuedTaskFactory, + private val localEchoRepository: LocalEchoRepository, + private val cryptoService: CryptoService +) { private val storage = context.getSharedPreferences("QueueMemento_$sessionId", Context.MODE_PRIVATE) private val trackedTasks = mutableListOf() @@ -74,11 +76,11 @@ internal class QueueMemento @Inject constructor(context: Context, encrypt = task.encrypt, order = order ) - is RedactQueuedTask -> RedactEventTaskInfo( + is RedactQueuedTask -> RedactEventTaskInfo( redactionLocalEcho = task.redactionLocalEchoId, order = order ) - else -> null + else -> null } } @@ -92,7 +94,7 @@ internal class QueueMemento @Inject constructor(context: Context, ?.forEach { info -> try { when (info) { - is SendEventTaskInfo -> { + is SendEventTaskInfo -> { localEchoRepository.getUpToDateEcho(info.localEchoId)?.let { if (it.sendState.isSending() && it.eventId != null && it.roomId != null) { localEchoRepository.updateSendState(it.eventId, it.roomId, SendState.UNSENT) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/SendEventQueuedTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/SendEventQueuedTask.kt index 49492e7990..1ba4e09caf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/SendEventQueuedTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/SendEventQueuedTask.kt @@ -45,7 +45,7 @@ internal class SendEventQueuedTask( localEchoRepository.deleteFailedEchoAsync(eventId = event.eventId, roomId = event.roomId ?: "") // TODO update aggregation :/ or it will stay locally } - else -> { + else -> { localEchoRepository.updateSendState(event.eventId!!, event.roomId, SendState.UNDELIVERED) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt index 60231892e1..2a980f3286 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt @@ -41,11 +41,12 @@ import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.internal.session.content.FileUploader import org.matrix.android.sdk.internal.session.permalinks.ViaParameterFinder -internal class DefaultStateService @AssistedInject constructor(@Assisted private val roomId: String, - private val stateEventDataSource: StateEventDataSource, - private val sendStateTask: SendStateTask, - private val fileUploader: FileUploader, - private val viaParameterFinder: ViaParameterFinder +internal class DefaultStateService @AssistedInject constructor( + @Assisted private val roomId: String, + private val stateEventDataSource: StateEventDataSource, + private val sendStateTask: SendStateTask, + private val fileUploader: FileUploader, + private val viaParameterFinder: ViaParameterFinder ) : StateService { @AssistedFactory @@ -87,7 +88,7 @@ internal class DefaultStateService @AssistedInject constructor(@Assisted private // Safe treatment for PowerLevelContent return when (eventType) { EventType.STATE_ROOM_POWER_LEVELS -> toSafePowerLevelsContentDict() - else -> this + else -> this } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/StateEventDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/StateEventDataSource.kt index 42d6677409..18c709adf2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/StateEventDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/StateEventDataSource.kt @@ -76,10 +76,11 @@ internal class StateEventDataSource @Inject constructor( } } - private fun buildStateEventQuery(realm: Realm, - roomId: String, - eventTypes: Set, - stateKey: QueryStringValue + private fun buildStateEventQuery( + realm: Realm, + roomId: String, + eventTypes: Set, + stateKey: QueryStringValue ): RealmQuery { return with(queryStringValueProcessor) { realm.where() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt index 496bc7097f..f10479d873 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt @@ -101,11 +101,11 @@ internal class Graph { // it's a candidate destination = it.destination } - inPath -> { + inPath -> { // Cycle!! backwardEdges.add(it) } - completed -> { + completed -> { // dead end } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/HierarchyLiveDataHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/HierarchyLiveDataHelper.kt index 29db8431fd..b141dfffa7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/HierarchyLiveDataHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/HierarchyLiveDataHelper.kt @@ -24,7 +24,8 @@ import org.matrix.android.sdk.api.util.Optional internal class HierarchyLiveDataHelper( val spaceId: String, val memberships: List, - val roomSummaryDataSource: RoomSummaryDataSource) { + val roomSummaryDataSource: RoomSummaryDataSource +) { private val sources = HashMap>>() private val mediatorLiveData = MediatorLiveData>() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryDataSource.kt index 4b453908e7..cb7dc270e8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryDataSource.kt @@ -85,16 +85,20 @@ internal class RoomSummaryDataSource @Inject constructor( } } - fun getRoomSummaries(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): List { + fun getRoomSummaries( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): List { return monarchy.fetchAllMappedSync( { roomSummariesQuery(it, queryParams).process(sortOrder) }, { roomSummaryMapper.map(it) } ) } - fun getRoomSummariesLive(queryParams: RoomSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): LiveData> { + fun getRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): LiveData> { return monarchy.findAllMappedWithChanges( { roomSummariesQuery(it, queryParams).process(sortOrder) @@ -103,8 +107,10 @@ internal class RoomSummaryDataSource @Inject constructor( ) } - fun getSpaceSummariesLive(queryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): LiveData> { + fun getSpaceSummariesLive( + queryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): LiveData> { return getRoomSummariesLive(queryParams, sortOrder) } @@ -129,8 +135,10 @@ internal class RoomSummaryDataSource @Inject constructor( } } - fun getSpaceSummaries(spaceSummaryQueryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder = RoomSortOrder.NONE): List { + fun getSpaceSummaries( + spaceSummaryQueryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder = RoomSortOrder.NONE + ): List { return getRoomSummaries(spaceSummaryQueryParams, sortOrder) } @@ -171,9 +179,11 @@ internal class RoomSummaryDataSource @Inject constructor( .sort(RoomSummaryEntityFields.BREADCRUMBS_INDEX) } - fun getSortedPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, - pagedListConfig: PagedList.Config, - sortOrder: RoomSortOrder): LiveData> { + fun getSortedPagedRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + pagedListConfig: PagedList.Config, + sortOrder: RoomSortOrder + ): LiveData> { val realmDataSourceFactory = monarchy.createDataSourceFactory { realm -> roomSummariesQuery(realm, queryParams).process(sortOrder) } @@ -186,10 +196,12 @@ internal class RoomSummaryDataSource @Inject constructor( ) } - fun getUpdatablePagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, - pagedListConfig: PagedList.Config, - sortOrder: RoomSortOrder, - getFlattenedParents: Boolean = false): UpdatableLivePageResult { + fun getUpdatablePagedRoomSummariesLive( + queryParams: RoomSummaryQueryParams, + pagedListConfig: PagedList.Config, + sortOrder: RoomSortOrder, + getFlattenedParents: Boolean = false + ): UpdatableLivePageResult { val realmDataSourceFactory = monarchy.createDataSourceFactory { realm -> roomSummariesQuery(realm, queryParams).process(sortOrder) } @@ -293,19 +305,19 @@ internal class RoomSummaryDataSource @Inject constructor( query.equalTo(RoomSummaryEntityFields.ROOM_TYPE, it) } when (queryParams.roomCategoryFilter) { - RoomCategoryFilter.ONLY_DM -> query.equalTo(RoomSummaryEntityFields.IS_DIRECT, true) - RoomCategoryFilter.ONLY_ROOMS -> query.equalTo(RoomSummaryEntityFields.IS_DIRECT, false) + RoomCategoryFilter.ONLY_DM -> query.equalTo(RoomSummaryEntityFields.IS_DIRECT, true) + RoomCategoryFilter.ONLY_ROOMS -> query.equalTo(RoomSummaryEntityFields.IS_DIRECT, false) RoomCategoryFilter.ONLY_WITH_NOTIFICATIONS -> query.greaterThan(RoomSummaryEntityFields.NOTIFICATION_COUNT, 0) - null -> Unit + null -> Unit } // Timber.w("VAL: activeSpaceId : ${queryParams.activeSpaceId}") when (queryParams.spaceFilter) { - SpaceFilter.OrphanRooms -> { + SpaceFilter.OrphanRooms -> { // orphan rooms query.isNull(RoomSummaryEntityFields.FLATTEN_PARENT_IDS) } - is SpaceFilter.ActiveSpace -> { + is SpaceFilter.ActiveSpace -> { // It's annoying but for now realm java does not support querying in primitive list :/ // https://github.com/realm/realm-java/issues/5361 query.contains(RoomSummaryEntityFields.FLATTEN_PARENT_IDS, queryParams.spaceFilter.spaceId) @@ -313,7 +325,7 @@ internal class RoomSummaryDataSource @Inject constructor( is SpaceFilter.ExcludeSpace -> { query.not().contains(RoomSummaryEntityFields.FLATTEN_PARENT_IDS, queryParams.spaceFilter.spaceId) } - null -> Unit // nop + null -> Unit // nop } queryParams.activeGroupId?.let { activeGroupId -> @@ -424,11 +436,13 @@ internal class RoomSummaryDataSource @Inject constructor( } } - fun flattenSubSpace(current: RoomSummary, - parenting: List, - output: MutableList, - memberShips: List, - includeCurrent: Boolean = true) { + fun flattenSubSpace( + current: RoomSummary, + parenting: List, + output: MutableList, + memberShips: List, + includeCurrent: Boolean = true + ) { if (includeCurrent) { output.add(current) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt index 611d6dc65e..e4afe7aa49 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt @@ -85,13 +85,15 @@ internal class RoomSummaryUpdater @Inject constructor( } } - fun update(realm: Realm, - roomId: String, - membership: Membership? = null, - roomSummary: RoomSyncSummary? = null, - unreadNotifications: RoomSyncUnreadNotifications? = null, - updateMembers: Boolean = false, - inviterId: String? = null) { + fun update( + realm: Realm, + roomId: String, + membership: Membership? = null, + roomSummary: RoomSyncSummary? = null, + unreadNotifications: RoomSyncUnreadNotifications? = null, + updateMembers: Boolean = false, + inviterId: String? = null + ) { val roomSummaryEntity = RoomSummaryEntity.getOrCreate(realm, roomId) if (roomSummary != null) { if (roomSummary.heroes.isNotEmpty()) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt index fad21c0918..44a786a95d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt @@ -259,8 +259,8 @@ internal class DefaultTimeline( strategy = when { rootThreadEventId != null -> buildStrategy(LoadTimelineStrategy.Mode.Thread(rootThreadEventId)) - eventId == null -> buildStrategy(LoadTimelineStrategy.Mode.Live) - else -> buildStrategy(LoadTimelineStrategy.Mode.Permalink(eventId)) + eventId == null -> buildStrategy(LoadTimelineStrategy.Mode.Live) + else -> buildStrategy(LoadTimelineStrategy.Mode.Permalink(eventId)) } rootThreadEventId?.let { @@ -344,7 +344,7 @@ internal class DefaultTimeline( private fun updateState(direction: Timeline.Direction, update: (Timeline.PaginationState) -> Timeline.PaginationState) { val stateReference = when (direction) { - Timeline.Direction.FORWARDS -> forwardState + Timeline.Direction.FORWARDS -> forwardState Timeline.Direction.BACKWARDS -> backwardState } val currentValue = stateReference.get() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveTimelineEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveTimelineEvent.kt index e765e05578..4be97efd6c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveTimelineEvent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveTimelineEvent.kt @@ -36,11 +36,13 @@ import org.matrix.android.sdk.internal.database.query.where /** * This class takes care of handling case where local echo is replaced by the synced event in the db. */ -internal class LiveTimelineEvent(private val monarchy: Monarchy, - private val coroutineScope: CoroutineScope, - private val timelineEventMapper: TimelineEventMapper, - private val roomId: String, - private val eventId: String) : +internal class LiveTimelineEvent( + private val monarchy: Monarchy, + private val coroutineScope: CoroutineScope, + private val timelineEventMapper: TimelineEventMapper, + private val roomId: String, + private val eventId: String +) : MediatorLiveData>() { init { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt index 4f65f85ce4..c5d4d346fd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt @@ -267,7 +267,7 @@ internal class LoadTimelineStrategy constructor( private fun getChunkEntity(realm: Realm): RealmResults { return when (mode) { - is Mode.Live -> { + is Mode.Live -> { ChunkEntity.where(realm, roomId) .equalTo(ChunkEntityFields.IS_LAST_FORWARD, true) .findAll() @@ -275,7 +275,7 @@ internal class LoadTimelineStrategy constructor( is Mode.Permalink -> { ChunkEntity.findAllIncludingEvents(realm, listOf(mode.originEventId)) } - is Mode.Thread -> { + is Mode.Thread -> { recreateThreadChunkEntity(realm, mode.rootThreadEventId) ChunkEntity.where(realm, roomId) .equalTo(ChunkEntityFields.ROOT_THREAD_EVENT_ID, mode.rootThreadEventId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/PaginationDirection.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/PaginationDirection.kt index 930d01759e..37092de9c4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/PaginationDirection.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/PaginationDirection.kt @@ -31,7 +31,7 @@ internal enum class PaginationDirection(val value: String) { fun reversed(): PaginationDirection { return when (this) { - FORWARDS -> BACKWARDS + FORWARDS -> BACKWARDS BACKWARDS -> FORWARDS } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt index 6a5f9da8a6..fd76d5ae28 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt @@ -213,7 +213,7 @@ internal class TimelineChunk( fetchFromServerIfNeeded -> { fetchFromServer(offsetCount, chunkEntity.nextToken, direction) } - else -> { + else -> { LoadMoreResult.SUCCESS } } @@ -231,7 +231,7 @@ internal class TimelineChunk( fetchFromServerIfNeeded -> { fetchFromServer(offsetCount, chunkEntity.prevToken, direction) } - else -> { + else -> { LoadMoreResult.SUCCESS } } @@ -457,7 +457,7 @@ internal class TimelineChunk( return when (this) { TokenChunkEventPersistor.Result.REACHED_END -> LoadMoreResult.REACHED_END TokenChunkEventPersistor.Result.SHOULD_FETCH_MORE, - TokenChunkEventPersistor.Result.SUCCESS -> LoadMoreResult.SUCCESS + TokenChunkEventPersistor.Result.SUCCESS -> LoadMoreResult.SUCCESS } } @@ -465,7 +465,7 @@ internal class TimelineChunk( return when (this) { DefaultFetchThreadTimelineTask.Result.REACHED_END -> LoadMoreResult.REACHED_END DefaultFetchThreadTimelineTask.Result.SHOULD_FETCH_MORE, - DefaultFetchThreadTimelineTask.Result.SUCCESS -> LoadMoreResult.SUCCESS + DefaultFetchThreadTimelineTask.Result.SUCCESS -> LoadMoreResult.SUCCESS } } @@ -486,6 +486,35 @@ internal class TimelineChunk( private fun handleDatabaseChangeSet(results: RealmResults, changeSet: OrderedCollectionChangeSet) { val insertions = changeSet.insertionRanges for (range in insertions) { + // Check if the insertion's displayIndices match our expectations - or skip this insertion. + // Inconsistencies (missing messages) can happen otherwise if we get insertions before having loaded all timeline events of the chunk. + if (builtEvents.isNotEmpty()) { + // Check consistency to item before insertions + if (range.startIndex > 0) { + val firstInsertion = results[range.startIndex]!! + val lastBeforeInsertion = builtEvents[range.startIndex - 1] + if (firstInsertion.displayIndex + 1 != lastBeforeInsertion.displayIndex) { + Timber.i( + "handleDatabaseChangeSet: skip insertion at ${range.startIndex}/${builtEvents.size}, " + + "displayIndex mismatch at ${range.startIndex}: ${firstInsertion.displayIndex} -> ${lastBeforeInsertion.displayIndex}" + ) + continue + } + } + // Check consistency to item after insertions + if (range.startIndex < builtEvents.size) { + val lastInsertion = results[range.startIndex + range.length - 1]!! + val firstAfterInsertion = builtEvents[range.startIndex] + if (firstAfterInsertion.displayIndex + 1 != lastInsertion.displayIndex) { + Timber.i( + "handleDatabaseChangeSet: skip insertion at ${range.startIndex}/${builtEvents.size}, " + + "displayIndex mismatch at ${range.startIndex + range.length}: " + + "${firstAfterInsertion.displayIndex} -> ${lastInsertion.displayIndex}" + ) + continue + } + } + } val newItems = results .subList(range.startIndex, range.startIndex + range.length) .map { it.buildAndDecryptIfNeeded() } @@ -503,8 +532,12 @@ internal class TimelineChunk( for (range in modifications) { for (modificationIndex in (range.startIndex until range.startIndex + range.length)) { val updatedEntity = results[modificationIndex] ?: continue + val displayIndex = builtEventsIndexes[updatedEntity.eventId] + if (displayIndex == null) { + continue + } try { - builtEvents[modificationIndex] = updatedEntity.buildAndDecryptIfNeeded() + builtEvents[displayIndex] = updatedEntity.buildAndDecryptIfNeeded() } catch (failure: Throwable) { Timber.v("Fail to update items at index: $modificationIndex") } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineEventDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineEventDataSource.kt index 8b58d3ca5c..b9aca7d37b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineEventDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineEventDataSource.kt @@ -33,10 +33,12 @@ import org.matrix.android.sdk.internal.di.SessionDatabase import org.matrix.android.sdk.internal.task.TaskExecutor import javax.inject.Inject -internal class TimelineEventDataSource @Inject constructor(private val realmSessionProvider: RealmSessionProvider, - private val timelineEventMapper: TimelineEventMapper, - private val taskExecutor: TaskExecutor, - @SessionDatabase private val monarchy: Monarchy) { +internal class TimelineEventDataSource @Inject constructor( + private val realmSessionProvider: RealmSessionProvider, + private val timelineEventMapper: TimelineEventMapper, + private val taskExecutor: TaskExecutor, + @SessionDatabase private val monarchy: Monarchy +) { fun getTimelineEvent(roomId: String, eventId: String): TimelineEvent? { return realmSessionProvider.withRealm { realm -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TokenChunkEventPersistor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TokenChunkEventPersistor.kt index 96ceb6c6dc..da73727065 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TokenChunkEventPersistor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TokenChunkEventPersistor.kt @@ -65,9 +65,11 @@ internal class TokenChunkEventPersistor @Inject constructor( SUCCESS } - suspend fun insertInDb(receivedChunk: TokenChunkEvent, - roomId: String, - direction: PaginationDirection): Result { + suspend fun insertInDb( + receivedChunk: TokenChunkEvent, + roomId: String, + direction: PaginationDirection + ): Result { monarchy .awaitTransaction { realm -> Timber.v("Start persisting ${receivedChunk.events.size} events in $roomId towards $direction") @@ -203,7 +205,7 @@ internal class TokenChunkEventPersistor @Inject constructor( existingChunk.nextChunk = currentChunk } } - PaginationDirection.FORWARDS -> { + PaginationDirection.FORWARDS -> { if (currentChunk.prevChunk == existingChunk) { Timber.w("Avoid double link, shouldn't happen in an ideal world") } else { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt index 66bb04400b..04c72b5d6d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt @@ -74,7 +74,7 @@ internal class UIEchoManager( when (timelineEvent.root.getClearType()) { EventType.REDACTION -> { } - EventType.REACTION -> { + EventType.REACTION -> { val content: ReactionContent? = timelineEvent.root.content?.toModel() if (RelationType.ANNOTATION == content?.relatesTo?.type) { val reaction = content.relatesTo.key diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/DefaultSearchService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/DefaultSearchService.kt index 12ca36fa6b..5e33631f2c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/DefaultSearchService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/DefaultSearchService.kt @@ -24,14 +24,16 @@ internal class DefaultSearchService @Inject constructor( private val searchTask: SearchTask ) : SearchService { - override suspend fun search(searchTerm: String, - roomId: String, - nextBatch: String?, - orderByRecent: Boolean, - limit: Int, - beforeLimit: Int, - afterLimit: Int, - includeProfile: Boolean): SearchResult { + override suspend fun search( + searchTerm: String, + roomId: String, + nextBatch: String?, + orderByRecent: Boolean, + limit: Int, + beforeLimit: Int, + afterLimit: Int, + includeProfile: Boolean + ): SearchResult { return searchTask.execute( SearchTask.Params( searchTerm = searchTerm, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchAPI.kt index b5099e7238..4cd96c408a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchAPI.kt @@ -30,6 +30,8 @@ internal interface SearchAPI { * Ref: https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-search */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "search") - suspend fun search(@Query("next_batch") nextBatch: String?, - @Body body: SearchRequestBody): SearchResponse + suspend fun search( + @Query("next_batch") nextBatch: String?, + @Body body: SearchRequestBody + ): SearchResponse } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt index 07a5cbe5a0..8b35bd173e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt @@ -124,7 +124,7 @@ internal class SecretStoringUtils @Inject constructor( fun securelyStoreString(secret: String, keyAlias: String): ByteArray { return when { buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M -> encryptStringM(secret, keyAlias) - else -> encryptString(secret, keyAlias) + else -> encryptString(secret, keyAlias) } } @@ -138,8 +138,8 @@ internal class SecretStoringUtils @Inject constructor( // First get the format return when (val format = inputStream.read().toByte()) { FORMAT_API_M -> decryptStringM(inputStream, keyAlias) - FORMAT_1 -> decryptString(inputStream, keyAlias) - else -> throw IllegalArgumentException("Unknown format $format") + FORMAT_1 -> decryptString(inputStream, keyAlias) + else -> throw IllegalArgumentException("Unknown format $format") } } } @@ -148,7 +148,7 @@ internal class SecretStoringUtils @Inject constructor( fun securelyStoreObject(any: Any, keyAlias: String, output: OutputStream) { when { buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M -> saveSecureObjectM(keyAlias, output, any) - else -> saveSecureObject(keyAlias, output, any) + else -> saveSecureObject(keyAlias, output, any) } } @@ -157,8 +157,8 @@ internal class SecretStoringUtils @Inject constructor( // First get the format return when (val format = inputStream.read().toByte()) { FORMAT_API_M -> loadSecureObjectM(keyAlias, inputStream) - FORMAT_1 -> loadSecureObject(keyAlias, inputStream) - else -> throw IllegalArgumentException("Unknown format $format") + FORMAT_1 -> loadSecureObject(keyAlias, inputStream) + else -> throw IllegalArgumentException("Unknown format $format") } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/signout/DefaultSignOutService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/signout/DefaultSignOutService.kt index e7b20f905b..1bb86ecb4b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/signout/DefaultSignOutService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/signout/DefaultSignOutService.kt @@ -21,9 +21,10 @@ import org.matrix.android.sdk.api.session.signout.SignOutService import org.matrix.android.sdk.internal.auth.SessionParamsStore import javax.inject.Inject -internal class DefaultSignOutService @Inject constructor(private val signOutTask: SignOutTask, - private val signInAgainTask: SignInAgainTask, - private val sessionParamsStore: SessionParamsStore +internal class DefaultSignOutService @Inject constructor( + private val signOutTask: SignOutTask, + private val signInAgainTask: SignInAgainTask, + private val sessionParamsStore: SessionParamsStore ) : SignOutService { override suspend fun signInAgain(password: String) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpace.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpace.kt index 178a29a5a0..32faffa670 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpace.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpace.kt @@ -44,11 +44,13 @@ internal class DefaultSpace( return spaceSummaryDataSource.getSpaceSummary(room.roomId) } - override suspend fun addChildren(roomId: String, - viaServers: List?, - order: String?, + override suspend fun addChildren( + roomId: String, + viaServers: List?, + order: String?, // autoJoin: Boolean, - suggested: Boolean?) { + suggested: Boolean? + ) { // Find best via val bestVia = viaServers ?: (spaceSummaryDataSource.getRoomSummary(roomId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpaceService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpaceService.kt index 9320665688..c08d9389a8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpaceService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/DefaultSpaceService.kt @@ -99,13 +99,17 @@ internal class DefaultSpaceService @Inject constructor( return spaceGetter.get(spaceId) } - override fun getSpaceSummariesLive(queryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder): LiveData> { + override fun getSpaceSummariesLive( + queryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder + ): LiveData> { return roomSummaryDataSource.getSpaceSummariesLive(queryParams, sortOrder) } - override fun getSpaceSummaries(spaceSummaryQueryParams: SpaceSummaryQueryParams, - sortOrder: RoomSortOrder): List { + override fun getSpaceSummaries( + spaceSummaryQueryParams: SpaceSummaryQueryParams, + sortOrder: RoomSortOrder + ): List { return roomSummaryDataSource.getSpaceSummaries(spaceSummaryQueryParams, sortOrder) } @@ -221,9 +225,11 @@ internal class DefaultSpaceService @Inject constructor( worldReadable = summary.isWorldReadable ) - override suspend fun joinSpace(spaceIdOrAlias: String, - reason: String?, - viaServers: List): JoinSpaceResult { + override suspend fun joinSpace( + spaceIdOrAlias: String, + reason: String?, + viaServers: List + ): JoinSpaceResult { return joinSpaceTask.execute(JoinSpaceTask.Params(spaceIdOrAlias, reason, viaServers)) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt index 33c3c3929f..126245d015 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt @@ -38,7 +38,8 @@ internal interface SpaceApi { @Query("suggested_only") suggestedOnly: Boolean?, @Query("limit") limit: Int?, @Query("max_depth") maxDepth: Int?, - @Query("from") from: String?): SpacesResponse + @Query("from") from: String? + ): SpacesResponse /** * Unstable version of [getSpaceHierarchy]. @@ -49,5 +50,6 @@ internal interface SpaceApi { @Query("suggested_only") suggestedOnly: Boolean?, @Query("limit") limit: Int?, @Query("max_depth") maxDepth: Int?, - @Query("from") from: String?): SpacesResponse + @Query("from") from: String? + ): SpacesResponse } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/DefaultSyncService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/DefaultSyncService.kt new file mode 100644 index 0000000000..37869b88f9 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/DefaultSyncService.kt @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session.sync + +import androidx.lifecycle.LiveData +import org.matrix.android.sdk.api.session.sync.SyncRequestState +import org.matrix.android.sdk.api.session.sync.SyncService +import org.matrix.android.sdk.internal.di.SessionId +import org.matrix.android.sdk.internal.di.WorkManagerProvider +import org.matrix.android.sdk.internal.session.SessionState +import org.matrix.android.sdk.internal.session.sync.job.SyncThread +import org.matrix.android.sdk.internal.session.sync.job.SyncWorker +import timber.log.Timber +import javax.inject.Inject +import javax.inject.Provider + +internal class DefaultSyncService @Inject constructor( + @SessionId val sessionId: String, + private val workManagerProvider: WorkManagerProvider, + private val syncThreadProvider: Provider, + private val syncTokenStore: SyncTokenStore, + private val syncRequestStateTracker: SyncRequestStateTracker, + private val sessionState: SessionState, +) : SyncService { + private var syncThread: SyncThread? = null + + override fun requireBackgroundSync() { + SyncWorker.requireBackgroundSync(workManagerProvider, sessionId) + } + + override fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) { + SyncWorker.automaticallyBackgroundSync(workManagerProvider, sessionId, timeOutInSeconds, repeatDelayInSeconds) + } + + override fun stopAnyBackgroundSync() { + SyncWorker.stopAnyBackgroundSync(workManagerProvider) + } + + override fun startSync(fromForeground: Boolean) { + Timber.i("Starting sync thread") + assert(sessionState.isOpen) + val localSyncThread = getSyncThread() + localSyncThread.setInitialForeground(fromForeground) + if (!localSyncThread.isAlive) { + localSyncThread.start() + } else { + localSyncThread.restart() + Timber.w("Attempt to start an already started thread") + } + } + + override fun stopSync() { + assert(sessionState.isOpen) + syncThread?.kill() + syncThread = null + } + + override fun getSyncStateLive() = getSyncThread().liveState() + + override fun syncFlow() = getSyncThread().syncFlow() + + override fun getSyncState() = getSyncThread().currentState() + + override fun getSyncRequestStateLive(): LiveData { + return syncRequestStateTracker.syncRequestState + } + + override fun hasAlreadySynced(): Boolean { + return syncTokenStore.getLastToken() != null + } + + private fun getSyncThread(): SyncThread { + return syncThread ?: syncThreadProvider.get().also { + syncThread = it + } + } +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/Extensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/Extensions.kt new file mode 100644 index 0000000000..ae542103b7 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/Extensions.kt @@ -0,0 +1,49 @@ +/* + * Copyright 2021 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session.sync + +import org.matrix.android.sdk.api.session.sync.InitialSyncStep + +internal inline fun reportSubtask( + reporter: ProgressReporter?, + initialSyncStep: InitialSyncStep, + totalProgress: Int, + parentWeight: Float, + block: () -> T +): T { + reporter?.startTask(initialSyncStep, totalProgress, parentWeight) + return block().also { + reporter?.endTask() + } +} + +internal inline fun Map.mapWithProgress( + reporter: ProgressReporter?, + initialSyncStep: InitialSyncStep, + parentWeight: Float, + transform: (Map.Entry) -> R +): List { + var current = 0F + reporter?.startTask(initialSyncStep, count() + 1, parentWeight) + return map { + reporter?.reportProgress(current) + current++ + transform.invoke(it) + }.also { + reporter?.endTask() + } +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/ProgressReporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/ProgressReporter.kt similarity index 74% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/ProgressReporter.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/ProgressReporter.kt index 8a7b26b4b8..6d77b9be5e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/ProgressReporter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/ProgressReporter.kt @@ -14,14 +14,16 @@ * limitations under the License. */ -package org.matrix.android.sdk.internal.session.initsync +package org.matrix.android.sdk.internal.session.sync -import org.matrix.android.sdk.api.session.initsync.InitSyncStep +import org.matrix.android.sdk.api.session.sync.InitialSyncStep internal interface ProgressReporter { - fun startTask(initSyncStep: InitSyncStep, - totalProgress: Int, - parentWeight: Float) + fun startTask( + initialSyncStep: InitialSyncStep, + totalProgress: Int, + parentWeight: Float + ) fun reportProgress(progress: Float) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt index 6c8a71f35e..2a2fd6ab1d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt @@ -31,10 +31,11 @@ internal interface SyncAPI { * Set all the timeouts to 1 minute by default. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sync") - suspend fun sync(@QueryMap params: Map, - @Header(TimeOutInterceptor.CONNECT_TIMEOUT) connectTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, - @Header(TimeOutInterceptor.READ_TIMEOUT) readTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, - @Header(TimeOutInterceptor.WRITE_TIMEOUT) writeTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT + suspend fun sync( + @QueryMap params: Map, + @Header(TimeOutInterceptor.CONNECT_TIMEOUT) connectTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, + @Header(TimeOutInterceptor.READ_TIMEOUT) readTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, + @Header(TimeOutInterceptor.WRITE_TIMEOUT) writeTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT ): SyncResponse /** @@ -42,9 +43,10 @@ internal interface SyncAPI { */ @Streaming @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sync") - fun syncStream(@QueryMap params: Map, - @Header(TimeOutInterceptor.CONNECT_TIMEOUT) connectTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, - @Header(TimeOutInterceptor.READ_TIMEOUT) readTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, - @Header(TimeOutInterceptor.WRITE_TIMEOUT) writeTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT + fun syncStream( + @QueryMap params: Map, + @Header(TimeOutInterceptor.CONNECT_TIMEOUT) connectTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, + @Header(TimeOutInterceptor.READ_TIMEOUT) readTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT, + @Header(TimeOutInterceptor.WRITE_TIMEOUT) writeTimeOut: Long = TimeOutInterceptor.DEFAULT_LONG_TIMEOUT ): Call } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncModule.kt index 4b31dc4d9b..d78070439c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncModule.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.internal.session.sync import dagger.Binds import dagger.Module import dagger.Provides +import org.matrix.android.sdk.api.session.sync.SyncService import org.matrix.android.sdk.internal.session.SessionScope import retrofit2.Retrofit @@ -35,6 +36,9 @@ internal abstract class SyncModule { } } + @Binds + abstract fun bindSyncService(service: DefaultSyncService): SyncService + @Binds abstract fun bindSyncTask(task: DefaultSyncTask): SyncTask diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt index ce41a4568c..9df6d52ad3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt @@ -35,9 +35,9 @@ internal enum class SyncPresence(val value: String) { companion object { fun from(presenceEnum: PresenceEnum): SyncPresence { return when (presenceEnum) { - PresenceEnum.ONLINE -> Online - PresenceEnum.OFFLINE -> Offline - PresenceEnum.BUSY -> Busy + PresenceEnum.ONLINE -> Online + PresenceEnum.OFFLINE -> Offline + PresenceEnum.BUSY -> Busy PresenceEnum.UNAVAILABLE -> Unavailable } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncRequestStateTracker.kt similarity index 63% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncRequestStateTracker.kt index 2aa0be80c9..bcc5fcf9ab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncRequestStateTracker.kt @@ -13,52 +13,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.matrix.android.sdk.internal.session.initsync -import androidx.lifecycle.LiveData +package org.matrix.android.sdk.internal.session.sync + import androidx.lifecycle.MutableLiveData -import org.matrix.android.sdk.api.session.initsync.InitSyncStep -import org.matrix.android.sdk.api.session.initsync.SyncStatusService +import org.matrix.android.sdk.api.session.sync.InitialSyncStep +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.internal.session.SessionScope import javax.inject.Inject @SessionScope -internal class DefaultSyncStatusService @Inject constructor() : - SyncStatusService, +internal class SyncRequestStateTracker @Inject constructor() : ProgressReporter { - private val status = MutableLiveData() + val syncRequestState = MutableLiveData() private var rootTask: TaskInfo? = null - override fun getSyncStatusLive(): LiveData { - return status - } - // Only to be used for incremental sync - fun setStatus(newStatus: SyncStatusService.Status.IncrementalSyncStatus) { - status.postValue(newStatus) + fun setSyncRequestState(newSyncRequestState: SyncRequestState.IncrementalSyncRequestState) { + syncRequestState.postValue(newSyncRequestState) } /** * Create a rootTask. */ - fun startRoot(initSyncStep: InitSyncStep, - totalProgress: Int) { + fun startRoot( + initialSyncStep: InitialSyncStep, + totalProgress: Int + ) { endAll() - rootTask = TaskInfo(initSyncStep, totalProgress, null, 1F) + rootTask = TaskInfo(initialSyncStep, totalProgress, null, 1F) reportProgress(0F) } /** * Add a child to the leaf. */ - override fun startTask(initSyncStep: InitSyncStep, - totalProgress: Int, - parentWeight: Float) { + override fun startTask( + initialSyncStep: InitialSyncStep, + totalProgress: Int, + parentWeight: Float + ) { val currentLeaf = rootTask?.leaf() ?: return currentLeaf.child = TaskInfo( - initSyncStep = initSyncStep, + initialSyncStep = initialSyncStep, totalProgress = totalProgress, parent = currentLeaf, parentWeight = parentWeight @@ -72,7 +71,7 @@ internal class DefaultSyncStatusService @Inject constructor() : // Update the progress of the leaf and all its parents leaf.setProgress(progress) // Then update the live data using leaf wording and root progress - status.postValue(SyncStatusService.Status.InitialSyncProgressing(leaf.initSyncStep, root.currentProgress.toInt())) + syncRequestState.postValue(SyncRequestState.InitialSyncProgressing(leaf.initialSyncStep, root.currentProgress.toInt())) } } } @@ -87,13 +86,13 @@ internal class DefaultSyncStatusService @Inject constructor() : // And close it endedTask.parent.child = null } else { - status.postValue(SyncStatusService.Status.Idle) + syncRequestState.postValue(SyncRequestState.Idle) } } } fun endAll() { rootTask = null - status.postValue(SyncStatusService.Status.Idle) + syncRequestState.postValue(SyncRequestState.Idle) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncResponseHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncResponseHandler.kt index 02a7a9a37f..9e5302222a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncResponseHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncResponseHandler.kt @@ -18,9 +18,9 @@ package org.matrix.android.sdk.internal.session.sync import androidx.work.ExistingPeriodicWorkPolicy import com.zhuinden.monarchy.Monarchy -import org.matrix.android.sdk.api.session.initsync.InitSyncStep import org.matrix.android.sdk.api.session.pushrules.PushRuleService import org.matrix.android.sdk.api.session.pushrules.RuleScope +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import org.matrix.android.sdk.api.session.sync.model.GroupsSyncResponse import org.matrix.android.sdk.api.session.sync.model.RoomsSyncResponse import org.matrix.android.sdk.api.session.sync.model.SyncResponse @@ -32,8 +32,6 @@ import org.matrix.android.sdk.internal.di.WorkManagerProvider import org.matrix.android.sdk.internal.session.SessionListeners import org.matrix.android.sdk.internal.session.dispatchTo import org.matrix.android.sdk.internal.session.group.GetGroupDataWorker -import org.matrix.android.sdk.internal.session.initsync.ProgressReporter -import org.matrix.android.sdk.internal.session.initsync.reportSubtask import org.matrix.android.sdk.internal.session.pushrules.ProcessEventForPushTask import org.matrix.android.sdk.internal.session.sync.handler.CryptoSyncHandler import org.matrix.android.sdk.internal.session.sync.handler.GroupSyncHandler @@ -68,9 +66,11 @@ internal class SyncResponseHandler @Inject constructor( private val presenceSyncHandler: PresenceSyncHandler ) { - suspend fun handleResponse(syncResponse: SyncResponse, - fromToken: String?, - reporter: ProgressReporter?) { + suspend fun handleResponse( + syncResponse: SyncResponse, + fromToken: String?, + reporter: ProgressReporter? + ) { val isInitialSync = fromToken == null Timber.v("Start handling sync, is InitialSync: $isInitialSync") @@ -88,7 +88,7 @@ internal class SyncResponseHandler @Inject constructor( // to ensure to decrypt them properly measureTimeMillis { Timber.v("Handle toDevice") - reportSubtask(reporter, InitSyncStep.ImportingAccountCrypto, 100, 0.1f) { + reportSubtask(reporter, InitialSyncStep.ImportingAccountCrypto, 100, 0.1f) { if (syncResponse.toDevice != null) { cryptoSyncHandler.handleToDevice(syncResponse.toDevice, reporter) } @@ -109,7 +109,7 @@ internal class SyncResponseHandler @Inject constructor( // IMPORTANT nothing should be suspend here as we are accessing the realm instance (thread local) measureTimeMillis { Timber.v("Handle rooms") - reportSubtask(reporter, InitSyncStep.ImportingAccountRoom, 1, 0.7f) { + reportSubtask(reporter, InitialSyncStep.ImportingAccountRoom, 1, 0.7f) { if (syncResponse.rooms != null) { roomSyncHandler.handle(realm, syncResponse.rooms, isInitialSync, aggregator, reporter) } @@ -119,7 +119,7 @@ internal class SyncResponseHandler @Inject constructor( } measureTimeMillis { - reportSubtask(reporter, InitSyncStep.ImportingAccountGroups, 1, 0.1f) { + reportSubtask(reporter, InitialSyncStep.ImportingAccountGroups, 1, 0.1f) { Timber.v("Handle groups") if (syncResponse.groups != null) { groupSyncHandler.handle(realm, syncResponse.groups, reporter) @@ -130,7 +130,7 @@ internal class SyncResponseHandler @Inject constructor( } measureTimeMillis { - reportSubtask(reporter, InitSyncStep.ImportingAccountData, 1, 0.1f) { + reportSubtask(reporter, InitialSyncStep.ImportingAccountData, 1, 0.1f) { Timber.v("Handle accountData") userAccountDataSyncHandler.handle(realm, syncResponse.accountData) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt index f88d973101..ea296d379d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt @@ -21,10 +21,10 @@ import okhttp3.ResponseBody import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.logger.LoggerTag import org.matrix.android.sdk.api.session.Session -import org.matrix.android.sdk.api.session.initsync.InitSyncStep -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.statistics.StatisticEvent +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import org.matrix.android.sdk.api.session.sync.InitialSyncStrategy +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.sync.initialSyncStrategy import org.matrix.android.sdk.api.session.sync.model.LazyRoomSyncEphemeral import org.matrix.android.sdk.api.session.sync.model.SyncResponse @@ -38,8 +38,6 @@ import org.matrix.android.sdk.internal.session.SessionListeners import org.matrix.android.sdk.internal.session.dispatchTo import org.matrix.android.sdk.internal.session.filter.FilterRepository import org.matrix.android.sdk.internal.session.homeserver.GetHomeServerCapabilitiesTask -import org.matrix.android.sdk.internal.session.initsync.DefaultSyncStatusService -import org.matrix.android.sdk.internal.session.initsync.reportSubtask import org.matrix.android.sdk.internal.session.sync.parsing.InitialSyncResponseParser import org.matrix.android.sdk.internal.session.user.UserStore import org.matrix.android.sdk.internal.task.Task @@ -68,7 +66,7 @@ internal class DefaultSyncTask @Inject constructor( @UserId private val userId: String, private val filterRepository: FilterRepository, private val syncResponseHandler: SyncResponseHandler, - private val defaultSyncStatusService: DefaultSyncStatusService, + private val syncRequestStateTracker: SyncRequestStateTracker, private val syncTokenStore: SyncTokenStore, private val getHomeServerCapabilitiesTask: GetHomeServerCapabilitiesTask, private val userStore: UserStore, @@ -115,7 +113,7 @@ internal class DefaultSyncTask @Inject constructor( displayName = user?.displayName, avatarUrl = user?.avatarUrl ) - defaultSyncStatusService.startRoot(InitSyncStep.ImportingAccount, 100) + syncRequestStateTracker.startRoot(InitialSyncStep.ImportingAccount, 100) } // Maybe refresh the homeserver capabilities data we know getHomeServerCapabilitiesTask.execute(GetHomeServerCapabilitiesTask.Params(forceRefresh = false)) @@ -132,7 +130,7 @@ internal class DefaultSyncTask @Inject constructor( roomSyncEphemeralTemporaryStore.reset() workingDir.mkdirs() val file = downloadInitSyncResponse(requestParams, syncStatisticsData) - syncResponseToReturn = reportSubtask(defaultSyncStatusService, InitSyncStep.ImportingAccount, 1, 0.7F) { + syncResponseToReturn = reportSubtask(syncRequestStateTracker, InitialSyncStep.ImportingAccount, 1, 0.7F) { handleSyncFile(file, initSyncStrategy) } // Delete all files @@ -150,15 +148,15 @@ internal class DefaultSyncTask @Inject constructor( syncStatisticsData.requestInitSyncTime = SystemClock.elapsedRealtime() syncStatisticsData.downloadInitSyncTime = syncStatisticsData.requestInitSyncTime logDuration("INIT_SYNC Database insertion", loggerTag, clock) { - syncResponseHandler.handleResponse(syncResponse, token, defaultSyncStatusService) + syncResponseHandler.handleResponse(syncResponse, token, syncRequestStateTracker) } syncResponseToReturn = syncResponse } } - defaultSyncStatusService.endAll() + syncRequestStateTracker.endAll() } else { Timber.tag(loggerTag.value).d("Start incremental sync request with since token $token") - defaultSyncStatusService.setStatus(SyncStatusService.Status.IncrementalSyncIdle) + syncRequestStateTracker.setSyncRequestState(SyncRequestState.IncrementalSyncIdle) val syncResponse = try { executeRequest(globalErrorReceiver) { syncAPI.sync( @@ -168,7 +166,7 @@ internal class DefaultSyncTask @Inject constructor( } } catch (throwable: Throwable) { Timber.tag(loggerTag.value).e(throwable, "Incremental sync request error") - defaultSyncStatusService.setStatus(SyncStatusService.Status.IncrementalSyncError) + syncRequestStateTracker.setSyncRequestState(SyncRequestState.IncrementalSyncError) throw throwable } val nbRooms = syncResponse.rooms?.invite.orEmpty().size + syncResponse.rooms?.join.orEmpty().size + syncResponse.rooms?.leave.orEmpty().size @@ -177,8 +175,8 @@ internal class DefaultSyncTask @Inject constructor( Timber.tag(loggerTag.value).d( "Incremental sync request parsing, $nbRooms room(s) $nbToDevice toDevice(s). Got nextBatch: $nextBatch" ) - defaultSyncStatusService.setStatus( - SyncStatusService.Status.IncrementalSyncParsing( + syncRequestStateTracker.setSyncRequestState( + SyncRequestState.IncrementalSyncParsing( rooms = nbRooms, toDevice = nbToDevice ) @@ -186,7 +184,7 @@ internal class DefaultSyncTask @Inject constructor( syncResponseHandler.handleResponse(syncResponse, token, null) syncResponseToReturn = syncResponse Timber.tag(loggerTag.value).d("Incremental sync done") - defaultSyncStatusService.setStatus(SyncStatusService.Status.IncrementalSyncDone) + syncRequestStateTracker.setSyncRequestState(SyncRequestState.IncrementalSyncDone) } syncStatisticsData.treatmentSyncTime = SystemClock.elapsedRealtime() syncStatisticsData.nbOfRooms = syncResponseToReturn?.rooms?.join?.size ?: 0 @@ -201,20 +199,20 @@ internal class DefaultSyncTask @Inject constructor( val status = initialSyncStatusRepository.getStep() if (workingFile.exists() && status >= InitialSyncStatus.STEP_DOWNLOADED) { Timber.tag(loggerTag.value).d("INIT_SYNC file is already here") - reportSubtask(defaultSyncStatusService, InitSyncStep.Downloading, 1, 0.3f) { + reportSubtask(syncRequestStateTracker, InitialSyncStep.Downloading, 1, 0.3f) { // Empty task } } else { initialSyncStatusRepository.setStep(InitialSyncStatus.STEP_DOWNLOADING) val syncResponse = logDuration("INIT_SYNC Perform server request", loggerTag, clock) { - reportSubtask(defaultSyncStatusService, InitSyncStep.ServerComputing, 1, 0.2f) { + reportSubtask(syncRequestStateTracker, InitialSyncStep.ServerComputing, 1, 0.2f) { getSyncResponse(requestParams, MAX_NUMBER_OF_RETRY_AFTER_TIMEOUT) } } syncStatisticsData.requestInitSyncTime = SystemClock.elapsedRealtime() if (syncResponse.isSuccessful) { logDuration("INIT_SYNC Download and save to file", loggerTag, clock) { - reportSubtask(defaultSyncStatusService, InitSyncStep.Downloading, 1, 0.1f) { + reportSubtask(syncRequestStateTracker, InitialSyncStep.Downloading, 1, 0.1f) { syncResponse.body()?.byteStream()?.use { inputStream -> workingFile.outputStream().use { outputStream -> inputStream.copyTo(outputStream) @@ -263,7 +261,7 @@ internal class DefaultSyncTask @Inject constructor( Timber.tag(loggerTag.value).d("INIT_SYNC $nbOfJoinedRooms rooms, $nbOfJoinedRoomsInFile ephemeral stored into files") logDuration("INIT_SYNC Database insertion", loggerTag, clock) { - syncResponseHandler.handleResponse(syncResponse, null, defaultSyncStatusService) + syncResponseHandler.handleResponse(syncResponse, null, syncRequestStateTracker) } initialSyncStatusRepository.setStep(InitialSyncStatus.STEP_SUCCESS) syncResponse diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/TaskInfo.kt similarity index 81% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/TaskInfo.kt index fef16bf1d7..7032aae2b2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/TaskInfo.kt @@ -14,15 +14,17 @@ * limitations under the License. */ -package org.matrix.android.sdk.internal.session.initsync +package org.matrix.android.sdk.internal.session.sync -import org.matrix.android.sdk.api.session.initsync.InitSyncStep +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import timber.log.Timber -internal class TaskInfo(val initSyncStep: InitSyncStep, - val totalProgress: Int, - val parent: TaskInfo?, - val parentWeight: Float) { +internal class TaskInfo( + val initialSyncStep: InitialSyncStep, + val totalProgress: Int, + val parent: TaskInfo?, + val parentWeight: Float +) { var child: TaskInfo? = null var currentProgress = 0F private set diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt index e5a5a0bbad..b6142b3a7a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt @@ -29,14 +29,16 @@ import org.matrix.android.sdk.api.session.sync.model.SyncResponse import org.matrix.android.sdk.api.session.sync.model.ToDeviceSyncResponse import org.matrix.android.sdk.internal.crypto.DefaultCryptoService import org.matrix.android.sdk.internal.crypto.verification.DefaultVerificationService -import org.matrix.android.sdk.internal.session.initsync.ProgressReporter +import org.matrix.android.sdk.internal.session.sync.ProgressReporter import timber.log.Timber import javax.inject.Inject private val loggerTag = LoggerTag("CryptoSyncHandler", LoggerTag.CRYPTO) -internal class CryptoSyncHandler @Inject constructor(private val cryptoService: DefaultCryptoService, - private val verificationService: DefaultVerificationService) { +internal class CryptoSyncHandler @Inject constructor( + private val cryptoService: DefaultCryptoService, + private val verificationService: DefaultVerificationService +) { suspend fun handleToDevice(toDevice: ToDeviceSyncResponse, progressReporter: ProgressReporter? = null) { val total = toDevice.events?.size ?: 0 diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/GroupSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/GroupSyncHandler.kt index 552462e25e..1983d9f433 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/GroupSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/GroupSyncHandler.kt @@ -17,16 +17,16 @@ package org.matrix.android.sdk.internal.session.sync.handler import io.realm.Realm -import org.matrix.android.sdk.api.session.initsync.InitSyncStep import org.matrix.android.sdk.api.session.room.model.Membership +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import org.matrix.android.sdk.api.session.sync.model.GroupsSyncResponse import org.matrix.android.sdk.api.session.sync.model.InvitedGroupSync import org.matrix.android.sdk.internal.database.model.GroupEntity import org.matrix.android.sdk.internal.database.model.GroupSummaryEntity import org.matrix.android.sdk.internal.database.query.getOrCreate import org.matrix.android.sdk.internal.database.query.where -import org.matrix.android.sdk.internal.session.initsync.ProgressReporter -import org.matrix.android.sdk.internal.session.initsync.mapWithProgress +import org.matrix.android.sdk.internal.session.sync.ProgressReporter +import org.matrix.android.sdk.internal.session.sync.mapWithProgress import javax.inject.Inject internal class GroupSyncHandler @Inject constructor() { @@ -37,9 +37,11 @@ internal class GroupSyncHandler @Inject constructor() { data class LEFT(val data: Map) : HandlingStrategy() } - fun handle(realm: Realm, - roomsSyncResponse: GroupsSyncResponse, - reporter: ProgressReporter? = null) { + fun handle( + realm: Realm, + roomsSyncResponse: GroupsSyncResponse, + reporter: ProgressReporter? = null + ) { handleGroupSync(realm, HandlingStrategy.JOINED(roomsSyncResponse.join), reporter) handleGroupSync(realm, HandlingStrategy.INVITED(roomsSyncResponse.invite), reporter) handleGroupSync(realm, HandlingStrategy.LEFT(roomsSyncResponse.leave), reporter) @@ -49,26 +51,28 @@ internal class GroupSyncHandler @Inject constructor() { private fun handleGroupSync(realm: Realm, handlingStrategy: HandlingStrategy, reporter: ProgressReporter?) { val groups = when (handlingStrategy) { - is HandlingStrategy.JOINED -> - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountGroups, 0.6f) { + is HandlingStrategy.JOINED -> + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountGroups, 0.6f) { handleJoinedGroup(realm, it.key) } is HandlingStrategy.INVITED -> - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountGroups, 0.3f) { + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountGroups, 0.3f) { handleInvitedGroup(realm, it.key) } - is HandlingStrategy.LEFT -> - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountGroups, 0.1f) { + is HandlingStrategy.LEFT -> + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountGroups, 0.1f) { handleLeftGroup(realm, it.key) } } realm.insertOrUpdate(groups) } - private fun handleJoinedGroup(realm: Realm, - groupId: String): GroupEntity { + private fun handleJoinedGroup( + realm: Realm, + groupId: String + ): GroupEntity { val groupEntity = GroupEntity.where(realm, groupId).findFirst() ?: GroupEntity(groupId) val groupSummaryEntity = GroupSummaryEntity.getOrCreate(realm, groupId) groupEntity.membership = Membership.JOIN @@ -76,8 +80,10 @@ internal class GroupSyncHandler @Inject constructor() { return groupEntity } - private fun handleInvitedGroup(realm: Realm, - groupId: String): GroupEntity { + private fun handleInvitedGroup( + realm: Realm, + groupId: String + ): GroupEntity { val groupEntity = GroupEntity.where(realm, groupId).findFirst() ?: GroupEntity(groupId) val groupSummaryEntity = GroupSummaryEntity.getOrCreate(realm, groupId) groupEntity.membership = Membership.INVITE @@ -85,8 +91,10 @@ internal class GroupSyncHandler @Inject constructor() { return groupEntity } - private fun handleLeftGroup(realm: Realm, - groupId: String): GroupEntity { + private fun handleLeftGroup( + realm: Realm, + groupId: String + ): GroupEntity { val groupEntity = GroupEntity.where(realm, groupId).findFirst() ?: GroupEntity(groupId) val groupSummaryEntity = GroupSummaryEntity.getOrCreate(realm, groupId) groupEntity.membership = Membership.LEAVE diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/UserAccountDataSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/UserAccountDataSyncHandler.kt index c213ea4bcf..0f296ded5d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/UserAccountDataSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/UserAccountDataSyncHandler.kt @@ -84,10 +84,10 @@ internal class UserAccountDataSyncHandler @Inject constructor( // Generic handling, just save in base handleGenericAccountData(realm, event.type, event.content) when (event.type) { - UserAccountDataTypes.TYPE_DIRECT_MESSAGES -> handleDirectChatRooms(realm, event) - UserAccountDataTypes.TYPE_PUSH_RULES -> handlePushRules(realm, event) + UserAccountDataTypes.TYPE_DIRECT_MESSAGES -> handleDirectChatRooms(realm, event) + UserAccountDataTypes.TYPE_PUSH_RULES -> handlePushRules(realm, event) UserAccountDataTypes.TYPE_IGNORED_USER_LIST -> handleIgnoredUsers(realm, event) - UserAccountDataTypes.TYPE_BREADCRUMBS -> handleBreadcrumbs(realm, event) + UserAccountDataTypes.TYPE_BREADCRUMBS -> handleBreadcrumbs(realm, event) } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ReadReceiptHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ReadReceiptHandler.kt index 77bee18df9..7329611a01 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ReadReceiptHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ReadReceiptHandler.kt @@ -44,9 +44,11 @@ internal class ReadReceiptHandler @Inject constructor( companion object { - fun createContent(userId: String, - eventId: String, - currentTimeMillis: Long): ReadReceiptContent { + fun createContent( + userId: String, + eventId: String, + currentTimeMillis: Long + ): ReadReceiptContent { return mapOf( eventId to mapOf( READ_KEY to mapOf( @@ -59,11 +61,13 @@ internal class ReadReceiptHandler @Inject constructor( } } - fun handle(realm: Realm, - roomId: String, - content: ReadReceiptContent?, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator?) { + fun handle( + realm: Realm, + roomId: String, + content: ReadReceiptContent?, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator? + ) { content ?: return try { @@ -73,11 +77,13 @@ internal class ReadReceiptHandler @Inject constructor( } } - private fun handleReadReceiptContent(realm: Realm, - roomId: String, - content: ReadReceiptContent, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator?) { + private fun handleReadReceiptContent( + realm: Realm, + roomId: String, + content: ReadReceiptContent, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator? + ) { if (isInitialSync) { initialSyncStrategy(realm, roomId, content) } else { @@ -101,10 +107,12 @@ internal class ReadReceiptHandler @Inject constructor( realm.insertOrUpdate(readReceiptSummaries) } - private fun incrementalSyncStrategy(realm: Realm, - roomId: String, - content: ReadReceiptContent, - aggregator: SyncResponsePostTreatmentAggregator?) { + private fun incrementalSyncStrategy( + realm: Realm, + roomId: String, + content: ReadReceiptContent, + aggregator: SyncResponsePostTreatmentAggregator? + ) { // First check if we have data from init sync to handle getContentFromInitSync(roomId)?.let { Timber.w("INIT_SYNC Insert during incremental sync RR for room $roomId") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt index 53fc9dc6b9..c854587853 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt @@ -27,11 +27,11 @@ import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.homeserver.HomeServerCapabilitiesService -import org.matrix.android.sdk.api.session.initsync.InitSyncStep import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomMemberContent import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.threads.model.ThreadSummaryUpdateType +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import org.matrix.android.sdk.api.session.sync.InitialSyncStrategy import org.matrix.android.sdk.api.session.sync.initialSyncStrategy import org.matrix.android.sdk.api.session.sync.model.InvitedRoomSync @@ -67,17 +67,17 @@ import org.matrix.android.sdk.internal.di.UserId import org.matrix.android.sdk.internal.extensions.clearWith import org.matrix.android.sdk.internal.session.StreamEventsManager import org.matrix.android.sdk.internal.session.events.getFixedRoomMemberContent -import org.matrix.android.sdk.internal.session.initsync.ProgressReporter -import org.matrix.android.sdk.internal.session.initsync.mapWithProgress -import org.matrix.android.sdk.internal.session.initsync.reportSubtask import org.matrix.android.sdk.internal.session.room.membership.RoomChangeMembershipStateDataSource import org.matrix.android.sdk.internal.session.room.membership.RoomMemberEventHandler import org.matrix.android.sdk.internal.session.room.summary.RoomSummaryUpdater import org.matrix.android.sdk.internal.session.room.timeline.PaginationDirection import org.matrix.android.sdk.internal.session.room.timeline.TimelineInput import org.matrix.android.sdk.internal.session.room.typing.TypingEventContent +import org.matrix.android.sdk.internal.session.sync.ProgressReporter import org.matrix.android.sdk.internal.session.sync.SyncResponsePostTreatmentAggregator +import org.matrix.android.sdk.internal.session.sync.mapWithProgress import org.matrix.android.sdk.internal.session.sync.parsing.RoomSyncAccountDataHandler +import org.matrix.android.sdk.internal.session.sync.reportSubtask import org.matrix.android.sdk.internal.util.computeBestChunkSize import org.matrix.android.sdk.internal.util.time.Clock import timber.log.Timber @@ -106,11 +106,13 @@ internal class RoomSyncHandler @Inject constructor( data class LEFT(val data: Map) : HandlingStrategy() } - fun handle(realm: Realm, - roomsSyncResponse: RoomsSyncResponse, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator, - reporter: ProgressReporter? = null) { + fun handle( + realm: Realm, + roomsSyncResponse: RoomsSyncResponse, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator, + reporter: ProgressReporter? = null + ) { handleRoomSync(realm, HandlingStrategy.JOINED(roomsSyncResponse.join), isInitialSync, aggregator, reporter) handleRoomSync(realm, HandlingStrategy.INVITED(roomsSyncResponse.invite), isInitialSync, aggregator, reporter) handleRoomSync(realm, HandlingStrategy.LEFT(roomsSyncResponse.leave), isInitialSync, aggregator, reporter) @@ -124,11 +126,13 @@ internal class RoomSyncHandler @Inject constructor( } // PRIVATE METHODS ***************************************************************************** - private fun handleRoomSync(realm: Realm, - handlingStrategy: HandlingStrategy, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator, - reporter: ProgressReporter?) { + private fun handleRoomSync( + realm: Realm, + handlingStrategy: HandlingStrategy, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator, + reporter: ProgressReporter? + ) { val insertType = if (isInitialSync) { EventInsertType.INITIAL_SYNC } else { @@ -136,24 +140,24 @@ internal class RoomSyncHandler @Inject constructor( } val syncLocalTimeStampMillis = clock.epochMillis() val rooms = when (handlingStrategy) { - is HandlingStrategy.JOINED -> { + is HandlingStrategy.JOINED -> { if (isInitialSync && initialSyncStrategy is InitialSyncStrategy.Optimized) { insertJoinRoomsFromInitSync(realm, handlingStrategy, syncLocalTimeStampMillis, aggregator, reporter) // Rooms are already inserted, return an empty list emptyList() } else { - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountJoinedRooms, 0.6f) { + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountJoinedRooms, 0.6f) { handleJoinedRoom(realm, it.key, it.value, insertType, syncLocalTimeStampMillis, aggregator) } } } is HandlingStrategy.INVITED -> - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountInvitedRooms, 0.1f) { + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountInvitedRooms, 0.1f) { handleInvitedRoom(realm, it.key, it.value, insertType, syncLocalTimeStampMillis) } - is HandlingStrategy.LEFT -> { - handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountLeftRooms, 0.3f) { + is HandlingStrategy.LEFT -> { + handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountLeftRooms, 0.3f) { handleLeftRoom(realm, it.key, it.value, insertType, syncLocalTimeStampMillis) } } @@ -161,18 +165,20 @@ internal class RoomSyncHandler @Inject constructor( realm.insertOrUpdate(rooms) } - private fun insertJoinRoomsFromInitSync(realm: Realm, - handlingStrategy: HandlingStrategy.JOINED, - syncLocalTimeStampMillis: Long, - aggregator: SyncResponsePostTreatmentAggregator, - reporter: ProgressReporter?) { + private fun insertJoinRoomsFromInitSync( + realm: Realm, + handlingStrategy: HandlingStrategy.JOINED, + syncLocalTimeStampMillis: Long, + aggregator: SyncResponsePostTreatmentAggregator, + reporter: ProgressReporter? + ) { val bestChunkSize = computeBestChunkSize( listSize = handlingStrategy.data.keys.size, limit = (initialSyncStrategy as? InitialSyncStrategy.Optimized)?.maxRoomsToInsert ?: Int.MAX_VALUE ) if (bestChunkSize.shouldChunk()) { - reportSubtask(reporter, InitSyncStep.ImportingAccountJoinedRooms, bestChunkSize.numberOfChunks, 0.6f) { + reportSubtask(reporter, InitialSyncStep.ImportingAccountJoinedRooms, bestChunkSize.numberOfChunks, 0.6f) { Timber.d("INIT_SYNC ${handlingStrategy.data.keys.size} rooms to insert, split with $bestChunkSize") // I cannot find a better way to chunk a map, so chunk the keys and then create new maps handlingStrategy.data.keys @@ -196,19 +202,21 @@ internal class RoomSyncHandler @Inject constructor( } } else { // No need to split - val rooms = handlingStrategy.data.mapWithProgress(reporter, InitSyncStep.ImportingAccountJoinedRooms, 0.6f) { + val rooms = handlingStrategy.data.mapWithProgress(reporter, InitialSyncStep.ImportingAccountJoinedRooms, 0.6f) { handleJoinedRoom(realm, it.key, it.value, EventInsertType.INITIAL_SYNC, syncLocalTimeStampMillis, aggregator) } realm.insertOrUpdate(rooms) } } - private fun handleJoinedRoom(realm: Realm, - roomId: String, - roomSync: RoomSync, - insertType: EventInsertType, - syncLocalTimestampMillis: Long, - aggregator: SyncResponsePostTreatmentAggregator): RoomEntity { + private fun handleJoinedRoom( + realm: Realm, + roomId: String, + roomSync: RoomSync, + insertType: EventInsertType, + syncLocalTimestampMillis: Long, + aggregator: SyncResponsePostTreatmentAggregator + ): RoomEntity { Timber.v("Handle join sync for room $roomId") val isInitialSync = insertType == EventInsertType.INITIAL_SYNC @@ -281,11 +289,13 @@ internal class RoomSyncHandler @Inject constructor( return roomEntity } - private fun handleInvitedRoom(realm: Realm, - roomId: String, - roomSync: InvitedRoomSync, - insertType: EventInsertType, - syncLocalTimestampMillis: Long): RoomEntity { + private fun handleInvitedRoom( + realm: Realm, + roomId: String, + roomSync: InvitedRoomSync, + insertType: EventInsertType, + syncLocalTimestampMillis: Long + ): RoomEntity { Timber.v("Handle invited sync for room $roomId") val isInitialSync = insertType == EventInsertType.INITIAL_SYNC val roomEntity = RoomEntity.getOrCreate(realm, roomId) @@ -312,11 +322,13 @@ internal class RoomSyncHandler @Inject constructor( return roomEntity } - private fun handleLeftRoom(realm: Realm, - roomId: String, - roomSync: RoomSync, - insertType: EventInsertType, - syncLocalTimestampMillis: Long): RoomEntity { + private fun handleLeftRoom( + realm: Realm, + roomId: String, + roomSync: RoomSync, + insertType: EventInsertType, + syncLocalTimestampMillis: Long + ): RoomEntity { val isInitialSync = insertType == EventInsertType.INITIAL_SYNC val roomEntity = RoomEntity.getOrCreate(realm, roomId) for (event in roomSync.state?.events.orEmpty()) { @@ -357,15 +369,17 @@ internal class RoomSyncHandler @Inject constructor( return roomEntity } - private fun handleTimelineEvents(realm: Realm, - roomId: String, - roomEntity: RoomEntity, - eventList: List, - prevToken: String? = null, - isLimited: Boolean = true, - insertType: EventInsertType, - syncLocalTimestampMillis: Long, - aggregator: SyncResponsePostTreatmentAggregator): ChunkEntity { + private fun handleTimelineEvents( + realm: Realm, + roomId: String, + roomEntity: RoomEntity, + eventList: List, + prevToken: String? = null, + isLimited: Boolean = true, + insertType: EventInsertType, + syncLocalTimestampMillis: Long, + aggregator: SyncResponsePostTreatmentAggregator + ): ChunkEntity { val lastChunk = ChunkEntity.findLastForwardChunkOfRoom(realm, roomEntity.roomId) if (isLimited && lastChunk != null) { lastChunk.deleteOnCascade(deleteStateEvents = false, canDeleteRoot = true) @@ -500,11 +514,13 @@ internal class RoomSyncHandler @Inject constructor( * Adds new event to the appropriate thread chunk. If the event is already in * the thread timeline and /relations api, we should not added it */ - private fun addToThreadChunkIfNeeded(realm: Realm, - roomId: String, - threadId: String, - timelineEventEntity: TimelineEventEntity?, - roomEntity: RoomEntity) { + private fun addToThreadChunkIfNeeded( + realm: Realm, + roomId: String, + threadId: String, + timelineEventEntity: TimelineEventEntity?, + roomEntity: RoomEntity + ) { val eventId = timelineEventEntity?.eventId ?: return ChunkEntity.findLastForwardChunkOfThread(realm, roomId, threadId)?.let { threadChunk -> @@ -546,11 +562,13 @@ internal class RoomSyncHandler @Inject constructor( val typingUserIds: List = emptyList() ) - private fun handleEphemeral(realm: Realm, - roomId: String, - ephemeralEvents: List, - isInitialSync: Boolean, - aggregator: SyncResponsePostTreatmentAggregator): EphemeralResult { + private fun handleEphemeral( + realm: Realm, + roomId: String, + ephemeralEvents: List, + isInitialSync: Boolean, + aggregator: SyncResponsePostTreatmentAggregator + ): EphemeralResult { var result = EphemeralResult() for (event in ephemeralEvents) { when (event.type) { @@ -560,12 +578,12 @@ internal class RoomSyncHandler @Inject constructor( readReceiptHandler.handle(realm, roomId, readReceiptContent, isInitialSync, aggregator) } } - EventType.TYPING -> { + EventType.TYPING -> { event.content.toModel()?.let { typingEventContent -> result = result.copy(typingUserIds = typingEventContent.typingUserIds) } } - else -> Timber.w("Ephemeral event type '${event.type}' not yet supported") + else -> Timber.w("Ephemeral event type '${event.type}' not yet supported") } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomTypingUsersHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomTypingUsersHandler.kt index 63db13a5b8..54bb63753c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomTypingUsersHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomTypingUsersHandler.kt @@ -23,8 +23,10 @@ import org.matrix.android.sdk.internal.session.room.membership.RoomMemberHelper import org.matrix.android.sdk.internal.session.typing.DefaultTypingUsersTracker import javax.inject.Inject -internal class RoomTypingUsersHandler @Inject constructor(@UserId private val userId: String, - private val typingUsersTracker: DefaultTypingUsersTracker) { +internal class RoomTypingUsersHandler @Inject constructor( + @UserId private val userId: String, + private val typingUsersTracker: DefaultTypingUsersTracker +) { // TODO This could be handled outside of the Realm transaction. Use the new aggregator? fun handle(realm: Realm, roomId: String, ephemeralResult: RoomSyncHandler.EphemeralResult?) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt index 9beb8333a4..8c7557a5b8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt @@ -156,10 +156,12 @@ internal class ThreadsAwarenessHandler @Inject constructor( * Handle events mainly coming from the RoomSyncHandler. * @return The content to inject in the roomSyncHandler live events */ - fun makeEventThreadAware(realm: Realm, - roomId: String?, - event: Event?, - eventEntity: EventEntity? = null): String? { + fun makeEventThreadAware( + realm: Realm, + roomId: String?, + event: Event?, + eventEntity: EventEntity? = null + ): String? { event ?: return null roomId ?: return null if (lightweightSettingsStorage.areThreadMessagesEnabled() && !isReplyEvent(event)) return null @@ -271,10 +273,12 @@ internal class ThreadsAwarenessHandler @Inject constructor( * Actual update the eventEntity with the new payload. * @return the content to inject when this is executed by RoomSyncHandler */ - private fun updateEventEntity(event: Event, - eventEntity: EventEntity?, - eventPayload: MutableMap, - messageTextContent: Content): String? { + private fun updateEventEntity( + event: Event, + eventEntity: EventEntity?, + eventPayload: MutableMap, + messageTextContent: Content + ): String? { eventPayload["content"] = messageTextContent if (event.isEncrypted()) { @@ -304,11 +308,12 @@ internal class ThreadsAwarenessHandler @Inject constructor( * @param threadRelation the information about thread * @return The final content with the injected event */ - private fun injectEvent(roomId: String, - eventBody: String, - eventToInject: Event, - eventToInjectBody: String, - threadRelation: RelationDefaultContent? + private fun injectEvent( + roomId: String, + eventBody: String, + eventToInject: Event, + eventToInjectBody: String, + threadRelation: RelationDefaultContent? ): Content? { val eventToInjectId = eventToInject.eventId ?: return null val eventIdToInjectSenderId = eventToInject.senderId.orEmpty() @@ -334,11 +339,13 @@ internal class ThreadsAwarenessHandler @Inject constructor( /** * Integrate fallback Quote reply. */ - private fun injectFallbackIndicator(event: Event, - eventBody: String, - eventEntity: EventEntity?, - eventPayload: MutableMap, - threadRelation: RelationDefaultContent?): String? { + private fun injectFallbackIndicator( + event: Event, + eventBody: String, + eventEntity: EventEntity?, + eventPayload: MutableMap, + threadRelation: RelationDefaultContent? + ): String? { val replyFormatted = LocalEchoEventFactory.QUOTE_PATTERN.format( "In reply to a thread", eventBody diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncThread.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncThread.kt index fc6a4e03d6..24a60a80da 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncThread.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncThread.kt @@ -56,11 +56,12 @@ private const val DEFAULT_LONG_POOL_TIMEOUT = 30_000L private val loggerTag = LoggerTag("SyncThread", LoggerTag.SYNC) -internal class SyncThread @Inject constructor(private val syncTask: SyncTask, - private val networkConnectivityChecker: NetworkConnectivityChecker, - private val backgroundDetectionObserver: BackgroundDetectionObserver, - private val activeCallHandler: ActiveCallHandler, - private val lightweightSettingsStorage: DefaultLightweightSettingsStorage +internal class SyncThread @Inject constructor( + private val syncTask: SyncTask, + private val networkConnectivityChecker: NetworkConnectivityChecker, + private val backgroundDetectionObserver: BackgroundDetectionObserver, + private val activeCallHandler: ActiveCallHandler, + private val lightweightSettingsStorage: DefaultLightweightSettingsStorage ) : Thread("SyncThread"), NetworkConnectivityChecker.Listener, BackgroundDetectionObserver.Listener { private var state: SyncState = SyncState.Idle @@ -179,8 +180,8 @@ internal class SyncThread @Inject constructor(private val syncTask: SyncTask, val afterPause = state.let { it is SyncState.Running && it.afterPause } val timeout = when { previousSyncResponseHasToDevice -> 0L /* Force timeout to 0 */ - afterPause -> 0L /* No timeout after a pause */ - else -> DEFAULT_LONG_POOL_TIMEOUT + afterPause -> 0L /* No timeout after a pause */ + else -> DEFAULT_LONG_POOL_TIMEOUT } Timber.tag(loggerTag.value).d("Execute sync request with timeout $timeout") val presence = lightweightSettingsStorage.getSyncPresenceStatus() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt index bbb18b664c..0cc7944d58 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt @@ -119,9 +119,11 @@ internal class SyncWorker(context: Context, workerParameters: WorkerParameters, companion object { private const val BG_SYNC_WORK_NAME = "BG_SYNCP" - fun requireBackgroundSync(workManagerProvider: WorkManagerProvider, - sessionId: String, - serverTimeoutInSeconds: Long = 0) { + fun requireBackgroundSync( + workManagerProvider: WorkManagerProvider, + sessionId: String, + serverTimeoutInSeconds: Long = 0 + ) { val data = WorkerParamsFactory.toData( Params( sessionId = sessionId, @@ -139,11 +141,13 @@ internal class SyncWorker(context: Context, workerParameters: WorkerParameters, .enqueueUniqueWork(BG_SYNC_WORK_NAME, ExistingWorkPolicy.APPEND_OR_REPLACE, workRequest) } - fun automaticallyBackgroundSync(workManagerProvider: WorkManagerProvider, - sessionId: String, - serverTimeoutInSeconds: Long = 0, - delayInSeconds: Long = 30, - forceImmediate: Boolean = false) { + fun automaticallyBackgroundSync( + workManagerProvider: WorkManagerProvider, + sessionId: String, + serverTimeoutInSeconds: Long = 0, + delayInSeconds: Long = 30, + forceImmediate: Boolean = false + ) { val data = WorkerParamsFactory.toData( Params( sessionId = sessionId, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/TokensChunkResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/TokensChunkResponse.kt index 533ba70b05..40fdcbbb84 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/TokensChunkResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/TokensChunkResponse.kt @@ -22,4 +22,5 @@ import com.squareup.moshi.JsonClass internal data class TokensChunkResponse( val start: String? = null, val end: String? = null, - val chunk: List? = null) + val chunk: List? = null +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/parsing/RoomSyncAccountDataHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/parsing/RoomSyncAccountDataHandler.kt index 5e7bde87e7..b1b2bfef33 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/parsing/RoomSyncAccountDataHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/parsing/RoomSyncAccountDataHandler.kt @@ -32,8 +32,10 @@ import org.matrix.android.sdk.internal.session.sync.handler.room.RoomFullyReadHa import org.matrix.android.sdk.internal.session.sync.handler.room.RoomTagHandler import javax.inject.Inject -internal class RoomSyncAccountDataHandler @Inject constructor(private val roomTagHandler: RoomTagHandler, - private val roomFullyReadHandler: RoomFullyReadHandler) { +internal class RoomSyncAccountDataHandler @Inject constructor( + private val roomTagHandler: RoomTagHandler, + private val roomFullyReadHandler: RoomFullyReadHandler +) { fun handle(realm: Realm, roomId: String, accountData: RoomSyncAccountData) { if (accountData.events.isNullOrEmpty()) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt index 9876643bed..b687f5833a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt @@ -51,8 +51,10 @@ internal class DefaultTermsService @Inject constructor( private val updateUserAccountDataTask: UpdateUserAccountDataTask ) : TermsService { - override suspend fun getTerms(serviceType: TermsService.ServiceType, - baseUrl: String): GetTermsResponse { + override suspend fun getTerms( + serviceType: TermsService.ServiceType, + baseUrl: String + ): GetTermsResponse { val url = buildUrl(baseUrl, serviceType) val termsResponse = executeRequest(null) { termsAPI.getTerms("${url}terms") @@ -90,10 +92,12 @@ internal class DefaultTermsService @Inject constructor( } } - override suspend fun agreeToTerms(serviceType: TermsService.ServiceType, - baseUrl: String, - agreedUrls: List, - token: String?) { + override suspend fun agreeToTerms( + serviceType: TermsService.ServiceType, + baseUrl: String, + agreedUrls: List, + token: String? + ) { val url = buildUrl(baseUrl, serviceType) val tokenToUse = token?.takeIf { it.isNotEmpty() } ?: getToken(baseUrl) @@ -128,7 +132,7 @@ internal class DefaultTermsService @Inject constructor( private fun buildUrl(baseUrl: String, serviceType: TermsService.ServiceType): String { val servicePath = when (serviceType) { TermsService.ServiceType.IntegrationManager -> NetworkConstants.URI_INTEGRATION_MANAGER_PATH - TermsService.ServiceType.IdentityService -> NetworkConstants.URI_IDENTITY_PATH_V2 + TermsService.ServiceType.IdentityService -> NetworkConstants.URI_IDENTITY_PATH_V2 } return "${baseUrl.ensureTrailingSlash()}$servicePath" } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt index f6f57bf0ef..6a3328ee52 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt @@ -37,15 +37,19 @@ internal interface TermsAPI { * This request requires authentication. */ @POST - suspend fun agreeToTerms(@Url url: String, - @Body params: AcceptTermsBody, - @Header(HttpHeaders.Authorization) token: String) + suspend fun agreeToTerms( + @Url url: String, + @Body params: AcceptTermsBody, + @Header(HttpHeaders.Authorization) token: String + ) /** * API to retrieve the terms for a homeserver. The API /terms does not exist yet, so retrieve the terms from the login flow. * We do not care about the result (Credentials). */ @POST - suspend fun register(@Url url: String, - @Body body: JsonDict = emptyJsonDict) + suspend fun register( + @Url url: String, + @Body body: JsonDict = emptyJsonDict + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsModule.kt index d7b6f68add..06d12bfe76 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsModule.kt @@ -34,8 +34,10 @@ internal abstract class TermsModule { @Provides @JvmStatic @SessionScope - fun providesTermsAPI(@UnauthenticatedWithCertificate unauthenticatedOkHttpClient: Lazy, - retrofitFactory: RetrofitFactory): TermsAPI { + fun providesTermsAPI( + @UnauthenticatedWithCertificate unauthenticatedOkHttpClient: Lazy, + retrofitFactory: RetrofitFactory + ): TermsAPI { val retrofit = retrofitFactory.create(unauthenticatedOkHttpClient, "https://foo.bar") return retrofit.create(TermsAPI::class.java) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/DefaultThirdPartyService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/DefaultThirdPartyService.kt index 210cb192e7..c8b9eaf810 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/DefaultThirdPartyService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/DefaultThirdPartyService.kt @@ -21,8 +21,10 @@ import org.matrix.android.sdk.api.session.thirdparty.ThirdPartyService import org.matrix.android.sdk.api.session.thirdparty.model.ThirdPartyUser import javax.inject.Inject -internal class DefaultThirdPartyService @Inject constructor(private val getThirdPartyProtocolTask: GetThirdPartyProtocolsTask, - private val getThirdPartyUserTask: GetThirdPartyUserTask) : +internal class DefaultThirdPartyService @Inject constructor( + private val getThirdPartyProtocolTask: GetThirdPartyProtocolsTask, + private val getThirdPartyUserTask: GetThirdPartyUserTask +) : ThirdPartyService { override suspend fun getThirdPartyProtocols(): Map { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/ThirdPartyAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/ThirdPartyAPI.kt index 3ecc39ac94..6759205bf3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/ThirdPartyAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/thirdparty/ThirdPartyAPI.kt @@ -39,6 +39,8 @@ internal interface ThirdPartyAPI { * Ref: https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-thirdparty-user-protocol */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "thirdparty/user/{protocol}") - suspend fun getThirdPartyUser(@Path("protocol") protocol: String, - @QueryMap params: Map?): List + suspend fun getThirdPartyUser( + @Path("protocol") protocol: String, + @QueryMap params: Map? + ): List } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/DefaultUserService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/DefaultUserService.kt index 4ffc42e714..660cf118df 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/DefaultUserService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/DefaultUserService.kt @@ -26,10 +26,12 @@ import org.matrix.android.sdk.internal.session.user.accountdata.UpdateIgnoredUse import org.matrix.android.sdk.internal.session.user.model.SearchUserTask import javax.inject.Inject -internal class DefaultUserService @Inject constructor(private val userDataSource: UserDataSource, - private val searchUserTask: SearchUserTask, - private val updateIgnoredUserIdsTask: UpdateIgnoredUserIdsTask, - private val getProfileInfoTask: GetProfileInfoTask) : UserService { +internal class DefaultUserService @Inject constructor( + private val userDataSource: UserDataSource, + private val searchUserTask: SearchUserTask, + private val updateIgnoredUserIdsTask: UpdateIgnoredUserIdsTask, + private val getProfileInfoTask: GetProfileInfoTask +) : UserService { override fun getUser(userId: String): User? { return userDataSource.getUser(userId) @@ -59,9 +61,11 @@ internal class DefaultUserService @Inject constructor(private val userDataSource return userDataSource.getIgnoredUsersLive() } - override suspend fun searchUsersDirectory(search: String, - limit: Int, - excludedUserIds: Set): List { + override suspend fun searchUsersDirectory( + search: String, + limit: Int, + excludedUserIds: Set + ): List { val params = SearchUserTask.Params(limit, search, excludedUserIds) return searchUserTask.execute(params) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/UserDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/UserDataSource.kt index e83725b10d..f9feb04e97 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/UserDataSource.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/UserDataSource.kt @@ -36,8 +36,10 @@ import org.matrix.android.sdk.internal.database.query.where import org.matrix.android.sdk.internal.di.SessionDatabase import javax.inject.Inject -internal class UserDataSource @Inject constructor(@SessionDatabase private val monarchy: Monarchy, - private val realmSessionProvider: RealmSessionProvider) { +internal class UserDataSource @Inject constructor( + @SessionDatabase private val monarchy: Monarchy, + private val realmSessionProvider: RealmSessionProvider +) { private val realmDataSourceFactory: Monarchy.RealmDataSourceFactory by lazy { monarchy.createDataSourceFactory { realm -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataAPI.kt index 178f349ec8..b283d51845 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataAPI.kt @@ -31,7 +31,9 @@ internal interface AccountDataAPI { * @param params the put params */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/account_data/{type}") - suspend fun setAccountData(@Path("userId") userId: String, - @Path("type") type: String, - @Body params: Any) + suspend fun setAccountData( + @Path("userId") userId: String, + @Path("type") type: String, + @Body params: Any + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/UpdateUserAccountDataTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/UpdateUserAccountDataTask.kt index 88db381852..ff0e960f0f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/UpdateUserAccountDataTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/UpdateUserAccountDataTask.kt @@ -35,8 +35,9 @@ internal interface UpdateUserAccountDataTask : Task> + data class DirectChatParams( + override val type: String = UserAccountDataTypes.TYPE_DIRECT_MESSAGES, + private val directMessages: Map> ) : Params { override fun getData(): Any { @@ -63,8 +66,9 @@ internal interface UpdateUserAccountDataTask : Task { ) } -internal class DefaultCreateWidgetTask @Inject constructor(@SessionDatabase private val monarchy: Monarchy, - private val roomAPI: RoomAPI, - @UserId private val userId: String, - private val globalErrorReceiver: GlobalErrorReceiver) : CreateWidgetTask { +internal class DefaultCreateWidgetTask @Inject constructor( + @SessionDatabase private val monarchy: Monarchy, + private val roomAPI: RoomAPI, + @UserId private val userId: String, + private val globalErrorReceiver: GlobalErrorReceiver +) : CreateWidgetTask { override suspend fun execute(params: CreateWidgetTask.Params): String { val response = executeRequest(globalErrorReceiver) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt index 857105f6ef..2665809d9a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt @@ -27,8 +27,10 @@ import timber.log.Timber import java.lang.reflect.Type import javax.inject.Inject -internal class DefaultWidgetPostAPIMediator @Inject constructor(private val moshi: Moshi, - private val widgetPostMessageAPIProvider: WidgetPostMessageAPIProvider) : +internal class DefaultWidgetPostAPIMediator @Inject constructor( + private val moshi: Moshi, + private val widgetPostMessageAPIProvider: WidgetPostMessageAPIProvider +) : WidgetPostAPIMediator { private val jsonAdapter = moshi.adapter(JSON_DICT_PARAMETERIZED_TYPE) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetService.kt index 53a435d217..7b2edf2dbf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetService.kt @@ -26,9 +26,11 @@ import org.matrix.android.sdk.api.session.widgets.model.Widget import javax.inject.Inject import javax.inject.Provider -internal class DefaultWidgetService @Inject constructor(private val widgetManager: WidgetManager, - private val widgetURLFormatter: WidgetURLFormatter, - private val widgetPostAPIMediator: Provider) : +internal class DefaultWidgetService @Inject constructor( + private val widgetManager: WidgetManager, + private val widgetURLFormatter: WidgetURLFormatter, + private val widgetPostAPIMediator: Provider +) : WidgetService { override fun getWidgetURLFormatter(): WidgetURLFormatter { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetURLFormatter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetURLFormatter.kt index 5879b62446..019edf21b6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetURLFormatter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetURLFormatter.kt @@ -30,9 +30,10 @@ import org.matrix.android.sdk.internal.session.widgets.token.GetScalarTokenTask import javax.inject.Inject @SessionScope -internal class DefaultWidgetURLFormatter @Inject constructor(private val integrationManager: IntegrationManager, - private val getScalarTokenTask: GetScalarTokenTask, - private val matrixConfiguration: MatrixConfiguration +internal class DefaultWidgetURLFormatter @Inject constructor( + private val integrationManager: IntegrationManager, + private val getScalarTokenTask: GetScalarTokenTask, + private val matrixConfiguration: MatrixConfiguration ) : IntegrationManagerService.Listener, WidgetURLFormatter, SessionLifecycleObserver { private lateinit var currentConfig: IntegrationManagerConfig diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetManager.kt index 07ed91c179..3f7db93b97 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetManager.kt @@ -45,12 +45,14 @@ import org.matrix.android.sdk.internal.session.widgets.helper.extractWidgetSeque import javax.inject.Inject @SessionScope -internal class WidgetManager @Inject constructor(private val integrationManager: IntegrationManager, - private val userAccountDataDataSource: UserAccountDataDataSource, - private val stateEventDataSource: StateEventDataSource, - private val createWidgetTask: CreateWidgetTask, - private val widgetFactory: WidgetFactory, - @UserId private val userId: String) : +internal class WidgetManager @Inject constructor( + private val integrationManager: IntegrationManager, + private val userAccountDataDataSource: UserAccountDataDataSource, + private val stateEventDataSource: StateEventDataSource, + private val createWidgetTask: CreateWidgetTask, + private val widgetFactory: WidgetFactory, + @UserId private val userId: String +) : IntegrationManagerService.Listener, SessionLifecycleObserver { @@ -103,8 +105,10 @@ internal class WidgetManager @Inject constructor(private val integrationManager: return widgetFactory.computeURL(widget, isLightTheme) } - private fun List.mapEventsToWidgets(widgetTypes: Set? = null, - excludedTypes: Set? = null): List { + private fun List.mapEventsToWidgets( + widgetTypes: Set? = null, + excludedTypes: Set? = null + ): List { val widgetEvents = this // Widget id -> widget val widgets: MutableMap = HashMap() @@ -149,8 +153,10 @@ internal class WidgetManager @Inject constructor(private val integrationManager: return widgetsAccountData.mapToWidgets(widgetTypes, excludedTypes) } - private fun UserAccountDataEvent.mapToWidgets(widgetTypes: Set? = null, - excludedTypes: Set? = null): List { + private fun UserAccountDataEvent.mapToWidgets( + widgetTypes: Set? = null, + excludedTypes: Set? = null + ): List { return extractWidgetSequence(widgetFactory) .filter { val widgetType = it.widgetContent.type ?: return@filter false diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt index 97b40e545e..2a4af9ffaa 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt @@ -30,10 +30,14 @@ internal interface WidgetsAPI { * @param version the widget API version */ @POST("register") - suspend fun register(@Body body: OpenIdToken, - @Query("v") version: String?): RegisterWidgetResponse + suspend fun register( + @Body body: OpenIdToken, + @Query("v") version: String? + ): RegisterWidgetResponse @GET("account") - suspend fun validateToken(@Query("scalar_token") scalarToken: String?, - @Query("v") version: String?) + suspend fun validateToken( + @Query("scalar_token") scalarToken: String?, + @Query("v") version: String? + ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPIProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPIProvider.kt index 48c8fcdb03..25caadbade 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPIProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPIProvider.kt @@ -24,8 +24,10 @@ import org.matrix.android.sdk.internal.session.SessionScope import javax.inject.Inject @SessionScope -internal class WidgetsAPIProvider @Inject constructor(@Unauthenticated private val okHttpClient: Lazy, - private val retrofitFactory: RetrofitFactory) { +internal class WidgetsAPIProvider @Inject constructor( + @Unauthenticated private val okHttpClient: Lazy, + private val retrofitFactory: RetrofitFactory +) { // Map to keep one WidgetAPI instance by serverUrl private val widgetsAPIs = mutableMapOf() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/helper/WidgetFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/helper/WidgetFactory.kt index a5e74a8af0..8bd61a7bdf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/helper/WidgetFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/helper/WidgetFactory.kt @@ -33,11 +33,13 @@ import org.matrix.android.sdk.internal.session.user.UserDataSource import java.net.URLEncoder import javax.inject.Inject -internal class WidgetFactory @Inject constructor(private val userDataSource: UserDataSource, - private val realmSessionProvider: RealmSessionProvider, - private val displayNameResolver: DisplayNameResolver, - private val urlResolver: ContentUrlResolver, - @UserId private val userId: String) { +internal class WidgetFactory @Inject constructor( + private val userDataSource: UserDataSource, + private val realmSessionProvider: RealmSessionProvider, + private val displayNameResolver: DisplayNameResolver, + private val urlResolver: ContentUrlResolver, + @UserId private val userId: String +) { fun create(widgetEvent: Event): Widget? { val widgetContent = widgetEvent.content.toModel() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/token/GetScalarTokenTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/token/GetScalarTokenTask.kt index 17797cad52..49ae52afaa 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/token/GetScalarTokenTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/token/GetScalarTokenTask.kt @@ -37,9 +37,11 @@ internal interface GetScalarTokenTask : Task private const val WIDGET_API_VERSION = "1.1" -internal class DefaultGetScalarTokenTask @Inject constructor(private val widgetsAPIProvider: WidgetsAPIProvider, - private val scalarTokenStore: ScalarTokenStore, - private val getOpenIdTokenTask: GetOpenIdTokenTask) : GetScalarTokenTask { +internal class DefaultGetScalarTokenTask @Inject constructor( + private val widgetsAPIProvider: WidgetsAPIProvider, + private val scalarTokenStore: ScalarTokenStore, + private val getOpenIdTokenTask: GetOpenIdTokenTask +) : GetScalarTokenTask { override suspend fun execute(params: GetScalarTokenTask.Params): String { val widgetsAPI = widgetsAPIProvider.get(params.serverUrl) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/ConfigurableTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/ConfigurableTask.kt index bc80cf7ee8..eead25b57c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/ConfigurableTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/ConfigurableTask.kt @@ -21,8 +21,9 @@ import org.matrix.android.sdk.api.NoOpMatrixCallback import org.matrix.android.sdk.api.util.Cancelable import java.util.UUID -internal fun Task.configureWith(params: PARAMS, - init: (ConfigurableTask.Builder.() -> Unit) = {} +internal fun Task.configureWith( + params: PARAMS, + init: (ConfigurableTask.Builder.() -> Unit) = {} ): ConfigurableTask { return ConfigurableTask.Builder(this, params).apply(init).build() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/TaskExecutor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/TaskExecutor.kt index 57574a96fa..5e685bd546 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/TaskExecutor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/task/TaskExecutor.kt @@ -57,11 +57,11 @@ internal class TaskExecutor @Inject constructor(private val coroutineDispatchers fun cancelAll() = executorScope.coroutineContext.cancelChildren() private fun TaskThread.toDispatcher() = when (this) { - TaskThread.MAIN -> coroutineDispatchers.main + TaskThread.MAIN -> coroutineDispatchers.main TaskThread.COMPUTATION -> coroutineDispatchers.computation - TaskThread.IO -> coroutineDispatchers.io - TaskThread.CALLER -> EmptyCoroutineContext - TaskThread.CRYPTO -> coroutineDispatchers.crypto - TaskThread.DM_VERIF -> coroutineDispatchers.dmVerif + TaskThread.IO -> coroutineDispatchers.io + TaskThread.CALLER -> EmptyCoroutineContext + TaskThread.CRYPTO -> coroutineDispatchers.crypto + TaskThread.DM_VERIF -> coroutineDispatchers.dmVerif } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableWork.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableWork.kt index 6b04cea936..2240a408ef 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableWork.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableWork.kt @@ -20,8 +20,10 @@ import androidx.work.WorkManager import org.matrix.android.sdk.api.util.Cancelable import java.util.UUID -internal class CancelableWork(private val workManager: WorkManager, - private val workId: UUID) : Cancelable { +internal class CancelableWork( + private val workManager: WorkManager, + private val workId: UUID +) : Cancelable { override fun cancel() { workManager.cancelWorkById(workId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Glob.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Glob.kt index 60f9609586..a4aae80348 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Glob.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Glob.kt @@ -27,9 +27,9 @@ internal fun String.simpleGlobToRegExp(): String { // append("^") string.forEach { char -> when (char) { - '*' -> append(".*") - '?' -> append(".") - '.' -> append("\\.") + '*' -> append(".*") + '?' -> append(".") + '.' -> append("\\.") '\\' -> append("\\\\") else -> append(char) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt index c50b7fe675..6e6007f491 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt @@ -58,7 +58,7 @@ internal object JsonCanonicalizer { */ private fun canonicalizeRecursive(any: Any): String { when (any) { - is JSONArray -> { + is JSONArray -> { // Canonicalize each element of the array return (0 until any.length()).joinToString(separator = ",", prefix = "[", postfix = "]") { canonicalizeRecursive(any.get(it)) @@ -88,8 +88,8 @@ internal object JsonCanonicalizer { append("}") } } - is String -> return JSONObject.quote(any) - else -> return any.toString() + is String -> return JSONObject.quote(any) + else -> return any.toString() } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/LogUtil.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/LogUtil.kt index ffad0b856c..2306ddf850 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/LogUtil.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/LogUtil.kt @@ -33,10 +33,12 @@ internal fun Collection.logLimit(maxQuantity: Int = 5): String { } } -internal suspend fun logDuration(message: String, - loggerTag: LoggerTag, - clock: Clock, - block: suspend () -> T): T { +internal suspend fun logDuration( + message: String, + loggerTag: LoggerTag, + clock: Clock, + block: suspend () -> T +): T { Timber.tag(loggerTag.value).d("$message -- BEGIN") val start = clock.epochMillis() val result = logRamUsage(message) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt index fbbec1a100..cbaec586d0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt @@ -32,9 +32,9 @@ internal fun String.isValidUrl(): Boolean { */ internal fun String.ensureProtocol(): String { return when { - isEmpty() -> this + isEmpty() -> this !startsWith("http") -> "https://$this" - else -> this + else -> this } } @@ -43,8 +43,8 @@ internal fun String.ensureProtocol(): String { */ internal fun String.ensureTrailingSlash(): String { return when { - isEmpty() -> this + isEmpty() -> this !endsWith("/") -> "$this/" - else -> this + else -> this } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/database/RealmMigrator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/database/RealmMigrator.kt index 8f3c89f2d4..8da1bed97e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/database/RealmMigrator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/database/RealmMigrator.kt @@ -20,8 +20,10 @@ import io.realm.DynamicRealm import io.realm.RealmObjectSchema import timber.log.Timber -internal abstract class RealmMigrator(private val realm: DynamicRealm, - private val targetSchemaVersion: Int) { +internal abstract class RealmMigrator( + private val realm: DynamicRealm, + private val targetSchemaVersion: Int +) { fun perform() { Timber.d("Migrate ${realm.configuration.realmFileName} to $targetSchemaVersion") doMigrate(realm) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt index 31549155d3..003bdab9cb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt @@ -101,25 +101,25 @@ internal class DefaultGetWellknownTask @Inject constructor( } } catch (throwable: Throwable) { when (throwable) { - is UnrecognizedCertificateException -> { + is UnrecognizedCertificateException -> { throw Failure.UnrecognizedCertificateFailure( "https://$domain", throwable.fingerprint ) } - is Failure.NetworkConnection -> { + is Failure.NetworkConnection -> { WellknownResult.Ignore } - is Failure.OtherServerError -> { + is Failure.OtherServerError -> { when (throwable.httpCode) { HttpsURLConnection.HTTP_NOT_FOUND -> WellknownResult.Ignore - else -> WellknownResult.FailPrompt(null, null) + else -> WellknownResult.FailPrompt(null, null) } } is MalformedJsonException, is EOFException -> { WellknownResult.FailPrompt(null, null) } - else -> { + else -> { throw throwable } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/MatrixWorkerFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/MatrixWorkerFactory.kt index a8ef3e0748..52146ef484 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/MatrixWorkerFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/MatrixWorkerFactory.kt @@ -49,27 +49,27 @@ internal class MatrixWorkerFactory @Inject constructor(private val sessionManage ): ListenableWorker? { Timber.d("MatrixWorkerFactory.createWorker for $workerClassName") return when (workerClassName) { - CheckFactoryWorker::class.java.name -> + CheckFactoryWorker::class.java.name -> CheckFactoryWorker(appContext, workerParameters, true) - AddPusherWorker::class.java.name -> + AddPusherWorker::class.java.name -> AddPusherWorker(appContext, workerParameters, sessionManager) - GetGroupDataWorker::class.java.name -> + GetGroupDataWorker::class.java.name -> GetGroupDataWorker(appContext, workerParameters, sessionManager) MultipleEventSendingDispatcherWorker::class.java.name -> MultipleEventSendingDispatcherWorker(appContext, workerParameters, sessionManager) - RedactEventWorker::class.java.name -> + RedactEventWorker::class.java.name -> RedactEventWorker(appContext, workerParameters, sessionManager) - SendEventWorker::class.java.name -> + SendEventWorker::class.java.name -> SendEventWorker(appContext, workerParameters, sessionManager) - SyncWorker::class.java.name -> + SyncWorker::class.java.name -> SyncWorker(appContext, workerParameters, sessionManager) - UpdateTrustWorker::class.java.name -> + UpdateTrustWorker::class.java.name -> UpdateTrustWorker(appContext, workerParameters, sessionManager) - UploadContentWorker::class.java.name -> + UploadContentWorker::class.java.name -> UploadContentWorker(appContext, workerParameters, sessionManager) DeactivateLiveLocationShareWorker::class.java.name -> DeactivateLiveLocationShareWorker(appContext, workerParameters, sessionManager) - else -> { + else -> { Timber.w("No worker defined on MatrixWorkerFactory for $workerClassName will delegate to default.") // Return null to delegate to the default WorkerFactory. null @@ -81,9 +81,11 @@ internal class MatrixWorkerFactory @Inject constructor(private val sessionManage * This worker is launched by the factory with the isCreatedByMatrixWorkerFactory flag to true. * If the MatrixWorkerFactory is not set up, it will default to the other constructor and it will throw */ - class CheckFactoryWorker(context: Context, - workerParameters: WorkerParameters, - private val isCreatedByMatrixWorkerFactory: Boolean) : + class CheckFactoryWorker( + context: Context, + workerParameters: WorkerParameters, + private val isCreatedByMatrixWorkerFactory: Boolean + ) : CoroutineWorker(context, workerParameters) { // Called by WorkManager if there is no MatrixWorkerFactory diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersionTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersionTest.kt new file mode 100644 index 0000000000..413af9c434 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/version/HomeServerVersionTest.kt @@ -0,0 +1,57 @@ +/* + * Copyright 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.matrix.android.sdk.internal.auth.version + +import org.amshove.kluent.internal.assertEquals +import org.junit.Test + +class HomeServerVersionTest { + + @Test + fun `given a semantic version, when parsing, then converts to home server version`() { + val supportedVersions = listOf( + case("1.5", expected = aVersion(1, 5, 0)), + case("0.5.1", expected = aVersion(0, 5, 1)), + case("1.0.0", expected = aVersion(1, 0, 0)), + case("1.10.3", expected = aVersion(1, 10, 3)), + ).withPrefixes("v", "r") + + val unsupportedVersions = listOf( + case("v-1.5.1", expected = null), + case("1.4.", expected = null), + case("1.5.1.", expected = null), + case("r1", expected = null), + case("a", expected = null), + case("1a.2b.3c", expected = null), + case("r", expected = null), + ) + + (supportedVersions + unsupportedVersions).forEach { (input, expected) -> + val result = HomeServerVersion.parse(input) + + assertEquals(expected, result, "Expected $input to be $expected but got $result") + } + } +} + +private fun aVersion(major: Int, minor: Int, patch: Int) = HomeServerVersion(major, minor, patch) +private fun case(input: String, expected: HomeServerVersion?) = Case(input, expected) + +private fun List.withPrefixes(vararg prefixes: String) = map { case -> + prefixes.map { prefix -> case.copy(input = "$prefix${case.input}") } +}.flatten() + +private data class Case(val input: String, val expected: HomeServerVersion?) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeRequestExecutor.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeRequestExecutor.kt index 2f332a89a8..ad20abf63c 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeRequestExecutor.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeRequestExecutor.kt @@ -21,11 +21,13 @@ import org.matrix.android.sdk.internal.network.RequestExecutor internal class FakeRequestExecutor : RequestExecutor { - override suspend fun executeRequest(globalErrorReceiver: GlobalErrorReceiver?, - canRetry: Boolean, - maxDelayBeforeRetry: Long, - maxRetriesCount: Int, - requestBlock: suspend () -> DATA): DATA { + override suspend fun executeRequest( + globalErrorReceiver: GlobalErrorReceiver?, + canRetry: Boolean, + maxDelayBeforeRetry: Long, + maxRetriesCount: Int, + requestBlock: suspend () -> DATA + ): DATA { return requestBlock() } } diff --git a/vector/build.gradle b/vector/build.gradle index dea95b607a..14fd55c3cd 100644 --- a/vector/build.gradle +++ b/vector/build.gradle @@ -31,7 +31,7 @@ ext.versionMinor = 4 // Note: even values are reserved for regular release, odd values for hotfix release. // When creating a hotfix, you should decrease the value, since the current value // is the value for the next regular release. -ext.versionPatch = 20 +ext.versionPatch = 22 static def getGitTimestamp() { def cmd = 'git show -s --format=%ct' @@ -244,6 +244,7 @@ android { buildConfigField "boolean", "ENABLE_STRICT_MODE_LOGS", "false" signingConfig signingConfigs.debug + testCoverageEnabled true } release { @@ -380,7 +381,7 @@ dependencies { implementation 'com.facebook.stetho:stetho:1.6.0' // Phone number https://github.com/google/libphonenumber - implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.49' + implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.50' // FlowBinding implementation libs.github.flowBinding diff --git a/vector/src/androidTest/java/im/vector/app/EspressoExt.kt b/vector/src/androidTest/java/im/vector/app/EspressoExt.kt index efb28cdff5..72137ed8e8 100644 --- a/vector/src/androidTest/java/im/vector/app/EspressoExt.kt +++ b/vector/src/androidTest/java/im/vector/app/EspressoExt.kt @@ -142,7 +142,7 @@ fun initialSyncIdlingResource(session: Session): IdlingResource { override fun getName() = "InitialSyncIdlingResource for ${session.myUserId}" override fun isIdleNow(): Boolean { - val isIdle = session.hasAlreadySynced() + val isIdle = session.syncService().hasAlreadySynced() return isIdle } @@ -151,16 +151,16 @@ fun initialSyncIdlingResource(session: Session): IdlingResource { } override fun onChanged(t: SyncState?) { - val isIdle = session.hasAlreadySynced() + val isIdle = session.syncService().hasAlreadySynced() if (isIdle) { callback?.onTransitionToIdle() - session.getSyncStateLive().removeObserver(this) + session.syncService().getSyncStateLive().removeObserver(this) } } } runOnUiThread { - session.getSyncStateLive().observeForever(res) + session.syncService().getSyncStateLive().observeForever(res) } return res @@ -202,7 +202,7 @@ fun activityIdlingResource(activityClass: Class<*>): IdlingResource { println("*** [$name] onActivityLifecycleChanged callback: $callback") callback?.onTransitionToIdle() } - else -> { + else -> { // do nothing, we're blocking until the activity resumes } } diff --git a/vector/src/androidTest/java/im/vector/app/RegistrationTest.kt b/vector/src/androidTest/java/im/vector/app/RegistrationTest.kt index 344a2ecfb1..1399d1d6a9 100644 --- a/vector/src/androidTest/java/im/vector/app/RegistrationTest.kt +++ b/vector/src/androidTest/java/im/vector/app/RegistrationTest.kt @@ -31,6 +31,7 @@ import androidx.test.filters.LargeTest import im.vector.app.features.MainActivity import im.vector.app.features.home.HomeActivity import org.hamcrest.CoreMatchers.not +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -38,6 +39,7 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @LargeTest +@Ignore class RegistrationTest { @get:Rule diff --git a/vector/src/androidTest/java/im/vector/app/SecurityBootstrapTest.kt b/vector/src/androidTest/java/im/vector/app/SecurityBootstrapTest.kt index eaf39310a8..7dc20178f2 100644 --- a/vector/src/androidTest/java/im/vector/app/SecurityBootstrapTest.kt +++ b/vector/src/androidTest/java/im/vector/app/SecurityBootstrapTest.kt @@ -44,6 +44,7 @@ import im.vector.app.features.crypto.recover.SetupMode import im.vector.app.features.home.HomeActivity import org.hamcrest.CoreMatchers.not import org.junit.Before +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -52,6 +53,7 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @LargeTest +@Ignore class SecurityBootstrapTest : VerificationTestBase() { var existingSession: Session? = null diff --git a/vector/src/androidTest/java/im/vector/app/TestMatrixCallback.kt b/vector/src/androidTest/java/im/vector/app/TestMatrixCallback.kt index 2e254d48ef..f39960ce7e 100644 --- a/vector/src/androidTest/java/im/vector/app/TestMatrixCallback.kt +++ b/vector/src/androidTest/java/im/vector/app/TestMatrixCallback.kt @@ -27,8 +27,10 @@ import java.util.concurrent.CountDownLatch * @param onlySuccessful true to fail if an error occurs. This is the default behavior * @param */ -open class TestMatrixCallback(private val countDownLatch: CountDownLatch, - private val onlySuccessful: Boolean = true) : MatrixCallback { +open class TestMatrixCallback( + private val countDownLatch: CountDownLatch, + private val onlySuccessful: Boolean = true +) : MatrixCallback { @CallSuper override fun onSuccess(data: T) { diff --git a/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt b/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt index 6ac3226674..97a2a14da3 100644 --- a/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt +++ b/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt @@ -42,10 +42,12 @@ abstract class VerificationTestBase { protected val uiTestBase = OnboardingRobot() - fun createAccountAndSync(matrix: Matrix, - userName: String, - password: String, - withInitialSync: Boolean): Session { + fun createAccountAndSync( + matrix: Matrix, + userName: String, + password: String, + withInitialSync: Boolean + ): Session { val hs = createHomeServerConfig() runBlockingTest { @@ -114,14 +116,14 @@ abstract class VerificationTestBase { GlobalScope.launch(Dispatchers.Main) { session.open() } - session.startSync(true) + session.syncService().startSync(true) val syncLiveData = runBlocking(Dispatchers.Main) { - session.getSyncStateLive() + session.syncService().getSyncStateLive() } val syncObserver = object : Observer { override fun onChanged(t: SyncState?) { - if (session.hasAlreadySynced()) { + if (session.syncService().hasAlreadySynced()) { lock.countDown() syncLiveData.removeObserver(this) } diff --git a/vector/src/androidTest/java/im/vector/app/VerifySessionInteractiveTest.kt b/vector/src/androidTest/java/im/vector/app/VerifySessionInteractiveTest.kt index c970d0049f..8c9faee336 100644 --- a/vector/src/androidTest/java/im/vector/app/VerifySessionInteractiveTest.kt +++ b/vector/src/androidTest/java/im/vector/app/VerifySessionInteractiveTest.kt @@ -38,6 +38,7 @@ import im.vector.app.features.MainActivity import im.vector.app.features.home.HomeActivity import org.hamcrest.CoreMatchers.not import org.junit.Before +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -57,6 +58,7 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @LargeTest +@Ignore class VerifySessionInteractiveTest : VerificationTestBase() { var existingSession: Session? = null diff --git a/vector/src/androidTest/java/im/vector/app/VerifySessionPassphraseTest.kt b/vector/src/androidTest/java/im/vector/app/VerifySessionPassphraseTest.kt index 7efae073e5..23a662dcc8 100644 --- a/vector/src/androidTest/java/im/vector/app/VerifySessionPassphraseTest.kt +++ b/vector/src/androidTest/java/im/vector/app/VerifySessionPassphraseTest.kt @@ -43,6 +43,7 @@ import im.vector.app.features.crypto.recover.SetupMode import im.vector.app.features.home.HomeActivity import kotlinx.coroutines.runBlocking import org.junit.Before +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -57,6 +58,7 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @LargeTest +@Ignore class VerifySessionPassphraseTest : VerificationTestBase() { var existingSession: Session? = null diff --git a/vector/src/androidTest/java/im/vector/app/core/utils/TemporaryStoreTest.kt b/vector/src/androidTest/java/im/vector/app/core/utils/TemporaryStoreTest.kt index d8619f1824..71a83f2e9b 100644 --- a/vector/src/androidTest/java/im/vector/app/core/utils/TemporaryStoreTest.kt +++ b/vector/src/androidTest/java/im/vector/app/core/utils/TemporaryStoreTest.kt @@ -24,14 +24,14 @@ class TemporaryStoreTest { @Test fun testTemporaryStore() { - // Keep the data 30 millis - val store = TemporaryStore(30) + // Keep the data 300 millis + val store = TemporaryStore(300) store.data = "test" store.data shouldBe "test" - sleep(15) + sleep(10) store.data shouldBe "test" - sleep(20) + sleep(300) store.data shouldBe null } } diff --git a/vector/src/androidTest/java/im/vector/app/features/html/SpanUtilsTest.kt b/vector/src/androidTest/java/im/vector/app/features/html/SpanUtilsTest.kt index 31d8770123..428efdea86 100644 --- a/vector/src/androidTest/java/im/vector/app/features/html/SpanUtilsTest.kt +++ b/vector/src/androidTest/java/im/vector/app/features/html/SpanUtilsTest.kt @@ -29,6 +29,7 @@ import im.vector.app.InstrumentedTest import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeTrue import org.junit.FixMethodOrder +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -38,6 +39,7 @@ import java.util.concurrent.TimeUnit @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) +@Ignore class SpanUtilsTest : InstrumentedTest { private val spanUtils = SpanUtils { diff --git a/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt b/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt index b9292bd916..35027843d6 100644 --- a/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt +++ b/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt @@ -129,7 +129,7 @@ class ElementRobot { // We need to wait for the initial sync to complete; but we can't // use waitForHome() like login does. - // waitForHome() -- does not work because we have already fufilled the initialSync + // waitForHome() -- does not work because we have already fufilled the initialSync // so we can racily have an IllegalStateException that we have transitioned from busy -> idle // but never having sent the signal. @@ -141,7 +141,7 @@ class ElementRobot { // I hereby cheat and write: Thread.sleep(30_000) } - else -> { + else -> { } } } diff --git a/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingRobot.kt b/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingRobot.kt index 97e3b281c0..350bbf8ba3 100644 --- a/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingRobot.kt +++ b/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingRobot.kt @@ -79,10 +79,12 @@ class OnboardingRobot { initSession(false, userId, password, homeServerUrl) } - private fun initSession(createAccount: Boolean, - userId: String, - password: String, - homeServerUrl: String) { + private fun initSession( + createAccount: Boolean, + userId: String, + password: String, + homeServerUrl: String + ) { waitUntilViewVisible(withId(R.id.loginSplashSubmit)) assertDisplayed(R.id.loginSplashSubmit, R.string.login_splash_create_account) if (createAccount) { diff --git a/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingServersRobot.kt b/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingServersRobot.kt index 1625b4580d..050e5ab5c0 100644 --- a/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingServersRobot.kt +++ b/vector/src/androidTest/java/im/vector/app/ui/robot/OnboardingServersRobot.kt @@ -83,7 +83,7 @@ class OnboardingServersRobot { private fun assetMatrixSignInOptions(isSignUp: Boolean) { waitUntilViewVisible(ViewMatchers.withId(R.id.loginTitle)) when (isSignUp) { - true -> BaristaVisibilityAssertions.assertDisplayed(R.id.loginTitle, "Sign up to matrix.org") + true -> BaristaVisibilityAssertions.assertDisplayed(R.id.loginTitle, "Sign up to matrix.org") false -> BaristaVisibilityAssertions.assertDisplayed(R.id.loginTitle, "Connect to matrix.org") } } diff --git a/vector/src/debug/java/im/vector/app/features/debug/features/BooleanFeatureItem.kt b/vector/src/debug/java/im/vector/app/features/debug/features/BooleanFeatureItem.kt index 02c0aa82af..8665081102 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/features/BooleanFeatureItem.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/features/BooleanFeatureItem.kt @@ -56,7 +56,7 @@ abstract class BooleanFeatureItem : VectorEpoxyModel( onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (position) { - 0 -> listener?.onBooleanOptionSelected(option = null, feature) + 0 -> listener?.onBooleanOptionSelected(option = null, feature) else -> listener?.onBooleanOptionSelected(options[position].fromEmoji(), feature) } } @@ -80,7 +80,7 @@ abstract class BooleanFeatureItem : VectorEpoxyModel( private fun Boolean.toEmoji() = if (this) "✅" else "❌" private fun String.fromEmoji() = when (this) { - "✅" -> true - "❌" -> false + "✅" -> true + "❌" -> false else -> error("unexpected input $this") } diff --git a/vector/src/debug/java/im/vector/app/features/debug/features/EnumFeatureItem.kt b/vector/src/debug/java/im/vector/app/features/debug/features/EnumFeatureItem.kt index d5b2ec1080..a06147c4f8 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/features/EnumFeatureItem.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/features/EnumFeatureItem.kt @@ -52,7 +52,7 @@ abstract class EnumFeatureItem : VectorEpoxyModel() { onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (position) { - 0 -> listener?.onEnumOptionSelected(option = null, feature) + 0 -> listener?.onEnumOptionSelected(option = null, feature) else -> feature.onOptionSelected(position - 1) } } diff --git a/vector/src/debug/java/im/vector/app/features/debug/settings/DebugPrivateSettingsViewModel.kt b/vector/src/debug/java/im/vector/app/features/debug/settings/DebugPrivateSettingsViewModel.kt index dfe412117f..59949c6c7b 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/settings/DebugPrivateSettingsViewModel.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/settings/DebugPrivateSettingsViewModel.kt @@ -68,10 +68,10 @@ class DebugPrivateSettingsViewModel @AssistedInject constructor( override fun handle(action: DebugPrivateSettingsViewActions) { when (action) { - is DebugPrivateSettingsViewActions.SetDialPadVisibility -> handleSetDialPadVisibility(action) + is DebugPrivateSettingsViewActions.SetDialPadVisibility -> handleSetDialPadVisibility(action) is DebugPrivateSettingsViewActions.SetForceLoginFallbackEnabled -> handleSetForceLoginFallbackEnabled(action) - is SetDisplayNameCapabilityOverride -> handleSetDisplayNameCapabilityOverride(action) - is SetAvatarCapabilityOverride -> handleSetAvatarCapabilityOverride(action) + is SetDisplayNameCapabilityOverride -> handleSetDisplayNameCapabilityOverride(action) + is SetAvatarCapabilityOverride -> handleSetAvatarCapabilityOverride(action) } } diff --git a/vector/src/debug/java/im/vector/app/features/debug/settings/OverrideDropdownView.kt b/vector/src/debug/java/im/vector/app/features/debug/settings/OverrideDropdownView.kt index b8f89eaf88..7f510ee5e9 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/settings/OverrideDropdownView.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/settings/OverrideDropdownView.kt @@ -57,7 +57,7 @@ class OverrideDropdownView @JvmOverloads constructor( onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (position) { - 0 -> listener.onOverrideSelected(option = null) + 0 -> listener.onOverrideSelected(option = null) else -> listener.onOverrideSelected(feature.options[position - 1]) } } diff --git a/vector/src/debug/java/im/vector/app/features/debug/settings/PrivateSettingOverrides.kt b/vector/src/debug/java/im/vector/app/features/debug/settings/PrivateSettingOverrides.kt index 316e8fb901..5ed0693ef2 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/settings/PrivateSettingOverrides.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/settings/PrivateSettingOverrides.kt @@ -20,8 +20,8 @@ sealed interface BooleanHomeserverCapabilitiesOverride : OverrideOption { companion object { fun from(value: Boolean?) = when (value) { - null -> null - true -> ForceEnabled + null -> null + true -> ForceEnabled false -> ForceDisabled } } @@ -36,7 +36,7 @@ sealed interface BooleanHomeserverCapabilitiesOverride : OverrideOption { } fun BooleanHomeserverCapabilitiesOverride?.toBoolean() = when (this) { - null -> null + null -> null BooleanHomeserverCapabilitiesOverride.ForceDisabled -> false - BooleanHomeserverCapabilitiesOverride.ForceEnabled -> true + BooleanHomeserverCapabilitiesOverride.ForceEnabled -> true } diff --git a/vector/src/debug/java/im/vector/app/receivers/DebugReceiver.kt b/vector/src/debug/java/im/vector/app/receivers/DebugReceiver.kt index 0cea9e3d8e..9ec475d6d3 100644 --- a/vector/src/debug/java/im/vector/app/receivers/DebugReceiver.kt +++ b/vector/src/debug/java/im/vector/app/receivers/DebugReceiver.kt @@ -36,8 +36,8 @@ class DebugReceiver : BroadcastReceiver() { intent.action?.let { when { - it.endsWith(DEBUG_ACTION_DUMP_FILESYSTEM) -> lsFiles(context) - it.endsWith(DEBUG_ACTION_DUMP_PREFERENCES) -> dumpPreferences(context) + it.endsWith(DEBUG_ACTION_DUMP_FILESYSTEM) -> lsFiles(context) + it.endsWith(DEBUG_ACTION_DUMP_PREFERENCES) -> dumpPreferences(context) it.endsWith(DEBUG_ACTION_ALTER_SCALAR_TOKEN) -> alterScalarToken(context) } } diff --git a/vector/src/fdroid/java/im/vector/app/fdroid/BackgroundSyncStarter.kt b/vector/src/fdroid/java/im/vector/app/fdroid/BackgroundSyncStarter.kt index e890180c4f..e2ac4f8822 100644 --- a/vector/src/fdroid/java/im/vector/app/fdroid/BackgroundSyncStarter.kt +++ b/vector/src/fdroid/java/im/vector/app/fdroid/BackgroundSyncStarter.kt @@ -25,17 +25,19 @@ import im.vector.app.features.settings.VectorPreferences import timber.log.Timber object BackgroundSyncStarter { - fun start(context: Context, - vectorPreferences: VectorPreferences, - activeSessionHolder: ActiveSessionHolder, - clock: Clock) { + fun start( + context: Context, + vectorPreferences: VectorPreferences, + activeSessionHolder: ActiveSessionHolder, + clock: Clock + ) { if (vectorPreferences.areNotificationEnabledForDevice()) { val activeSession = activeSessionHolder.getSafeActiveSession() ?: return when (vectorPreferences.getFdroidSyncBackgroundMode()) { - BackgroundSyncMode.FDROID_BACKGROUND_SYNC_MODE_FOR_BATTERY -> { + BackgroundSyncMode.FDROID_BACKGROUND_SYNC_MODE_FOR_BATTERY -> { // we rely on periodic worker Timber.i("## Sync: Work scheduled to periodically sync in ${vectorPreferences.backgroundSyncDelay()}s") - activeSession.startAutomaticBackgroundSync( + activeSession.syncService().startAutomaticBackgroundSync( vectorPreferences.backgroundSyncTimeOut().toLong(), vectorPreferences.backgroundSyncDelay().toLong() ) @@ -50,7 +52,7 @@ object BackgroundSyncStarter { ) Timber.i("## Sync: Alarm scheduled to start syncing") } - BackgroundSyncMode.FDROID_BACKGROUND_SYNC_MODE_DISABLED -> { + BackgroundSyncMode.FDROID_BACKGROUND_SYNC_MODE_DISABLED -> { // we do nothing Timber.i("## Sync: background sync is disabled") } diff --git a/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestAutoStartBoot.kt b/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestAutoStartBoot.kt index 6d741a36ba..e028ed0988 100644 --- a/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestAutoStartBoot.kt +++ b/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestAutoStartBoot.kt @@ -26,8 +26,10 @@ import javax.inject.Inject /** * Test that the application is started on boot */ -class TestAutoStartBoot @Inject constructor(private val vectorPreferences: VectorPreferences, - private val stringProvider: StringProvider) : +class TestAutoStartBoot @Inject constructor( + private val vectorPreferences: VectorPreferences, + private val stringProvider: StringProvider +) : TroubleshootTest(R.string.settings_troubleshoot_test_service_boot_title) { override fun perform(activityResultLauncher: ActivityResultLauncher) { diff --git a/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestBackgroundRestrictions.kt b/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestBackgroundRestrictions.kt index 5932d2c372..ebd8d07540 100644 --- a/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestBackgroundRestrictions.kt +++ b/vector/src/fdroid/java/im/vector/app/fdroid/features/settings/troubleshoot/TestBackgroundRestrictions.kt @@ -26,8 +26,10 @@ import im.vector.app.core.resources.StringProvider import im.vector.app.features.settings.troubleshoot.TroubleshootTest import javax.inject.Inject -class TestBackgroundRestrictions @Inject constructor(private val context: FragmentActivity, - private val stringProvider: StringProvider) : +class TestBackgroundRestrictions @Inject constructor( + private val context: FragmentActivity, + private val stringProvider: StringProvider +) : TroubleshootTest(R.string.settings_troubleshoot_test_bg_restricted_title) { override fun perform(activityResultLauncher: ActivityResultLauncher) { @@ -36,7 +38,7 @@ class TestBackgroundRestrictions @Inject constructor(private val context: Fragme if (isActiveNetworkMetered) { // Checks user’s Data Saver settings. when (ConnectivityManagerCompat.getRestrictBackgroundStatus(this)) { - ConnectivityManagerCompat.RESTRICT_BACKGROUND_STATUS_ENABLED -> { + ConnectivityManagerCompat.RESTRICT_BACKGROUND_STATUS_ENABLED -> { // Background data usage is blocked for this app. Wherever possible, // the app should also use less data in the foreground. description = stringProvider.getString( @@ -56,7 +58,7 @@ class TestBackgroundRestrictions @Inject constructor(private val context: Fragme status = TestStatus.SUCCESS quickFix = null } - ConnectivityManagerCompat.RESTRICT_BACKGROUND_STATUS_DISABLED -> { + ConnectivityManagerCompat.RESTRICT_BACKGROUND_STATUS_DISABLED -> { // Data Saver is disabled. Since the device is connected to a // metered network, the app should use less data wherever possible. description = stringProvider.getString( diff --git a/vector/src/fdroid/java/im/vector/app/fdroid/receiver/AlarmSyncBroadcastReceiver.kt b/vector/src/fdroid/java/im/vector/app/fdroid/receiver/AlarmSyncBroadcastReceiver.kt index 09bd56654d..bd1e0eb0ee 100644 --- a/vector/src/fdroid/java/im/vector/app/fdroid/receiver/AlarmSyncBroadcastReceiver.kt +++ b/vector/src/fdroid/java/im/vector/app/fdroid/receiver/AlarmSyncBroadcastReceiver.kt @@ -26,9 +26,9 @@ import androidx.core.content.ContextCompat import androidx.core.content.getSystemService import im.vector.app.core.extensions.singletonEntryPoint import im.vector.app.core.platform.PendingIntentCompat -import im.vector.app.core.services.VectorSyncService +import im.vector.app.core.services.VectorSyncAndroidService import im.vector.app.core.time.Clock -import org.matrix.android.sdk.api.session.sync.job.SyncService +import org.matrix.android.sdk.api.session.sync.job.SyncAndroidService import timber.log.Timber class AlarmSyncBroadcastReceiver : BroadcastReceiver() { @@ -43,8 +43,8 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() { val vectorPreferences = singletonEntryPoint.vectorPreferences() val clock = singletonEntryPoint.clock() - val sessionId = intent.getStringExtra(SyncService.EXTRA_SESSION_ID) ?: return - VectorSyncService.newPeriodicIntent( + val sessionId = intent.getStringExtra(SyncAndroidService.EXTRA_SESSION_ID) ?: return + VectorSyncAndroidService.newPeriodicIntent( context = context, sessionId = sessionId, syncTimeoutSeconds = vectorPreferences.backgroundSyncTimeOut(), @@ -69,8 +69,8 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() { // Reschedule Timber.v("## Sync: Scheduling alarm for background sync in $delayInSeconds seconds") val intent = Intent(context, AlarmSyncBroadcastReceiver::class.java).apply { - putExtra(SyncService.EXTRA_SESSION_ID, sessionId) - putExtra(SyncService.EXTRA_PERIODIC, true) + putExtra(SyncAndroidService.EXTRA_SESSION_ID, sessionId) + putExtra(SyncAndroidService.EXTRA_PERIODIC, true) } val pIntent = PendingIntent.getBroadcast( context, @@ -100,7 +100,7 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() { alarmMgr.cancel(pIntent) // Stop current service to restart - VectorSyncService.stopIntent(context).let { + VectorSyncAndroidService.stopIntent(context).let { try { ContextCompat.startForegroundService(context, it) } catch (ex: Throwable) { diff --git a/vector/src/fdroid/java/im/vector/app/push/fcm/FcmHelper.kt b/vector/src/fdroid/java/im/vector/app/push/fcm/FcmHelper.kt index 6e36d5dd81..7533eae856 100755 --- a/vector/src/fdroid/java/im/vector/app/push/fcm/FcmHelper.kt +++ b/vector/src/fdroid/java/im/vector/app/push/fcm/FcmHelper.kt @@ -63,14 +63,16 @@ object FcmHelper { fun onEnterForeground(context: Context, activeSessionHolder: ActiveSessionHolder) { // try to stop all regardless of background mode - activeSessionHolder.getSafeActiveSession()?.stopAnyBackgroundSync() + activeSessionHolder.getSafeActiveSession()?.syncService()?.stopAnyBackgroundSync() AlarmSyncBroadcastReceiver.cancelAlarm(context) } - fun onEnterBackground(context: Context, - vectorPreferences: VectorPreferences, - activeSessionHolder: ActiveSessionHolder, - clock: Clock) { + fun onEnterBackground( + context: Context, + vectorPreferences: VectorPreferences, + activeSessionHolder: ActiveSessionHolder, + clock: Clock + ) { BackgroundSyncStarter.start(context, vectorPreferences, activeSessionHolder, clock) } } diff --git a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestFirebaseToken.kt b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestFirebaseToken.kt index 89270cce55..5a9dc90ec4 100644 --- a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestFirebaseToken.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestFirebaseToken.kt @@ -30,8 +30,10 @@ import javax.inject.Inject /* * Test that app can successfully retrieve a token via firebase */ -class TestFirebaseToken @Inject constructor(private val context: FragmentActivity, - private val stringProvider: StringProvider) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) { +class TestFirebaseToken @Inject constructor( + private val context: FragmentActivity, + private val stringProvider: StringProvider +) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) { override fun perform(activityResultLauncher: ActivityResultLauncher) { status = TestStatus.RUNNING @@ -41,13 +43,13 @@ class TestFirebaseToken @Inject constructor(private val context: FragmentActivit if (!task.isSuccessful) { // Can't find where this constant is (not documented -or deprecated in docs- and all obfuscated) description = when (val errorMsg = task.exception?.localizedMessage ?: "Unknown") { - "SERVICE_NOT_AVAILABLE" -> { + "SERVICE_NOT_AVAILABLE" -> { stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed_service_not_available, errorMsg) } "TOO_MANY_REGISTRATIONS" -> { stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed_too_many_registration, errorMsg) } - "ACCOUNT_MISSING" -> { + "ACCOUNT_MISSING" -> { quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_fcm_failed_account_missing_quick_fix) { override fun doFix() { startAddGoogleAccountIntent(context, activityResultLauncher) @@ -55,7 +57,7 @@ class TestFirebaseToken @Inject constructor(private val context: FragmentActivit } stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed_account_missing, errorMsg) } - else -> { + else -> { stringProvider.getString(R.string.settings_troubleshoot_test_fcm_failed, errorMsg) } } diff --git a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPlayServices.kt b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPlayServices.kt index ecb457bf9f..f1ea4a4153 100644 --- a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPlayServices.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPlayServices.kt @@ -29,8 +29,10 @@ import javax.inject.Inject /* * Check that the play services APK is available an up-to-date. If needed provide quick fix to install it. */ -class TestPlayServices @Inject constructor(private val context: FragmentActivity, - private val stringProvider: StringProvider) : +class TestPlayServices @Inject constructor( + private val context: FragmentActivity, + private val stringProvider: StringProvider +) : TroubleshootTest(R.string.settings_troubleshoot_test_play_services_title) { override fun perform(activityResultLauncher: ActivityResultLauncher) { diff --git a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPushFromPushGateway.kt b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPushFromPushGateway.kt index f485de760a..b4b8a936d0 100644 --- a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPushFromPushGateway.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestPushFromPushGateway.kt @@ -36,11 +36,13 @@ import javax.inject.Inject /** * Test Push by asking the Push Gateway to send a Push back */ -class TestPushFromPushGateway @Inject constructor(private val context: FragmentActivity, - private val stringProvider: StringProvider, - private val errorFormatter: ErrorFormatter, - private val pushersManager: PushersManager, - private val activeSessionHolder: ActiveSessionHolder) : +class TestPushFromPushGateway @Inject constructor( + private val context: FragmentActivity, + private val stringProvider: StringProvider, + private val errorFormatter: ErrorFormatter, + private val pushersManager: PushersManager, + private val activeSessionHolder: ActiveSessionHolder +) : TroubleshootTest(R.string.settings_troubleshoot_test_push_loop_title) { private var action: Job? = null diff --git a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestTokenRegistration.kt b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestTokenRegistration.kt index 2db03f3428..a6220c2018 100644 --- a/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestTokenRegistration.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/features/settings/troubleshoot/TestTokenRegistration.kt @@ -33,10 +33,12 @@ import javax.inject.Inject /** * Force registration of the token to HomeServer */ -class TestTokenRegistration @Inject constructor(private val context: FragmentActivity, - private val stringProvider: StringProvider, - private val pushersManager: PushersManager, - private val activeSessionHolder: ActiveSessionHolder) : +class TestTokenRegistration @Inject constructor( + private val context: FragmentActivity, + private val stringProvider: StringProvider, + private val pushersManager: PushersManager, + private val activeSessionHolder: ActiveSessionHolder +) : TroubleshootTest(R.string.settings_troubleshoot_test_token_registration_title) { override fun perform(activityResultLauncher: ActivityResultLauncher) { diff --git a/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt b/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt index a7d814052a..8d0126d6af 100755 --- a/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt @@ -164,7 +164,7 @@ class VectorFirebaseMessagingService : FirebaseMessagingService() { getEventFastLane(session, roomId, eventId) Timber.tag(loggerTag.value).d("Requesting background sync") - session.requireBackgroundSync() + session.syncService().requireBackgroundSync() } } } catch (e: Exception) { diff --git a/vector/src/gplay/java/im/vector/app/push/fcm/FcmHelper.kt b/vector/src/gplay/java/im/vector/app/push/fcm/FcmHelper.kt index 74ab3b38f1..ac2d063700 100755 --- a/vector/src/gplay/java/im/vector/app/push/fcm/FcmHelper.kt +++ b/vector/src/gplay/java/im/vector/app/push/fcm/FcmHelper.kt @@ -55,8 +55,10 @@ object FcmHelper { * @param context android context * @param token the token to store */ - fun storeFcmToken(context: Context, - token: String?) { + fun storeFcmToken( + context: Context, + token: String? + ) { DefaultSharedPreferences.getInstance(context).edit { putString(PREFS_KEY_FCM_TOKEN, token) } @@ -108,10 +110,12 @@ object FcmHelper { } @Suppress("UNUSED_PARAMETER") - fun onEnterBackground(context: Context, - vectorPreferences: VectorPreferences, - activeSessionHolder: ActiveSessionHolder, - clock: Clock) { + fun onEnterBackground( + context: Context, + vectorPreferences: VectorPreferences, + activeSessionHolder: ActiveSessionHolder, + clock: Clock + ) { // No op } } diff --git a/vector/src/main/AndroidManifest.xml b/vector/src/main/AndroidManifest.xml index 2e31439e73..89c600b052 100644 --- a/vector/src/main/AndroidManifest.xml +++ b/vector/src/main/AndroidManifest.xml @@ -358,7 +358,7 @@ diff --git a/vector/src/main/java/im/vector/app/AppStateHandler.kt b/vector/src/main/java/im/vector/app/AppStateHandler.kt index d44af53a55..d366927d6d 100644 --- a/vector/src/main/java/im/vector/app/AppStateHandler.kt +++ b/vector/src/main/java/im/vector/app/AppStateHandler.kt @@ -41,8 +41,8 @@ import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.getRoomSummary import org.matrix.android.sdk.api.session.group.model.GroupSummary -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.room.model.RoomSummary +import org.matrix.android.sdk.api.session.sync.SyncRequestState import javax.inject.Inject import javax.inject.Singleton @@ -147,9 +147,9 @@ class AppStateHandler @Inject constructor( } private fun observeSyncStatus(session: Session) { - session.syncStatusService().getSyncStatusLive() + session.syncService().getSyncRequestStateLive() .asFlow() - .filterIsInstance() + .filterIsInstance() .map { session.spaceService().getRootSpaceSummaries().size } .distinctUntilChanged() .onEach { spacesNumber -> @@ -175,7 +175,7 @@ class AppStateHandler @Inject constructor( coroutineScope.coroutineContext.cancelChildren() val session = activeSessionHolder.getSafeActiveSession() ?: return when (val currentMethod = selectedSpaceDataSource.currentValue?.orNull() ?: RoomGroupingMethod.BySpace(null)) { - is RoomGroupingMethod.BySpace -> { + is RoomGroupingMethod.BySpace -> { uiStateRepository.storeGroupingMethod(true, session.sessionId) uiStateRepository.storeSelectedSpace(currentMethod.spaceSummary?.roomId, session.sessionId) } diff --git a/vector/src/main/java/im/vector/app/AutoRageShaker.kt b/vector/src/main/java/im/vector/app/AutoRageShaker.kt index c77ce2b647..dc561aa821 100644 --- a/vector/src/main/java/im/vector/app/AutoRageShaker.kt +++ b/vector/src/main/java/im/vector/app/AutoRageShaker.kt @@ -36,7 +36,7 @@ import kotlinx.coroutines.launch import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toContent -import org.matrix.android.sdk.api.session.initsync.SyncStatusService +import org.matrix.android.sdk.api.session.sync.SyncRequestState import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @@ -260,11 +260,11 @@ class AutoRageShaker @Inject constructor( } this.currentActiveSessionId = sessionId - hasSynced = session.hasAlreadySynced() - session.syncStatusService().getSyncStatusLive() + hasSynced = session.syncService().hasAlreadySynced() + session.syncService().getSyncRequestStateLive() .asFlow() .onEach { - hasSynced = it !is SyncStatusService.Status.InitialSyncProgressing + hasSynced = it !is SyncRequestState.InitialSyncProgressing } .launchIn(session.coroutineScope) activeSessionIds.add(sessionId) diff --git a/vector/src/main/java/im/vector/app/VectorApplication.kt b/vector/src/main/java/im/vector/app/VectorApplication.kt index a55351f74b..7db0f99f5f 100644 --- a/vector/src/main/java/im/vector/app/VectorApplication.kt +++ b/vector/src/main/java/im/vector/app/VectorApplication.kt @@ -176,7 +176,7 @@ class VectorApplication : Timber.i("App entered foreground") FcmHelper.onEnterForeground(appContext, activeSessionHolder) activeSessionHolder.getSafeActiveSession()?.also { - it.stopAnyBackgroundSync() + it.syncService().stopAnyBackgroundSync() } } diff --git a/vector/src/main/java/im/vector/app/core/date/DateFormatterProviders.kt b/vector/src/main/java/im/vector/app/core/date/DateFormatterProviders.kt index a216b6b5d8..a686c1e410 100644 --- a/vector/src/main/java/im/vector/app/core/date/DateFormatterProviders.kt +++ b/vector/src/main/java/im/vector/app/core/date/DateFormatterProviders.kt @@ -18,8 +18,10 @@ package im.vector.app.core.date import javax.inject.Inject -class DateFormatterProviders @Inject constructor(private val defaultDateFormatterProvider: DefaultDateFormatterProvider, - private val abbrevDateFormatterProvider: AbbrevDateFormatterProvider) { +class DateFormatterProviders @Inject constructor( + private val defaultDateFormatterProvider: DefaultDateFormatterProvider, + private val abbrevDateFormatterProvider: AbbrevDateFormatterProvider +) { fun provide(abbrev: Boolean): DateFormatterProvider { return if (abbrev) { diff --git a/vector/src/main/java/im/vector/app/core/date/DefaultDateFormatterProvider.kt b/vector/src/main/java/im/vector/app/core/date/DefaultDateFormatterProvider.kt index 361868cd95..138cc51cc4 100644 --- a/vector/src/main/java/im/vector/app/core/date/DefaultDateFormatterProvider.kt +++ b/vector/src/main/java/im/vector/app/core/date/DefaultDateFormatterProvider.kt @@ -22,8 +22,10 @@ import im.vector.app.core.resources.LocaleProvider import org.threeten.bp.format.DateTimeFormatter import javax.inject.Inject -class DefaultDateFormatterProvider @Inject constructor(private val context: Context, - private val localeProvider: LocaleProvider) : +class DefaultDateFormatterProvider @Inject constructor( + private val context: Context, + private val localeProvider: LocaleProvider +) : DateFormatterProvider { override val dateWithMonthFormatter: DateTimeFormatter by lazy { diff --git a/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt b/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt index b3bd671583..780a3ab705 100644 --- a/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt +++ b/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt @@ -66,20 +66,20 @@ class VectorDateFormatter @Inject constructor( val localDateTime = DateProvider.toLocalDateTime(ts) return when (dateFormatKind) { DateFormatKind.DEFAULT_DATE_AND_TIME -> formatDateAndTime(ts) - DateFormatKind.ROOM_LIST -> formatTimeOrDate( + DateFormatKind.ROOM_LIST -> formatTimeOrDate( date = localDateTime, showTimeIfSameDay = true, abbrev = true, useRelative = true ) - DateFormatKind.TIMELINE_DAY_DIVIDER -> formatTimeOrDate( + DateFormatKind.TIMELINE_DAY_DIVIDER -> formatTimeOrDate( date = localDateTime, alwaysShowYear = true ) - DateFormatKind.MESSAGE_DETAIL -> formatFullDate(localDateTime) - DateFormatKind.MESSAGE_SIMPLE -> formatHour(localDateTime) - DateFormatKind.EDIT_HISTORY_ROW -> formatHour(localDateTime) - DateFormatKind.EDIT_HISTORY_HEADER -> formatTimeOrDate( + DateFormatKind.MESSAGE_DETAIL -> formatFullDate(localDateTime) + DateFormatKind.MESSAGE_SIMPLE -> formatHour(localDateTime) + DateFormatKind.EDIT_HISTORY_ROW -> formatHour(localDateTime) + DateFormatKind.EDIT_HISTORY_HEADER -> formatTimeOrDate( date = localDateTime, abbrev = true, useRelative = true diff --git a/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt b/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt index 983850e3be..f0c956365f 100644 --- a/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt +++ b/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt @@ -31,14 +31,15 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class ActiveSessionHolder @Inject constructor(private val activeSessionDataSource: ActiveSessionDataSource, - private val keyRequestHandler: KeyRequestHandler, - private val incomingVerificationRequestHandler: IncomingVerificationRequestHandler, - private val callManager: WebRtcCallManager, - private val pushRuleTriggerListener: PushRuleTriggerListener, - private val sessionListener: SessionListener, - private val imageManager: ImageManager, - private val guardServiceStarter: GuardServiceStarter +class ActiveSessionHolder @Inject constructor( + private val activeSessionDataSource: ActiveSessionDataSource, + private val keyRequestHandler: KeyRequestHandler, + private val incomingVerificationRequestHandler: IncomingVerificationRequestHandler, + private val callManager: WebRtcCallManager, + private val pushRuleTriggerListener: PushRuleTriggerListener, + private val sessionListener: SessionListener, + private val imageManager: ImageManager, + private val guardServiceStarter: GuardServiceStarter ) { private var activeSession: AtomicReference = AtomicReference() diff --git a/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt b/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt index 44f8bb1b3e..085a9a5d12 100644 --- a/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt +++ b/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt @@ -119,7 +119,8 @@ object VectorStaticModule { @Provides fun providesMatrixConfiguration( vectorPreferences: VectorPreferences, - vectorRoomDisplayNameFallbackProvider: VectorRoomDisplayNameFallbackProvider): MatrixConfiguration { + vectorRoomDisplayNameFallbackProvider: VectorRoomDisplayNameFallbackProvider + ): MatrixConfiguration { return MatrixConfiguration( applicationFlavor = BuildConfig.FLAVOR_DESCRIPTION, roomDisplayNameFallbackProvider = vectorRoomDisplayNameFallbackProvider, diff --git a/vector/src/main/java/im/vector/app/core/dialogs/ConfirmationDialogBuilder.kt b/vector/src/main/java/im/vector/app/core/dialogs/ConfirmationDialogBuilder.kt index 6f45091cf9..01d369b019 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/ConfirmationDialogBuilder.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/ConfirmationDialogBuilder.kt @@ -25,13 +25,15 @@ import im.vector.app.databinding.DialogConfirmationWithReasonBinding object ConfirmationDialogBuilder { - fun show(activity: Activity, - askForReason: Boolean, - @StringRes titleRes: Int, - @StringRes confirmationRes: Int, - @StringRes positiveRes: Int, - @StringRes reasonHintRes: Int, - confirmation: (String?) -> Unit) { + fun show( + activity: Activity, + askForReason: Boolean, + @StringRes titleRes: Int, + @StringRes confirmationRes: Int, + @StringRes positiveRes: Int, + @StringRes reasonHintRes: Int, + confirmation: (String?) -> Unit + ) { val layout = activity.layoutInflater.inflate(R.layout.dialog_confirmation_with_reason, null) val views = DialogConfirmationWithReasonBinding.bind(layout) views.dialogConfirmationText.setText(confirmationRes) diff --git a/vector/src/main/java/im/vector/app/core/dialogs/ExportKeysDialog.kt b/vector/src/main/java/im/vector/app/core/dialogs/ExportKeysDialog.kt index 024d283c4c..d0de7e6a3f 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/ExportKeysDialog.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/ExportKeysDialog.kt @@ -35,7 +35,7 @@ class ExportKeysDialog { val textWatcher = object : SimpleTextWatcher() { override fun afterTextChanged(s: Editable) { when { - views.exportDialogEt.text.isNullOrEmpty() -> { + views.exportDialogEt.text.isNullOrEmpty() -> { views.exportDialogSubmit.isEnabled = false views.exportDialogTilConfirm.error = null } @@ -43,7 +43,7 @@ class ExportKeysDialog { views.exportDialogSubmit.isEnabled = true views.exportDialogTilConfirm.error = null } - else -> { + else -> { views.exportDialogSubmit.isEnabled = false views.exportDialogTilConfirm.error = activity.getString(R.string.passphrase_passphrase_does_not_match) } diff --git a/vector/src/main/java/im/vector/app/core/dialogs/GalleryOrCameraDialogHelper.kt b/vector/src/main/java/im/vector/app/core/dialogs/GalleryOrCameraDialogHelper.kt index a9e223709a..c2af05123b 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/GalleryOrCameraDialogHelper.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/GalleryOrCameraDialogHelper.kt @@ -123,7 +123,7 @@ class GalleryOrCameraDialogHelper( private fun onAvatarTypeSelected(type: Type) { when (type) { - Type.Camera -> + Type.Camera -> if (checkPermissions(PERMISSIONS_FOR_TAKING_PHOTO, activity, takePhotoPermissionActivityResultLauncher)) { doOpenCamera() } diff --git a/vector/src/main/java/im/vector/app/core/dialogs/PhotoOrVideoDialog.kt b/vector/src/main/java/im/vector/app/core/dialogs/PhotoOrVideoDialog.kt index 0b76446ce2..9effa4c489 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/PhotoOrVideoDialog.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/PhotoOrVideoDialog.kt @@ -42,7 +42,7 @@ class PhotoOrVideoDialog( VectorPreferences.TAKE_PHOTO_VIDEO_MODE_PHOTO -> listener.takePhoto() VectorPreferences.TAKE_PHOTO_VIDEO_MODE_VIDEO -> listener.takeVideo() /* VectorPreferences.TAKE_PHOTO_VIDEO_MODE_ALWAYS_ASK */ - else -> { + else -> { val dialogLayout = activity.layoutInflater.inflate(R.layout.dialog_photo_or_video, null) val views = DialogPhotoOrVideoBinding.bind(dialogLayout) @@ -63,9 +63,11 @@ class PhotoOrVideoDialog( } } - private fun submit(views: DialogPhotoOrVideoBinding, - vectorPreferences: VectorPreferences, - listener: PhotoOrVideoDialogListener) { + private fun submit( + views: DialogPhotoOrVideoBinding, + vectorPreferences: VectorPreferences, + listener: PhotoOrVideoDialogListener + ) { val mode = if (views.dialogPhotoOrVideoPhoto.isChecked) { VectorPreferences.TAKE_PHOTO_VIDEO_MODE_PHOTO } else { @@ -111,7 +113,7 @@ class PhotoOrVideoDialog( when { views.dialogPhotoOrVideoPhoto.isChecked -> VectorPreferences.TAKE_PHOTO_VIDEO_MODE_PHOTO views.dialogPhotoOrVideoVideo.isChecked -> VectorPreferences.TAKE_PHOTO_VIDEO_MODE_VIDEO - else -> VectorPreferences.TAKE_PHOTO_VIDEO_MODE_ALWAYS_ASK + else -> VectorPreferences.TAKE_PHOTO_VIDEO_MODE_ALWAYS_ASK } ) } diff --git a/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt b/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt index 8eaced1c48..df50175f87 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt @@ -43,9 +43,11 @@ class UnrecognizedCertificateDialog @Inject constructor( * @param unrecognizedFingerprint the fingerprint for the unknown certificate * @param callback callback to fire when the user makes a decision */ - fun show(activity: Activity, - unrecognizedFingerprint: Fingerprint, - callback: Callback) { + fun show( + activity: Activity, + unrecognizedFingerprint: Fingerprint, + callback: Callback + ) { val userId = activeSessionHolder.getSafeActiveSession()?.myUserId val hsConfig = activeSessionHolder.getSafeActiveSession()?.sessionParams?.homeServerConnectionConfig ?: return @@ -63,10 +65,12 @@ class UnrecognizedCertificateDialog @Inject constructor( /** * To use during login flow. */ - fun show(activity: Activity, - unrecognizedFingerprint: Fingerprint, - homeServerUrl: String, - callback: Callback) { + fun show( + activity: Activity, + unrecognizedFingerprint: Fingerprint, + homeServerUrl: String, + callback: Callback + ) { internalShow( activity = activity, unrecognizedFingerprint = unrecognizedFingerprint, @@ -89,13 +93,15 @@ class UnrecognizedCertificateDialog @Inject constructor( * @param homeServerUrl the homeserver url * @param homeServerConnectionConfigHasFingerprints true if the homeServerConnectionConfig has fingerprint */ - private fun internalShow(activity: Activity, - unrecognizedFingerprint: Fingerprint, - existing: Boolean, - callback: Callback, - userId: String?, - homeServerUrl: String, - homeServerConnectionConfigHasFingerprints: Boolean) { + private fun internalShow( + activity: Activity, + unrecognizedFingerprint: Fingerprint, + existing: Boolean, + callback: Callback, + userId: String?, + homeServerUrl: String, + homeServerConnectionConfigHasFingerprints: Boolean + ) { val dialogId = userId ?: homeServerUrl + unrecognizedFingerprint.displayableHexRepr if (openDialogIds.contains(dialogId)) { diff --git a/vector/src/main/java/im/vector/app/core/dispatchers/CoroutineDispatchers.kt b/vector/src/main/java/im/vector/app/core/dispatchers/CoroutineDispatchers.kt index 008ca4a9ce..8fdc9dc637 100644 --- a/vector/src/main/java/im/vector/app/core/dispatchers/CoroutineDispatchers.kt +++ b/vector/src/main/java/im/vector/app/core/dispatchers/CoroutineDispatchers.kt @@ -21,4 +21,5 @@ import javax.inject.Inject data class CoroutineDispatchers @Inject constructor( val io: CoroutineDispatcher, - val computation: CoroutineDispatcher) + val computation: CoroutineDispatcher +) diff --git a/vector/src/main/java/im/vector/app/core/error/ErrorFormatter.kt b/vector/src/main/java/im/vector/app/core/error/ErrorFormatter.kt index a6f80a256e..8fbd89a6c1 100644 --- a/vector/src/main/java/im/vector/app/core/error/ErrorFormatter.kt +++ b/vector/src/main/java/im/vector/app/core/error/ErrorFormatter.kt @@ -42,102 +42,102 @@ class DefaultErrorFormatter @Inject constructor( override fun toHumanReadable(throwable: Throwable?): String { return when (throwable) { - null -> null - is IdentityServiceError -> identityServerError(throwable) - is Failure.NetworkConnection -> { + null -> null + is IdentityServiceError -> identityServerError(throwable) + is Failure.NetworkConnection -> { when (throwable.ioException) { - is SocketTimeoutException -> + is SocketTimeoutException -> stringProvider.getString(R.string.error_network_timeout) is SSLPeerUnverifiedException -> stringProvider.getString(R.string.login_error_ssl_peer_unverified) - is SSLException -> + is SSLException -> stringProvider.getString(R.string.login_error_ssl_other) - else -> + else -> // TODO Check network state, airplane mode, etc. stringProvider.getString(R.string.error_no_network) } } - is Failure.ServerError -> { + is Failure.ServerError -> { when { - throwable.error.code == MatrixError.M_CONSENT_NOT_GIVEN -> { + throwable.error.code == MatrixError.M_CONSENT_NOT_GIVEN -> { // Special case for terms and conditions stringProvider.getString(R.string.error_terms_not_accepted) } - throwable.isInvalidPassword() -> { + throwable.isInvalidPassword() -> { stringProvider.getString(R.string.auth_invalid_login_param) } - throwable.error.code == MatrixError.M_USER_IN_USE -> { + throwable.error.code == MatrixError.M_USER_IN_USE -> { stringProvider.getString(R.string.login_signup_error_user_in_use) } - throwable.error.code == MatrixError.M_BAD_JSON -> { + throwable.error.code == MatrixError.M_BAD_JSON -> { stringProvider.getString(R.string.login_error_bad_json) } - throwable.error.code == MatrixError.M_NOT_JSON -> { + throwable.error.code == MatrixError.M_NOT_JSON -> { stringProvider.getString(R.string.login_error_not_json) } - throwable.error.code == MatrixError.M_THREEPID_DENIED -> { + throwable.error.code == MatrixError.M_THREEPID_DENIED -> { stringProvider.getString(R.string.login_error_threepid_denied) } - throwable.isLimitExceededError() -> { + throwable.isLimitExceededError() -> { limitExceededError(throwable.error) } - throwable.error.code == MatrixError.M_TOO_LARGE -> { + throwable.error.code == MatrixError.M_TOO_LARGE -> { stringProvider.getString(R.string.error_file_too_big_simple) } - throwable.error.code == MatrixError.M_THREEPID_NOT_FOUND -> { + throwable.error.code == MatrixError.M_THREEPID_NOT_FOUND -> { stringProvider.getString(R.string.login_reset_password_error_not_found) } - throwable.error.code == MatrixError.M_USER_DEACTIVATED -> { + throwable.error.code == MatrixError.M_USER_DEACTIVATED -> { stringProvider.getString(R.string.auth_invalid_login_deactivated_account) } throwable.error.code == MatrixError.M_THREEPID_IN_USE && - throwable.error.message == "Email is already in use" -> { + throwable.error.message == "Email is already in use" -> { stringProvider.getString(R.string.account_email_already_used_error) } throwable.error.code == MatrixError.M_THREEPID_IN_USE && - throwable.error.message == "MSISDN is already in use" -> { + throwable.error.message == "MSISDN is already in use" -> { stringProvider.getString(R.string.account_phone_number_already_used_error) } - throwable.error.code == MatrixError.M_THREEPID_AUTH_FAILED -> { + throwable.error.code == MatrixError.M_THREEPID_AUTH_FAILED -> { stringProvider.getString(R.string.error_threepid_auth_failed) } throwable.error.code == MatrixError.M_UNKNOWN && throwable.error.message == "Not allowed to join this room" -> { stringProvider.getString(R.string.room_error_access_unauthorized) } - else -> { + else -> { throwable.error.message.takeIf { it.isNotEmpty() } ?: throwable.error.code.takeIf { it.isNotEmpty() } } } } - is Failure.OtherServerError -> { + is Failure.OtherServerError -> { when (throwable.httpCode) { - HttpURLConnection.HTTP_NOT_FOUND -> + HttpURLConnection.HTTP_NOT_FOUND -> // homeserver not found stringProvider.getString(R.string.login_error_no_homeserver_found) HttpURLConnection.HTTP_UNAUTHORIZED -> // uia errors? stringProvider.getString(R.string.error_unauthorized) - else -> + else -> throwable.localizedMessage } } is DialPadLookup.Failure.NumberIsYours -> stringProvider.getString(R.string.cannot_call_yourself) - is DialPadLookup.Failure.NoResult -> + is DialPadLookup.Failure.NoResult -> stringProvider.getString(R.string.call_dial_pad_lookup_error) - is MatrixIdFailure.InvalidMatrixId -> + is MatrixIdFailure.InvalidMatrixId -> stringProvider.getString(R.string.login_signin_matrix_id_error_invalid_matrix_id) - is VoiceFailure -> voiceMessageError(throwable) - else -> throwable.localizedMessage + is VoiceFailure -> voiceMessageError(throwable) + else -> throwable.localizedMessage } ?: stringProvider.getString(R.string.unknown_error) } private fun voiceMessageError(throwable: VoiceFailure): String { return when (throwable) { - is VoiceFailure.UnableToPlay -> stringProvider.getString(R.string.error_voice_message_unable_to_play) + is VoiceFailure.UnableToPlay -> stringProvider.getString(R.string.error_voice_message_unable_to_play) is VoiceFailure.UnableToRecord -> stringProvider.getString(R.string.error_voice_message_unable_to_record) } } @@ -157,14 +157,14 @@ class DefaultErrorFormatter @Inject constructor( private fun identityServerError(identityServiceError: IdentityServiceError): String { return stringProvider.getString( when (identityServiceError) { - IdentityServiceError.OutdatedIdentityServer -> R.string.identity_server_error_outdated_identity_server - IdentityServiceError.OutdatedHomeServer -> R.string.identity_server_error_outdated_home_server - IdentityServiceError.NoIdentityServerConfigured -> R.string.identity_server_error_no_identity_server_configured - IdentityServiceError.TermsNotSignedException -> R.string.identity_server_error_terms_not_signed + IdentityServiceError.OutdatedIdentityServer -> R.string.identity_server_error_outdated_identity_server + IdentityServiceError.OutdatedHomeServer -> R.string.identity_server_error_outdated_home_server + IdentityServiceError.NoIdentityServerConfigured -> R.string.identity_server_error_no_identity_server_configured + IdentityServiceError.TermsNotSignedException -> R.string.identity_server_error_terms_not_signed IdentityServiceError.BulkLookupSha256NotSupported -> R.string.identity_server_error_bulk_sha256_not_supported - IdentityServiceError.BindingError -> R.string.identity_server_error_binding_error - IdentityServiceError.NoCurrentBindingError -> R.string.identity_server_error_no_current_binding_error - IdentityServiceError.UserConsentNotProvided -> R.string.identity_server_user_consent_not_provided + IdentityServiceError.BindingError -> R.string.identity_server_error_binding_error + IdentityServiceError.NoCurrentBindingError -> R.string.identity_server_error_no_current_binding_error + IdentityServiceError.UserConsentNotProvided -> R.string.identity_server_user_consent_not_provided } ) } diff --git a/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt b/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt index da9a63d4c0..cfe9d2db58 100644 --- a/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt +++ b/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt @@ -34,10 +34,12 @@ class ResourceLimitErrorFormatter(private val context: Context) { object Hard : Mode(R.string.resource_limit_hard_mau, R.string.resource_limit_hard_default, R.string.resource_limit_hard_contact) } - fun format(matrixError: MatrixError, - mode: Mode, - separator: CharSequence = " ", - clickable: Boolean = false): CharSequence { + fun format( + matrixError: MatrixError, + mode: Mode, + separator: CharSequence = " ", + clickable: Boolean = false + ): CharSequence { val error = if (MatrixError.LIMIT_TYPE_MAU == matrixError.limitType) { context.getString(mode.mauErrorRes) } else { diff --git a/vector/src/main/java/im/vector/app/core/extensions/Activity.kt b/vector/src/main/java/im/vector/app/core/extensions/Activity.kt index 6f2ea9699a..77808c3fbf 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Activity.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Activity.kt @@ -39,7 +39,8 @@ fun ComponentActivity.registerStartForActivityResult(onResult: (ActivityResult) fun AppCompatActivity.addFragment( container: ViewGroup, fragment: Fragment, - allowStateLoss: Boolean = false) { + allowStateLoss: Boolean = false +) { supportFragmentManager.commitTransaction(allowStateLoss) { add(container.id, fragment) } } @@ -48,7 +49,8 @@ fun AppCompatActivity.addFragment( fragmentClass: Class, params: Parcelable? = null, tag: String? = null, - allowStateLoss: Boolean = false) { + allowStateLoss: Boolean = false +) { supportFragmentManager.commitTransaction(allowStateLoss) { add(container.id, fragmentClass, params.toMvRxBundle(), tag) } @@ -58,7 +60,8 @@ fun AppCompatActivity.replaceFragment( container: ViewGroup, fragment: Fragment, tag: String? = null, - allowStateLoss: Boolean = false) { + allowStateLoss: Boolean = false +) { supportFragmentManager.commitTransaction(allowStateLoss) { replace(container.id, fragment, tag) } @@ -70,7 +73,8 @@ fun AppCompatActivity.replaceFragment( params: Parcelable? = null, tag: String? = null, allowStateLoss: Boolean = false, - useCustomAnimation: Boolean = false) { + useCustomAnimation: Boolean = false +) { supportFragmentManager.commitTransaction(allowStateLoss) { if (useCustomAnimation) { setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out) @@ -83,7 +87,8 @@ fun AppCompatActivity.addFragmentToBackstack( container: ViewGroup, fragment: Fragment, tag: String? = null, - allowStateLoss: Boolean = false) { + allowStateLoss: Boolean = false +) { supportFragmentManager.commitTransaction(allowStateLoss) { replace(container.id, fragment).addToBackStack(tag) } @@ -95,7 +100,8 @@ fun AppCompatActivity.addFragmentToBackstack( params: Parcelable? = null, tag: String? = null, allowStateLoss: Boolean = false, - option: ((FragmentTransaction) -> Unit)? = null) { + option: ((FragmentTransaction) -> Unit)? = null +) { supportFragmentManager.commitTransaction(allowStateLoss) { option?.invoke(this) replace(container.id, fragmentClass, params.toMvRxBundle(), tag).addToBackStack(tag) diff --git a/vector/src/main/java/im/vector/app/core/extensions/Context.kt b/vector/src/main/java/im/vector/app/core/extensions/Context.kt index 81844a403b..509dd6a862 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Context.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Context.kt @@ -59,9 +59,10 @@ fun Context.getResTintedDrawable(@DrawableRes drawableRes: Int, @ColorRes tint: return getTintedDrawable(drawableRes, ContextCompat.getColor(this, tint), alpha) } -fun Context.getTintedDrawable(@DrawableRes drawableRes: Int, - @ColorInt tint: Int, - @FloatRange(from = 0.0, to = 1.0) alpha: Float = 1f +fun Context.getTintedDrawable( + @DrawableRes drawableRes: Int, + @ColorInt tint: Int, + @FloatRange(from = 0.0, to = 1.0) alpha: Float = 1f ) = ContextCompat.getDrawable(this, drawableRes) ?.mutate() ?.also { drawable -> @@ -98,16 +99,16 @@ fun Context.inferNoConnectivity(buildMeta: BuildMeta): Boolean { val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) when { networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true -> false - networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true -> false - networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true -> false - else -> true + networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true -> false + networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true -> false + else -> true } } else { when (connectivityManager.activeNetworkInfo?.type) { - ConnectivityManager.TYPE_WIFI -> false + ConnectivityManager.TYPE_WIFI -> false ConnectivityManager.TYPE_MOBILE -> false - ConnectivityManager.TYPE_VPN -> false - else -> true + ConnectivityManager.TYPE_VPN -> false + else -> true } } } diff --git a/vector/src/main/java/im/vector/app/core/extensions/EditText.kt b/vector/src/main/java/im/vector/app/core/extensions/EditText.kt index 0eb9dcdaf9..24c8e6bd36 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/EditText.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/EditText.kt @@ -27,8 +27,10 @@ import androidx.annotation.DrawableRes import im.vector.app.R import im.vector.app.core.platform.SimpleTextWatcher -fun EditText.setupAsSearch(@DrawableRes searchIconRes: Int = R.drawable.ic_search, - @DrawableRes clearIconRes: Int = R.drawable.ic_x_gray) { +fun EditText.setupAsSearch( + @DrawableRes searchIconRes: Int = R.drawable.ic_search, + @DrawableRes clearIconRes: Int = R.drawable.ic_x_gray +) { addTextChangedListener(object : SimpleTextWatcher() { override fun afterTextChanged(s: Editable) { val clearIcon = if (s.isNotEmpty()) clearIconRes else 0 diff --git a/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt b/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt index eeb5ddce03..3ee20e362d 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt @@ -27,13 +27,15 @@ import com.airbnb.epoxy.EpoxyVisibilityTracker /** * Apply a Vertical LinearLayout Manager to the recyclerView and set the adapter from the epoxy controller. */ -fun RecyclerView.configureWith(epoxyController: EpoxyController, - itemAnimator: RecyclerView.ItemAnimator? = null, - viewPool: RecyclerView.RecycledViewPool? = null, - @DrawableRes - dividerDrawable: Int? = null, - hasFixedSize: Boolean = true, - disableItemAnimation: Boolean = false) { +fun RecyclerView.configureWith( + epoxyController: EpoxyController, + itemAnimator: RecyclerView.ItemAnimator? = null, + viewPool: RecyclerView.RecycledViewPool? = null, + @DrawableRes + dividerDrawable: Int? = null, + hasFixedSize: Boolean = true, + disableItemAnimation: Boolean = false +) { layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false).apply { recycleChildrenOnDetach = viewPool != null } diff --git a/vector/src/main/java/im/vector/app/core/extensions/Session.kt b/vector/src/main/java/im/vector/app/core/extensions/Session.kt index 2a2198d96b..caed413e2b 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Session.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Session.kt @@ -20,7 +20,7 @@ import android.content.Context import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.ProcessLifecycleOwner -import im.vector.app.core.services.VectorSyncService +import im.vector.app.core.services.VectorSyncAndroidService import im.vector.app.features.session.VectorSessionStore import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState @@ -40,9 +40,9 @@ fun Session.configureAndStart(context: Context, startSyncing: Boolean = true) { fun Session.startSyncing(context: Context) { val applicationContext = context.applicationContext - if (!hasAlreadySynced()) { + if (!syncService().hasAlreadySynced()) { // initial sync is done as a service so it can continue below app lifecycle - VectorSyncService.newOneShotIntent( + VectorSyncAndroidService.newOneShotIntent( context = applicationContext, sessionId = sessionId ) @@ -57,7 +57,7 @@ fun Session.startSyncing(context: Context) { } else { val isAtLeastStarted = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) Timber.v("--> is at least started? $isAtLeastStarted") - startSync(isAtLeastStarted) + syncService().startSync(isAtLeastStarted) } } diff --git a/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt b/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt index 205a0f40c4..c5009bd072 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt @@ -53,7 +53,7 @@ fun TextInputLayout.setOnImeDoneListener(action: () -> Unit) { action() true } - else -> false + else -> false } } } diff --git a/vector/src/main/java/im/vector/app/core/extensions/TextView.kt b/vector/src/main/java/im/vector/app/core/extensions/TextView.kt index 7d8b60ed58..3c453d854d 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/TextView.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/TextView.kt @@ -60,11 +60,13 @@ fun TextView.setTextOrHide(newText: CharSequence?, hideWhenBlank: Boolean = true * @param underline true to also underline the text. Default to false * @param onClick attributes to handle click on the colored part if needed */ -fun TextView.setTextWithColoredPart(@StringRes fullTextRes: Int, - @StringRes coloredTextRes: Int, - @AttrRes colorAttribute: Int = R.attr.colorPrimary, - underline: Boolean = false, - onClick: (() -> Unit)? = null) { +fun TextView.setTextWithColoredPart( + @StringRes fullTextRes: Int, + @StringRes coloredTextRes: Int, + @AttrRes colorAttribute: Int = R.attr.colorPrimary, + underline: Boolean = false, + onClick: (() -> Unit)? = null +) { val coloredPart = resources.getString(coloredTextRes) // Insert colored part into the full text val fullText = resources.getString(fullTextRes, coloredPart) @@ -80,11 +82,13 @@ fun TextView.setTextWithColoredPart(@StringRes fullTextRes: Int, * @param underline true to also underline the text. Default to false * @param onClick attributes to handle click on the colored part if needed */ -fun TextView.setTextWithColoredPart(fullText: String, - coloredPart: String, - @AttrRes colorAttribute: Int = R.attr.colorPrimary, - underline: Boolean = true, - onClick: (() -> Unit)? = null) { +fun TextView.setTextWithColoredPart( + fullText: String, + coloredPart: String, + @AttrRes colorAttribute: Int = R.attr.colorPrimary, + underline: Boolean = true, + onClick: (() -> Unit)? = null +) { val color = ThemeUtils.getColor(context, colorAttribute) val foregroundSpan = ForegroundColorSpan(color) diff --git a/vector/src/main/java/im/vector/app/core/extensions/ThreePid.kt b/vector/src/main/java/im/vector/app/core/extensions/ThreePid.kt index 2e451cfc1e..ea86b39e89 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/ThreePid.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/ThreePid.kt @@ -23,7 +23,7 @@ import org.matrix.android.sdk.api.session.identity.ThreePid fun ThreePid.getFormattedValue(): String { return when (this) { - is ThreePid.Email -> email + is ThreePid.Email -> email is ThreePid.Msisdn -> { tryOrNull(message = "Unable to parse the phone number") { PhoneNumberUtil.getInstance().parse(msisdn.ensurePrefix("+"), null) diff --git a/vector/src/main/java/im/vector/app/core/extensions/ViewPager2.kt b/vector/src/main/java/im/vector/app/core/extensions/ViewPager2.kt index ff3f02e55c..7d3a678af1 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/ViewPager2.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/ViewPager2.kt @@ -40,7 +40,7 @@ fun ViewPager2.setCurrentItem( kotlin.runCatching { when { isRtl -> fakeDragBy(currentPxToDrag) - else -> fakeDragBy(-currentPxToDrag) + else -> fakeDragBy(-currentPxToDrag) } previousValue = currentValue }.onFailure { animator.cancel() } diff --git a/vector/src/main/java/im/vector/app/core/files/FileSaver.kt b/vector/src/main/java/im/vector/app/core/files/FileSaver.kt index d0f2247f33..7de5286854 100644 --- a/vector/src/main/java/im/vector/app/core/files/FileSaver.kt +++ b/vector/src/main/java/im/vector/app/core/files/FileSaver.kt @@ -55,11 +55,13 @@ fun writeToFile(data: ByteArray, file: File): Try { } } -fun addEntryToDownloadManager(context: Context, - file: File, - mimeType: String, - title: String = file.name, - description: String = file.name): Uri? { +fun addEntryToDownloadManager( + context: Context, + file: File, + mimeType: String, + title: String = file.name, + description: String = file.name +): Uri? { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val contentValues = ContentValues().apply { diff --git a/vector/src/main/java/im/vector/app/core/glide/VectorGlideModelLoader.kt b/vector/src/main/java/im/vector/app/core/glide/VectorGlideModelLoader.kt index a643ee908c..92c95d3062 100644 --- a/vector/src/main/java/im/vector/app/core/glide/VectorGlideModelLoader.kt +++ b/vector/src/main/java/im/vector/app/core/glide/VectorGlideModelLoader.kt @@ -60,10 +60,12 @@ class VectorGlideModelLoader(private val context: Context) : } } -class VectorGlideDataFetcher(context: Context, - private val data: ImageContentRenderer.Data, - private val width: Int, - private val height: Int) : +class VectorGlideDataFetcher( + context: Context, + private val data: ImageContentRenderer.Data, + private val width: Int, + private val height: Int +) : DataFetcher { private val localFilesHelper = LocalFilesHelper(context) diff --git a/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt b/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt index d2184d9bd7..8af2a19dd4 100644 --- a/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt +++ b/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt @@ -121,7 +121,7 @@ object VectorLinkify { remove = if (a.important) i + 1 else i } else { when { - b.end <= a.end -> + b.end <= a.end -> // b is inside a -> b should be removed remove = i + 1 a.end - a.start > b.end - b.start -> @@ -143,10 +143,12 @@ object VectorLinkify { } } - private data class LinkSpec(val span: URLSpan, - val start: Int, - val end: Int, - val important: Boolean = false) + private data class LinkSpec( + val span: URLSpan, + val start: Int, + val end: Int, + val important: Boolean = false + ) private val COMPARATOR = Comparator { (_, startA, endA), (_, startB, endB) -> if (startA < startB) { diff --git a/vector/src/main/java/im/vector/app/core/platform/LifecycleAwareLazy.kt b/vector/src/main/java/im/vector/app/core/platform/LifecycleAwareLazy.kt index 54add00459..c4d2a8511a 100644 --- a/vector/src/main/java/im/vector/app/core/platform/LifecycleAwareLazy.kt +++ b/vector/src/main/java/im/vector/app/core/platform/LifecycleAwareLazy.kt @@ -64,7 +64,7 @@ class LifecycleAwareLazy( private fun getLifecycleOwner() = when (owner) { is Fragment -> owner.viewLifecycleOwner - else -> owner + else -> owner } override fun isInitialized(): Boolean = _value !== UninitializedValue diff --git a/vector/src/main/java/im/vector/app/core/platform/ScreenOrientationLocker.kt b/vector/src/main/java/im/vector/app/core/platform/ScreenOrientationLocker.kt index 4b62090d3f..37a0352dc6 100644 --- a/vector/src/main/java/im/vector/app/core/platform/ScreenOrientationLocker.kt +++ b/vector/src/main/java/im/vector/app/core/platform/ScreenOrientationLocker.kt @@ -31,7 +31,7 @@ class ScreenOrientationLocker @Inject constructor( @SuppressLint("SourceLockedOrientationActivity") fun lockPhonesToPortrait(activity: AppCompatActivity) { when (resources.getBoolean(R.bool.is_tablet)) { - true -> { + true -> { // do nothing } false -> { diff --git a/vector/src/main/java/im/vector/app/core/platform/StateView.kt b/vector/src/main/java/im/vector/app/core/platform/StateView.kt index a70bf54aa1..6f36787d0c 100755 --- a/vector/src/main/java/im/vector/app/core/platform/StateView.kt +++ b/vector/src/main/java/im/vector/app/core/platform/StateView.kt @@ -78,7 +78,7 @@ class StateView @JvmOverloads constructor(context: Context, attrs: AttributeSet? when (newState) { is State.Content -> Unit is State.Loading -> Unit - is State.Empty -> { + is State.Empty -> { views.emptyImageView.setImageDrawable(newState.image) views.emptyView.updateConstraintSet { it.constrainPercentHeight(R.id.emptyImageView, if (newState.isBigImage) 0.5f else 0.1f) @@ -86,7 +86,7 @@ class StateView @JvmOverloads constructor(context: Context, attrs: AttributeSet? views.emptyMessageView.text = newState.message views.emptyTitleView.text = newState.title } - is State.Error -> { + is State.Error -> { views.errorMessageView.text = newState.message } } diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt b/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt index 8a4aaa4b26..571d2d38c0 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt @@ -261,11 +261,11 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver private fun handleGlobalError(globalError: GlobalError) { when (globalError) { - is GlobalError.InvalidToken -> handleInvalidToken(globalError) + is GlobalError.InvalidToken -> handleInvalidToken(globalError) is GlobalError.ConsentNotGivenError -> displayConsentNotGivenDialog(globalError) - is GlobalError.CertificateError -> handleCertificateError(globalError) - GlobalError.ExpiredAccount -> Unit // TODO Handle account expiration - is GlobalError.InitialSyncRequest -> handleInitialSyncRequest(globalError) + is GlobalError.CertificateError -> handleCertificateError(globalError) + GlobalError.ExpiredAccount -> Unit // TODO Handle account expiration + is GlobalError.InitialSyncRequest -> handleInitialSyncRequest(globalError) } } @@ -346,7 +346,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver // FIXME I cannot use this anymore :/ // finishActivity(PinActivity.PIN_REQUEST_CODE) } - else -> { + else -> { if (pinLocker.getLiveState().value != PinLocker.State.UNLOCKED) { // Remove the task, to be sure that PIN code will be requested when resumed finishAndRemoveTask() diff --git a/vector/src/main/java/im/vector/app/core/platform/livedata/SharedPreferenceLiveData.kt b/vector/src/main/java/im/vector/app/core/platform/livedata/SharedPreferenceLiveData.kt index 3e0733b35d..dddce313ff 100644 --- a/vector/src/main/java/im/vector/app/core/platform/livedata/SharedPreferenceLiveData.kt +++ b/vector/src/main/java/im/vector/app/core/platform/livedata/SharedPreferenceLiveData.kt @@ -19,9 +19,11 @@ package im.vector.app.core.platform.livedata import android.content.SharedPreferences import androidx.lifecycle.LiveData -abstract class SharedPreferenceLiveData(protected val sharedPrefs: SharedPreferences, - protected val key: String, - private val defValue: T) : LiveData() { +abstract class SharedPreferenceLiveData( + protected val sharedPrefs: SharedPreferences, + protected val key: String, + private val defValue: T +) : LiveData() { private val preferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == this.key) { diff --git a/vector/src/main/java/im/vector/app/core/preference/KeywordPreference.kt b/vector/src/main/java/im/vector/app/core/preference/KeywordPreference.kt index 6101f8a597..8ec9012367 100644 --- a/vector/src/main/java/im/vector/app/core/preference/KeywordPreference.kt +++ b/vector/src/main/java/im/vector/app/core/preference/KeywordPreference.kt @@ -133,13 +133,13 @@ class KeywordPreference : VectorPreference { keyword.startsWith(".") -> { context.getString(R.string.settings_notification_keyword_contains_dot) } - keyword.contains("\\") -> { + keyword.contains("\\") -> { context.getString(R.string.settings_notification_keyword_contains_invalid_character, "\\") } - keyword.contains("/") -> { + keyword.contains("/") -> { context.getString(R.string.settings_notification_keyword_contains_invalid_character, "/") } - else -> null + else -> null } chipTextInputLayout.isErrorEnabled = errorMessage != null diff --git a/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt b/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt index bea29195c9..c0ff80a0e7 100644 --- a/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt +++ b/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt @@ -58,8 +58,8 @@ class PushRulePreference : VectorPreference { private fun refreshSummary() { summary = context.getString( when (index) { - NotificationIndex.OFF -> R.string.notification_off - NotificationIndex.SILENT -> R.string.notification_silent + NotificationIndex.OFF -> R.string.notification_off + NotificationIndex.SILENT -> R.string.notification_silent NotificationIndex.NOISY, null -> R.string.notification_noisy } ) @@ -76,27 +76,27 @@ class PushRulePreference : VectorPreference { radioGroup?.setOnCheckedChangeListener(null) when (index) { - NotificationIndex.OFF -> { + NotificationIndex.OFF -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleOff) } NotificationIndex.SILENT -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleSilent) } - NotificationIndex.NOISY -> { + NotificationIndex.NOISY -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleNoisy) } - null -> Unit + null -> Unit } radioGroup?.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { - R.id.bingPreferenceRadioBingRuleOff -> { + R.id.bingPreferenceRadioBingRuleOff -> { onPreferenceChangeListener?.onPreferenceChange(this, NotificationIndex.OFF) } R.id.bingPreferenceRadioBingRuleSilent -> { onPreferenceChangeListener?.onPreferenceChange(this, NotificationIndex.SILENT) } - R.id.bingPreferenceRadioBingRuleNoisy -> { + R.id.bingPreferenceRadioBingRuleNoisy -> { onPreferenceChangeListener?.onPreferenceChange(this, NotificationIndex.NOISY) } } diff --git a/vector/src/main/java/im/vector/app/core/qrcode/QrCode.kt b/vector/src/main/java/im/vector/app/core/qrcode/QrCode.kt index 170baa04fe..226ec5ee59 100644 --- a/vector/src/main/java/im/vector/app/core/qrcode/QrCode.kt +++ b/vector/src/main/java/im/vector/app/core/qrcode/QrCode.kt @@ -32,8 +32,10 @@ fun String.toBitMatrix(size: Int): BitMatrix { ) } -fun BitMatrix.toBitmap(@ColorInt backgroundColor: Int = Color.WHITE, - @ColorInt foregroundColor: Int = Color.BLACK): Bitmap { +fun BitMatrix.toBitmap( + @ColorInt backgroundColor: Int = Color.WHITE, + @ColorInt foregroundColor: Int = Color.BLACK +): Bitmap { val colorBuffer = IntArray(width * height) var rowOffset = 0 for (y in 0 until height) { diff --git a/vector/src/main/java/im/vector/app/core/resources/LocaleProvider.kt b/vector/src/main/java/im/vector/app/core/resources/LocaleProvider.kt index 2f1b46b555..d91a09e6df 100644 --- a/vector/src/main/java/im/vector/app/core/resources/LocaleProvider.kt +++ b/vector/src/main/java/im/vector/app/core/resources/LocaleProvider.kt @@ -26,7 +26,7 @@ import javax.inject.Inject class LocaleProvider @Inject constructor(private val resources: Resources) { fun current(): Locale { - return ConfigurationCompat.getLocales(resources.configuration)[0] + return ConfigurationCompat.getLocales(resources.configuration).get(0) ?: Locale.getDefault() } } diff --git a/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt b/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt index d050890509..829fec1652 100644 --- a/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt +++ b/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt @@ -54,9 +54,9 @@ class BluetoothHeadsetReceiver : BroadcastReceiver() { // STATE_DISCONNECTED}, STATE_CONNECTING, STATE_CONNECTED, STATE_DISCONNECTING val headsetConnected = when (intent?.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, -1)) { - BluetoothAdapter.STATE_CONNECTED -> true + BluetoothAdapter.STATE_CONNECTED -> true BluetoothAdapter.STATE_DISCONNECTED -> false - else -> return // ignore intermediate states + else -> return // ignore intermediate states } val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) @@ -74,7 +74,7 @@ class BluetoothHeadsetReceiver : BroadcastReceiver() { ) ) } - else -> return + else -> return } } diff --git a/vector/src/main/java/im/vector/app/core/services/CallService.kt b/vector/src/main/java/im/vector/app/core/services/CallService.kt index df9e670423..4edc4d6ace 100644 --- a/vector/src/main/java/im/vector/app/core/services/CallService.kt +++ b/vector/src/main/java/im/vector/app/core/services/CallService.kt @@ -120,15 +120,15 @@ class CallService : VectorService() { callRingPlayerOutgoing?.start() displayOutgoingRingingCallNotification(intent) } - ACTION_ONGOING_CALL -> { + ACTION_ONGOING_CALL -> { callRingPlayerIncoming?.stop() callRingPlayerOutgoing?.stop() displayCallInProgressNotification(intent) } - ACTION_CALL_TERMINATED -> { + ACTION_CALL_TERMINATED -> { handleCallTerminated(intent) } - else -> { + else -> { handleUnexpectedState(null) } } @@ -321,9 +321,11 @@ class CallService : VectorService() { private const val EXTRA_END_CALL_REJECTED = "EXTRA_END_CALL_REJECTED" private const val EXTRA_END_CALL_REASON = "EXTRA_END_CALL_REASON" - fun onIncomingCallRinging(context: Context, - callId: String, - isInBackground: Boolean) { + fun onIncomingCallRinging( + context: Context, + callId: String, + isInBackground: Boolean + ) { val intent = Intent(context, CallService::class.java) .apply { action = ACTION_INCOMING_RINGING_CALL @@ -333,8 +335,10 @@ class CallService : VectorService() { ContextCompat.startForegroundService(context, intent) } - fun onOutgoingCallRinging(context: Context, - callId: String) { + fun onOutgoingCallRinging( + context: Context, + callId: String + ) { val intent = Intent(context, CallService::class.java) .apply { action = ACTION_OUTGOING_RINGING_CALL @@ -343,8 +347,10 @@ class CallService : VectorService() { ContextCompat.startForegroundService(context, intent) } - fun onPendingCall(context: Context, - callId: String) { + fun onPendingCall( + context: Context, + callId: String + ) { val intent = Intent(context, CallService::class.java) .apply { action = ACTION_ONGOING_CALL @@ -353,10 +359,12 @@ class CallService : VectorService() { ContextCompat.startForegroundService(context, intent) } - fun onCallTerminated(context: Context, - callId: String, - endCallReason: EndCallReason, - rejected: Boolean) { + fun onCallTerminated( + context: Context, + callId: String, + endCallReason: EndCallReason, + rejected: Boolean + ) { val intent = Intent(context, CallService::class.java) .apply { action = ACTION_CALL_TERMINATED diff --git a/vector/src/main/java/im/vector/app/core/services/VectorSyncService.kt b/vector/src/main/java/im/vector/app/core/services/VectorSyncAndroidService.kt similarity index 81% rename from vector/src/main/java/im/vector/app/core/services/VectorSyncService.kt rename to vector/src/main/java/im/vector/app/core/services/VectorSyncAndroidService.kt index 131276bea6..864f69a136 100644 --- a/vector/src/main/java/im/vector/app/core/services/VectorSyncService.kt +++ b/vector/src/main/java/im/vector/app/core/services/VectorSyncAndroidService.kt @@ -38,30 +38,34 @@ import im.vector.app.core.time.DefaultClock import im.vector.app.features.notifications.NotificationUtils import im.vector.app.features.settings.BackgroundSyncMode import org.matrix.android.sdk.api.Matrix -import org.matrix.android.sdk.api.session.sync.job.SyncService +import org.matrix.android.sdk.api.session.sync.job.SyncAndroidService import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint -class VectorSyncService : SyncService() { +class VectorSyncAndroidService : SyncAndroidService() { companion object { - fun newOneShotIntent(context: Context, - sessionId: String): Intent { - return Intent(context, VectorSyncService::class.java).also { + fun newOneShotIntent( + context: Context, + sessionId: String + ): Intent { + return Intent(context, VectorSyncAndroidService::class.java).also { it.putExtra(EXTRA_SESSION_ID, sessionId) it.putExtra(EXTRA_TIMEOUT_SECONDS, 0) it.putExtra(EXTRA_PERIODIC, false) } } - fun newPeriodicIntent(context: Context, - sessionId: String, - syncTimeoutSeconds: Int, - syncDelaySeconds: Int, - isNetworkBack: Boolean): Intent { - return Intent(context, VectorSyncService::class.java).also { + fun newPeriodicIntent( + context: Context, + sessionId: String, + syncTimeoutSeconds: Int, + syncDelaySeconds: Int, + isNetworkBack: Boolean + ): Intent { + return Intent(context, VectorSyncAndroidService::class.java).also { it.putExtra(EXTRA_SESSION_ID, sessionId) it.putExtra(EXTRA_TIMEOUT_SECONDS, syncTimeoutSeconds) it.putExtra(EXTRA_PERIODIC, true) @@ -71,7 +75,7 @@ class VectorSyncService : SyncService() { } fun stopIntent(context: Context): Intent { - return Intent(context, VectorSyncService::class.java).also { + return Intent(context, VectorSyncAndroidService::class.java).also { it.action = ACTION_STOP } } @@ -97,9 +101,11 @@ class VectorSyncService : SyncService() { startForeground(NotificationUtils.NOTIFICATION_ID_FOREGROUND_SERVICE, notification) } - override fun onRescheduleAsked(sessionId: String, - syncTimeoutSeconds: Int, - syncDelaySeconds: Int) { + override fun onRescheduleAsked( + sessionId: String, + syncTimeoutSeconds: Int, + syncDelaySeconds: Int + ) { rescheduleSyncService( sessionId = sessionId, syncTimeoutSeconds = syncTimeoutSeconds, @@ -110,10 +116,12 @@ class VectorSyncService : SyncService() { ) } - override fun onNetworkError(sessionId: String, - syncTimeoutSeconds: Int, - syncDelaySeconds: Int, - isPeriodic: Boolean) { + override fun onNetworkError( + sessionId: String, + syncTimeoutSeconds: Int, + syncDelaySeconds: Int, + isPeriodic: Boolean + ) { Timber.d("## Sync: A network error occurred during sync") val rescheduleSyncWorkRequest: WorkRequest = OneTimeWorkRequestBuilder() @@ -169,10 +177,11 @@ class VectorSyncService : SyncService() { } companion object { - fun createInputData(sessionId: String, - syncTimeoutSeconds: Int, - syncDelaySeconds: Int, - isPeriodic: Boolean + fun createInputData( + sessionId: String, + syncTimeoutSeconds: Int, + syncDelaySeconds: Int, + isPeriodic: Boolean ): Data { return Data.Builder() .putString(KEY_SESSION_ID, sessionId) @@ -190,15 +199,17 @@ class VectorSyncService : SyncService() { } } -private fun Context.rescheduleSyncService(sessionId: String, - syncTimeoutSeconds: Int, - syncDelaySeconds: Int, - isPeriodic: Boolean, - isNetworkBack: Boolean, - currentTimeMillis: Long) { +private fun Context.rescheduleSyncService( + sessionId: String, + syncTimeoutSeconds: Int, + syncDelaySeconds: Int, + isPeriodic: Boolean, + isNetworkBack: Boolean, + currentTimeMillis: Long +) { Timber.d("## Sync: rescheduleSyncService") val intent = if (isPeriodic) { - VectorSyncService.newPeriodicIntent( + VectorSyncAndroidService.newPeriodicIntent( context = this, sessionId = sessionId, syncTimeoutSeconds = syncTimeoutSeconds, @@ -206,7 +217,7 @@ private fun Context.rescheduleSyncService(sessionId: String, isNetworkBack = isNetworkBack ) } else { - VectorSyncService.newOneShotIntent( + VectorSyncAndroidService.newOneShotIntent( context = this, sessionId = sessionId ) diff --git a/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt b/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt index 0d3ebafb04..a223352095 100644 --- a/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt +++ b/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt @@ -48,14 +48,14 @@ class WiredHeadsetStateReceiver : BroadcastReceiver() { // microphone 1 if headset has a microphone, 0 otherwise val isPlugged = when (intent?.getIntExtra("state", -1)) { - 0 -> false - 1 -> true + 0 -> false + 1 -> true else -> return Unit.also { Timber.v("## VOIP WiredHeadsetStateReceiver invalid state") } } val hasMicrophone = when (intent.getIntExtra("microphone", -1)) { - 1 -> true + 1 -> true else -> false } diff --git a/vector/src/main/java/im/vector/app/core/ui/list/ItemStyle.kt b/vector/src/main/java/im/vector/app/core/ui/list/ItemStyle.kt index b98d29040d..63e023ecd7 100644 --- a/vector/src/main/java/im/vector/app/core/ui/list/ItemStyle.kt +++ b/vector/src/main/java/im/vector/app/core/ui/list/ItemStyle.kt @@ -34,10 +34,10 @@ enum class ItemStyle { fun toTextSize(): Float { return when (this) { - BIG_TEXT -> 18f + BIG_TEXT -> 18f NORMAL_TEXT -> 14f - TITLE -> 20f - SUBHEADER -> 16f + TITLE -> 20f + SUBHEADER -> 16f } } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/CompatKonfetti.kt b/vector/src/main/java/im/vector/app/core/ui/views/CompatKonfetti.kt index 6b969fe2a5..4e2daef4e0 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/CompatKonfetti.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/CompatKonfetti.kt @@ -34,7 +34,7 @@ class CompatKonfetti @JvmOverloads constructor( override fun onVisibilityChanged(changedView: View, visibility: Int) { when (Build.VERSION.SDK_INT) { Build.VERSION_CODES.LOLLIPOP, Build.VERSION_CODES.LOLLIPOP_MR1 -> safeOnVisibilityChanged(changedView, visibility) - else -> super.onVisibilityChanged(changedView, visibility) + else -> super.onVisibilityChanged(changedView, visibility) } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/CurrentCallsView.kt b/vector/src/main/java/im/vector/app/core/ui/views/CurrentCallsView.kt index 2f7eecc22c..3f129274c4 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/CurrentCallsView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/CurrentCallsView.kt @@ -58,13 +58,13 @@ class CurrentCallsView @JvmOverloads constructor( is CallState.Idle, is CallState.CreateOffer, is CallState.LocalRinging, - is CallState.Dialing -> { + is CallState.Dialing -> { resources.getString(R.string.call_ringing) } is CallState.Answering -> { resources.getString(R.string.call_connecting) } - else -> { + else -> { resources.getString(R.string.call_one_active, formattedDuration) } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt b/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt index 80603aa3bf..e789585b63 100755 --- a/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt @@ -67,28 +67,28 @@ class KeysBackupBanner @JvmOverloads constructor( hideAll() when (newState) { - State.Initial -> renderInitial() - State.Hidden -> renderHidden() - is State.Setup -> renderSetup(newState.numberOfKeys) + State.Initial -> renderInitial() + State.Hidden -> renderHidden() + is State.Setup -> renderSetup(newState.numberOfKeys) is State.Recover -> renderRecover(newState.version) - is State.Update -> renderUpdate(newState.version) - State.BackingUp -> renderBackingUp() + is State.Update -> renderUpdate(newState.version) + State.BackingUp -> renderBackingUp() } } override fun onClick(v: View?) { when (state) { - is State.Setup -> delegate?.setupKeysBackup() + is State.Setup -> delegate?.setupKeysBackup() is State.Update, is State.Recover -> delegate?.recoverKeysBackup() - else -> Unit + else -> Unit } } private fun onCloseClicked() { state.let { when (it) { - is State.Setup -> { + is State.Setup -> { DefaultSharedPreferences.getInstance(context).edit { putBoolean(BANNER_SETUP_DO_NOT_SHOW_AGAIN, true) } @@ -98,12 +98,12 @@ class KeysBackupBanner @JvmOverloads constructor( putString(BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION, it.version) } } - is State.Update -> { + is State.Update -> { DefaultSharedPreferences.getInstance(context).edit { putString(BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION, it.version) } } - else -> { + else -> { // Should not happen, close button is not displayed in other cases } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt b/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt index d9624f65e9..b298a6d4d5 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt @@ -69,12 +69,12 @@ class NotificationAreaView @JvmOverloads constructor( cleanUp() state = newState when (newState) { - State.Initial -> Unit - is State.Default -> renderDefault() - is State.Hidden -> renderHidden() - is State.NoPermissionToPost -> renderNoPermissionToPost() - is State.UnsupportedAlgorithm -> renderUnsupportedAlgorithm(newState) - is State.Tombstone -> renderTombstone() + State.Initial -> Unit + is State.Default -> renderDefault() + is State.Hidden -> renderHidden() + is State.NoPermissionToPost -> renderNoPermissionToPost() + is State.UnsupportedAlgorithm -> renderUnsupportedAlgorithm(newState) + is State.Tombstone -> renderTombstone() is State.ResourceLimitExceededError -> renderResourceLimitExceededError(newState) } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt b/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt index 04bc821387..eb5b05e79b 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt @@ -35,7 +35,8 @@ import im.vector.app.databinding.ViewPasswordStrengthBarBinding class PasswordStrengthBar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, - defStyleAttr: Int = 0) : + defStyleAttr: Int = 0 +) : LinearLayout(context, attrs, defStyleAttr) { private val views: ViewPasswordStrengthBarBinding diff --git a/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt b/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt index a1d3e49f3b..0176901bfb 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt @@ -37,7 +37,7 @@ class PresenceStateImageView @JvmOverloads constructor( isVisible = showPresence && userPresence != null when (userPresence?.presence) { - PresenceEnum.ONLINE -> { + PresenceEnum.ONLINE -> { setImageResource(R.drawable.ic_presence_online) contentDescription = context.getString(R.string.a11y_presence_online) } @@ -45,15 +45,15 @@ class PresenceStateImageView @JvmOverloads constructor( setImageResource(R.drawable.ic_presence_away) contentDescription = context.getString(R.string.a11y_presence_unavailable) } - PresenceEnum.OFFLINE -> { + PresenceEnum.OFFLINE -> { setImageResource(R.drawable.ic_presence_offline) contentDescription = context.getString(R.string.a11y_presence_offline) } - PresenceEnum.BUSY -> { + PresenceEnum.BUSY -> { setImageResource(R.drawable.ic_presence_busy) contentDescription = context.getString(R.string.a11y_presence_busy) } - null -> Unit + null -> Unit } } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/ReadReceiptsView.kt b/vector/src/main/java/im/vector/app/core/ui/views/ReadReceiptsView.kt index 8477eddeea..db5dae5222 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/ReadReceiptsView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/ReadReceiptsView.kt @@ -28,8 +28,7 @@ import im.vector.app.features.home.AvatarRenderer import im.vector.app.features.home.room.detail.timeline.item.ReadReceiptData import im.vector.app.features.home.room.detail.timeline.item.toMatrixItem -private const val MAX_RECEIPT_DISPLAYED = 5 -private const val MAX_RECEIPT_DESCRIBED = 3 +private const val MAX_RECEIPT_DISPLAYED = 3 class ReadReceiptsView @JvmOverloads constructor( context: Context, @@ -45,13 +44,7 @@ class ReadReceiptsView @JvmOverloads constructor( } private val receiptAvatars: List by lazy { - listOf( - views.receiptAvatar1, - views.receiptAvatar2, - views.receiptAvatar3, - views.receiptAvatar4, - views.receiptAvatar5 - ) + listOf(views.receiptAvatar1, views.receiptAvatar2, views.receiptAvatar3) } private fun setupView() { @@ -60,66 +53,58 @@ class ReadReceiptsView @JvmOverloads constructor( } fun render(readReceipts: List, avatarRenderer: AvatarRenderer) { - if (readReceipts.isNotEmpty()) { - isVisible = true - for (index in 0 until MAX_RECEIPT_DISPLAYED) { - val receiptData = readReceipts.getOrNull(index) - if (receiptData == null) { - receiptAvatars[index].visibility = View.INVISIBLE - } else { - receiptAvatars[index].visibility = View.VISIBLE - avatarRenderer.render(receiptData.toMatrixItem(), receiptAvatars[index]) - } - } + receiptAvatars.forEach { it.isVisible = false } - val displayNames = readReceipts - .mapNotNull { it.displayName } - .filter { it.isNotBlank() } - .take(MAX_RECEIPT_DESCRIBED) + readReceipts.take(MAX_RECEIPT_DISPLAYED).forEachIndexed { index, receiptData -> + receiptAvatars[index].isVisible = true + avatarRenderer.render(receiptData.toMatrixItem(), receiptAvatars[index]) + } - if (readReceipts.size > MAX_RECEIPT_DISPLAYED) { - views.receiptMore.visibility = View.VISIBLE - views.receiptMore.text = context.getString( - R.string.x_plus, readReceipts.size - MAX_RECEIPT_DISPLAYED - ) - } else { - views.receiptMore.visibility = View.GONE - } - contentDescription = when (readReceipts.size) { - 1 -> - if (displayNames.size == 1) { - context.getString(R.string.one_user_read, displayNames[0]) - } else { - context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) - } - 2 -> - if (displayNames.size == 2) { - context.getString(R.string.two_users_read, displayNames[0], displayNames[1]) - } else { - context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) - } - 3 -> - if (displayNames.size == 3) { - context.getString(R.string.three_users_read, displayNames[0], displayNames[1], displayNames[2]) - } else { - context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) - } - else -> - if (displayNames.size >= 2) { - val qty = readReceipts.size - 2 - context.resources.getQuantityString( - R.plurals.two_and_some_others_read, - qty, - displayNames[0], - displayNames[1], - qty - ) - } else { - context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) - } - } + val displayNames = readReceipts + .mapNotNull { it.displayName } + .filter { it.isNotBlank() } + .take(MAX_RECEIPT_DISPLAYED) + + if (readReceipts.size > MAX_RECEIPT_DISPLAYED) { + views.receiptMore.visibility = View.VISIBLE + views.receiptMore.text = context.getString( + R.string.x_plus, readReceipts.size - MAX_RECEIPT_DISPLAYED + ) } else { - isVisible = false + views.receiptMore.visibility = View.GONE + } + contentDescription = when (readReceipts.size) { + 1 -> + if (displayNames.size == 1) { + context.getString(R.string.one_user_read, displayNames[0]) + } else { + context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) + } + 2 -> + if (displayNames.size == 2) { + context.getString(R.string.two_users_read, displayNames[0], displayNames[1]) + } else { + context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) + } + 3 -> + if (displayNames.size == 3) { + context.getString(R.string.three_users_read, displayNames[0], displayNames[1], displayNames[2]) + } else { + context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) + } + else -> + if (displayNames.size >= 2) { + val qty = readReceipts.size - 2 + context.resources.getQuantityString( + R.plurals.two_and_some_others_read, + qty, + displayNames[0], + displayNames[1], + qty + ) + } else { + context.resources.getQuantityString(R.plurals.fallback_users_read, readReceipts.size) + } } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/SendStateImageView.kt b/vector/src/main/java/im/vector/app/core/ui/views/SendStateImageView.kt index 3d710e2b24..77b0204783 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/SendStateImageView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/SendStateImageView.kt @@ -45,20 +45,20 @@ class SendStateImageView @JvmOverloads constructor( contentDescription = context.getString(R.string.event_status_a11y_sending) false } - SendStateDecoration.SENT -> { + SendStateDecoration.SENT -> { setImageResource(R.drawable.ic_message_sent) imageTintList = ColorStateList.valueOf(ThemeUtils.getColor(context, R.attr.vctr_content_tertiary)) contentDescription = context.getString(R.string.event_status_a11y_sent) false } - SendStateDecoration.FAILED -> { + SendStateDecoration.FAILED -> { setImageResource(R.drawable.ic_sending_message_failed) imageTintList = null contentDescription = context.getString(R.string.event_status_a11y_failed) false } SendStateDecoration.SENDING_MEDIA, - SendStateDecoration.NONE -> { + SendStateDecoration.NONE -> { true } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/ShieldImageView.kt b/vector/src/main/java/im/vector/app/core/ui/views/ShieldImageView.kt index a82a9a30b4..4d947f134b 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/ShieldImageView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/ShieldImageView.kt @@ -40,21 +40,21 @@ class ShieldImageView @JvmOverloads constructor( isVisible = roomEncryptionTrustLevel != null when (roomEncryptionTrustLevel) { - RoomEncryptionTrustLevel.Default -> { + RoomEncryptionTrustLevel.Default -> { contentDescription = context.getString(R.string.a11y_trust_level_default) setImageResource( if (borderLess) R.drawable.ic_shield_black_no_border else R.drawable.ic_shield_black ) } - RoomEncryptionTrustLevel.Warning -> { + RoomEncryptionTrustLevel.Warning -> { contentDescription = context.getString(R.string.a11y_trust_level_warning) setImageResource( if (borderLess) R.drawable.ic_shield_warning_no_border else R.drawable.ic_shield_warning ) } - RoomEncryptionTrustLevel.Trusted -> { + RoomEncryptionTrustLevel.Trusted -> { contentDescription = context.getString(R.string.a11y_trust_level_trusted) setImageResource( if (borderLess) R.drawable.ic_shield_trusted_no_border @@ -65,7 +65,7 @@ class ShieldImageView @JvmOverloads constructor( contentDescription = context.getString(R.string.a11y_trust_level_trusted) setImageResource(R.drawable.ic_warning_badge) } - null -> Unit + null -> Unit } } } @@ -73,9 +73,9 @@ class ShieldImageView @JvmOverloads constructor( @DrawableRes fun RoomEncryptionTrustLevel.toDrawableRes(): Int { return when (this) { - RoomEncryptionTrustLevel.Default -> R.drawable.ic_shield_black - RoomEncryptionTrustLevel.Warning -> R.drawable.ic_shield_warning - RoomEncryptionTrustLevel.Trusted -> R.drawable.ic_shield_trusted + RoomEncryptionTrustLevel.Default -> R.drawable.ic_shield_black + RoomEncryptionTrustLevel.Warning -> R.drawable.ic_shield_warning + RoomEncryptionTrustLevel.Trusted -> R.drawable.ic_shield_trusted RoomEncryptionTrustLevel.E2EWithUnsupportedAlgorithm -> R.drawable.ic_warning_badge } } diff --git a/vector/src/main/java/im/vector/app/core/utils/Dialogs.kt b/vector/src/main/java/im/vector/app/core/utils/Dialogs.kt index 9f3e6a91cf..c9bd4e54b0 100644 --- a/vector/src/main/java/im/vector/app/core/utils/Dialogs.kt +++ b/vector/src/main/java/im/vector/app/core/utils/Dialogs.kt @@ -45,8 +45,10 @@ fun Context.displayInWebView(url: String) { .show() } -fun Context.showIdentityServerConsentDialog(identityServerWithTerms: ServerAndPolicies?, - consentCallBack: (() -> Unit)) { +fun Context.showIdentityServerConsentDialog( + identityServerWithTerms: ServerAndPolicies?, + consentCallBack: (() -> Unit) +) { // Build the message val content = span { +getString(R.string.identity_server_consent_dialog_content_3) diff --git a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt index 9616e35840..68fe488391 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt @@ -89,9 +89,11 @@ fun openUrlInExternalBrowser(context: Context, uri: Uri?) { * If several compatible browsers are installed, the user will be proposed to choose one. * Ref: https://developer.chrome.com/multidevice/android/customtabs. */ -fun openUrlInChromeCustomTab(context: Context, - session: CustomTabsSession?, - url: String) { +fun openUrlInChromeCustomTab( + context: Context, + session: CustomTabsSession?, + url: String +) { try { CustomTabsIntent.Builder() .setDefaultColorSchemeParams( @@ -103,8 +105,8 @@ fun openUrlInChromeCustomTab(context: Context, .setColorScheme( when { ThemeUtils.isSystemTheme(context) -> CustomTabsIntent.COLOR_SCHEME_SYSTEM - ThemeUtils.isLightTheme(context) -> CustomTabsIntent.COLOR_SCHEME_LIGHT - else -> CustomTabsIntent.COLOR_SCHEME_DARK + ThemeUtils.isLightTheme(context) -> CustomTabsIntent.COLOR_SCHEME_LIGHT + else -> CustomTabsIntent.COLOR_SCHEME_DARK } ) // Note: setting close button icon does not work @@ -122,10 +124,12 @@ fun openUrlInChromeCustomTab(context: Context, /** * Open file selection activity. */ -fun openFileSelection(activity: Activity, - activityResultLauncher: ActivityResultLauncher?, - allowMultipleSelection: Boolean, - requestCode: Int) { +fun openFileSelection( + activity: Activity, + activityResultLauncher: ActivityResultLauncher?, + allowMultipleSelection: Boolean, + requestCode: Int +) { val fileIntent = Intent(Intent.ACTION_GET_CONTENT) fileIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, allowMultipleSelection) @@ -251,12 +255,14 @@ private fun appendTimeToFilename(name: String): String { return """${filename}_$dateExtension.$fileExtension""" } -suspend fun saveMedia(context: Context, - file: File, - title: String, - mediaMimeType: String?, - notificationUtils: NotificationUtils, - currentTimeMillis: Long) { +suspend fun saveMedia( + context: Context, + file: File, + title: String, + mediaMimeType: String?, + notificationUtils: NotificationUtils, + currentTimeMillis: Long +) { withContext(Dispatchers.IO) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val filename = appendTimeToFilename(title) @@ -272,7 +278,7 @@ suspend fun saveMedia(context: Context, mediaMimeType?.isMimeTypeImage() == true -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI mediaMimeType?.isMimeTypeVideo() == true -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI mediaMimeType?.isMimeTypeAudio() == true -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI - else -> MediaStore.Downloads.EXTERNAL_CONTENT_URI + else -> MediaStore.Downloads.EXTERNAL_CONTENT_URI } val uri = context.contentResolver.insert(externalContentUri, values) @@ -303,11 +309,13 @@ suspend fun saveMedia(context: Context, } @Suppress("DEPRECATION") -private fun saveMediaLegacy(context: Context, - mediaMimeType: String?, - title: String, - file: File, - currentTimeMillis: Long) { +private fun saveMediaLegacy( + context: Context, + mediaMimeType: String?, + title: String, + file: File, + currentTimeMillis: Long +) { val state = Environment.getExternalStorageState() if (Environment.MEDIA_MOUNTED != state) { context.toast(context.getString(R.string.error_saving_media_file)) @@ -318,7 +326,7 @@ private fun saveMediaLegacy(context: Context, mediaMimeType?.isMimeTypeImage() == true -> Environment.DIRECTORY_PICTURES mediaMimeType?.isMimeTypeVideo() == true -> Environment.DIRECTORY_MOVIES mediaMimeType?.isMimeTypeAudio() == true -> Environment.DIRECTORY_MUSIC - else -> Environment.DIRECTORY_DOWNLOADS + else -> Environment.DIRECTORY_DOWNLOADS } val downloadDir = Environment.getExternalStoragePublicDirectory(dest) try { diff --git a/vector/src/main/java/im/vector/app/core/utils/FirstThrottler.kt b/vector/src/main/java/im/vector/app/core/utils/FirstThrottler.kt index 004f500c4e..99300993fb 100644 --- a/vector/src/main/java/im/vector/app/core/utils/FirstThrottler.kt +++ b/vector/src/main/java/im/vector/app/core/utils/FirstThrottler.kt @@ -30,7 +30,7 @@ class FirstThrottler(private val minimumInterval: Long = 800) { fun waitMillis(): Long { return when (this) { - Yes -> 0 + Yes -> 0 is No -> shouldWaitMillis } } diff --git a/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt b/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt index 705f683d2e..9ad95d3c55 100644 --- a/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt +++ b/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt @@ -100,10 +100,12 @@ private fun onPermissionResult(result: Map, lambda: (allGranted * @param rationaleMessage message to be displayed BEFORE requesting for the permission * @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow) */ -fun checkPermissions(permissionsToBeGranted: List, - activity: Activity, - activityResultLauncher: ActivityResultLauncher>, - @StringRes rationaleMessage: Int = 0): Boolean { +fun checkPermissions( + permissionsToBeGranted: List, + activity: Activity, + activityResultLauncher: ActivityResultLauncher>, + @StringRes rationaleMessage: Int = 0 +): Boolean { // retrieve the permissions to be granted according to the permission list val missingPermissions = permissionsToBeGranted.filter { permission -> ContextCompat.checkSelfPermission(activity.applicationContext, permission) == PackageManager.PERMISSION_DENIED @@ -143,8 +145,10 @@ fun checkPermissions(permissionsToBeGranted: List, * * @return true if one of the permission has been denied and the user check the do not ask again checkbox */ -private fun permissionsDeniedPermanently(permissionsToBeGranted: List, - activity: Activity): Boolean { +private fun permissionsDeniedPermanently( + permissionsToBeGranted: List, + activity: Activity +): Boolean { return permissionsToBeGranted .filter { permission -> ContextCompat.checkSelfPermission(activity.applicationContext, permission) == PackageManager.PERMISSION_DENIED diff --git a/vector/src/main/java/im/vector/app/core/utils/SnapHelperUtils.kt b/vector/src/main/java/im/vector/app/core/utils/SnapHelperUtils.kt index 070c953a3f..7d1bfc926d 100644 --- a/vector/src/main/java/im/vector/app/core/utils/SnapHelperUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/SnapHelperUtils.kt @@ -27,7 +27,8 @@ interface OnSnapPositionChangeListener { fun RecyclerView.attachSnapHelperWithListener( snapHelper: SnapHelper, behavior: SnapOnScrollListener.Behavior = SnapOnScrollListener.Behavior.NOTIFY_ON_SCROLL_STATE_IDLE, - onSnapPositionChangeListener: OnSnapPositionChangeListener) { + onSnapPositionChangeListener: OnSnapPositionChangeListener +) { snapHelper.attachToRecyclerView(this) val snapOnScrollListener = SnapOnScrollListener(snapHelper, behavior, onSnapPositionChangeListener) addOnScrollListener(snapOnScrollListener) diff --git a/vector/src/main/java/im/vector/app/core/utils/SpannableUtils.kt b/vector/src/main/java/im/vector/app/core/utils/SpannableUtils.kt index aa1917e326..146df82e35 100644 --- a/vector/src/main/java/im/vector/app/core/utils/SpannableUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/SpannableUtils.kt @@ -48,8 +48,10 @@ fun Spannable.tappableMatchingText(match: String, clickSpan: ClickableSpan): Spa return this } -fun Span.bullet(text: CharSequence = "", - init: Span.() -> Unit = {}): Span = apply { +fun Span.bullet( + text: CharSequence = "", + init: Span.() -> Unit = {} +): Span = apply { append(Span(parent = this).apply { this.text = text this.spans.add(BulletSpan()) diff --git a/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt b/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt index 1d9ac6c3ef..1939bdf6a9 100644 --- a/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt @@ -145,12 +145,14 @@ fun startInstallFromSourceIntent(context: Context, activityResultLauncher: Activ } } -fun startSharePlainTextIntent(fragment: Fragment, - activityResultLauncher: ActivityResultLauncher?, - chooserTitle: String?, - text: String, - subject: String? = null, - extraTitle: String? = null) { +fun startSharePlainTextIntent( + fragment: Fragment, + activityResultLauncher: ActivityResultLauncher?, + chooserTitle: String?, + text: String, + subject: String? = null, + extraTitle: String? = null +) { val share = Intent(Intent.ACTION_SEND) share.type = "text/plain" share.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT) diff --git a/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt b/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt index d6af3f5afb..db42df92e7 100644 --- a/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt @@ -61,10 +61,10 @@ object TextUtils { } else { // First convert the size when { - sizeBytes < 1024 -> sizeBytes - sizeBytes < 1024 * 1024 -> sizeBytes * 1000 / 1024 + sizeBytes < 1024 -> sizeBytes + sizeBytes < 1024 * 1024 -> sizeBytes * 1000 / 1024 sizeBytes < 1024 * 1024 * 1024 -> sizeBytes * 1000 / 1024 * 1000 / 1024 - else -> sizeBytes * 1000 / 1024 * 1000 / 1024 * 1000 / 1024 + else -> sizeBytes * 1000 / 1024 * 1000 / 1024 * 1000 / 1024 } } @@ -108,7 +108,7 @@ object TextUtils { val seconds = getSeconds(duration) val builder = StringBuilder() when { - hours > 0 -> { + hours > 0 -> { appendHours(getString, builder, hours) if (minutes > 0) { builder.append(" ") @@ -126,7 +126,7 @@ object TextUtils { appendSeconds(getString, builder, seconds) } } - else -> { + else -> { appendSeconds(getString, builder, seconds) } } diff --git a/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt b/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt index c829313256..b2509a145d 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt @@ -32,35 +32,41 @@ class ToggleableAppBarLayoutBehavior : AppBarLayout.Behavior { var isEnabled = true - override fun onStartNestedScroll(parent: CoordinatorLayout, - child: AppBarLayout, - directTargetChild: View, - target: View, - nestedScrollAxes: Int, - type: Int): Boolean { + override fun onStartNestedScroll( + parent: CoordinatorLayout, + child: AppBarLayout, + directTargetChild: View, + target: View, + nestedScrollAxes: Int, + type: Int + ): Boolean { return isEnabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes, type) } - override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, - child: AppBarLayout, - target: View, - dxConsumed: Int, - dyConsumed: Int, - dxUnconsumed: Int, - dyUnconsumed: Int, - type: Int, - consumed: IntArray) { + override fun onNestedScroll( + coordinatorLayout: CoordinatorLayout, + child: AppBarLayout, + target: View, + dxConsumed: Int, + dyConsumed: Int, + dxUnconsumed: Int, + dyUnconsumed: Int, + type: Int, + consumed: IntArray + ) { if (!isEnabled) return super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed) } - override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, - child: AppBarLayout, - target: View, - dx: Int, - dy: Int, - consumed: IntArray, - type: Int) { + override fun onNestedPreScroll( + coordinatorLayout: CoordinatorLayout, + child: AppBarLayout, + target: View, + dx: Int, + dy: Int, + consumed: IntArray, + type: Int + ) { if (!isEnabled) return super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) } diff --git a/vector/src/main/java/im/vector/app/core/utils/UrlUtils.kt b/vector/src/main/java/im/vector/app/core/utils/UrlUtils.kt index 70cda17ae6..3f0421351e 100644 --- a/vector/src/main/java/im/vector/app/core/utils/UrlUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/UrlUtils.kt @@ -32,16 +32,16 @@ fun String.isValidUrl(): Boolean { */ fun String.ensureProtocol(): String { return when { - isEmpty() -> this + isEmpty() -> this !startsWith("http") -> "https://$this" - else -> this + else -> this } } fun String.ensureTrailingSlash(): String { return when { - isEmpty() -> this + isEmpty() -> this !endsWith("/") -> "$this/" - else -> this + else -> this } } diff --git a/vector/src/main/java/im/vector/app/features/MainActivity.kt b/vector/src/main/java/im/vector/app/features/MainActivity.kt index 17bf02dc4f..91004a0be4 100644 --- a/vector/src/main/java/im/vector/app/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/app/features/MainActivity.kt @@ -157,7 +157,7 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity startNextActivityAndFinish() } } - args.clearCredentials -> { + args.clearCredentials -> { lifecycleScope.launch { try { session.signOutService().signOut(!args.isUserLoggedOut) @@ -171,7 +171,7 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity startNextActivityAndFinish() } } - args.clearCache -> { + args.clearCache -> { lifecycleScope.launch { session.clearCache() doLocalCleanup(clearPreferences = false, onboardingStore) @@ -229,15 +229,15 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity navigator.openLogin(this, null) null } - args.isSoftLogout -> { + args.isSoftLogout -> { // The homeserver has invalidated the token, with a soft logout navigator.softLogout(this) null } - args.isUserLoggedOut -> + args.isUserLoggedOut -> // the homeserver has invalidated the token (password changed, device deleted, other security reasons) SignedOutActivity.newIntent(this) - sessionHolder.hasActiveSession() -> + sessionHolder.hasActiveSession() -> // We have a session. // Check it can be opened if (sessionHolder.getActiveSession().isOpenable) { @@ -247,7 +247,7 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity navigator.softLogout(this) null } - else -> { + else -> { // First start, or no active session navigator.openLogin(this, null) null diff --git a/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt b/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt index e020ec1cf7..d97c46c3cb 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt @@ -147,10 +147,10 @@ class DecryptionFailureTracker @Inject constructor( val detailed = "$name | mxc_crypto_error_type" val errorName = when (this) { MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID, - MXCryptoError.ErrorType.KEYS_WITHHELD -> Error.Name.OlmKeysNotSentError - MXCryptoError.ErrorType.OLM -> Error.Name.OlmUnspecifiedError + MXCryptoError.ErrorType.KEYS_WITHHELD -> Error.Name.OlmKeysNotSentError + MXCryptoError.ErrorType.OLM -> Error.Name.OlmUnspecifiedError MXCryptoError.ErrorType.UNKNOWN_MESSAGE_INDEX -> Error.Name.OlmIndexError - else -> Error.Name.UnknownError + else -> Error.Name.UnknownError } return DetailedErrorName(detailed, errorName) } diff --git a/vector/src/main/java/im/vector/app/features/analytics/accountdata/AnalyticsAccountDataViewModel.kt b/vector/src/main/java/im/vector/app/features/analytics/accountdata/AnalyticsAccountDataViewModel.kt index 221a9d8843..05358decc9 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/accountdata/AnalyticsAccountDataViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/accountdata/AnalyticsAccountDataViewModel.kt @@ -37,7 +37,7 @@ import kotlinx.coroutines.launch import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.api.session.initsync.SyncStatusService +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.flow.flow import timber.log.Timber import java.util.UUID @@ -66,11 +66,11 @@ class AnalyticsAccountDataViewModel @AssistedInject constructor( private fun observeInitSync() { combine( - session.syncStatusService().getSyncStatusLive().asFlow(), + session.syncService().getSyncRequestStateLive().asFlow(), analytics.getUserConsent(), analytics.getAnalyticsId() ) { status, userConsent, analyticsId -> - if (status is SyncStatusService.Status.IncrementalSyncIdle && + if (status is SyncRequestState.IncrementalSyncIdle && userConsent && analyticsId.isEmpty() && !checkDone) { diff --git a/vector/src/main/java/im/vector/app/features/analytics/extensions/JoinedRoomExt.kt b/vector/src/main/java/im/vector/app/features/analytics/extensions/JoinedRoomExt.kt index 27ce3e9a23..45f39da2cd 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/extensions/JoinedRoomExt.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/extensions/JoinedRoomExt.kt @@ -25,11 +25,11 @@ import org.matrix.android.sdk.api.session.room.model.roomdirectory.PublicRoom fun Int?.toAnalyticsRoomSize(): JoinedRoom.RoomSize { return when (this) { null, - 2 -> JoinedRoom.RoomSize.Two - in 3..10 -> JoinedRoom.RoomSize.ThreeToTen - in 11..100 -> JoinedRoom.RoomSize.ElevenToOneHundred + 2 -> JoinedRoom.RoomSize.Two + in 3..10 -> JoinedRoom.RoomSize.ThreeToTen + in 11..100 -> JoinedRoom.RoomSize.ElevenToOneHundred in 101..1000 -> JoinedRoom.RoomSize.OneHundredAndOneToAThousand - else -> JoinedRoom.RoomSize.MoreThanAThousand + else -> JoinedRoom.RoomSize.MoreThanAThousand } } diff --git a/vector/src/main/java/im/vector/app/features/analytics/extensions/PerformanceTimerExt.kt b/vector/src/main/java/im/vector/app/features/analytics/extensions/PerformanceTimerExt.kt index 11b4b670d3..e1054b15be 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/extensions/PerformanceTimerExt.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/extensions/PerformanceTimerExt.kt @@ -34,7 +34,7 @@ fun StatisticEvent.toListOfPerformanceTimer(): List { itemCount = nbOfJoinedRooms ) ) - is StatisticEvent.SyncTreatment -> + is StatisticEvent.SyncTreatment -> if (afterPause) { listOf( PerformanceTimer( diff --git a/vector/src/main/java/im/vector/app/features/analytics/extensions/SignUpExt.kt b/vector/src/main/java/im/vector/app/features/analytics/extensions/SignUpExt.kt new file mode 100644 index 0000000000..e63aafbfc4 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/analytics/extensions/SignUpExt.kt @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.analytics.extensions + +import im.vector.app.features.analytics.plan.Signup +import im.vector.app.features.onboarding.AuthenticationDescription + +fun AuthenticationDescription.AuthenticationType.toAnalyticsType() = when (this) { + AuthenticationDescription.AuthenticationType.Password -> Signup.AuthenticationType.Password + AuthenticationDescription.AuthenticationType.Apple -> Signup.AuthenticationType.Apple + AuthenticationDescription.AuthenticationType.Facebook -> Signup.AuthenticationType.Facebook + AuthenticationDescription.AuthenticationType.GitHub -> Signup.AuthenticationType.GitHub + AuthenticationDescription.AuthenticationType.GitLab -> Signup.AuthenticationType.GitLab + AuthenticationDescription.AuthenticationType.Google -> Signup.AuthenticationType.Google + AuthenticationDescription.AuthenticationType.SSO -> Signup.AuthenticationType.SSO + AuthenticationDescription.AuthenticationType.Other -> Signup.AuthenticationType.Other +} diff --git a/vector/src/main/java/im/vector/app/features/analytics/extensions/UserPropertiesExt.kt b/vector/src/main/java/im/vector/app/features/analytics/extensions/UserPropertiesExt.kt index 7fad43783b..e5446f438b 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/extensions/UserPropertiesExt.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/extensions/UserPropertiesExt.kt @@ -22,8 +22,8 @@ import im.vector.app.features.onboarding.FtueUseCase fun FtueUseCase.toTrackingValue(): UserProperties.FtueUseCaseSelection { return when (this) { FtueUseCase.FRIENDS_FAMILY -> UserProperties.FtueUseCaseSelection.PersonalMessaging - FtueUseCase.TEAMS -> UserProperties.FtueUseCaseSelection.WorkMessaging - FtueUseCase.COMMUNITIES -> UserProperties.FtueUseCaseSelection.CommunityMessaging - FtueUseCase.SKIP -> UserProperties.FtueUseCaseSelection.Skip + FtueUseCase.TEAMS -> UserProperties.FtueUseCaseSelection.WorkMessaging + FtueUseCase.COMMUNITIES -> UserProperties.FtueUseCaseSelection.CommunityMessaging + FtueUseCase.SKIP -> UserProperties.FtueUseCaseSelection.Skip } } diff --git a/vector/src/main/java/im/vector/app/features/analytics/extensions/ViewRoomExt.kt b/vector/src/main/java/im/vector/app/features/analytics/extensions/ViewRoomExt.kt index ada936a3b5..b259477ebd 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/extensions/ViewRoomExt.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/extensions/ViewRoomExt.kt @@ -26,7 +26,7 @@ fun RoomSummary?.toAnalyticsViewRoom(trigger: ViewRoom.Trigger?, groupingMethod: val activeSpace = groupingMethod?.let { when (it) { is RoomGroupingMethod.BySpace -> it.spaceSummary?.toActiveSpace() ?: ViewRoom.ActiveSpace.Home - else -> null + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt index 87f0e8c13b..be847dcb7f 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt @@ -49,7 +49,7 @@ class DefaultVectorAnalytics @Inject constructor( private val posthog: PostHog? = when { analyticsConfig.isEnabled -> postHogFactory.createPosthog() - else -> { + else -> { Timber.tag(analyticsTag.value).w("Analytics is disabled") null } diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt index da80787a65..5c082f530e 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt @@ -35,6 +35,7 @@ data class Error( enum class Domain { E2EE, + TO_DEVICE, VOIP, } @@ -42,6 +43,7 @@ data class Error( OlmIndexError, OlmKeysNotSentError, OlmUnspecifiedError, + ToDeviceFailedToDecrypt, UnknownError, VoipIceFailed, VoipIceTimeout, diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/Interaction.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/Interaction.kt index 4e4bfe53be..deb9088259 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/Interaction.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/Interaction.kt @@ -105,6 +105,12 @@ data class Interaction( */ WebHomeExploreRoomsButton, + /** + * User clicked on the mini avatar uploader in the home page of Element + * Web/Desktop. + */ + WebHomeMiniAvatarUploadButton, + /** * User clicked the explore rooms button next to the search field at the * top of the left panel in Element Web/Desktop. diff --git a/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt b/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt index d1f0efae6c..c85c3aa6b5 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt @@ -51,9 +51,10 @@ private const val ANIMATION_DURATION = 250 * It will return result through [Callback]. */ -class AttachmentTypeSelectorView(context: Context, - inflater: LayoutInflater, - var callback: Callback? +class AttachmentTypeSelectorView( + context: Context, + inflater: LayoutInflater, + var callback: Callback? ) : PopupWindow(context) { interface Callback { @@ -126,12 +127,12 @@ class AttachmentTypeSelectorView(context: Context, fun setAttachmentVisibility(type: Type, isVisible: Boolean) { when (type) { - Type.CAMERA -> views.attachmentCameraButton - Type.GALLERY -> views.attachmentGalleryButton - Type.FILE -> views.attachmentFileButton - Type.STICKER -> views.attachmentStickersButton - Type.CONTACT -> views.attachmentContactButton - Type.POLL -> views.attachmentPollButton + Type.CAMERA -> views.attachmentCameraButton + Type.GALLERY -> views.attachmentGalleryButton + Type.FILE -> views.attachmentFileButton + Type.STICKER -> views.attachmentStickersButton + Type.CONTACT -> views.attachmentContactButton + Type.POLL -> views.attachmentPollButton Type.LOCATION -> views.attachmentLocationButton }.let { it.isVisible = isVisible diff --git a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt index 14324896bc..d5f65a4aef 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt @@ -96,10 +96,12 @@ class AttachmentsHelper(val context: Context, val callback: Callback) : Restorab /** * Starts the process for handling image/video capture. Can open a dialog */ - fun openCamera(activity: Activity, - vectorPreferences: VectorPreferences, - cameraActivityResultLauncher: ActivityResultLauncher, - cameraVideoActivityResultLauncher: ActivityResultLauncher) { + fun openCamera( + activity: Activity, + vectorPreferences: VectorPreferences, + cameraActivityResultLauncher: ActivityResultLauncher, + cameraVideoActivityResultLauncher: ActivityResultLauncher + ) { PhotoOrVideoDialog(activity, vectorPreferences).show(object : PhotoOrVideoDialog.PhotoOrVideoDialogListener { override fun takePhoto() { captureUri = MultiPicker.get(MultiPicker.CAMERA).startWithExpectingFile(context, cameraActivityResultLauncher) diff --git a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsMapper.kt b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsMapper.kt index 00ed6dd6cc..1f87064165 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsMapper.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsMapper.kt @@ -67,7 +67,7 @@ private fun MultiPickerBaseType.mapType(): ContentAttachmentData.Type { mimeType?.isMimeTypeImage() == true -> ContentAttachmentData.Type.IMAGE mimeType?.isMimeTypeVideo() == true -> ContentAttachmentData.Type.VIDEO mimeType?.isMimeTypeAudio() == true -> ContentAttachmentData.Type.AUDIO - else -> ContentAttachmentData.Type.FILE + else -> ContentAttachmentData.Type.FILE } } @@ -76,8 +76,8 @@ fun MultiPickerBaseType.toContentAttachmentData(): ContentAttachmentData { is MultiPickerImageType -> toContentAttachmentData() is MultiPickerVideoType -> toContentAttachmentData() is MultiPickerAudioType -> toContentAttachmentData(isVoiceMessage = false) - is MultiPickerFileType -> toContentAttachmentData() - else -> throw IllegalStateException("Unknown file type") + is MultiPickerFileType -> toContentAttachmentData() + else -> throw IllegalStateException("Unknown file type") } } @@ -85,7 +85,7 @@ fun MultiPickerBaseMediaType.toContentAttachmentData(): ContentAttachmentData { return when (this) { is MultiPickerImageType -> toContentAttachmentData() is MultiPickerVideoType -> toContentAttachmentData() - else -> throw IllegalStateException("Unknown media type") + else -> throw IllegalStateException("Unknown media type") } } diff --git a/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewFragment.kt b/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewFragment.kt index 729ac10d4b..dfe74fa47e 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewFragment.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewFragment.kt @@ -103,11 +103,11 @@ class AttachmentsPreviewFragment @Inject constructor( handleRemoveAction() true } - R.id.attachmentsPreviewEditAction -> { + R.id.attachmentsPreviewEditAction -> { handleEditAction() true } - else -> { + else -> { super.onOptionsItemSelected(item) } } @@ -152,7 +152,7 @@ class AttachmentsPreviewFragment @Inject constructor( return when { nbVideos == 0 -> resources.getQuantityString(R.plurals.send_images_with_original_size, nbImages) nbImages == 0 -> resources.getQuantityString(R.plurals.send_videos_with_original_size, nbVideos) - else -> getString(R.string.send_images_and_video_with_original_size) + else -> getString(R.string.send_images_and_video_with_original_size) } } diff --git a/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewViewModel.kt b/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewViewModel.kt index 81f0994899..89d8ef648e 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/preview/AttachmentsPreviewViewModel.kt @@ -24,9 +24,9 @@ class AttachmentsPreviewViewModel(initialState: AttachmentsPreviewViewState) : override fun handle(action: AttachmentsPreviewAction) { when (action) { - is AttachmentsPreviewAction.SetCurrentAttachment -> handleSetCurrentAttachment(action) + is AttachmentsPreviewAction.SetCurrentAttachment -> handleSetCurrentAttachment(action) is AttachmentsPreviewAction.UpdatePathOfCurrentAttachment -> handleUpdatePathOfCurrentAttachment(action) - AttachmentsPreviewAction.RemoveCurrentAttachment -> handleRemoveCurrentAttachment() + AttachmentsPreviewAction.RemoveCurrentAttachment -> handleRemoveCurrentAttachment() } } diff --git a/vector/src/main/java/im/vector/app/features/auth/PromptFragment.kt b/vector/src/main/java/im/vector/app/features/auth/PromptFragment.kt index bd44a5b9cd..38f098612b 100644 --- a/vector/src/main/java/im/vector/app/features/auth/PromptFragment.kt +++ b/vector/src/main/java/im/vector/app/features/auth/PromptFragment.kt @@ -44,7 +44,7 @@ class PromptFragment : VectorBaseFragment() { private fun onButtonClicked() = withState(viewModel) { state -> when (state.flowType) { - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { viewModel.handle(ReAuthActions.StartSSOFallback) } LoginFlowTypes.PASSWORD -> { @@ -57,7 +57,7 @@ class PromptFragment : VectorBaseFragment() { viewModel.handle(ReAuthActions.ReAuthWithPass(password)) } } - else -> { + else -> { // not supported } } @@ -65,7 +65,7 @@ class PromptFragment : VectorBaseFragment() { override fun invalidate() = withState(viewModel) { when (it.flowType) { - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { views.passwordFieldTil.isVisible = false views.reAuthConfirmButton.text = getString(R.string.auth_login_sso) } @@ -73,21 +73,21 @@ class PromptFragment : VectorBaseFragment() { views.passwordFieldTil.isVisible = true views.reAuthConfirmButton.text = getString(R.string._continue) } - else -> { + else -> { // This login flow is not supported, you should use web? } } if (it.lastErrorCode != null) { when (it.flowType) { - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { views.genericErrorText.isVisible = true views.genericErrorText.text = getString(R.string.authentication_error) } LoginFlowTypes.PASSWORD -> { views.passwordFieldTil.error = getString(R.string.authentication_error) } - else -> { + else -> { // nop } } diff --git a/vector/src/main/java/im/vector/app/features/auth/ReAuthActivity.kt b/vector/src/main/java/im/vector/app/features/auth/ReAuthActivity.kt index f92ec8ea9e..3f0b49e9f1 100644 --- a/vector/src/main/java/im/vector/app/features/auth/ReAuthActivity.kt +++ b/vector/src/main/java/im/vector/app/features/auth/ReAuthActivity.kt @@ -86,10 +86,10 @@ class ReAuthActivity : SimpleFragmentActivity() { sharedViewModel.observeViewEvents { when (it) { - is ReAuthEvents.OpenSsoURl -> { + is ReAuthEvents.OpenSsoURl -> { openInCustomTab(it.url) } - ReAuthEvents.Dismiss -> { + ReAuthEvents.Dismiss -> { setResult(RESULT_CANCELED) finish() } @@ -196,19 +196,21 @@ class ReAuthActivity : SimpleFragmentActivity() { const val RESULT_VALUE = "RESULT_VALUE" const val DEFAULT_RESULT_KEYSTORE_ALIAS = "ReAuthActivity" - fun newIntent(context: Context, - fromError: RegistrationFlowResponse, - lastErrorCode: String?, - reasonTitle: String?, - resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { + fun newIntent( + context: Context, + fromError: RegistrationFlowResponse, + lastErrorCode: String?, + reasonTitle: String?, + resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS + ): Intent { val authType = when (fromError.nextUncompletedStage()) { LoginFlowTypes.PASSWORD -> { LoginFlowTypes.PASSWORD } - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { LoginFlowTypes.SSO } - else -> { + else -> { // TODO, support more auth type? null } diff --git a/vector/src/main/java/im/vector/app/features/auth/ReAuthViewModel.kt b/vector/src/main/java/im/vector/app/features/auth/ReAuthViewModel.kt index 0bd26870e5..c504982666 100644 --- a/vector/src/main/java/im/vector/app/features/auth/ReAuthViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/auth/ReAuthViewModel.kt @@ -42,7 +42,7 @@ class ReAuthViewModel @AssistedInject constructor( override fun handle(action: ReAuthActions) = withState { state -> when (action) { - ReAuthActions.StartSSOFallback -> { + ReAuthActions.StartSSOFallback -> { if (state.flowType == LoginFlowTypes.SSO) { setState { copy(ssoFallbackPageWasShown = true) } val ssoURL = session.getUiaSsoFallbackUrl(initialState.session ?: "") @@ -55,7 +55,7 @@ class ReAuthViewModel @AssistedInject constructor( ReAuthActions.FallBackPageClosed -> { // Should we do something here? } - is ReAuthActions.ReAuthWithPass -> { + is ReAuthActions.ReAuthWithPass -> { val safeForIntentCypher = ByteArrayOutputStream().also { it.use { session.secureStorageService().securelyStoreObject(action.password, initialState.resultKeyStoreAlias, it) diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/command/AutocompleteCommandPresenter.kt b/vector/src/main/java/im/vector/app/features/autocomplete/command/AutocompleteCommandPresenter.kt index 5e4528d381..497c5b5d51 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/command/AutocompleteCommandPresenter.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/command/AutocompleteCommandPresenter.kt @@ -30,7 +30,8 @@ class AutocompleteCommandPresenter @AssistedInject constructor( @Assisted val isInThreadTimeline: Boolean, context: Context, private val controller: AutocompleteCommandController, - private val vectorPreferences: VectorPreferences) : + private val vectorPreferences: VectorPreferences +) : RecyclerViewPresenter(context), AutocompleteClickListener { @AssistedFactory diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/emoji/AutocompleteEmojiPresenter.kt b/vector/src/main/java/im/vector/app/features/autocomplete/emoji/AutocompleteEmojiPresenter.kt index 4f272c7a24..2b83c1dc30 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/emoji/AutocompleteEmojiPresenter.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/emoji/AutocompleteEmojiPresenter.kt @@ -28,9 +28,11 @@ import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.launch import javax.inject.Inject -class AutocompleteEmojiPresenter @Inject constructor(context: Context, - private val emojiDataSource: EmojiDataSource, - private val controller: AutocompleteEmojiController) : +class AutocompleteEmojiPresenter @Inject constructor( + context: Context, + private val emojiDataSource: EmojiDataSource, + private val controller: AutocompleteEmojiController +) : RecyclerViewPresenter(context), AutocompleteClickListener { private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/group/AutocompleteGroupPresenter.kt b/vector/src/main/java/im/vector/app/features/autocomplete/group/AutocompleteGroupPresenter.kt index fc7479eb21..32a1bed1c6 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/group/AutocompleteGroupPresenter.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/group/AutocompleteGroupPresenter.kt @@ -26,9 +26,10 @@ import org.matrix.android.sdk.api.session.group.groupSummaryQueryParams import org.matrix.android.sdk.api.session.group.model.GroupSummary import javax.inject.Inject -class AutocompleteGroupPresenter @Inject constructor(context: Context, - private val controller: AutocompleteGroupController, - private val session: Session +class AutocompleteGroupPresenter @Inject constructor( + context: Context, + private val controller: AutocompleteGroupController, + private val session: Session ) : RecyclerViewPresenter(context), AutocompleteClickListener { init { diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberController.kt b/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberController.kt index 2034cee90a..8552851254 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberController.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberController.kt @@ -52,9 +52,9 @@ class AutocompleteMemberController @Inject constructor(private val context: Cont } data.forEach { item -> when (item) { - is AutocompleteMemberItem.Header -> buildHeaderItem(item) + is AutocompleteMemberItem.Header -> buildHeaderItem(item) is AutocompleteMemberItem.RoomMember -> buildRoomMemberItem(item) - is AutocompleteMemberItem.Everyone -> buildEveryoneItem(item) + is AutocompleteMemberItem.Everyone -> buildEveryoneItem(item) } } } diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberPresenter.kt b/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberPresenter.kt index 88d015ec0c..a480b1c279 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberPresenter.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/member/AutocompleteMemberPresenter.kt @@ -36,10 +36,11 @@ import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent import org.matrix.android.sdk.api.session.room.model.RoomMemberSummary import org.matrix.android.sdk.api.util.MatrixItem -class AutocompleteMemberPresenter @AssistedInject constructor(context: Context, - @Assisted val roomId: String, - private val session: Session, - private val controller: AutocompleteMemberController +class AutocompleteMemberPresenter @AssistedInject constructor( + context: Context, + @Assisted val roomId: String, + private val session: Session, + private val controller: AutocompleteMemberController ) : RecyclerViewPresenter(context), AutocompleteClickListener { /* ========================================================================================== diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/room/AutocompleteRoomPresenter.kt b/vector/src/main/java/im/vector/app/features/autocomplete/room/AutocompleteRoomPresenter.kt index d9310e295d..2d61508796 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/room/AutocompleteRoomPresenter.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/room/AutocompleteRoomPresenter.kt @@ -26,9 +26,10 @@ import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import javax.inject.Inject -class AutocompleteRoomPresenter @Inject constructor(context: Context, - private val controller: AutocompleteRoomController, - private val session: Session +class AutocompleteRoomPresenter @Inject constructor( + context: Context, + private val controller: AutocompleteRoomController, + private val session: Session ) : RecyclerViewPresenter(context), AutocompleteClickListener { init { diff --git a/vector/src/main/java/im/vector/app/features/call/CallControlsView.kt b/vector/src/main/java/im/vector/app/features/call/CallControlsView.kt index f0158fc4d6..fee8739e4c 100644 --- a/vector/src/main/java/im/vector/app/features/call/CallControlsView.kt +++ b/vector/src/main/java/im/vector/app/features/call/CallControlsView.kt @@ -103,17 +103,17 @@ class CallControlsView @JvmOverloads constructor( CallState.Idle, is CallState.Connected, is CallState.Dialing, - is CallState.Answering -> { + is CallState.Answering -> { views.ringingControls.isVisible = false views.connectedControls.isVisible = true views.videoToggleIcon.isVisible = state.isVideoCall views.moreIcon.isVisible = callState is CallState.Connected && callState.iceConnectionState == MxPeerConnectionState.CONNECTED } - is CallState.Ended -> { + is CallState.Ended -> { views.ringingControls.isVisible = false views.connectedControls.isVisible = false } - null -> Unit + null -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/call/CallSoundDeviceChooserBottomSheet.kt b/vector/src/main/java/im/vector/app/features/call/CallSoundDeviceChooserBottomSheet.kt index 649b7fee3e..1d7815b721 100644 --- a/vector/src/main/java/im/vector/app/features/call/CallSoundDeviceChooserBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/call/CallSoundDeviceChooserBottomSheet.kt @@ -45,7 +45,7 @@ class CallSoundDeviceChooserBottomSheet : VectorBaseBottomSheetDialogFragment { render(it.available, it.current) } - else -> { + else -> { } } } @@ -56,7 +56,7 @@ class CallSoundDeviceChooserBottomSheet : VectorBaseBottomSheetDialogFragment val title = when (device) { is CallAudioManager.Device.WirelessHeadset -> device.name ?: getString(device.titleRes) - else -> getString(device.titleRes) + else -> getString(device.titleRes) } BottomSheetActionItem_().apply { id(device.titleRes) diff --git a/vector/src/main/java/im/vector/app/features/call/VectorCallActivity.kt b/vector/src/main/java/im/vector/app/features/call/VectorCallActivity.kt index a904658e9c..579a5851c6 100644 --- a/vector/src/main/java/im/vector/app/features/call/VectorCallActivity.kt +++ b/vector/src/main/java/im/vector/app/features/call/VectorCallActivity.kt @@ -267,7 +267,7 @@ class VectorCallActivity : VectorBaseActivity(), CallContro is CallState.Idle, is CallState.CreateOffer, is CallState.LocalRinging, - is CallState.Dialing -> { + is CallState.Dialing -> { views.fullscreenRenderer.isVisible = false views.pipRendererWrapper.isVisible = false views.callInfoGroup.isVisible = true @@ -333,14 +333,14 @@ class VectorCallActivity : VectorBaseActivity(), CallContro toolbar?.setSubtitle(R.string.call_connecting) } } - is CallState.Ended -> { + is CallState.Ended -> { views.fullscreenRenderer.isVisible = false views.pipRendererWrapper.isVisible = false views.callInfoGroup.isVisible = true toolbar?.setSubtitle(R.string.call_ended) configureCallInfo(state) } - else -> { + else -> { views.fullscreenRenderer.isVisible = false views.pipRendererWrapper.isVisible = false views.callInfoGroup.isInvisible = true @@ -380,7 +380,7 @@ class VectorCallActivity : VectorBaseActivity(), CallContro views.callInfoGroup.isVisible = false } } - else -> { + else -> { views.fullscreenRenderer.isVisible = false views.callInfoGroup.isVisible = false } @@ -395,13 +395,13 @@ class VectorCallActivity : VectorBaseActivity(), CallContro startActivity(startIntent) } when (callState.reason) { - EndCallReason.USER_BUSY -> { + EndCallReason.USER_BUSY -> { showEndCallDialog(R.string.call_ended_user_busy_title, R.string.call_ended_user_busy_description) } EndCallReason.INVITE_TIMEOUT -> { showEndCallDialog(R.string.call_ended_invite_timeout_title, R.string.call_error_user_not_responding) } - else -> { + else -> { finish() } } @@ -522,22 +522,22 @@ class VectorCallActivity : VectorBaseActivity(), CallContro private fun handleViewEvents(event: VectorCallViewEvents?) { Timber.tag(loggerTag.value).v("handleViewEvents $event") when (event) { - is VectorCallViewEvents.ConnectionTimeout -> { + is VectorCallViewEvents.ConnectionTimeout -> { onErrorTimoutConnect(event.turn) } - is VectorCallViewEvents.ShowDialPad -> { + is VectorCallViewEvents.ShowDialPad -> { CallDialPadBottomSheet.newInstance(false).apply { callback = dialPadCallback }.show(supportFragmentManager, FRAGMENT_DIAL_PAD_TAG) } - is VectorCallViewEvents.ShowCallTransferScreen -> { + is VectorCallViewEvents.ShowCallTransferScreen -> { val callId = withState(callViewModel) { it.callId } navigator.openCallTransfer(this, callTransferActivityResultLauncher, callId) } - is VectorCallViewEvents.FailToTransfer -> showSnackbar(getString(R.string.call_transfer_failure)) + is VectorCallViewEvents.FailToTransfer -> showSnackbar(getString(R.string.call_transfer_failure)) is VectorCallViewEvents.ShowScreenSharingPermissionDialog -> handleShowScreenSharingPermissionDialog() - is VectorCallViewEvents.StopScreenSharingService -> handleStopScreenSharingService() - else -> Unit + is VectorCallViewEvents.StopScreenSharingService -> handleStopScreenSharingService() + else -> Unit } } @@ -546,7 +546,7 @@ class VectorCallActivity : VectorBaseActivity(), CallContro Activity.RESULT_CANCELED -> { callViewModel.handle(VectorCallViewActions.CallTransferSelectionCancelled) } - Activity.RESULT_OK -> { + Activity.RESULT_OK -> { CallTransferActivity.getCallTransferResult(activityResult.data) ?.let { callViewModel.handle(VectorCallViewActions.CallTransferSelectionResult(it)) } } @@ -706,13 +706,15 @@ class VectorCallActivity : VectorBaseActivity(), CallContro } } - fun newIntent(context: Context, - callId: String, - signalingRoomId: String, - otherUserId: String, - isIncomingCall: Boolean, - isVideoCall: Boolean, - mode: String?): Intent { + fun newIntent( + context: Context, + callId: String, + signalingRoomId: String, + otherUserId: String, + isIncomingCall: Boolean, + isVideoCall: Boolean, + mode: String? + ): Intent { val callArgs = CallArgs(signalingRoomId, callId, otherUserId, isIncomingCall, isVideoCall) return Intent(context, VectorCallActivity::class.java).apply { // what could be the best flags? diff --git a/vector/src/main/java/im/vector/app/features/call/VectorCallViewModel.kt b/vector/src/main/java/im/vector/app/features/call/VectorCallViewModel.kt index e2cedbe1b0..f5ae6a8597 100644 --- a/vector/src/main/java/im/vector/app/features/call/VectorCallViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/call/VectorCallViewModel.kt @@ -264,30 +264,30 @@ class VectorCallViewModel @AssistedInject constructor( override fun handle(action: VectorCallViewActions) = withState { state -> when (action) { - VectorCallViewActions.EndCall -> { + VectorCallViewActions.EndCall -> { call?.endCall() _viewEvents.post(VectorCallViewEvents.StopScreenSharingService) } - VectorCallViewActions.AcceptCall -> { + VectorCallViewActions.AcceptCall -> { setState { copy(callState = Loading()) } call?.acceptIncomingCall() } - VectorCallViewActions.DeclineCall -> { + VectorCallViewActions.DeclineCall -> { setState { copy(callState = Loading()) } call?.endCall() } - VectorCallViewActions.ToggleMute -> { + VectorCallViewActions.ToggleMute -> { val muted = state.isAudioMuted call?.muteCall(!muted) setState { copy(isAudioMuted = !muted) } } - VectorCallViewActions.ToggleVideo -> { + VectorCallViewActions.ToggleVideo -> { if (state.isVideoCall) { val videoEnabled = state.isVideoEnabled call?.enableVideo(!videoEnabled) @@ -297,19 +297,19 @@ class VectorCallViewModel @AssistedInject constructor( } Unit } - VectorCallViewActions.ToggleHoldResume -> { + VectorCallViewActions.ToggleHoldResume -> { val isRemoteOnHold = state.isRemoteOnHold call?.updateRemoteOnHold(!isRemoteOnHold) } - is VectorCallViewActions.ChangeAudioDevice -> { + is VectorCallViewActions.ChangeAudioDevice -> { callManager.audioManager.setAudioDevice(action.device) } - VectorCallViewActions.SwitchSoundDevice -> { + VectorCallViewActions.SwitchSoundDevice -> { _viewEvents.post( VectorCallViewEvents.ShowSoundDeviceChooser(state.availableDevices, state.device) ) } - VectorCallViewActions.HeadSetButtonPressed -> { + VectorCallViewActions.HeadSetButtonPressed -> { if (state.callState.invoke() is CallState.LocalRinging) { // accept call call?.acceptIncomingCall() @@ -320,20 +320,20 @@ class VectorCallViewModel @AssistedInject constructor( } Unit } - VectorCallViewActions.ToggleCamera -> { + VectorCallViewActions.ToggleCamera -> { call?.switchCamera() } - VectorCallViewActions.ToggleHDSD -> { + VectorCallViewActions.ToggleHDSD -> { if (!state.isVideoCall) return@withState call?.setCaptureFormat(if (state.isHD) CaptureFormat.SD else CaptureFormat.HD) } - VectorCallViewActions.OpenDialPad -> { + VectorCallViewActions.OpenDialPad -> { _viewEvents.post(VectorCallViewEvents.ShowDialPad) } - is VectorCallViewActions.SendDtmfDigit -> { + is VectorCallViewActions.SendDtmfDigit -> { call?.sendDtmfDigit(action.digit) } - VectorCallViewActions.InitiateCallTransfer -> { + VectorCallViewActions.InitiateCallTransfer -> { call?.updateRemoteOnHold(true) _viewEvents.post( VectorCallViewEvents.ShowCallTransferScreen @@ -345,17 +345,17 @@ class VectorCallViewModel @AssistedInject constructor( is VectorCallViewActions.CallTransferSelectionResult -> { handleCallTransferSelectionResult(action.callTransferResult) } - VectorCallViewActions.TransferCall -> { + VectorCallViewActions.TransferCall -> { handleCallTransfer() } - is VectorCallViewActions.SwitchCall -> { + is VectorCallViewActions.SwitchCall -> { setState { VectorCallViewState(action.callArgs) } setupCallWithCurrentState() } - is VectorCallViewActions.ToggleScreenSharing -> { + is VectorCallViewActions.ToggleScreenSharing -> { handleToggleScreenSharing(state.isSharingScreen) } - is VectorCallViewActions.StartScreenSharing -> { + is VectorCallViewActions.StartScreenSharing -> { call?.startSharingScreen(action.videoCapturer) proximityManager.stop() setState { @@ -394,7 +394,7 @@ class VectorCallViewModel @AssistedInject constructor( private fun handleCallTransferSelectionResult(result: CallTransferResult) { when (result) { - is CallTransferResult.ConnectWithUserId -> connectWithUserId(result) + is CallTransferResult.ConnectWithUserId -> connectWithUserId(result) is CallTransferResult.ConnectWithPhoneNumber -> connectWithPhoneNumber(result) } } diff --git a/vector/src/main/java/im/vector/app/features/call/audio/API21AudioDeviceDetector.kt b/vector/src/main/java/im/vector/app/features/call/audio/API21AudioDeviceDetector.kt index 15d213e017..1c7dcd841d 100644 --- a/vector/src/main/java/im/vector/app/features/call/audio/API21AudioDeviceDetector.kt +++ b/vector/src/main/java/im/vector/app/features/call/audio/API21AudioDeviceDetector.kt @@ -30,9 +30,10 @@ import timber.log.Timber private val loggerTag = LoggerTag("API21AudioDeviceDetector", LoggerTag.VOIP) -internal class API21AudioDeviceDetector(private val context: Context, - private val audioManager: AudioManager, - private val callAudioManager: CallAudioManager +internal class API21AudioDeviceDetector( + private val context: Context, + private val audioManager: AudioManager, + private val callAudioManager: CallAudioManager ) : CallAudioManager.AudioDeviceDetector, WiredHeadsetStateReceiver.HeadsetEventListener, BluetoothHeadsetReceiver.EventListener { private var bluetoothAdapter: BluetoothAdapter? = null diff --git a/vector/src/main/java/im/vector/app/features/call/audio/API23AudioDeviceDetector.kt b/vector/src/main/java/im/vector/app/features/call/audio/API23AudioDeviceDetector.kt index ccf79cc02d..0b82de6cbe 100644 --- a/vector/src/main/java/im/vector/app/features/call/audio/API23AudioDeviceDetector.kt +++ b/vector/src/main/java/im/vector/app/features/call/audio/API23AudioDeviceDetector.kt @@ -23,8 +23,9 @@ import androidx.annotation.RequiresApi import timber.log.Timber @RequiresApi(Build.VERSION_CODES.M) -internal class API23AudioDeviceDetector(private val audioManager: AudioManager, - private val callAudioManager: CallAudioManager +internal class API23AudioDeviceDetector( + private val audioManager: AudioManager, + private val callAudioManager: CallAudioManager ) : CallAudioManager.AudioDeviceDetector { private val onAudioDeviceChangeRunner = Runnable { @@ -32,9 +33,9 @@ internal class API23AudioDeviceDetector(private val audioManager: AudioManager, val deviceInfos = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS) for (info in deviceInfos) { when (info.type) { - AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> devices.add(CallAudioManager.Device.WirelessHeadset(info.productName.toString())) - AudioDeviceInfo.TYPE_BUILTIN_EARPIECE -> devices.add(CallAudioManager.Device.Phone) - AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> devices.add(CallAudioManager.Device.Speaker) + AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> devices.add(CallAudioManager.Device.WirelessHeadset(info.productName.toString())) + AudioDeviceInfo.TYPE_BUILTIN_EARPIECE -> devices.add(CallAudioManager.Device.Phone) + AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> devices.add(CallAudioManager.Device.Speaker) AudioDeviceInfo.TYPE_WIRED_HEADPHONES, AudioDeviceInfo.TYPE_WIRED_HEADSET, TYPE_USB_HEADSET -> devices.add(CallAudioManager.Device.Headset) } @@ -45,13 +46,15 @@ internal class API23AudioDeviceDetector(private val audioManager: AudioManager, } private val audioDeviceCallback: AudioDeviceCallback = object : AudioDeviceCallback() { override fun onAudioDevicesAdded( - addedDevices: Array) { + addedDevices: Array + ) { Timber.d(" Audio devices added") onAudioDeviceChange() } override fun onAudioDevicesRemoved( - removedDevices: Array) { + removedDevices: Array + ) { Timber.d(" Audio devices removed") onAudioDeviceChange() } diff --git a/vector/src/main/java/im/vector/app/features/call/audio/DefaultAudioDeviceRouter.kt b/vector/src/main/java/im/vector/app/features/call/audio/DefaultAudioDeviceRouter.kt index c3500c7bc2..7251c2d423 100644 --- a/vector/src/main/java/im/vector/app/features/call/audio/DefaultAudioDeviceRouter.kt +++ b/vector/src/main/java/im/vector/app/features/call/audio/DefaultAudioDeviceRouter.kt @@ -22,8 +22,9 @@ import androidx.media.AudioFocusRequestCompat import androidx.media.AudioManagerCompat import timber.log.Timber -class DefaultAudioDeviceRouter(private val audioManager: AudioManager, - private val callAudioManager: CallAudioManager +class DefaultAudioDeviceRouter( + private val audioManager: AudioManager, + private val callAudioManager: CallAudioManager ) : CallAudioManager.AudioDeviceRouter, AudioManager.OnAudioFocusChangeListener { private var audioFocusLost = false @@ -95,7 +96,7 @@ class DefaultAudioDeviceRouter(private val audioManager: AudioManager, override fun onAudioFocusChange(focusChange: Int) { callAudioManager.runInAudioThread { when (focusChange) { - AudioManager.AUDIOFOCUS_GAIN -> { + AudioManager.AUDIOFOCUS_GAIN -> { Timber.d(" Audio focus gained") if (audioFocusLost) { callAudioManager.resetAudioRoute() diff --git a/vector/src/main/java/im/vector/app/features/call/conference/ConferenceEvent.kt b/vector/src/main/java/im/vector/app/features/call/conference/ConferenceEvent.kt index 0d8e538eca..08612fe573 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/ConferenceEvent.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/ConferenceEvent.kt @@ -49,8 +49,10 @@ class ConferenceEventEmitter(private val context: Context) { } } -class ConferenceEventObserver(private val context: Context, - private val onBroadcastEvent: (ConferenceEvent) -> Unit) : +class ConferenceEventObserver( + private val context: Context, + private val onBroadcastEvent: (ConferenceEvent) -> Unit +) : DefaultLifecycleObserver { // See https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-android-sdk#listening-for-broadcasted-events @@ -83,10 +85,10 @@ class ConferenceEventObserver(private val context: Context, private fun onBroadcastReceived(intent: Intent) { val event = BroadcastEvent(intent) val conferenceEvent = when (event.type) { - BroadcastEvent.Type.CONFERENCE_JOINED -> ConferenceEvent.Joined(event.data) + BroadcastEvent.Type.CONFERENCE_JOINED -> ConferenceEvent.Joined(event.data) BroadcastEvent.Type.CONFERENCE_TERMINATED -> ConferenceEvent.Terminated(event.data) - BroadcastEvent.Type.CONFERENCE_WILL_JOIN -> ConferenceEvent.WillJoin(event.data) - else -> null + BroadcastEvent.Type.CONFERENCE_WILL_JOIN -> ConferenceEvent.WillJoin(event.data) + else -> null } if (conferenceEvent != null) { onBroadcastEvent(conferenceEvent) diff --git a/vector/src/main/java/im/vector/app/features/call/conference/JitsiActiveConferenceHolder.kt b/vector/src/main/java/im/vector/app/features/call/conference/JitsiActiveConferenceHolder.kt index 179956612d..cdc89959b7 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/JitsiActiveConferenceHolder.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/JitsiActiveConferenceHolder.kt @@ -37,9 +37,9 @@ class JitsiActiveConferenceHolder @Inject constructor(context: Context) { private fun onBroadcastEvent(conferenceEvent: ConferenceEvent) { when (conferenceEvent) { - is ConferenceEvent.Joined -> activeConference = conferenceEvent.extractConferenceUrl() + is ConferenceEvent.Joined -> activeConference = conferenceEvent.extractConferenceUrl() is ConferenceEvent.Terminated -> activeConference = null - else -> Unit + else -> Unit } } } diff --git a/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewActions.kt b/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewActions.kt index 7c9b9385f9..be0d8775d6 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewActions.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewActions.kt @@ -19,8 +19,10 @@ package im.vector.app.features.call.conference import im.vector.app.core.platform.VectorViewModelAction sealed class JitsiCallViewActions : VectorViewModelAction { - data class SwitchTo(val args: VectorJitsiActivity.Args, - val withConfirmation: Boolean) : JitsiCallViewActions() + data class SwitchTo( + val args: VectorJitsiActivity.Args, + val withConfirmation: Boolean + ) : JitsiCallViewActions() /** * The ViewModel will either ask the View to finish, or to join another conf. diff --git a/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewModel.kt b/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewModel.kt index 0ea380734d..2082cdcfef 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/JitsiCallViewModel.kt @@ -99,7 +99,7 @@ class JitsiCallViewModel @AssistedInject constructor( override fun handle(action: JitsiCallViewActions) { when (action) { - is JitsiCallViewActions.SwitchTo -> handleSwitchTo(action) + is JitsiCallViewActions.SwitchTo -> handleSwitchTo(action) JitsiCallViewActions.OnConferenceLeft -> handleOnConferenceLeft() } } diff --git a/vector/src/main/java/im/vector/app/features/call/conference/RemoveJitsiWidgetView.kt b/vector/src/main/java/im/vector/app/features/call/conference/RemoveJitsiWidgetView.kt index e7659fb3e6..e2574d973c 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/RemoveJitsiWidgetView.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/RemoveJitsiWidgetView.kt @@ -53,7 +53,7 @@ import org.matrix.android.sdk.api.session.room.model.Membership views.removeJitsiSlidingContainer.setOnTouchListener { _, event -> val currentState = state return@setOnTouchListener when (event.action) { - MotionEvent.ACTION_DOWN -> { + MotionEvent.ACTION_DOWN -> { if (currentState == State.Idle) { val initialX = views.removeJitsiSlidingContainer.x - event.rawX updateState(State.Sliding(initialX, 0f, false)) @@ -71,7 +71,7 @@ import org.matrix.android.sdk.api.session.room.model.Membership } true } - MotionEvent.ACTION_MOVE -> { + MotionEvent.ACTION_MOVE -> { if (currentState is State.Sliding) { val translationX = (currentState.initialX + event.rawX).coerceAtLeast(0f) val hasReachedActivationThreshold = translationX >= views.root.width / 4 @@ -79,7 +79,7 @@ import org.matrix.android.sdk.api.session.room.model.Membership } true } - else -> false + else -> false } } renderInternalState(state) @@ -119,12 +119,12 @@ import org.matrix.android.sdk.api.session.room.model.Membership private fun renderInternalState(state: State) { isVisible = state != State.Unmount when (state) { - State.Progress -> { + State.Progress -> { isVisible = true views.updateVisibilities(true) views.updateHangupColors(true) } - State.Idle -> { + State.Idle -> { isVisible = true views.updateVisibilities(false) views.removeJitsiSlidingContainer.translationX = 0f @@ -136,7 +136,7 @@ import org.matrix.android.sdk.api.session.room.model.Membership views.removeJitsiSlidingContainer.translationX = state.translationX views.updateHangupColors(state.hasReachedActivationThreshold) } - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/call/conference/VectorJitsiActivity.kt b/vector/src/main/java/im/vector/app/features/call/conference/VectorJitsiActivity.kt index 5a12337e4f..86136eab15 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/VectorJitsiActivity.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/VectorJitsiActivity.kt @@ -73,11 +73,11 @@ class VectorJitsiActivity : VectorBaseActivity(), JitsiMee jitsiViewModel.observeViewEvents { when (it) { - is JitsiCallViewEvents.JoinConference -> configureJitsiView(it) + is JitsiCallViewEvents.JoinConference -> configureJitsiView(it) is JitsiCallViewEvents.ConfirmSwitchingConference -> handleConfirmSwitching(it) - JitsiCallViewEvents.FailJoiningConference -> handleFailJoining() - JitsiCallViewEvents.Finish -> finish() - JitsiCallViewEvents.LeaveConference -> handleLeaveConference() + JitsiCallViewEvents.FailJoiningConference -> handleFailJoining() + JitsiCallViewEvents.Finish -> finish() + JitsiCallViewEvents.LeaveConference -> handleLeaveConference() } } lifecycle.addObserver(ConferenceEventObserver(this, this::onBroadcastEvent)) @@ -138,8 +138,10 @@ class VectorJitsiActivity : VectorBaseActivity(), JitsiMee .show() } - override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, - newConfig: Configuration) { + override fun onPictureInPictureModeChanged( + isInPictureInPictureMode: Boolean, + newConfig: Configuration + ) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) checkIfActivityShouldBeFinished() Timber.w("onPictureInPictureModeChanged($isInPictureInPictureMode)") @@ -155,12 +157,12 @@ class VectorJitsiActivity : VectorBaseActivity(), JitsiMee private fun renderState(viewState: JitsiCallViewState) { when (viewState.widget) { - is Fail -> finish() + is Fail -> finish() is Success -> { views.jitsiProgressLayout.isVisible = false jitsiMeetView?.isVisible = true } - else -> { + else -> { jitsiMeetView?.isVisible = false views.jitsiProgressLayout.isVisible = true } @@ -220,7 +222,7 @@ class VectorJitsiActivity : VectorBaseActivity(), JitsiMee Timber.v("Broadcast received: $event") when (event) { is ConferenceEvent.Terminated -> onConferenceTerminated(event.data) - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/call/conference/jwt/JitsiJWTFactory.kt b/vector/src/main/java/im/vector/app/features/call/conference/jwt/JitsiJWTFactory.kt index 39b87c5d63..8809606e6e 100644 --- a/vector/src/main/java/im/vector/app/features/call/conference/jwt/JitsiJWTFactory.kt +++ b/vector/src/main/java/im/vector/app/features/call/conference/jwt/JitsiJWTFactory.kt @@ -29,11 +29,13 @@ class JitsiJWTFactory @Inject constructor() { * Create a JWT token for jitsi openidtoken-jwt authentication * See https://github.com/matrix-org/prosody-mod-auth-matrix-user-verification */ - fun create(openIdToken: OpenIdToken, - jitsiServerDomain: String, - roomId: String, - userAvatarUrl: String, - userDisplayName: String): String { + fun create( + openIdToken: OpenIdToken, + jitsiServerDomain: String, + roomId: String, + userAvatarUrl: String, + userDisplayName: String + ): String { // The secret key here is irrelevant, we're only using the JWT to transport data to Prosody in the Jitsi stack. val key = Keys.secretKeyFor(SignatureAlgorithm.HS256) val context = mapOf( diff --git a/vector/src/main/java/im/vector/app/features/call/dialpad/DialPadFragment.kt b/vector/src/main/java/im/vector/app/features/call/dialpad/DialPadFragment.kt index 606ba1d1e9..05337e2064 100644 --- a/vector/src/main/java/im/vector/app/features/call/dialpad/DialPadFragment.kt +++ b/vector/src/main/java/im/vector/app/features/call/dialpad/DialPadFragment.kt @@ -73,7 +73,8 @@ class DialPadFragment : Fragment(), TextWatcher { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle?): View { + savedInstanceState: Bundle? + ): View { initArgs(savedInstanceState) val view = inflater.inflate(R.layout.dialpad_fragment, container, false) view.setBackgroundColor(ThemeUtils.getColor(requireContext(), R.attr.backgroundColor)) diff --git a/vector/src/main/java/im/vector/app/features/call/lookup/CallProtocolsChecker.kt b/vector/src/main/java/im/vector/app/features/call/lookup/CallProtocolsChecker.kt index 9f6a24fd25..8173ce1400 100644 --- a/vector/src/main/java/im/vector/app/features/call/lookup/CallProtocolsChecker.kt +++ b/vector/src/main/java/im/vector/app/features/call/lookup/CallProtocolsChecker.kt @@ -93,8 +93,8 @@ class CallProtocolsChecker(private val session: Session) { private fun Map.extractPSTN(): String? { return when { containsKey(PROTOCOL_PSTN_PREFIXED) -> PROTOCOL_PSTN_PREFIXED - containsKey(PROTOCOL_PSTN) -> PROTOCOL_PSTN - else -> null + containsKey(PROTOCOL_PSTN) -> PROTOCOL_PSTN + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferActivity.kt b/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferActivity.kt index 81173568b5..25e0273528 100644 --- a/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferActivity.kt +++ b/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferActivity.kt @@ -65,7 +65,7 @@ class CallTransferActivity : VectorBaseActivity() { TabLayoutMediator(views.callTransferTabLayout, views.callTransferViewPager) { tab, position -> when (position) { CallTransferPagerAdapter.USER_LIST_INDEX -> tab.text = getString(R.string.call_transfer_users_tab_title) - CallTransferPagerAdapter.DIAL_PAD_INDEX -> tab.text = getString(R.string.call_dial_pad_title) + CallTransferPagerAdapter.DIAL_PAD_INDEX -> tab.text = getString(R.string.call_dial_pad_title) } }.attach() setupToolbar(views.callTransferToolbar) @@ -81,7 +81,7 @@ class CallTransferActivity : VectorBaseActivity() { val result = CallTransferResult.ConnectWithUserId(views.callTransferConsultCheckBox.isChecked, selectedUser) handleComplete(result) } - CallTransferPagerAdapter.DIAL_PAD_INDEX -> { + CallTransferPagerAdapter.DIAL_PAD_INDEX -> { val phoneNumber = sectionsPagerAdapter.dialPadFragment?.getRawInput() ?: return@debouncedClicks val result = CallTransferResult.ConnectWithPhoneNumber(views.callTransferConsultCheckBox.isChecked, phoneNumber) handleComplete(result) diff --git a/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferViewModel.kt b/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferViewModel.kt index 67f0949dcf..189b1ab2a7 100644 --- a/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/call/transfer/CallTransferViewModel.kt @@ -29,8 +29,10 @@ import im.vector.app.features.call.webrtc.WebRtcCallManager import org.matrix.android.sdk.api.session.call.CallState import org.matrix.android.sdk.api.session.call.MxCall -class CallTransferViewModel @AssistedInject constructor(@Assisted initialState: CallTransferViewState, - private val callManager: WebRtcCallManager) : +class CallTransferViewModel @AssistedInject constructor( + @Assisted initialState: CallTransferViewState, + private val callManager: WebRtcCallManager +) : VectorViewModel(initialState) { @AssistedFactory diff --git a/vector/src/main/java/im/vector/app/features/call/webrtc/PeerConnectionObserver.kt b/vector/src/main/java/im/vector/app/features/call/webrtc/PeerConnectionObserver.kt index c776951f93..99c26c5ebe 100644 --- a/vector/src/main/java/im/vector/app/features/call/webrtc/PeerConnectionObserver.kt +++ b/vector/src/main/java/im/vector/app/features/call/webrtc/PeerConnectionObserver.kt @@ -37,13 +37,13 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * Every ICE transport used by the connection is either in use (state "connected" or "completed") * or is closed (state "closed"); in addition, at least one transport is either "connected" or "completed" */ - PeerConnection.PeerConnectionState.CONNECTED -> { + PeerConnection.PeerConnectionState.CONNECTED -> { webRtcCall.mxCall.state = CallState.Connected(MxPeerConnectionState.CONNECTED) } /** * One or more of the ICE transports on the connection is in the "failed" state. */ - PeerConnection.PeerConnectionState.FAILED -> { + PeerConnection.PeerConnectionState.FAILED -> { // This can be temporary, e.g when other ice not yet received... // webRtcCall.mxCall.state = CallState.ERROR webRtcCall.mxCall.state = CallState.Connected(MxPeerConnectionState.FAILED) @@ -58,7 +58,7 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * One or more of the ICE transports are currently in the process of establishing a connection; * that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state */ - PeerConnection.PeerConnectionState.CONNECTING -> { + PeerConnection.PeerConnectionState.CONNECTING -> { webRtcCall.mxCall.state = CallState.Connected(MxPeerConnectionState.CONNECTING) } /** @@ -66,7 +66,7 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * This value was in the RTCSignalingState enum (and therefore found by reading the value of the signalingState) * property until the May 13, 2016 draft of the specification. */ - PeerConnection.PeerConnectionState.CLOSED -> { + PeerConnection.PeerConnectionState.CLOSED -> { webRtcCall.mxCall.state = CallState.Connected(MxPeerConnectionState.CLOSED) } /** @@ -76,7 +76,7 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio PeerConnection.PeerConnectionState.DISCONNECTED -> { webRtcCall.mxCall.state = CallState.Connected(MxPeerConnectionState.DISCONNECTED) } - null -> { + null -> { } } } @@ -101,14 +101,14 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * the ICE agent is gathering addresses or is waiting to be given remote candidates through * calls to RTCPeerConnection.addIceCandidate() (or both). */ - PeerConnection.IceConnectionState.NEW -> { + PeerConnection.IceConnectionState.NEW -> { } /** * The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates * against one another to try to find a compatible match, but has not yet found a pair which will allow * the peer connection to be made. It's possible that gathering of candidates is also still underway. */ - PeerConnection.IceConnectionState.CHECKING -> { + PeerConnection.IceConnectionState.CHECKING -> { } /** @@ -117,7 +117,7 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking * candidates against one another looking for a better connection to use. */ - PeerConnection.IceConnectionState.CONNECTED -> { + PeerConnection.IceConnectionState.CONNECTED -> { } /** * Checks to ensure that components are still connected failed for at least one component of the RTCPeerConnection. @@ -131,18 +131,18 @@ class PeerConnectionObserver(private val webRtcCall: WebRtcCall) : PeerConnectio * compatible matches for all components of the connection. * It is, however, possible that the ICE agent did find compatible connections for some components. */ - PeerConnection.IceConnectionState.FAILED -> { + PeerConnection.IceConnectionState.FAILED -> { webRtcCall.onRenegotiationNeeded(restartIce = true) } /** * The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. */ - PeerConnection.IceConnectionState.COMPLETED -> { + PeerConnection.IceConnectionState.COMPLETED -> { } /** * The ICE agent for this RTCPeerConnection has shut down and is no longer handling requests. */ - PeerConnection.IceConnectionState.CLOSED -> { + PeerConnection.IceConnectionState.CLOSED -> { } } } diff --git a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt index b92316c292..79c3930c89 100644 --- a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt +++ b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt @@ -381,7 +381,7 @@ class WebRtcCall( localSurfaceRenderers.addIfNeeded(localViewRenderer) remoteSurfaceRenderers.addIfNeeded(remoteViewRenderer) when (mode) { - VectorCallActivity.INCOMING_ACCEPT -> { + VectorCallActivity.INCOMING_ACCEPT -> { internalAcceptIncomingCall() } VectorCallActivity.INCOMING_RINGING -> { @@ -391,7 +391,7 @@ class WebRtcCall( VectorCallActivity.OUTGOING_CREATED -> { setupOutgoingCall() } - else -> { + else -> { // sink existing tracks (configuration change, e.g screen rotation) attachViewRenderersInternal() } diff --git a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt index 5f50747d77..fa991501ea 100644 --- a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt +++ b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt @@ -273,7 +273,7 @@ class WebRtcCallManager @Inject constructor( // did we start background sync? so we should stop it if (isInBackground) { if (FcmHelper.isPushSupported()) { - currentSession?.stopAnyBackgroundSync() + currentSession?.syncService()?.stopAnyBackgroundSync() } else { // for fdroid we should not stop, it should continue syncing // maybe we should restore default timeout/delay though? @@ -380,7 +380,7 @@ class WebRtcCallManager @Inject constructor( if (isInBackground) { if (FcmHelper.isPushSupported()) { // only for push version as fdroid version is already doing it? - currentSession?.startAutomaticBackgroundSync(30, 0) + currentSession?.syncService()?.startAutomaticBackgroundSync(30, 0) } else { // Maybe increase sync freq? but how to set back to default values? } diff --git a/vector/src/main/java/im/vector/app/features/command/Command.kt b/vector/src/main/java/im/vector/app/features/command/Command.kt index 24b4ed5300..20c8f9d8fe 100644 --- a/vector/src/main/java/im/vector/app/features/command/Command.kt +++ b/vector/src/main/java/im/vector/app/features/command/Command.kt @@ -24,12 +24,14 @@ import im.vector.app.R * The user can write theses messages to perform some actions. * The list will be displayed in this order. */ -enum class Command(val command: String, - val aliases: Array?, - val parameters: String, - @StringRes val description: Int, - val isDevCommand: Boolean, - val isThreadCommand: Boolean) { +enum class Command( + val command: String, + val aliases: Array?, + val parameters: String, + @StringRes val description: Int, + val isDevCommand: Boolean, + val isThreadCommand: Boolean +) { EMOTE("/me", null, "", R.string.command_description_emote, false, true), BAN_USER("/ban", null, " [reason]", R.string.command_description_ban_user, false, false), UNBAN_USER("/unban", null, " [reason]", R.string.command_description_unban_user, false, false), diff --git a/vector/src/main/java/im/vector/app/features/command/CommandParser.kt b/vector/src/main/java/im/vector/app/features/command/CommandParser.kt index 17b8087601..1378321026 100644 --- a/vector/src/main/java/im/vector/app/features/command/CommandParser.kt +++ b/vector/src/main/java/im/vector/app/features/command/CommandParser.kt @@ -69,14 +69,14 @@ class CommandParser @Inject constructor() { } when { - Command.PLAIN.matches(slashCommand) -> { + Command.PLAIN.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.SendPlainText(message = message) } else { ParsedCommand.ErrorSyntax(Command.PLAIN) } } - Command.CHANGE_DISPLAY_NAME.matches(slashCommand) -> { + Command.CHANGE_DISPLAY_NAME.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.ChangeDisplayName(displayName = message) } else { @@ -90,7 +90,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.CHANGE_DISPLAY_NAME_FOR_ROOM) } } - Command.ROOM_AVATAR.matches(slashCommand) -> { + Command.ROOM_AVATAR.matches(slashCommand) -> { if (messageParts.size == 2) { val url = messageParts[1] @@ -103,7 +103,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.ROOM_AVATAR) } } - Command.CHANGE_AVATAR_FOR_ROOM.matches(slashCommand) -> { + Command.CHANGE_AVATAR_FOR_ROOM.matches(slashCommand) -> { if (messageParts.size == 2) { val url = messageParts[1] @@ -116,35 +116,35 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.CHANGE_AVATAR_FOR_ROOM) } } - Command.TOPIC.matches(slashCommand) -> { + Command.TOPIC.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.ChangeTopic(topic = message) } else { ParsedCommand.ErrorSyntax(Command.TOPIC) } } - Command.EMOTE.matches(slashCommand) -> { + Command.EMOTE.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.SendEmote(message) } else { ParsedCommand.ErrorSyntax(Command.EMOTE) } } - Command.RAINBOW.matches(slashCommand) -> { + Command.RAINBOW.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.SendRainbow(message) } else { ParsedCommand.ErrorSyntax(Command.RAINBOW) } } - Command.RAINBOW_EMOTE.matches(slashCommand) -> { + Command.RAINBOW_EMOTE.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.SendRainbowEmote(message) } else { ParsedCommand.ErrorSyntax(Command.RAINBOW_EMOTE) } } - Command.JOIN_ROOM.matches(slashCommand) -> { + Command.JOIN_ROOM.matches(slashCommand) -> { if (messageParts.size >= 2) { val roomAlias = messageParts[1] @@ -160,21 +160,21 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.JOIN_ROOM) } } - Command.PART.matches(slashCommand) -> { + Command.PART.matches(slashCommand) -> { when (messageParts.size) { - 1 -> ParsedCommand.PartRoom(null) - 2 -> ParsedCommand.PartRoom(messageParts[1]) + 1 -> ParsedCommand.PartRoom(null) + 2 -> ParsedCommand.PartRoom(messageParts[1]) else -> ParsedCommand.ErrorSyntax(Command.PART) } } - Command.ROOM_NAME.matches(slashCommand) -> { + Command.ROOM_NAME.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.ChangeRoomName(name = message) } else { ParsedCommand.ErrorSyntax(Command.ROOM_NAME) } } - Command.INVITE.matches(slashCommand) -> { + Command.INVITE.matches(slashCommand) -> { if (messageParts.size >= 2) { val userId = messageParts[1] @@ -185,13 +185,13 @@ class CommandParser @Inject constructor() { trimParts(textMessage, messageParts.take(2)) ) } - userId.isEmail() -> { + userId.isEmail() -> { ParsedCommand.Invite3Pid(ThreePid.Email(userId)) } - userId.isMsisdn() -> { + userId.isMsisdn() -> { ParsedCommand.Invite3Pid(ThreePid.Msisdn(userId)) } - else -> { + else -> { ParsedCommand.ErrorSyntax(Command.INVITE) } } @@ -199,7 +199,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.INVITE) } } - Command.REMOVE_USER.matches(slashCommand) -> { + Command.REMOVE_USER.matches(slashCommand) -> { if (messageParts.size >= 2) { val userId = messageParts[1] @@ -215,7 +215,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.REMOVE_USER) } } - Command.BAN_USER.matches(slashCommand) -> { + Command.BAN_USER.matches(slashCommand) -> { if (messageParts.size >= 2) { val userId = messageParts[1] @@ -231,7 +231,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.BAN_USER) } } - Command.UNBAN_USER.matches(slashCommand) -> { + Command.UNBAN_USER.matches(slashCommand) -> { if (messageParts.size >= 2) { val userId = messageParts[1] @@ -247,7 +247,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.UNBAN_USER) } } - Command.IGNORE_USER.matches(slashCommand) -> { + Command.IGNORE_USER.matches(slashCommand) -> { if (messageParts.size == 2) { val userId = messageParts[1] @@ -260,7 +260,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.IGNORE_USER) } } - Command.UNIGNORE_USER.matches(slashCommand) -> { + Command.UNIGNORE_USER.matches(slashCommand) -> { if (messageParts.size == 2) { val userId = messageParts[1] @@ -273,7 +273,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.UNIGNORE_USER) } } - Command.SET_USER_POWER_LEVEL.matches(slashCommand) -> { + Command.SET_USER_POWER_LEVEL.matches(slashCommand) -> { if (messageParts.size == 3) { val userId = messageParts[1] if (MatrixPatterns.isUserId(userId)) { @@ -293,7 +293,7 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.SET_USER_POWER_LEVEL) } } - Command.RESET_USER_POWER_LEVEL.matches(slashCommand) -> { + Command.RESET_USER_POWER_LEVEL.matches(slashCommand) -> { if (messageParts.size == 2) { val userId = messageParts[1] @@ -306,45 +306,45 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.SET_USER_POWER_LEVEL) } } - Command.MARKDOWN.matches(slashCommand) -> { + Command.MARKDOWN.matches(slashCommand) -> { if (messageParts.size == 2) { when { - "on".equals(messageParts[1], true) -> ParsedCommand.SetMarkdown(true) + "on".equals(messageParts[1], true) -> ParsedCommand.SetMarkdown(true) "off".equals(messageParts[1], true) -> ParsedCommand.SetMarkdown(false) - else -> ParsedCommand.ErrorSyntax(Command.MARKDOWN) + else -> ParsedCommand.ErrorSyntax(Command.MARKDOWN) } } else { ParsedCommand.ErrorSyntax(Command.MARKDOWN) } } - Command.CLEAR_SCALAR_TOKEN.matches(slashCommand) -> { + Command.CLEAR_SCALAR_TOKEN.matches(slashCommand) -> { if (messageParts.size == 1) { ParsedCommand.ClearScalarToken } else { ParsedCommand.ErrorSyntax(Command.CLEAR_SCALAR_TOKEN) } } - Command.SPOILER.matches(slashCommand) -> { + Command.SPOILER.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.SendSpoiler(message) } else { ParsedCommand.ErrorSyntax(Command.SPOILER) } } - Command.SHRUG.matches(slashCommand) -> { + Command.SHRUG.matches(slashCommand) -> { ParsedCommand.SendShrug(message) } - Command.LENNY.matches(slashCommand) -> { + Command.LENNY.matches(slashCommand) -> { ParsedCommand.SendLenny(message) } - Command.DISCARD_SESSION.matches(slashCommand) -> { + Command.DISCARD_SESSION.matches(slashCommand) -> { if (messageParts.size == 1) { ParsedCommand.DiscardSession } else { ParsedCommand.ErrorSyntax(Command.DISCARD_SESSION) } } - Command.WHOIS.matches(slashCommand) -> { + Command.WHOIS.matches(slashCommand) -> { if (messageParts.size == 2) { val userId = messageParts[1] @@ -357,13 +357,13 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.WHOIS) } } - Command.CONFETTI.matches(slashCommand) -> { + Command.CONFETTI.matches(slashCommand) -> { ParsedCommand.SendChatEffect(ChatEffect.CONFETTI, message) } - Command.SNOWFALL.matches(slashCommand) -> { + Command.SNOWFALL.matches(slashCommand) -> { ParsedCommand.SendChatEffect(ChatEffect.SNOWFALL, message) } - Command.CREATE_SPACE.matches(slashCommand) -> { + Command.CREATE_SPACE.matches(slashCommand) -> { if (messageParts.size >= 2) { ParsedCommand.CreateSpace( messageParts[1], @@ -373,31 +373,31 @@ class CommandParser @Inject constructor() { ParsedCommand.ErrorSyntax(Command.CREATE_SPACE) } } - Command.ADD_TO_SPACE.matches(slashCommand) -> { + Command.ADD_TO_SPACE.matches(slashCommand) -> { if (messageParts.size == 1) { ParsedCommand.AddToSpace(spaceId = message) } else { ParsedCommand.ErrorSyntax(Command.ADD_TO_SPACE) } } - Command.JOIN_SPACE.matches(slashCommand) -> { + Command.JOIN_SPACE.matches(slashCommand) -> { if (messageParts.size == 1) { ParsedCommand.JoinSpace(spaceIdOrAlias = message) } else { ParsedCommand.ErrorSyntax(Command.JOIN_SPACE) } } - Command.LEAVE_ROOM.matches(slashCommand) -> { + Command.LEAVE_ROOM.matches(slashCommand) -> { ParsedCommand.LeaveRoom(roomId = message) } - Command.UPGRADE_ROOM.matches(slashCommand) -> { + Command.UPGRADE_ROOM.matches(slashCommand) -> { if (message.isNotEmpty()) { ParsedCommand.UpgradeRoom(newVersion = message) } else { ParsedCommand.ErrorSyntax(Command.UPGRADE_ROOM) } } - else -> { + else -> { // Unknown command ParsedCommand.ErrorUnknownSlashCommand(slashCommand) } diff --git a/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt b/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt index 463954dff7..d2bb6b78b0 100644 --- a/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt +++ b/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt @@ -24,8 +24,10 @@ import im.vector.app.core.platform.Restorable import im.vector.app.features.webview.VectorWebViewActivity import im.vector.app.features.webview.WebViewMode -class ConsentNotGivenHelper(private val activity: Activity, - private val dialogLocker: DialogLocker) : +class ConsentNotGivenHelper( + private val activity: Activity, + private val dialogLocker: DialogLocker +) : Restorable by dialogLocker { /* ========================================================================================== diff --git a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookController.kt b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookController.kt index 219be0abeb..6113755159 100644 --- a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookController.kt +++ b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookController.kt @@ -35,7 +35,8 @@ import javax.inject.Inject class ContactsBookController @Inject constructor( private val stringProvider: StringProvider, private val avatarRenderer: AvatarRenderer, - private val errorFormatter: ErrorFormatter) : EpoxyController() { + private val errorFormatter: ErrorFormatter +) : EpoxyController() { private var state: ContactsBookViewState? = null @@ -50,9 +51,9 @@ class ContactsBookController @Inject constructor( val currentState = state ?: return when (val asyncMappedContacts = currentState.mappedContacts) { is Uninitialized -> renderEmptyState(false) - is Loading -> renderLoading() - is Success -> renderSuccess(currentState) - is Fail -> renderFailure(asyncMappedContacts.error) + is Loading -> renderLoading() + is Success -> renderSuccess(currentState) + is Fail -> renderFailure(asyncMappedContacts.error) } } diff --git a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookFragment.kt b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookFragment.kt index 7425e0ae8a..8cd7f2de45 100644 --- a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookFragment.kt +++ b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookFragment.kt @@ -70,7 +70,7 @@ class ContactsBookFragment @Inject constructor( .allowBack(useCross = true) contactsBookViewModel.observeViewEvents { when (it) { - is ContactsBookViewEvents.Failure -> showFailure(it.throwable) + is ContactsBookViewEvents.Failure -> showFailure(it.throwable) is ContactsBookViewEvents.OnPoliciesRetrieved -> showConsentDialog(it) } } diff --git a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookViewModel.kt b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookViewModel.kt index d016558764..402fc40c9a 100644 --- a/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/contactsbook/ContactsBookViewModel.kt @@ -160,10 +160,10 @@ class ContactsBookViewModel @AssistedInject constructor( override fun handle(action: ContactsBookAction) { when (action) { - is ContactsBookAction.FilterWith -> handleFilterWith(action) + is ContactsBookAction.FilterWith -> handleFilterWith(action) is ContactsBookAction.OnlyBoundContacts -> handleOnlyBoundContacts(action) - ContactsBookAction.UserConsentGranted -> handleUserConsentGranted() - ContactsBookAction.UserConsentRequest -> handleUserConsentRequest() + ContactsBookAction.UserConsentGranted -> handleUserConsentGranted() + ContactsBookAction.UserConsentRequest -> handleUserConsentRequest() } } diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt index 25fee28123..6292217b67 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt @@ -79,11 +79,11 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { .stream() .onEach { action -> when (action) { - UserListSharedAction.Close -> finish() - UserListSharedAction.GoBack -> onBackPressed() + UserListSharedAction.Close -> finish() + UserListSharedAction.GoBack -> onBackPressed() is UserListSharedAction.OnMenuItemSelected -> onMenuItemSelected(action) - UserListSharedAction.OpenPhoneBook -> openPhoneBook() - UserListSharedAction.AddByQrCode -> openAddByQrCode() + UserListSharedAction.OpenPhoneBook -> openPhoneBook() + UserListSharedAction.AddByQrCode -> openAddByQrCode() } } .launchIn(lifecycleScope) @@ -107,7 +107,7 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { Toast.makeText(this, R.string.invalid_qr_code_uri, Toast.LENGTH_SHORT).show() finish() } - CreateDirectRoomViewEvents.DmSelf -> { + CreateDirectRoomViewEvents.DmSelf -> { Toast.makeText(this, R.string.cannot_dm_self, Toast.LENGTH_SHORT).show() finish() } @@ -116,14 +116,14 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { qrViewModel.observeViewEvents { when (it) { - is QrCodeScannerEvents.CodeParsed -> { + is QrCodeScannerEvents.CodeParsed -> { viewModel.handle(CreateDirectRoomAction.QrScannedAction(it.result)) } is QrCodeScannerEvents.ParseFailed -> { Toast.makeText(this, R.string.qr_code_not_scanned, Toast.LENGTH_SHORT).show() finish() } - else -> Unit + else -> Unit } } } @@ -169,8 +169,8 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { when (state) { is Loading -> renderCreationLoading() is Success -> renderCreationSuccess(state()) - is Fail -> renderCreationFailure(state.error) - else -> Unit + is Fail -> renderCreationFailure(state.error) + else -> Unit } } @@ -181,7 +181,7 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { private fun renderCreationFailure(error: Throwable) { hideWaitingView() when (error) { - is CreateRoomFailure.CreatedWithTimeout -> { + is CreateRoomFailure.CreatedWithTimeout -> { finish() } is CreateRoomFailure.CreatedWithFederationFailure -> { @@ -191,7 +191,7 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { .setPositiveButton(R.string.ok) { _, _ -> finish() } .show() } - else -> { + else -> { val message = if (error is Failure.ServerError && error.httpCode == HttpURLConnection.HTTP_INTERNAL_ERROR /*500*/) { // This error happen if the invited userId does not exist. getString(R.string.create_room_dm_failure) diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt index a507f0d099..8374f9d513 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt @@ -60,7 +60,7 @@ class CreateDirectRoomViewModel @AssistedInject constructor( override fun handle(action: CreateDirectRoomAction) { when (action) { is CreateDirectRoomAction.CreateRoomAndInviteSelectedUsers -> onSubmitInvitees(action.selections) - is CreateDirectRoomAction.QrScannedAction -> onCodeParsed(action) + is CreateDirectRoomAction.QrScannedAction -> onCodeParsed(action) } } @@ -115,7 +115,7 @@ class CreateDirectRoomViewModel @AssistedInject constructor( .apply { selections.forEach { when (it) { - is PendingSelection.UserPendingSelection -> invitedUserIds.add(it.user.userId) + is PendingSelection.UserPendingSelection -> invitedUserIds.add(it.user.userId) is PendingSelection.ThreePidPendingSelection -> invite3pids.add(it.threePid) } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt index f5346980cb..4b3a657740 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt @@ -45,7 +45,7 @@ class KeysExporter @Inject constructor( private fun verifyExportedKeysOutputFileSize(uri: Uri, expectedSize: Long) { val output = context.contentResolver.openFileDescriptor(uri, "r", null) when { - output == null -> throw IllegalStateException("Exported file not found") + output == null -> throw IllegalStateException("Exported file not found") output.statSize != expectedSize -> { throw UnexpectedExportKeysFileSizeException( expectedFileSize = expectedSize, diff --git a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt index 4b27111851..b360055bc9 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt @@ -33,9 +33,11 @@ class KeysImporter @Inject constructor( /** * Import keys from provided Uri. */ - suspend fun import(uri: Uri, - mimetype: String?, - password: String): ImportRoomKeysResult { + suspend fun import( + uri: Uri, + mimetype: String?, + password: String + ): ImportRoomKeysResult { return withContext(Dispatchers.IO) { val resource = openResource(context, uri, mimetype ?: getMimeTypeFromUri(context, uri)) val stream = resource?.mContentStream ?: throw Exception("Error") diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt index a32cd7caa7..3089481255 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt @@ -93,16 +93,16 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { KeysBackupRestoreSharedViewModel.NAVIGATE_TO_RECOVER_WITH_KEY -> { addFragmentToBackstack(views.container, KeysBackupRestoreFromKeyFragment::class.java, allowStateLoss = true) } - KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> { + KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> { viewModel.keyVersionResult.value?.version?.let { KeysBackupBanner.onRecoverDoneForVersion(this, it) } replaceFragment(views.container, KeysBackupRestoreSuccessFragment::class.java, allowStateLoss = true) } - KeysBackupRestoreSharedViewModel.NAVIGATE_TO_4S -> { + KeysBackupRestoreSharedViewModel.NAVIGATE_TO_4S -> { launch4SActivity() } - KeysBackupRestoreSharedViewModel.NAVIGATE_FAILED_TO_LOAD_4S -> { + KeysBackupRestoreSharedViewModel.NAVIGATE_FAILED_TO_LOAD_4S -> { MaterialAlertDialogBuilder(this) .setTitle(R.string.unknown_error) .setMessage(R.string.error_failed_to_import_keys) diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt index a8c3f41efe..df24666285 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt @@ -83,7 +83,7 @@ class KeysBackupRestoreSharedViewModel @Inject constructor( val progressObserver = object : StepProgressListener { override fun onStepProgress(step: StepProgressListener.Step) { when (step) { - is StepProgressListener.Step.ComputingKey -> { + is StepProgressListener.Step.ComputingKey -> { loadingEvent.postValue( WaitingViewData( stringProvider.getString(R.string.keys_backup_restoring_waiting_message) + @@ -102,7 +102,7 @@ class KeysBackupRestoreSharedViewModel @Inject constructor( ) ) } - is StepProgressListener.Step.ImportingKey -> { + is StepProgressListener.Step.ImportingKey -> { Timber.d("backupKeys.ImportingKey.progress: ${step.progress}") // Progress 0 can take a while, display an indeterminate progress in this case if (step.progress == 0) { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt index e58746193b..aabd05d913 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt @@ -71,7 +71,7 @@ class KeysBackupManageActivity : SimpleFragmentActivity() { // Observe the deletion of keys backup viewModel.onEach(KeysBackupSettingViewState::deleteBackupRequest) { asyncDelete -> when (asyncDelete) { - is Fail -> { + is Fail -> { updateWaitingView(null) MaterialAlertDialogBuilder(this) @@ -84,7 +84,7 @@ class KeysBackupManageActivity : SimpleFragmentActivity() { is Loading -> { updateWaitingView(WaitingViewData(getString(R.string.keys_backup_settings_deleting_backup))) } - else -> { + else -> { updateWaitingView(null) } } @@ -92,7 +92,7 @@ class KeysBackupManageActivity : SimpleFragmentActivity() { viewModel.observeViewEvents { when (it) { - KeysBackupViewEvents.OpenLegacyCreateBackup -> { + KeysBackupViewEvents.OpenLegacyCreateBackup -> { startActivity(KeysBackupSetupActivity.intent(this, false)) } is KeysBackupViewEvents.RequestStore4SSecret -> { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingViewState.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingViewState.kt index 7c1105277b..8d43b72ad9 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingViewState.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingViewState.kt @@ -23,8 +23,10 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrust import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersionResult -data class KeysBackupSettingViewState(val keysBackupVersionTrust: Async = Uninitialized, - val keysBackupState: KeysBackupState? = null, - val keysBackupVersion: KeysVersionResult? = null, - val deleteBackupRequest: Async = Uninitialized) : +data class KeysBackupSettingViewState( + val keysBackupVersionTrust: Async = Uninitialized, + val keysBackupState: KeysBackupState? = null, + val keysBackupVersion: KeysVersionResult? = null, + val deleteBackupRequest: Async = Uninitialized +) : MavericksState diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt index d13b97a9ba..477684df8d 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt @@ -57,7 +57,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( val keyVersionResult = data.keysBackupVersion when (keyBackupState) { - KeysBackupState.Unknown -> { + KeysBackupState.Unknown -> { errorWithRetryItem { id("summary") text(host.stringProvider.getString(R.string.keys_backup_unable_to_get_keys_backup_data)) @@ -73,7 +73,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( loadingText(host.stringProvider.getString(R.string.keys_backup_settings_checking_backup_state)) } } - KeysBackupState.Disabled -> { + KeysBackupState.Disabled -> { genericItem { id("summary") title(host.stringProvider.getString(R.string.keys_backup_settings_status_not_setup).toEpoxyCharSequence()) @@ -88,7 +88,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( } KeysBackupState.WrongBackUpVersion, KeysBackupState.NotTrusted, - KeysBackupState.Enabling -> { + KeysBackupState.Enabling -> { genericItem { id("summary") title(host.stringProvider.getString(R.string.keys_backup_settings_status_ko).toEpoxyCharSequence()) @@ -103,7 +103,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( isBackupAlreadySetup = true } - KeysBackupState.ReadyToBackUp -> { + KeysBackupState.ReadyToBackUp -> { genericItem { id("summary") title(host.stringProvider.getString(R.string.keys_backup_settings_status_ok).toEpoxyCharSequence()) @@ -119,7 +119,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( isBackupAlreadySetup = true } KeysBackupState.WillBackUp, - KeysBackupState.BackingUp -> { + KeysBackupState.BackingUp -> { genericItem { id("summary") title(host.stringProvider.getString(R.string.keys_backup_settings_status_ok).toEpoxyCharSequence()) @@ -144,7 +144,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( isBackupAlreadySetup = true } - null -> Unit + null -> Unit } if (isBackupAlreadySetup) { @@ -187,12 +187,12 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( val host = this when (keysVersionTrust) { is Uninitialized -> Unit - is Loading -> { + is Loading -> { loadingItem { id("trust") } } - is Success -> { + is Success -> { keysVersionTrust() .signatures .filterIsInstance() @@ -293,7 +293,7 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( } } // end for each } - is Fail -> { + is Fail -> { errorWithRetryItem { id("trust") text(host.stringProvider.getString(R.string.keys_backup_unable_to_get_trust_info)) diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt index dea481dbad..3c0d47c79c 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt @@ -41,8 +41,9 @@ import org.matrix.android.sdk.api.util.awaitCallback import org.matrix.android.sdk.api.util.toBase64NoPadding import timber.log.Timber -class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialState: KeysBackupSettingViewState, - private val session: Session +class KeysBackupSettingsViewModel @AssistedInject constructor( + @Assisted initialState: KeysBackupSettingViewState, + private val session: Session ) : VectorViewModel(initialState), KeysBackupStateListener { @@ -70,14 +71,14 @@ class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialS override fun handle(action: KeyBackupSettingsAction) { when (action) { - KeyBackupSettingsAction.Init -> init() - KeyBackupSettingsAction.GetKeyBackupTrust -> getKeysBackupTrust() - KeyBackupSettingsAction.DeleteKeyBackup -> deleteCurrentBackup() - KeyBackupSettingsAction.SetUpKeyBackup -> viewModelScope.launch { + KeyBackupSettingsAction.Init -> init() + KeyBackupSettingsAction.GetKeyBackupTrust -> getKeysBackupTrust() + KeyBackupSettingsAction.DeleteKeyBackup -> deleteCurrentBackup() + KeyBackupSettingsAction.SetUpKeyBackup -> viewModelScope.launch { setUpKeyBackup() } KeyBackupSettingsAction.StoreIn4SReset, - KeyBackupSettingsAction.StoreIn4SFailure -> { + KeyBackupSettingsAction.StoreIn4SFailure -> { pendingBackupCreationInfo = null // nothing to do just stay on fragment } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupActivity.kt index 0db06209fe..7478adb165 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupActivity.kt @@ -78,15 +78,15 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() { viewModel.navigateEvent.observeEvent(this) { uxStateEvent -> when (uxStateEvent) { - KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_2 -> { + KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_2 -> { supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) replaceFragment(views.container, KeysBackupSetupStep2Fragment::class.java) } - KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_3 -> { + KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_3 -> { supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) replaceFragment(views.container, KeysBackupSetupStep3Fragment::class.java) } - KeysBackupSetupSharedViewModel.NAVIGATE_FINISH -> { + KeysBackupSetupSharedViewModel.NAVIGATE_FINISH -> { val resultIntent = Intent() viewModel.keysVersion.value?.version?.let { resultIntent.putExtra(KEYS_VERSION, it) @@ -105,7 +105,7 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() { } .show() } - KeysBackupSetupSharedViewModel.NAVIGATE_MANUAL_EXPORT -> { + KeysBackupSetupSharedViewModel.NAVIGATE_MANUAL_EXPORT -> { queryExportKeys(session.myUserId, saveStartForActivityResult) } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupStep2Fragment.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupStep2Fragment.kt index 6ccfa0911c..706076dae0 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupStep2Fragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/setup/KeysBackupSetupStep2Fragment.kt @@ -137,16 +137,16 @@ class KeysBackupSetupStep2Fragment @Inject constructor() : VectorBaseFragment { + viewModel.passphrase.value.isNullOrEmpty() -> { viewModel.passphraseError.value = context?.getString(R.string.passphrase_empty_error_message) } viewModel.passphrase.value != viewModel.confirmPassphrase.value -> { viewModel.confirmPassphraseError.value = context?.getString(R.string.passphrase_passphrase_does_not_match) } - viewModel.passwordStrength.value?.score ?: 0 < 4 -> { + viewModel.passwordStrength.value?.score ?: 0 < 4 -> { viewModel.passphraseError.value = context?.getString(R.string.passphrase_passphrase_too_weak) } - else -> { + else -> { viewModel.megolmBackupCreationInfo = null // Ensure passphrase is hidden during the process @@ -168,7 +168,7 @@ class KeysBackupSetupStep2Fragment @Inject constructor() : VectorBaseFragment { + else -> { // User has entered a passphrase but want to skip this step. viewModel.passphraseError.value = context?.getString(R.string.keys_backup_passphrase_not_empty_error_message) } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt index 034c667aac..b234b3109b 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt @@ -143,12 +143,14 @@ class KeyRequestHandler @Inject constructor( }) } - private fun postAlert(context: Context, - userId: String, - deviceId: String, - wasNewDevice: Boolean, - deviceInfo: CryptoDeviceInfo?, - moreInfo: DeviceInfo? = null) { + private fun postAlert( + context: Context, + userId: String, + deviceId: String, + wasNewDevice: Boolean, + deviceInfo: CryptoDeviceInfo?, + moreInfo: DeviceInfo? = null + ) { val deviceName = if (deviceInfo!!.displayName().isNullOrEmpty()) deviceInfo.deviceId else deviceInfo.displayName() val dialogText: String? diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt index 2018a5b053..5396ce908e 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt @@ -19,6 +19,7 @@ package im.vector.app.features.crypto.keysrequest enum class OutboundSessionKeySharingStrategy { /** * Keys will be sent for the first time when the first message is sent. + * This is handled by the Matrix SDK so there's no need to do it in Vector. */ WhenSendingEvent, diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt index 40ad2859fe..b39992256d 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt @@ -81,8 +81,8 @@ class SharedSecureStorageActivity : val fragment = when (state.step) { SharedSecureStorageViewState.Step.EnterPassphrase -> SharedSecuredStoragePassphraseFragment::class - SharedSecureStorageViewState.Step.EnterKey -> SharedSecuredStorageKeyFragment::class - SharedSecureStorageViewState.Step.ResetAll -> SharedSecuredStorageResetAllFragment::class + SharedSecureStorageViewState.Step.EnterKey -> SharedSecuredStorageKeyFragment::class + SharedSecureStorageViewState.Step.ResetAll -> SharedSecuredStorageResetAllFragment::class } showFragment(fragment) @@ -90,10 +90,10 @@ class SharedSecureStorageActivity : private fun observeViewEvents(it: SharedSecureStorageViewEvent?) { when (it) { - is SharedSecureStorageViewEvent.Dismiss -> { + is SharedSecureStorageViewEvent.Dismiss -> { finish() } - is SharedSecureStorageViewEvent.Error -> { + is SharedSecureStorageViewEvent.Error -> { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.dialog_title_error)) .setMessage(it.message) @@ -105,16 +105,16 @@ class SharedSecureStorageActivity : } .show() } - is SharedSecureStorageViewEvent.ShowModalLoading -> { + is SharedSecureStorageViewEvent.ShowModalLoading -> { showWaitingView() } - is SharedSecureStorageViewEvent.HideModalLoading -> { + is SharedSecureStorageViewEvent.HideModalLoading -> { hideWaitingView() } - is SharedSecureStorageViewEvent.UpdateLoadingState -> { + is SharedSecureStorageViewEvent.UpdateLoadingState -> { updateWaitingView(it.waitingData) } - is SharedSecureStorageViewEvent.FinishSuccess -> { + is SharedSecureStorageViewEvent.FinishSuccess -> { val dataResult = Intent() dataResult.putExtra(EXTRA_DATA_RESULT, it.cypherResult) setResult(RESULT_OK, dataResult) @@ -123,7 +123,7 @@ class SharedSecureStorageActivity : is SharedSecureStorageViewEvent.ShowResetBottomSheet -> { navigator.open4SSetup(this, SetupMode.HARD_RESET) } - else -> Unit + else -> Unit } } @@ -149,10 +149,12 @@ class SharedSecureStorageActivity : const val EXTRA_DATA_RESET = "EXTRA_DATA_RESET" const val DEFAULT_RESULT_KEYSTORE_ALIAS = "SharedSecureStorageActivity" - fun newReadIntent(context: Context, - keyId: String? = null, - requestedSecrets: List, - resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { + fun newReadIntent( + context: Context, + keyId: String? = null, + requestedSecrets: List, + resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS + ): Intent { require(requestedSecrets.isNotEmpty()) return Intent(context, SharedSecureStorageActivity::class.java).also { it.putExtra( @@ -166,10 +168,12 @@ class SharedSecureStorageActivity : } } - fun newWriteIntent(context: Context, - keyId: String? = null, - writeSecrets: List>, - resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { + fun newWriteIntent( + context: Context, + keyId: String? = null, + writeSecrets: List>, + resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS + ): Intent { require(writeSecrets.isNotEmpty()) return Intent(context, SharedSecureStorageActivity::class.java).also { it.putExtra( diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt index 649890cda9..48679f6dbe 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt @@ -86,7 +86,8 @@ data class SharedSecureStorageViewState( class SharedSecureStorageViewModel @AssistedInject constructor( @Assisted private val initialState: SharedSecureStorageViewState, private val stringProvider: StringProvider, - private val session: Session) : + private val session: Session +) : VectorViewModel(initialState) { @AssistedFactory @@ -148,13 +149,13 @@ class SharedSecureStorageViewModel @AssistedInject constructor( override fun handle(action: SharedSecureStorageAction) = withState { when (action) { - is SharedSecureStorageAction.Cancel -> handleCancel() + is SharedSecureStorageAction.Cancel -> handleCancel() is SharedSecureStorageAction.SubmitPassphrase -> handleSubmitPassphrase(action) - SharedSecureStorageAction.UseKey -> handleUseKey() - is SharedSecureStorageAction.SubmitKey -> handleSubmitKey(action) - SharedSecureStorageAction.Back -> handleBack() - SharedSecureStorageAction.ForgotResetAll -> handleResetAll() - SharedSecureStorageAction.DoResetAll -> handleDoResetAll() + SharedSecureStorageAction.UseKey -> handleUseKey() + is SharedSecureStorageAction.SubmitKey -> handleSubmitKey(action) + SharedSecureStorageAction.Back -> handleBack() + SharedSecureStorageAction.ForgotResetAll -> handleResetAll() + SharedSecureStorageAction.DoResetAll -> handleDoResetAll() } } @@ -206,7 +207,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor( ) } } - else -> { + else -> { _viewEvents.post(SharedSecureStorageViewEvent.Dismiss) } } @@ -262,7 +263,7 @@ class SharedSecureStorageViewModel @AssistedInject constructor( private suspend fun performRequest(keyInfo: KeyInfo, keySpec: RawBytesKeySpec, decryptedSecretMap: HashMap) { when (val requestType = initialState.requestType) { - is RequestType.ReadSecrets -> { + is RequestType.ReadSecrets -> { requestType.secretsName.forEach { if (session.accountDataService().getUserAccountDataEvent(it) != null) { val res = session.sharedSecretStorageService().getSecret( diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStorageKeyFragment.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStorageKeyFragment.kt index fd660367ae..5a7aba65a5 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStorageKeyFragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStorageKeyFragment.kt @@ -77,7 +77,7 @@ class SharedSecuredStorageKeyFragment @Inject constructor() : VectorBaseFragment is SharedSecureStorageViewEvent.KeyInlineError -> { views.ssssKeyEnterTil.error = it.message } - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStoragePassphraseFragment.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStoragePassphraseFragment.kt index 41507f2722..5af5480573 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStoragePassphraseFragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecuredStoragePassphraseFragment.kt @@ -86,7 +86,7 @@ class SharedSecuredStoragePassphraseFragment @Inject constructor( is SharedSecureStorageViewEvent.InlineError -> { views.ssssPassphraseEnterTil.error = it.message } - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt index 5d866c7220..b5300ef700 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt @@ -122,7 +122,7 @@ class BackupToQuadSMigrationTask @Inject constructor( } ) } - params.recoveryKey != null -> { + params.recoveryKey != null -> { reportProgress(params, R.string.bootstrap_progress_generating_ssss_recovery) quadS.generateKey( UUID.randomUUID().toString(), @@ -131,7 +131,7 @@ class BackupToQuadSMigrationTask @Inject constructor( EmptyKeySigner() ) } - else -> { + else -> { return Result.IllegalParams } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapBottomSheet.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapBottomSheet.kt index b8d168cca5..be02737ef8 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapBottomSheet.kt @@ -64,14 +64,14 @@ class BootstrapBottomSheet : VectorBaseBottomSheetDialogFragment if (activityResult.resultCode == Activity.RESULT_OK) { when (activityResult.data?.extras?.getString(ReAuthActivity.RESULT_FLOW_TYPE)) { - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { viewModel.handle(BootstrapActions.SsoAuthDone) } LoginFlowTypes.PASSWORD -> { val password = activityResult.data?.extras?.getString(ReAuthActivity.RESULT_VALUE) ?: "" viewModel.handle(BootstrapActions.PasswordAuthDone(password)) } - else -> { + else -> { viewModel.handle(BootstrapActions.ReAuthCancelled) } } @@ -84,11 +84,11 @@ class BootstrapBottomSheet : VectorBaseBottomSheetDialogFragment when (event) { - is BootstrapViewEvents.Dismiss -> { + is BootstrapViewEvents.Dismiss -> { bottomSheetResult = if (event.success) ResultListener.RESULT_OK else ResultListener.RESULT_CANCEL dismiss() } - is BootstrapViewEvents.ModalError -> { + is BootstrapViewEvents.ModalError -> { MaterialAlertDialogBuilder(requireActivity()) .setTitle(R.string.dialog_title_error) .setMessage(event.error) @@ -153,47 +153,47 @@ class BootstrapBottomSheet : VectorBaseBottomSheetDialogFragment when (state.step) { - is BootstrapStep.CheckingMigration -> { + is BootstrapStep.CheckingMigration -> { views.bootstrapIcon.isVisible = false views.bootstrapTitleText.text = getString(R.string.bottom_sheet_setup_secure_backup_title) showFragment(BootstrapWaitingFragment::class) } - is BootstrapStep.FirstForm -> { + is BootstrapStep.FirstForm -> { views.bootstrapIcon.isVisible = false views.bootstrapTitleText.text = getString(R.string.bottom_sheet_setup_secure_backup_title) showFragment(BootstrapSetupRecoveryKeyFragment::class) } - is BootstrapStep.SetupPassphrase -> { + is BootstrapStep.SetupPassphrase -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_security_phrase_24dp)) views.bootstrapTitleText.text = getString(R.string.set_a_security_phrase_title) showFragment(BootstrapEnterPassphraseFragment::class) } - is BootstrapStep.ConfirmPassphrase -> { + is BootstrapStep.ConfirmPassphrase -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_security_phrase_24dp)) views.bootstrapTitleText.text = getString(R.string.set_a_security_phrase_title) showFragment(BootstrapConfirmPassphraseFragment::class) } - is BootstrapStep.AccountReAuth -> { + is BootstrapStep.AccountReAuth -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_user)) views.bootstrapTitleText.text = getString(R.string.re_authentication_activity_title) showFragment(BootstrapReAuthFragment::class) } - is BootstrapStep.Initializing -> { + is BootstrapStep.Initializing -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_security_key_24dp)) views.bootstrapTitleText.text = getString(R.string.bootstrap_loading_title) showFragment(BootstrapWaitingFragment::class) } - is BootstrapStep.SaveRecoveryKey -> { + is BootstrapStep.SaveRecoveryKey -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_security_key_24dp)) views.bootstrapTitleText.text = getString(R.string.bottom_sheet_save_your_recovery_key_title) showFragment(BootstrapSaveRecoveryKeyFragment::class) } - is BootstrapStep.DoneSuccess -> { + is BootstrapStep.DoneSuccess -> { views.bootstrapIcon.isVisible = true views.bootstrapIcon.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_security_key_24dp)) views.bootstrapTitleText.text = getString(R.string.bootstrap_finish_title) diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapConfirmPassphraseFragment.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapConfirmPassphraseFragment.kt index 7920ab3b96..3c8137d087 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapConfirmPassphraseFragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapConfirmPassphraseFragment.kt @@ -92,11 +92,11 @@ class BootstrapConfirmPassphraseFragment @Inject constructor() : } val passphrase = views.ssssPassphraseEnterEdittext.text?.toString() when { - passphrase.isNullOrBlank() -> + passphrase.isNullOrBlank() -> views.ssssPassphraseEnterTil.error = getString(R.string.passphrase_empty_error_message) passphrase != state.passphrase -> views.ssssPassphraseEnterTil.error = getString(R.string.passphrase_passphrase_does_not_match) - else -> { + else -> { view?.hideKeyboard() sharedViewModel.handle(BootstrapActions.DoInitialize(passphrase)) } diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapSharedViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapSharedViewModel.kt index 15ea90ae0a..7c88c20d4a 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapSharedViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapSharedViewModel.kt @@ -108,13 +108,13 @@ class BootstrapSharedViewModel @AssistedInject constructor( when (initialState.setupMode) { SetupMode.PASSPHRASE_RESET, SetupMode.PASSPHRASE_AND_NEEDED_SECRETS_RESET, - SetupMode.HARD_RESET -> { + SetupMode.HARD_RESET -> { setState { copy( step = BootstrapStep.FirstForm( - keyBackUpExist = false, - reset = session.sharedSecretStorageService().isRecoverySetup(), - methods = this.secureBackupMethod + keyBackUpExist = false, + reset = session.sharedSecretStorageService().isRecoverySetup(), + methods = this.secureBackupMethod ) ) } @@ -125,7 +125,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( copy(step = BootstrapStep.AccountReAuth()) } } - SetupMode.NORMAL -> { + SetupMode.NORMAL -> { // need to check if user have an existing keybackup setState { copy(step = BootstrapStep.CheckingMigration) @@ -177,14 +177,14 @@ class BootstrapSharedViewModel @AssistedInject constructor( override fun handle(action: BootstrapActions) = withState { state -> when (action) { - is BootstrapActions.GoBack -> queryBack() - BootstrapActions.StartKeyBackupMigration -> { + is BootstrapActions.GoBack -> queryBack() + BootstrapActions.StartKeyBackupMigration -> { handleStartMigratingKeyBackup() } - is BootstrapActions.Start -> { + is BootstrapActions.Start -> { handleStart(action) } - is BootstrapActions.UpdateCandidatePassphrase -> { + is BootstrapActions.UpdateCandidatePassphrase -> { val strength = zxcvbn.measure(action.pass) setState { copy( @@ -193,7 +193,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( ) } } - is BootstrapActions.GoToConfirmPassphrase -> { + is BootstrapActions.GoToConfirmPassphrase -> { setState { copy( passphrase = action.passphrase, @@ -208,7 +208,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( ) } } - is BootstrapActions.DoInitialize -> { + is BootstrapActions.DoInitialize -> { if (state.passphrase == state.passphraseRepeat) { startInitializeFlow(state) } else { @@ -219,42 +219,42 @@ class BootstrapSharedViewModel @AssistedInject constructor( } } } - is BootstrapActions.DoInitializeGeneratedKey -> { + is BootstrapActions.DoInitializeGeneratedKey -> { startInitializeFlow(state) } - BootstrapActions.RecoveryKeySaved -> { + BootstrapActions.RecoveryKeySaved -> { _viewEvents.post(BootstrapViewEvents.RecoveryKeySaved) setState { copy(step = BootstrapStep.SaveRecoveryKey(true)) } } - BootstrapActions.Completed -> { + BootstrapActions.Completed -> { _viewEvents.post(BootstrapViewEvents.Dismiss(true)) } - BootstrapActions.GoToCompleted -> { + BootstrapActions.GoToCompleted -> { setState { copy(step = BootstrapStep.DoneSuccess) } } - BootstrapActions.SaveReqQueryStarted -> { + BootstrapActions.SaveReqQueryStarted -> { setState { copy(recoverySaveFileProcess = Loading()) } } - is BootstrapActions.SaveKeyToUri -> { + is BootstrapActions.SaveKeyToUri -> { saveRecoveryKeyToUri(action.os) } - BootstrapActions.SaveReqFailed -> { + BootstrapActions.SaveReqFailed -> { setState { copy(recoverySaveFileProcess = Uninitialized) } } - BootstrapActions.GoToEnterAccountPassword -> { + BootstrapActions.GoToEnterAccountPassword -> { setState { copy(step = BootstrapStep.AccountReAuth()) } } - BootstrapActions.HandleForgotBackupPassphrase -> { + BootstrapActions.HandleForgotBackupPassphrase -> { if (state.step is BootstrapStep.GetBackupSecretPassForMigration) { setState { copy(step = BootstrapStep.GetBackupSecretPassForMigration(true)) @@ -264,16 +264,16 @@ class BootstrapSharedViewModel @AssistedInject constructor( // is BootstrapActions.ReAuth -> { // startInitializeFlow(action.pass) // } - is BootstrapActions.DoMigrateWithPassphrase -> { + is BootstrapActions.DoMigrateWithPassphrase -> { startMigrationFlow(state.step, action.passphrase, null) } - is BootstrapActions.DoMigrateWithRecoveryKey -> { + is BootstrapActions.DoMigrateWithRecoveryKey -> { startMigrationFlow(state.step, null, action.recoveryKey) } - BootstrapActions.SsoAuthDone -> { + BootstrapActions.SsoAuthDone -> { uiaContinuation?.resume(DefaultBaseAuth(session = pendingAuth?.session ?: "")) } - is BootstrapActions.PasswordAuthDone -> { + is BootstrapActions.PasswordAuthDone -> { val decryptedPass = session.secureStorageService() .loadSecureSecret(action.password.fromBase64().inputStream(), ReAuthActivity.DEFAULT_RESULT_KEYSTORE_ALIAS) uiaContinuation?.resume( @@ -284,7 +284,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( ) ) } - BootstrapActions.ReAuthCancelled -> { + BootstrapActions.ReAuthCancelled -> { setState { copy(step = BootstrapStep.AccountReAuth(stringProvider.getString(R.string.authentication_error))) } @@ -414,7 +414,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( } _viewEvents.post(BootstrapViewEvents.RequestReAuth(flowResponse, errCode)) } - LoginFlowTypes.SSO -> { + LoginFlowTypes.SSO -> { pendingAuth = DefaultBaseAuth(flowResponse.session) uiaContinuation = promise setState { @@ -424,7 +424,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( } _viewEvents.post(BootstrapViewEvents.RequestReAuth(flowResponse, errCode)) } - else -> { + else -> { promise.resumeWithException(UnsupportedOperationException()) } } @@ -447,7 +447,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( is BootstrapResult.SuccessCrossSigningOnly -> { _viewEvents.post(BootstrapViewEvents.Dismiss(true)) } - is BootstrapResult.Success -> { + is BootstrapResult.Success -> { val isSecureBackupRequired = state.isSecureBackupRequired val secureBackupMethod = state.secureBackupMethod @@ -466,7 +466,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( } } } - is BootstrapResult.InvalidPasswordError -> { + is BootstrapResult.InvalidPasswordError -> { // it's a bad password / auth setState { copy( @@ -474,7 +474,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( ) } } - is BootstrapResult.Failure -> { + is BootstrapResult.Failure -> { if (bootstrapResult is BootstrapResult.GenericError && bootstrapResult.failure is Failure.OtherServerError && bootstrapResult.failure.httpCode == 401) { @@ -523,7 +523,7 @@ class BootstrapSharedViewModel @AssistedInject constructor( } } } - is BootstrapStep.SetupPassphrase -> { + is BootstrapStep.SetupPassphrase -> { setState { copy( step = BootstrapStep.FirstForm(keyBackUpExist = doesKeyBackupExist, methods = this.secureBackupMethod), @@ -533,14 +533,14 @@ class BootstrapSharedViewModel @AssistedInject constructor( ) } } - is BootstrapStep.ConfirmPassphrase -> { + is BootstrapStep.ConfirmPassphrase -> { setState { copy( step = BootstrapStep.SetupPassphrase ) } } - is BootstrapStep.AccountReAuth -> { + is BootstrapStep.AccountReAuth -> { if (state.canLeave) { _viewEvents.post(BootstrapViewEvents.SkipBootstrap(state.passphrase != null)) } else { @@ -555,29 +555,29 @@ class BootstrapSharedViewModel @AssistedInject constructor( } } } - BootstrapStep.Initializing -> { + BootstrapStep.Initializing -> { // do we let you cancel from here? if (state.canLeave) { _viewEvents.post(BootstrapViewEvents.SkipBootstrap(state.passphrase != null)) } } is BootstrapStep.SaveRecoveryKey, - BootstrapStep.DoneSuccess -> { + BootstrapStep.DoneSuccess -> { // nop } - BootstrapStep.CheckingMigration -> Unit - is BootstrapStep.FirstForm -> { + BootstrapStep.CheckingMigration -> Unit + is BootstrapStep.FirstForm -> { if (state.canLeave) { _viewEvents.post( when (state.setupMode) { SetupMode.CROSS_SIGNING_ONLY, SetupMode.NORMAL -> BootstrapViewEvents.SkipBootstrap() - else -> BootstrapViewEvents.Dismiss(success = false) + else -> BootstrapViewEvents.Dismiss(success = false) } ) } } - is BootstrapStep.GetBackupSecretForMigration -> { + is BootstrapStep.GetBackupSecretForMigration -> { setState { copy( step = BootstrapStep.FirstForm(keyBackUpExist = doesKeyBackupExist, methods = this.secureBackupMethod), @@ -595,10 +595,10 @@ class BootstrapSharedViewModel @AssistedInject constructor( private fun BackupToQuadSMigrationTask.Result.Failure.toHumanReadable(): String { return when (this) { is BackupToQuadSMigrationTask.Result.InvalidRecoverySecret -> stringProvider.getString(R.string.keys_backup_passphrase_error_decrypt) - is BackupToQuadSMigrationTask.Result.ErrorFailure -> errorFormatter.toHumanReadable(throwable) + is BackupToQuadSMigrationTask.Result.ErrorFailure -> errorFormatter.toHumanReadable(throwable) // is BackupToQuadSMigrationTask.Result.NoKeyBackupVersion, // is BackupToQuadSMigrationTask.Result.IllegalParams, - else -> stringProvider.getString(R.string.unexpected_error) + else -> stringProvider.getString(R.string.unexpected_error) } } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapStep.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapStep.kt index 3fb20ccf9f..3975f0e9a2 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapStep.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapStep.kt @@ -110,6 +110,6 @@ sealed class BootstrapStep { fun BootstrapStep.GetBackupSecretForMigration.useKey(): Boolean { return when (this) { is BootstrapStep.GetBackupSecretPassForMigration -> useKey - else -> true + else -> true } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapWaitingFragment.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapWaitingFragment.kt index cc566833d8..e0965e69f9 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapWaitingFragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BootstrapWaitingFragment.kt @@ -45,7 +45,7 @@ class BootstrapWaitingFragment @Inject constructor() : // bootstrapLoadingStatusText.isVisible = false // bootstrapDescriptionText.isVisible = false // } - else -> { + else -> { // just show the spinner views.bootstrapLoadingStatusText.isVisible = false views.bootstrapDescriptionText.isVisible = false diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/IncomingVerificationRequestHandler.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/IncomingVerificationRequestHandler.kt index e0aa4592a4..91bb3fa7f2 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/IncomingVerificationRequestHandler.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/IncomingVerificationRequestHandler.kt @@ -65,7 +65,7 @@ class IncomingVerificationRequestHandler @Inject constructor( // TODO maybe check also if val uid = "kvr_${tx.transactionId}" when (tx.state) { - is VerificationTxState.OnStarted -> { + is VerificationTxState.OnStarted -> { // Add a notification for every incoming request val user = session?.userService()?.getUser(tx.otherUserId) val name = user?.toMatrixItem()?.getBestName() ?: tx.otherUserId @@ -116,7 +116,7 @@ class IncomingVerificationRequestHandler @Inject constructor( // cancel related notification popupAlertManager.cancelAlert(uid) } - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt index dc79136cad..eae868eb26 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt @@ -93,16 +93,18 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment dismiss() + is VerificationBottomSheetViewEvents.Dismiss -> dismiss() is VerificationBottomSheetViewEvents.AccessSecretStore -> { - secretStartForActivityResult.launch(SharedSecureStorageActivity.newReadIntent( - requireContext(), - null, // use default key - listOf(MASTER_KEY_SSSS_NAME, USER_SIGNING_KEY_SSSS_NAME, SELF_SIGNING_KEY_SSSS_NAME, KEYBACKUP_SECRET_SSSS_NAME), - SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS - )) + secretStartForActivityResult.launch( + SharedSecureStorageActivity.newReadIntent( + requireContext(), + null, // use default key + listOf(MASTER_KEY_SSSS_NAME, USER_SIGNING_KEY_SSSS_NAME, SELF_SIGNING_KEY_SSSS_NAME, KEYBACKUP_SECRET_SSSS_NAME), + SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS + ) + ) } - is VerificationBottomSheetViewEvents.ModalError -> { + is VerificationBottomSheetViewEvents.ModalError -> { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.dialog_title_error)) .setMessage(it.errorMessage) @@ -111,7 +113,7 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment { + VerificationBottomSheetViewEvents.GoToSettings -> { dismiss() (activity as? VectorBaseActivity<*>)?.let { activity -> activity.navigator.openSettings(activity, VectorSettingsActivity.EXTRA_DIRECT_ACCESS_SECURITY_PRIVACY) @@ -240,7 +242,7 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment { + is VerificationTxState.Verified -> { showFragment( VerificationConclusionFragment::class, VerificationConclusionFragment.Args(true, null, state.isMe) @@ -252,14 +254,14 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment Unit + else -> Unit } return@withState } when (state.qrTransactionState) { - is VerificationTxState.QrScannedByOther -> { + is VerificationTxState.QrScannedByOther -> { showFragment(VerificationQrScannedByOtherFragment::class) return@withState } @@ -274,21 +276,21 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment { + is VerificationTxState.Verified -> { showFragment( VerificationConclusionFragment::class, VerificationConclusionFragment.Args(true, null, state.isMe) ) return@withState } - is VerificationTxState.Cancelled -> { + is VerificationTxState.Cancelled -> { showFragment( VerificationConclusionFragment::class, VerificationConclusionFragment.Args(false, state.qrTransactionState.cancelCode.value, state.isMe) ) return@withState } - else -> Unit + else -> Unit } // At this point there is no SAS transaction for this request diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt index a7fd166076..cc5b2d20e4 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt @@ -100,7 +100,8 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( private val rawService: RawService, private val session: Session, private val supportedVerificationMethodsProvider: SupportedVerificationMethodsProvider, - private val stringProvider: StringProvider) : + private val stringProvider: StringProvider +) : VectorViewModel(initialState), VerificationService.Listener { @@ -251,7 +252,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( ?: session.roomService().getExistingDirectRoomWithUser(otherUserId) when (action) { - is VerificationAction.RequestVerificationByDM -> { + is VerificationAction.RequestVerificationByDM -> { if (roomId == null) { val localId = LocalEcho.createLocalEchoId() setState { @@ -302,7 +303,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( } Unit } - is VerificationAction.StartSASVerification -> { + is VerificationAction.StartSASVerification -> { val request = session.cryptoService().verificationService().getExistingVerificationRequest(otherUserId, action.pendingRequestTransactionId) ?: return@withState val otherDevice = if (request.isIncoming) request.requestInfo?.fromDevice else request.readyInfo?.fromDevice @@ -324,7 +325,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( } Unit } - is VerificationAction.RemoteQrCodeScanned -> { + is VerificationAction.RemoteQrCodeScanned -> { val existingTransaction = session.cryptoService().verificationService() .getExistingTransaction(action.otherUserId, action.transactionId) as? QrCodeVerificationTransaction existingTransaction @@ -338,7 +339,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( existingTransaction ?.otherUserScannedMyQrCode() } - is VerificationAction.OtherUserDidNotScanned -> { + is VerificationAction.OtherUserDidNotScanned -> { val transactionId = state.transactionId ?: return@withState val existingTransaction = session.cryptoService().verificationService() @@ -346,18 +347,18 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( existingTransaction ?.otherUserDidNotScannedMyQrCode() } - is VerificationAction.SASMatchAction -> { + is VerificationAction.SASMatchAction -> { (session.cryptoService().verificationService() .getExistingTransaction(action.otherUserId, action.sasTransactionId) as? SasVerificationTransaction)?.userHasVerifiedShortCode() } - is VerificationAction.SASDoNotMatchAction -> { + is VerificationAction.SASDoNotMatchAction -> { (session.cryptoService().verificationService() .getExistingTransaction(action.otherUserId, action.sasTransactionId) as? SasVerificationTransaction) ?.shortCodeDoesNotMatch() } - is VerificationAction.GotItConclusion -> { + is VerificationAction.GotItConclusion -> { if (state.isVerificationRequired && !action.verified) { // we should go back to first screen setState { @@ -371,17 +372,17 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( _viewEvents.post(VerificationBottomSheetViewEvents.Dismiss) } } - is VerificationAction.SkipVerification -> { + is VerificationAction.SkipVerification -> { _viewEvents.post(VerificationBottomSheetViewEvents.Dismiss) } - is VerificationAction.VerifyFromPassphrase -> { + is VerificationAction.VerifyFromPassphrase -> { setState { copy(verifyingFrom4S = true) } _viewEvents.post(VerificationBottomSheetViewEvents.AccessSecretStore) } - is VerificationAction.GotResultFromSsss -> { + is VerificationAction.GotResultFromSsss -> { handleSecretBackFromSSSS(action) } - VerificationAction.SecuredStorageHasBeenReset -> { + VerificationAction.SecuredStorageHasBeenReset -> { if (session.cryptoService().crossSigningService().allPrivateKeysKnown()) { setState { copy(quadSHasBeenReset = true, verifyingFrom4S = false) @@ -389,7 +390,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( } Unit } - VerificationAction.CancelledFromSsss -> { + VerificationAction.CancelledFromSsss -> { setState { copy(verifyingFrom4S = false) } @@ -509,7 +510,7 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( } when (tx) { - is SasVerificationTransaction -> { + is SasVerificationTransaction -> { if (tx.transactionId == (state.pendingRequest.invoke()?.transactionId ?: state.transactionId)) { // A SAS tx has been started following this request setState { diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionController.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionController.kt index 9203b8ab0a..9c5829eb8e 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionController.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionController.kt @@ -49,7 +49,7 @@ class VerificationConclusionController @Inject constructor( val host = this when (state.conclusionState) { - ConclusionState.SUCCESS -> { + ConclusionState.SUCCESS -> { bottomSheetVerificationNoticeItem { id("notice") notice( @@ -68,7 +68,7 @@ class VerificationConclusionController @Inject constructor( bottomDone() } - ConclusionState.WARNING -> { + ConclusionState.WARNING -> { bottomSheetVerificationNoticeItem { id("notice") notice(host.stringProvider.getString(R.string.verification_conclusion_not_secure).toEpoxyCharSequence()) diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionViewModel.kt index 0e56a6857b..aff2d807ac 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/conclusion/VerificationConclusionViewModel.kt @@ -51,7 +51,7 @@ class VerificationConclusionViewModel(initialState: VerificationConclusionViewSt CancelCode.MismatchedKeys -> { VerificationConclusionViewState(ConclusionState.WARNING, args.isMe) } - else -> { + else -> { VerificationConclusionViewState( if (args.isSuccessFull) ConclusionState.SUCCESS else ConclusionState.CANCELLED, args.isMe diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeController.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeController.kt index 9f3e8ff690..98b163f4e3 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeController.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeController.kt @@ -81,13 +81,13 @@ class VerificationEmojiCodeController @Inject constructor( buildActions(state) } - is Fail -> { + is Fail -> { errorWithRetryItem { id("error") text(host.errorFormatter.toHumanReadable(emojiDescription.error)) } } - else -> { + else -> { bottomSheetVerificationWaitingItem { id("waiting") title(host.stringProvider.getString(R.string.please_wait)) @@ -112,13 +112,13 @@ class VerificationEmojiCodeController @Inject constructor( buildActions(state) } - is Fail -> { + is Fail -> { errorWithRetryItem { id("error") text(host.errorFormatter.toHumanReadable(decimalDescription.error)) } } - else -> { + else -> { bottomSheetVerificationWaitingItem { id("waiting") title(host.stringProvider.getString(R.string.please_wait)) diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeViewModel.kt index 95dd4263f9..db9a8fed4a 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/emoji/VerificationEmojiCodeViewModel.kt @@ -88,7 +88,7 @@ class VerificationEmojiCodeViewModel @AssistedInject constructor( is VerificationTxState.OnAccepted, is VerificationTxState.SendingKey, is VerificationTxState.KeySent, - is VerificationTxState.OnKeyReceived -> { + is VerificationTxState.OnKeyReceived -> { setState { copy( isWaitingFromOther = false, @@ -118,12 +118,12 @@ class VerificationEmojiCodeViewModel @AssistedInject constructor( is VerificationTxState.SendingMac, is VerificationTxState.MacSent, is VerificationTxState.Verifying, - is VerificationTxState.Verified -> { + is VerificationTxState.Verified -> { setState { copy(isWaitingFromOther = true) } } - is VerificationTxState.Cancelled -> { + is VerificationTxState.Cancelled -> { // The fragment should not be rendered in this state, // it should have been replaced by a conclusion fragment setState { @@ -135,7 +135,7 @@ class VerificationEmojiCodeViewModel @AssistedInject constructor( ) } } - null -> { + null -> { setState { copy( isWaitingFromOther = false, @@ -144,7 +144,7 @@ class VerificationEmojiCodeViewModel @AssistedInject constructor( ) } } - else -> Unit + else -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/request/VerificationRequestController.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/request/VerificationRequestController.kt index 3c7b4ffebd..e050c5bfb0 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/request/VerificationRequestController.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/request/VerificationRequestController.kt @@ -135,13 +135,13 @@ class VerificationRequestController @Inject constructor( listener { host.listener?.onClickOnVerificationStart() } } } - is Loading -> { + is Loading -> { bottomSheetVerificationWaitingItem { id("waiting") title(host.stringProvider.getString(R.string.verification_request_waiting_for, matrixItem.getBestName())) } } - is Success -> { + is Success -> { if (!pr.invoke().isReady) { if (state.isMe) { bottomSheetVerificationWaitingItem { @@ -156,7 +156,7 @@ class VerificationRequestController @Inject constructor( } } } - is Fail -> Unit + is Fail -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolActivity.kt b/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolActivity.kt index f1f6142fa2..6f661c5164 100644 --- a/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolActivity.kt +++ b/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolActivity.kt @@ -69,7 +69,7 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac viewModel.observeViewEvents { when (it) { - DevToolsViewEvents.Dismiss -> finish() + DevToolsViewEvents.Dismiss -> finish() is DevToolsViewEvents.ShowAlertMessage -> { MaterialAlertDialogBuilder(this) .setMessage(it.message) @@ -86,7 +86,7 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac private fun renderState(it: RoomDevToolViewState) { if (it.displayMode != currentDisplayMode) { when (it.displayMode) { - RoomDevToolViewState.Mode.Root -> { + RoomDevToolViewState.Mode.Root -> { val classJava = RoomDevToolFragment::class.java val tag = classJava.name if (supportFragmentManager.findFragmentByTag(tag) == null) { @@ -95,7 +95,7 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac supportFragmentManager.popBackStack() } } - RoomDevToolViewState.Mode.StateEventDetail -> { + RoomDevToolViewState.Mode.StateEventDetail -> { val frag = JSonViewerFragment.newInstance( jsonString = it.selectedEventJson ?: "", initialOpenDepth = -1, @@ -109,11 +109,11 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac val frag = createFragment(RoomDevToolStateEventListFragment::class.java) navigateTo(frag) } - RoomDevToolViewState.Mode.EditEventContent -> { + RoomDevToolViewState.Mode.EditEventContent -> { val frag = createFragment(RoomDevToolEditFragment::class.java) navigateTo(frag) } - is RoomDevToolViewState.Mode.SendEventForm -> { + is RoomDevToolViewState.Mode.SendEventForm -> { val frag = createFragment(RoomDevToolSendFormFragment::class.java) navigateTo(frag) } @@ -123,9 +123,9 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac } when (it.modalLoading) { - is Loading -> showWaitingView() - is Success -> hideWaitingView() - is Fail -> { + is Loading -> showWaitingView() + is Success -> hideWaitingView() + is Fail -> { hideWaitingView() } Uninitialized -> { @@ -184,7 +184,7 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac state.displayMode is RoomDevToolViewState.Mode.EditEventContent || state.displayMode is RoomDevToolViewState.Mode.SendEventForm } - else -> true + else -> true } it.isVisible = isVisible } @@ -206,22 +206,22 @@ class RoomDevToolActivity : SimpleFragmentActivity(), FragmentManager.OnBackStac private fun updateToolBar(state: RoomDevToolViewState) { val title = when (state.displayMode) { - RoomDevToolViewState.Mode.Root -> { + RoomDevToolViewState.Mode.Root -> { getString(getTitleRes()) } - RoomDevToolViewState.Mode.StateEventList -> { + RoomDevToolViewState.Mode.StateEventList -> { getString(R.string.dev_tools_state_event) } - RoomDevToolViewState.Mode.StateEventDetail -> { + RoomDevToolViewState.Mode.StateEventDetail -> { state.selectedEvent?.type } - RoomDevToolViewState.Mode.EditEventContent -> { + RoomDevToolViewState.Mode.EditEventContent -> { getString(R.string.dev_tools_edit_content) } RoomDevToolViewState.Mode.StateEventListByType -> { state.currentStateType ?: "" } - is RoomDevToolViewState.Mode.SendEventForm -> { + is RoomDevToolViewState.Mode.SendEventForm -> { getString( if (state.displayMode.isState) R.string.dev_tools_send_custom_state_event else R.string.dev_tools_send_custom_event diff --git a/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolViewModel.kt b/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolViewModel.kt index fb78f8581a..4d5fafbccc 100644 --- a/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/devtools/RoomDevToolViewModel.kt @@ -67,7 +67,7 @@ class RoomDevToolViewModel @AssistedInject constructor( override fun handle(action: RoomDevToolAction) { when (action) { - RoomDevToolAction.ExploreRoomState -> { + RoomDevToolAction.ExploreRoomState -> { setState { copy( displayMode = RoomDevToolViewState.Mode.StateEventList, @@ -75,7 +75,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - is RoomDevToolAction.ShowStateEvent -> { + is RoomDevToolAction.ShowStateEvent -> { val jsonString = MatrixJsonParser.getMoshi() .adapter(Event::class.java) .toJson(action.event) @@ -88,10 +88,10 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - RoomDevToolAction.OnBackPressed -> { + RoomDevToolAction.OnBackPressed -> { handleBack() } - RoomDevToolAction.MenuEdit -> { + RoomDevToolAction.MenuEdit -> { withState { if (it.displayMode == RoomDevToolViewState.Mode.StateEventDetail) { // we want to edit it @@ -105,7 +105,7 @@ class RoomDevToolViewModel @AssistedInject constructor( } } } - is RoomDevToolAction.ShowStateEventType -> { + is RoomDevToolAction.ShowStateEventType -> { setState { copy( displayMode = RoomDevToolViewState.Mode.StateEventListByType, @@ -113,15 +113,15 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - RoomDevToolAction.MenuItemSend -> { + RoomDevToolAction.MenuItemSend -> { handleMenuItemSend() } - is RoomDevToolAction.UpdateContentText -> { + is RoomDevToolAction.UpdateContentText -> { setState { copy(editedContent = action.contentJson) } } - is RoomDevToolAction.SendCustomEvent -> { + is RoomDevToolAction.SendCustomEvent -> { setState { copy( displayMode = RoomDevToolViewState.Mode.SendEventForm(action.isStateEvent), @@ -129,7 +129,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - is RoomDevToolAction.CustomEventTypeChange -> { + is RoomDevToolAction.CustomEventTypeChange -> { setState { copy( sendEventDraft = sendEventDraft?.copy(type = action.type) @@ -143,7 +143,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - is RoomDevToolAction.CustomEventContentChange -> { + is RoomDevToolAction.CustomEventContentChange -> { setState { copy( sendEventDraft = sendEventDraft?.copy(content = action.content) @@ -157,7 +157,7 @@ class RoomDevToolViewModel @AssistedInject constructor( when (state.displayMode) { RoomDevToolViewState.Mode.EditEventContent -> editEventContent(state) is RoomDevToolViewState.Mode.SendEventForm -> sendEventContent(state, state.displayMode.isState) - else -> Unit + else -> Unit } } @@ -244,10 +244,10 @@ class RoomDevToolViewModel @AssistedInject constructor( private fun handleBack() = withState { when (it.displayMode) { - RoomDevToolViewState.Mode.Root -> { + RoomDevToolViewState.Mode.Root -> { _viewEvents.post(DevToolsViewEvents.Dismiss) } - RoomDevToolViewState.Mode.StateEventList -> { + RoomDevToolViewState.Mode.StateEventList -> { setState { copy( selectedEvent = null, @@ -256,7 +256,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - RoomDevToolViewState.Mode.StateEventDetail -> { + RoomDevToolViewState.Mode.StateEventDetail -> { setState { copy( selectedEvent = null, @@ -265,7 +265,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - RoomDevToolViewState.Mode.EditEventContent -> { + RoomDevToolViewState.Mode.EditEventContent -> { setState { copy( displayMode = RoomDevToolViewState.Mode.StateEventDetail @@ -280,7 +280,7 @@ class RoomDevToolViewModel @AssistedInject constructor( ) } } - is RoomDevToolViewState.Mode.SendEventForm -> { + is RoomDevToolViewState.Mode.SendEventForm -> { setState { copy( displayMode = RoomDevToolViewState.Mode.Root diff --git a/vector/src/main/java/im/vector/app/features/devtools/RoomStateListController.kt b/vector/src/main/java/im/vector/app/features/devtools/RoomStateListController.kt index 3f05db8ed5..831091883a 100644 --- a/vector/src/main/java/im/vector/app/features/devtools/RoomStateListController.kt +++ b/vector/src/main/java/im/vector/app/features/devtools/RoomStateListController.kt @@ -37,7 +37,7 @@ class RoomStateListController @Inject constructor( override fun buildModels(data: RoomDevToolViewState?) { val host = this when (data?.displayMode) { - RoomDevToolViewState.Mode.StateEventList -> { + RoomDevToolViewState.Mode.StateEventList -> { val stateEventsGroups = data.stateEvents.invoke().orEmpty().groupBy { it.getClearType() } if (stateEventsGroups.isEmpty()) { @@ -98,7 +98,7 @@ class RoomStateListController @Inject constructor( } } } - else -> { + else -> { // nop } } diff --git a/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsController.kt b/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsController.kt index e7d74e3d38..cb0e1d3e91 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsController.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsController.kt @@ -55,7 +55,7 @@ class DiscoverySettingsController @Inject constructor( id("identityServerLoading") } } - is Fail -> { + is Fail -> { settingsInfoItem { id("identityServerError") helperText(data.identityServer.error.message) @@ -70,7 +70,7 @@ class DiscoverySettingsController @Inject constructor( buildMsisdnSection(data.phoneNumbersList) } } - else -> Unit + else -> Unit } } @@ -216,7 +216,7 @@ class DiscoverySettingsController @Inject constructor( id("emailsLoading") } } - is Fail -> { + is Fail -> { settingsInfoItem { id("emailsError") helperText(emails.error.message) @@ -250,7 +250,7 @@ class DiscoverySettingsController @Inject constructor( message(host.stringProvider.getString(R.string.settings_discovery_confirm_mail, pidInfo.threePid.value)) textColor(host.colorProvider.getColor(R.color.vector_info_color)) } - is Fail -> + is Fail -> settingsInformationItem { id("info${pidInfo.threePid.value}") message(host.stringProvider.getString(R.string.settings_discovery_confirm_mail_not_clicked, pidInfo.threePid.value)) @@ -260,7 +260,7 @@ class DiscoverySettingsController @Inject constructor( } when (pidInfo.finalRequest) { is Uninitialized, - is Fail -> + is Fail -> buildContinueCancel(pidInfo.threePid) is Loading -> settingsProgressItem { @@ -285,7 +285,7 @@ class DiscoverySettingsController @Inject constructor( id("msisdnLoading") } } - is Fail -> { + is Fail -> { settingsInfoItem { id("msisdnListError") helperText(msisdns.error.message) @@ -359,7 +359,7 @@ class DiscoverySettingsController @Inject constructor( is Loading -> { buttonIndeterminate(true) } - is Fail -> { + is Fail -> { buttonType(ButtonType.NORMAL) buttonStyle(ButtonStyle.DESTRUCTIVE) buttonTitle(host.stringProvider.getString(R.string.global_retry)) @@ -368,7 +368,7 @@ class DiscoverySettingsController @Inject constructor( } is Success -> when (pidInfo.isShared()) { SharedState.SHARED, - SharedState.NOT_SHARED -> { + SharedState.NOT_SHARED -> { buttonType(ButtonType.SWITCH) checked(pidInfo.isShared() == SharedState.SHARED) switchChangeListener { _, checked -> @@ -383,13 +383,13 @@ class DiscoverySettingsController @Inject constructor( buttonType(ButtonType.NO_BUTTON) when (pidInfo.finalRequest) { is Incomplete -> iconMode(IconMode.INFO) - is Fail -> iconMode(IconMode.ERROR) - else -> iconMode(IconMode.NONE) + is Fail -> iconMode(IconMode.ERROR) + else -> iconMode(IconMode.NONE) } } - null -> Unit + null -> Unit } - else -> Unit + else -> Unit } } } @@ -409,7 +409,7 @@ class DiscoverySettingsController @Inject constructor( id("bottom${threePid.value}") continueOnClick { when (threePid) { - is ThreePid.Email -> { + is ThreePid.Email -> { host.listener?.checkEmailVerification(threePid) } is ThreePid.Msisdn -> { diff --git a/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsViewModel.kt b/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsViewModel.kt index 47151223a4..2a975beb58 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/DiscoverySettingsViewModel.kt @@ -101,17 +101,17 @@ class DiscoverySettingsViewModel @AssistedInject constructor( override fun handle(action: DiscoverySettingsAction) { when (action) { - DiscoverySettingsAction.Refresh -> fetchContent() - DiscoverySettingsAction.RetrieveBinding -> retrieveBinding() - DiscoverySettingsAction.DisconnectIdentityServer -> disconnectIdentityServer() + DiscoverySettingsAction.Refresh -> fetchContent() + DiscoverySettingsAction.RetrieveBinding -> retrieveBinding() + DiscoverySettingsAction.DisconnectIdentityServer -> disconnectIdentityServer() is DiscoverySettingsAction.SetPoliciesExpandState -> updatePolicyUrlsExpandedState(action.expanded) - is DiscoverySettingsAction.ChangeIdentityServer -> changeIdentityServer(action) - is DiscoverySettingsAction.UpdateUserConsent -> handleUpdateUserConsent(action) - is DiscoverySettingsAction.RevokeThreePid -> revokeThreePid(action) - is DiscoverySettingsAction.ShareThreePid -> shareThreePid(action) - is DiscoverySettingsAction.FinalizeBind3pid -> finalizeBind3pid(action, true) - is DiscoverySettingsAction.SubmitMsisdnToken -> submitMsisdnToken(action) - is DiscoverySettingsAction.CancelBinding -> cancelBinding(action) + is DiscoverySettingsAction.ChangeIdentityServer -> changeIdentityServer(action) + is DiscoverySettingsAction.UpdateUserConsent -> handleUpdateUserConsent(action) + is DiscoverySettingsAction.RevokeThreePid -> revokeThreePid(action) + is DiscoverySettingsAction.ShareThreePid -> shareThreePid(action) + is DiscoverySettingsAction.FinalizeBind3pid -> finalizeBind3pid(action, true) + is DiscoverySettingsAction.SubmitMsisdnToken -> submitMsisdnToken(action) + is DiscoverySettingsAction.CancelBinding -> cancelBinding(action) } } @@ -232,7 +232,7 @@ class DiscoverySettingsViewModel @AssistedInject constructor( private fun revokeThreePid(action: DiscoverySettingsAction.RevokeThreePid) { when (action.threePid) { - is ThreePid.Email -> revokeEmail(action.threePid) + is ThreePid.Email -> revokeEmail(action.threePid) is ThreePid.Msisdn -> revokeMsisdn(action.threePid) } } @@ -359,7 +359,7 @@ class DiscoverySettingsViewModel @AssistedInject constructor( private fun finalizeBind3pid(action: DiscoverySettingsAction.FinalizeBind3pid, fromUser: Boolean) = withState { state -> val threePid = when (action.threePid) { - is ThreePid.Email -> { + is ThreePid.Email -> { state.emailList()?.find { it.threePid.value == action.threePid.email }?.threePid ?: return@withState } is ThreePid.Msisdn -> { @@ -389,7 +389,7 @@ class DiscoverySettingsViewModel @AssistedInject constructor( state.emailList()?.forEach { info -> when (info.isShared()) { SharedState.BINDING_IN_PROGRESS -> finalizeBind3pid(DiscoverySettingsAction.FinalizeBind3pid(info.threePid), false) - else -> Unit + else -> Unit } } viewModelScope.launch { diff --git a/vector/src/main/java/im/vector/app/features/discovery/Extensions.kt b/vector/src/main/java/im/vector/app/features/discovery/Extensions.kt index dc25a35646..1efe9f7bc2 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/Extensions.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/Extensions.kt @@ -36,9 +36,11 @@ suspend fun Session.fetchHomeserverWithTerms(userLanguage: String): ServerAndPol return buildServerAndPolicies(homeserverUrl, terms, userLanguage) } -private fun buildServerAndPolicies(serviceUrl: String, - termsResponse: TermsResponse, - userLanguage: String): ServerAndPolicies { +private fun buildServerAndPolicies( + serviceUrl: String, + termsResponse: TermsResponse, + userLanguage: String +): ServerAndPolicies { val terms = termsResponse.getLocalizedTerms(userLanguage) val policyUrls = terms.mapNotNull { val name = it.localizedName ?: it.policyName diff --git a/vector/src/main/java/im/vector/app/features/discovery/SettingsButtonItem.kt b/vector/src/main/java/im/vector/app/features/discovery/SettingsButtonItem.kt index 5a32616c06..c025779339 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/SettingsButtonItem.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/SettingsButtonItem.kt @@ -56,7 +56,7 @@ abstract class SettingsButtonItem : EpoxyModelWithHolder { + ButtonStyle.POSITIVE -> { holder.button.setTextColor(colorProvider.getColorFromAttribute(R.attr.colorPrimary)) } ButtonStyle.DESTRUCTIVE -> { diff --git a/vector/src/main/java/im/vector/app/features/discovery/SettingsTextButtonSingleLineItem.kt b/vector/src/main/java/im/vector/app/features/discovery/SettingsTextButtonSingleLineItem.kt index 29a44a1d8a..192ee404fb 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/SettingsTextButtonSingleLineItem.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/SettingsTextButtonSingleLineItem.kt @@ -111,11 +111,11 @@ abstract class SettingsTextButtonSingleLineItem : EpoxyModelWithHolder { + ButtonType.NORMAL -> { holder.mainButton.isVisible = true holder.switchButton.isVisible = false when (buttonStyle) { - ButtonStyle.POSITIVE -> { + ButtonStyle.POSITIVE -> { holder.mainButton.setTextColor(colorProvider.getColorFromAttribute(R.attr.colorPrimary)) } ButtonStyle.DESTRUCTIVE -> { @@ -124,7 +124,7 @@ abstract class SettingsTextButtonSingleLineItem : EpoxyModelWithHolder { + ButtonType.SWITCH -> { holder.mainButton.isVisible = false holder.switchButton.isVisible = true // set to null before changing the state @@ -136,10 +136,10 @@ abstract class SettingsTextButtonSingleLineItem : EpoxyModelWithHolder { + IconMode.NONE -> { holder.textView.setCompoundDrawables(null, null, null, null) } - IconMode.INFO -> { + IconMode.INFO -> { val errorColor = colorProvider.getColor(R.color.notification_accent_color) ContextCompat.getDrawable(holder.view.context, R.drawable.ic_notification_privacy_warning)?.apply { ThemeUtils.tintDrawableWithColor(this, errorColor) diff --git a/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerFragment.kt b/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerFragment.kt index fe2be713af..ee36345418 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerFragment.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerFragment.kt @@ -110,10 +110,10 @@ class SetIdentityServerFragment @Inject constructor( viewModel.observeViewEvents { when (it) { - is SetIdentityServerViewEvents.Loading -> showLoading(it.message) - is SetIdentityServerViewEvents.Failure -> handleFailure(it) - is SetIdentityServerViewEvents.OtherFailure -> showFailure(it.failure) - is SetIdentityServerViewEvents.NoTerms -> { + is SetIdentityServerViewEvents.Loading -> showLoading(it.message) + is SetIdentityServerViewEvents.Failure -> handleFailure(it) + is SetIdentityServerViewEvents.OtherFailure -> showFailure(it.failure) + is SetIdentityServerViewEvents.NoTerms -> { MaterialAlertDialogBuilder(requireActivity()) .setTitle(R.string.settings_discovery_no_terms_title) .setMessage(R.string.settings_discovery_no_terms) @@ -125,7 +125,7 @@ class SetIdentityServerFragment @Inject constructor( Unit } is SetIdentityServerViewEvents.TermsAccepted -> processIdentityServerChange() - is SetIdentityServerViewEvents.ShowTerms -> { + is SetIdentityServerViewEvents.ShowTerms -> { navigator.openTerms( requireContext(), termsActivityResultLauncher, diff --git a/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerViewModel.kt b/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerViewModel.kt index ae1c7f7753..b91feb0b3c 100644 --- a/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/discovery/change/SetIdentityServerViewModel.kt @@ -38,7 +38,8 @@ import java.net.UnknownHostException class SetIdentityServerViewModel @AssistedInject constructor( @Assisted initialState: SetIdentityServerState, private val mxSession: Session, - stringProvider: StringProvider) : + stringProvider: StringProvider +) : VectorViewModel(initialState) { @AssistedFactory @@ -64,7 +65,7 @@ class SetIdentityServerViewModel @AssistedInject constructor( override fun handle(action: SetIdentityServerAction) { when (action) { - SetIdentityServerAction.UseDefaultIdentityServer -> useDefault() + SetIdentityServerAction.UseDefaultIdentityServer -> useDefault() is SetIdentityServerAction.UseCustomIdentityServer -> usedCustomIdentityServerUrl(action) } } @@ -94,11 +95,11 @@ class SetIdentityServerViewModel @AssistedInject constructor( checkTerms(baseUrl) } catch (failure: Throwable) { when { - failure is IdentityServiceError.OutdatedIdentityServer -> + failure is IdentityServiceError.OutdatedIdentityServer -> _viewEvents.post(SetIdentityServerViewEvents.Failure(R.string.identity_server_error_outdated_identity_server, isDefault)) failure is Failure.NetworkConnection && failure.ioException is UnknownHostException -> _viewEvents.post(SetIdentityServerViewEvents.Failure(R.string.settings_discovery_bad_identity_server, isDefault)) - else -> + else -> _viewEvents.post(SetIdentityServerViewEvents.OtherFailure(failure)) } } diff --git a/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt b/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt index 5023c6bd83..c58b36fc88 100644 --- a/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt +++ b/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt @@ -133,7 +133,7 @@ abstract class FormEditTextItem : VectorEpoxyModel() { private fun configureInputType(holder: Holder) { val newInputType = inputType ?: when (singleLine) { - true -> InputType.TYPE_CLASS_TEXT + true -> InputType.TYPE_CLASS_TEXT false -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE } @@ -151,7 +151,7 @@ abstract class FormEditTextItem : VectorEpoxyModel() { private fun configureImeOptions(holder: Holder) { holder.textInputEditText.imeOptions = imeOptions ?: when (singleLine) { - true -> EditorInfo.IME_ACTION_NEXT + true -> EditorInfo.IME_ACTION_NEXT false -> EditorInfo.IME_ACTION_NONE } } diff --git a/vector/src/main/java/im/vector/app/features/form/FormEditTextWithDeleteItem.kt b/vector/src/main/java/im/vector/app/features/form/FormEditTextWithDeleteItem.kt index 09ca51cfb1..637955a66c 100644 --- a/vector/src/main/java/im/vector/app/features/form/FormEditTextWithDeleteItem.kt +++ b/vector/src/main/java/im/vector/app/features/form/FormEditTextWithDeleteItem.kt @@ -85,7 +85,7 @@ abstract class FormEditTextWithDeleteItem : VectorEpoxyModel EditorInfo.IME_ACTION_NEXT + true -> EditorInfo.IME_ACTION_NEXT false -> EditorInfo.IME_ACTION_NONE } diff --git a/vector/src/main/java/im/vector/app/features/form/FormEditableSquareAvatarItem.kt b/vector/src/main/java/im/vector/app/features/form/FormEditableSquareAvatarItem.kt index f8749f2978..a25050cad0 100644 --- a/vector/src/main/java/im/vector/app/features/form/FormEditableSquareAvatarItem.kt +++ b/vector/src/main/java/im/vector/app/features/form/FormEditableSquareAvatarItem.kt @@ -59,7 +59,7 @@ abstract class FormEditableSquareAvatarItem : EpoxyModelWithHolder { + imageUri != null -> { val corner = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 8f, @@ -73,7 +73,7 @@ abstract class FormEditableSquareAvatarItem : EpoxyModelWithHolder { avatarRenderer?.render(matrixItem!!, holder.image) } - else -> { + else -> { avatarRenderer?.clear(holder.image) } } diff --git a/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt b/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt index cb24382e6a..4b32f3307f 100644 --- a/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt +++ b/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt @@ -55,9 +55,11 @@ import javax.inject.Inject /** * This helper centralise ways to retrieve avatar into ImageView or even generic Target. */ -class AvatarRenderer @Inject constructor(private val activeSessionHolder: ActiveSessionHolder, - private val matrixItemColorProvider: MatrixItemColorProvider, - private val dimensionConverter: DimensionConverter) { +class AvatarRenderer @Inject constructor( + private val activeSessionHolder: ActiveSessionHolder, + private val matrixItemColorProvider: MatrixItemColorProvider, + private val dimensionConverter: DimensionConverter +) { companion object { private const val THUMBNAIL_SIZE = 250 @@ -150,9 +152,11 @@ class AvatarRenderer @Inject constructor(private val activeSessionHolder: Active } @UiThread - fun render(glideRequests: GlideRequests, - matrixItem: MatrixItem, - target: Target) { + fun render( + glideRequests: GlideRequests, + matrixItem: MatrixItem, + target: Target + ) { val placeholder = getPlaceholderDrawable(matrixItem) glideRequests.loadResolvedUrl(matrixItem.avatarUrl) .let { @@ -160,7 +164,7 @@ class AvatarRenderer @Inject constructor(private val activeSessionHolder: Active is MatrixItem.SpaceItem -> { it.transform(MultiTransformation(CenterCrop(), RoundedCorners(dimensionConverter.dpToPx(8)))) } - else -> { + else -> { it.apply(RequestOptions.circleCropTransform()) } } @@ -182,10 +186,12 @@ class AvatarRenderer @Inject constructor(private val activeSessionHolder: Active @AnyThread @Throws - fun adaptiveShortcutDrawable(glideRequests: GlideRequests, - matrixItem: MatrixItem, iconSize: Int, - adaptiveIconSize: Int, - adaptiveIconOuterSides: Float): Bitmap { + fun adaptiveShortcutDrawable( + glideRequests: GlideRequests, + matrixItem: MatrixItem, iconSize: Int, + adaptiveIconSize: Int, + adaptiveIconOuterSides: Float + ): Bitmap { return glideRequests .asBitmap() .avatarOrText(matrixItem, iconSize) @@ -216,12 +222,14 @@ class AvatarRenderer @Inject constructor(private val activeSessionHolder: Active } @UiThread - fun renderBlur(matrixItem: MatrixItem, - imageView: ImageView, - sampling: Int, - rounded: Boolean, - @ColorInt colorFilter: Int? = null, - addPlaceholder: Boolean) { + fun renderBlur( + matrixItem: MatrixItem, + imageView: ImageView, + sampling: Int, + rounded: Boolean, + @ColorInt colorFilter: Int? = null, + addPlaceholder: Boolean + ) { val transformations = mutableListOf>( BlurTransformation(20, sampling) ) @@ -269,7 +277,7 @@ class AvatarRenderer @Inject constructor(private val activeSessionHolder: Active is MatrixItem.SpaceItem -> { it.buildRoundRect(matrixItem.firstLetterOfDisplayName(), avatarColor, dimensionConverter.dpToPx(8)) } - else -> { + else -> { it.buildRound(matrixItem.firstLetterOfDisplayName(), avatarColor) } } diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt index 4ddd082f49..6f0e11f3b8 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt @@ -56,6 +56,7 @@ import im.vector.app.features.matrixto.MatrixToBottomSheet import im.vector.app.features.matrixto.OriginOfMatrixTo import im.vector.app.features.navigation.Navigator import im.vector.app.features.notifications.NotificationDrawerManager +import im.vector.app.features.onboarding.AuthenticationDescription import im.vector.app.features.permalink.NavigationInterceptor import im.vector.app.features.permalink.PermalinkHandler import im.vector.app.features.permalink.PermalinkHandler.Companion.MATRIX_TO_CUSTOM_SCHEME_URL_BASE @@ -80,9 +81,9 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.parcelize.Parcelize -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.permalinks.PermalinkService import org.matrix.android.sdk.api.session.sync.InitialSyncStrategy +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.sync.initialSyncStrategy import org.matrix.android.sdk.api.util.MatrixItem import timber.log.Timber @@ -91,7 +92,7 @@ import javax.inject.Inject @Parcelize data class HomeActivityArgs( val clearNotification: Boolean, - val accountCreation: Boolean, + val authenticationDescription: AuthenticationDescription? = null, val hasExistingSession: Boolean = false, val inviteNotificationRoomId: String? = null ) : Parcelable @@ -198,15 +199,15 @@ class HomeActivity : .stream() .onEach { sharedAction -> when (sharedAction) { - is HomeActivitySharedAction.OpenDrawer -> views.drawerLayout.openDrawer(GravityCompat.START) - is HomeActivitySharedAction.CloseDrawer -> views.drawerLayout.closeDrawer(GravityCompat.START) - is HomeActivitySharedAction.OpenGroup -> openGroup(sharedAction.shouldClearFragment) - is HomeActivitySharedAction.OpenSpacePreview -> startActivity(SpacePreviewActivity.newIntent(this, sharedAction.spaceId)) - is HomeActivitySharedAction.AddSpace -> createSpaceResultLauncher.launch(SpaceCreationActivity.newIntent(this)) + is HomeActivitySharedAction.OpenDrawer -> views.drawerLayout.openDrawer(GravityCompat.START) + is HomeActivitySharedAction.CloseDrawer -> views.drawerLayout.closeDrawer(GravityCompat.START) + is HomeActivitySharedAction.OpenGroup -> openGroup(sharedAction.shouldClearFragment) + is HomeActivitySharedAction.OpenSpacePreview -> startActivity(SpacePreviewActivity.newIntent(this, sharedAction.spaceId)) + is HomeActivitySharedAction.AddSpace -> createSpaceResultLauncher.launch(SpaceCreationActivity.newIntent(this)) is HomeActivitySharedAction.ShowSpaceSettings -> showSpaceSettings(sharedAction.spaceId) - is HomeActivitySharedAction.OpenSpaceInvite -> openSpaceInvite(sharedAction.spaceId) - HomeActivitySharedAction.SendSpaceFeedBack -> bugReporter.openBugReportScreen(this, ReportType.SPACE_BETA_FEEDBACK) - HomeActivitySharedAction.CloseGroup -> closeGroup() + is HomeActivitySharedAction.OpenSpaceInvite -> openSpaceInvite(sharedAction.spaceId) + HomeActivitySharedAction.SendSpaceFeedBack -> bugReporter.openBugReportScreen(this, ReportType.SPACE_BETA_FEEDBACK) + HomeActivitySharedAction.CloseGroup -> closeGroup() } } .launchIn(lifecycleScope) @@ -225,20 +226,20 @@ class HomeActivity : homeActivityViewModel.observeViewEvents { when (it) { is HomeActivityViewEvents.AskPasswordToInitCrossSigning -> handleAskPasswordToInitCrossSigning(it) - is HomeActivityViewEvents.OnNewSession -> handleOnNewSession(it) - HomeActivityViewEvents.PromptToEnableSessionPush -> handlePromptToEnablePush() - HomeActivityViewEvents.StartRecoverySetupFlow -> handleStartRecoverySetup() - is HomeActivityViewEvents.ForceVerification -> { + is HomeActivityViewEvents.OnNewSession -> handleOnNewSession(it) + HomeActivityViewEvents.PromptToEnableSessionPush -> handlePromptToEnablePush() + HomeActivityViewEvents.StartRecoverySetupFlow -> handleStartRecoverySetup() + is HomeActivityViewEvents.ForceVerification -> { if (it.sendRequest) { navigator.requestSelfSessionVerification(this) } else { navigator.waitSessionVerification(this) } } - is HomeActivityViewEvents.OnCrossSignedInvalidated -> handleCrossSigningInvalidated(it) - HomeActivityViewEvents.ShowAnalyticsOptIn -> handleShowAnalyticsOptIn() - HomeActivityViewEvents.NotifyUserForThreadsMigration -> handleNotifyUserForThreadsMigration() - is HomeActivityViewEvents.MigrateThreads -> migrateThreadsIfNeeded(it.checkSession) + is HomeActivityViewEvents.OnCrossSignedInvalidated -> handleCrossSigningInvalidated(it) + HomeActivityViewEvents.ShowAnalyticsOptIn -> handleShowAnalyticsOptIn() + HomeActivityViewEvents.NotifyUserForThreadsMigration -> handleNotifyUserForThreadsMigration() + is HomeActivityViewEvents.MigrateThreads -> migrateThreadsIfNeeded(it.checkSession) } } homeActivityViewModel.onEach { renderState(it) } @@ -336,12 +337,12 @@ class HomeActivity : when { deepLink.startsWith(USER_LINK_PREFIX) -> deepLink.substring(USER_LINK_PREFIX.length) deepLink.startsWith(ROOM_LINK_PREFIX) -> deepLink.substring(ROOM_LINK_PREFIX.length) - else -> null + else -> null }?.let { permalinkId -> activeSessionHolder.getSafeActiveSession()?.permalinkService()?.createPermalink(permalinkId) } } - else -> deepLink + else -> deepLink } lifecycleScope.launch { @@ -372,9 +373,9 @@ class HomeActivity : } private fun renderState(state: HomeActivityViewState) { - when (val status = state.syncStatusServiceStatus) { - is SyncStatusService.Status.InitialSyncProgressing -> { - val initSyncStepStr = initSyncStepFormatter.format(status.initSyncStep) + when (val status = state.syncRequestState) { + is SyncRequestState.InitialSyncProgressing -> { + val initSyncStepStr = initSyncStepFormatter.format(status.initialSyncStep) Timber.v("$initSyncStepStr ${status.percentProgress}") views.waitingView.root.setOnClickListener { // block interactions @@ -391,7 +392,7 @@ class HomeActivity : } views.waitingView.root.isVisible = true } - else -> { + else -> { // Idle or Incremental sync status views.waitingView.root.isVisible = false } @@ -543,15 +544,15 @@ class HomeActivity : override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { - R.id.menu_home_suggestion -> { + R.id.menu_home_suggestion -> { bugReporter.openBugReportScreen(this, ReportType.SUGGESTION) return true } - R.id.menu_home_report_bug -> { + R.id.menu_home_report_bug -> { bugReporter.openBugReportScreen(this, ReportType.BUG_REPORT) return true } - R.id.menu_home_init_sync_legacy -> { + R.id.menu_home_init_sync_legacy -> { // Configure the SDK initialSyncStrategy = InitialSyncStrategy.Legacy // And clear cache @@ -565,11 +566,11 @@ class HomeActivity : MainActivity.restartApp(this, MainActivityArgs(clearCache = true)) return true } - R.id.menu_home_filter -> { + R.id.menu_home_filter -> { navigator.openRoomsFiltering(this) return true } - R.id.menu_home_setting -> { + R.id.menu_home_setting -> { navigator.openSettings(this) return true } @@ -609,15 +610,16 @@ class HomeActivity : } companion object { - fun newIntent(context: Context, - clearNotification: Boolean = false, - accountCreation: Boolean = false, - existingSession: Boolean = false, - inviteNotificationRoomId: String? = null + fun newIntent( + context: Context, + clearNotification: Boolean = false, + authenticationDescription: AuthenticationDescription? = null, + existingSession: Boolean = false, + inviteNotificationRoomId: String? = null ): Intent { val args = HomeActivityArgs( clearNotification = clearNotification, - accountCreation = accountCreation, + authenticationDescription = authenticationDescription, hasExistingSession = existingSession, inviteNotificationRoomId = inviteNotificationRoomId ) diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt index 9fe8a1f60e..b45e6fbcb0 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt @@ -28,17 +28,25 @@ import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.MavericksAssistedViewModelFactory import im.vector.app.core.di.hiltMavericksViewModelFactory import im.vector.app.core.platform.VectorViewModel +import im.vector.app.features.analytics.AnalyticsTracker +import im.vector.app.features.analytics.extensions.toAnalyticsType +import im.vector.app.features.analytics.plan.Signup import im.vector.app.features.analytics.store.AnalyticsStore import im.vector.app.features.login.ReAuthHelper +import im.vector.app.features.onboarding.AuthenticationDescription import im.vector.app.features.raw.wellknown.ElementWellKnown import im.vector.app.features.raw.wellknown.getElementWellknown import im.vector.app.features.raw.wellknown.isSecureBackupRequired +import im.vector.app.features.raw.wellknown.withElementWellKnown import im.vector.app.features.session.coroutineScope import im.vector.app.features.settings.VectorPreferences import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.launch import org.matrix.android.sdk.api.auth.UIABaseAuth import org.matrix.android.sdk.api.auth.UserInteractiveAuthInterceptor @@ -52,10 +60,10 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.CrossSigningServic import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap import org.matrix.android.sdk.api.session.getUser -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.pushrules.RuleIds import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.settings.LightweightSettingsStorage import org.matrix.android.sdk.api.util.awaitCallback import org.matrix.android.sdk.api.util.toMatrixItem @@ -72,7 +80,8 @@ class HomeActivityViewModel @AssistedInject constructor( private val reAuthHelper: ReAuthHelper, private val analyticsStore: AnalyticsStore, private val lightweightSettingsStorage: LightweightSettingsStorage, - private val vectorPreferences: VectorPreferences + private val vectorPreferences: VectorPreferences, + private val analyticsTracker: AnalyticsTracker ) : VectorViewModel(initialState) { @AssistedFactory @@ -84,7 +93,7 @@ class HomeActivityViewModel @AssistedInject constructor( override fun initialState(viewModelContext: ViewModelContext): HomeActivityViewState? { val activity: HomeActivity = viewModelContext.activity() val args: HomeActivityArgs? = activity.intent.getParcelableExtra(Mavericks.KEY_ARG) - return args?.let { HomeActivityViewState(accountCreation = it.accountCreation) } + return args?.let { HomeActivityViewState(authenticationDescription = it.authenticationDescription) } ?: super.initialState(viewModelContext) } } @@ -113,9 +122,32 @@ class HomeActivityViewModel @AssistedInject constructor( } } .launchIn(viewModelScope) + + when (val recentAuthentication = initialState.authenticationDescription) { + is AuthenticationDescription.Register -> { + viewModelScope.launch { + analyticsStore.onUserGaveConsent { + analyticsTracker.capture(Signup(authenticationType = recentAuthentication.type.toAnalyticsType())) + } + } + } + AuthenticationDescription.Login -> { + // do nothing + } + null -> { + // do nothing + } + } } } + private suspend fun AnalyticsStore.onUserGaveConsent(action: () -> Unit) { + userConsentFlow + .takeWhile { !it } + .onCompletion { action() } + .collect() + } + private fun cleanupFiles() { // Mitigation: delete all cached decrypted files each time the application is started. activeSessionHolder.getSafeActiveSession()?.fileService()?.clearDecryptedCache() @@ -134,9 +166,8 @@ class HomeActivityViewModel @AssistedInject constructor( .onEach { info -> val isVerified = info.getOrNull()?.isTrusted() ?: false if (!isVerified && onceTrusted) { - viewModelScope.launch(Dispatchers.IO) { - val elementWellKnown = rawService.getElementWellknown(safeActiveSession.sessionParams) - sessionHasBeenUnverified(elementWellKnown) + rawService.withElementWellKnown(viewModelScope, safeActiveSession.sessionParams) { + sessionHasBeenUnverified(it) } } onceTrusted = isVerified @@ -167,7 +198,7 @@ class HomeActivityViewModel @AssistedInject constructor( vectorPreferences.userNotifiedAboutThreads() } // Migrate users with enabled lab settings - vectorPreferences.shouldNotifyUserAboutThreads() && vectorPreferences.shouldMigrateThreads() -> { + vectorPreferences.shouldNotifyUserAboutThreads() && vectorPreferences.shouldMigrateThreads() -> { Timber.i("----> Migrate threads with enabled labs") // If user had io.element.thread enabled then enable the new thread support, // clear cache to sync messages appropriately @@ -177,7 +208,7 @@ class HomeActivityViewModel @AssistedInject constructor( _viewEvents.post(HomeActivityViewEvents.MigrateThreads(checkSession = false)) } // Enable all users - vectorPreferences.shouldMigrateThreads() && vectorPreferences.areThreadMessagesEnabled() -> { + vectorPreferences.shouldMigrateThreads() && vectorPreferences.areThreadMessagesEnabled() -> { Timber.i("----> Try to migrate threads") _viewEvents.post(HomeActivityViewEvents.MigrateThreads(checkSession = true)) } @@ -187,25 +218,25 @@ class HomeActivityViewModel @AssistedInject constructor( private fun observeInitialSync() { val session = activeSessionHolder.getSafeActiveSession() ?: return - session.syncStatusService().getSyncStatusLive() + session.syncService().getSyncRequestStateLive() .asFlow() .onEach { status -> when (status) { - is SyncStatusService.Status.Idle -> { + is SyncRequestState.Idle -> { maybeVerifyOrBootstrapCrossSigning() } - else -> Unit + else -> Unit } setState { copy( - syncStatusServiceStatus = status + syncRequestState = status ) } } .launchIn(viewModelScope) - if (session.hasAlreadySynced()) { + if (session.syncService().hasAlreadySynced()) { maybeVerifyOrBootstrapCrossSigning() } } @@ -285,7 +316,7 @@ class HomeActivityViewModel @AssistedInject constructor( val isSecureBackupRequired = elementWellKnown?.isSecureBackupRequired() ?: false // In case of account creation, it is already done before - if (initialState.accountCreation) { + if (initialState.authenticationDescription is AuthenticationDescription.Register) { if (isSecureBackupRequired) { _viewEvents.post(HomeActivityViewEvents.StartRecoverySetupFlow) } else { @@ -395,7 +426,7 @@ class HomeActivityViewModel @AssistedInject constructor( HomeActivityViewActions.PushPromptHasBeenReviewed -> { vectorPreferences.setDidAskUserToEnableSessionPush() } - HomeActivityViewActions.ViewStarted -> { + HomeActivityViewActions.ViewStarted -> { initialize() } } diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewState.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewState.kt index 45fe04fc61..843f9bdfec 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewState.kt @@ -17,9 +17,10 @@ package im.vector.app.features.home import com.airbnb.mvrx.MavericksState -import org.matrix.android.sdk.api.session.initsync.SyncStatusService +import im.vector.app.features.onboarding.AuthenticationDescription +import org.matrix.android.sdk.api.session.sync.SyncRequestState data class HomeActivityViewState( - val syncStatusServiceStatus: SyncStatusService.Status = SyncStatusService.Status.Idle, - val accountCreation: Boolean = false + val syncRequestState: SyncRequestState = SyncRequestState.Idle, + val authenticationDescription: AuthenticationDescription? = null ) : MavericksState diff --git a/vector/src/main/java/im/vector/app/features/home/HomeDetailFragment.kt b/vector/src/main/java/im/vector/app/features/home/HomeDetailFragment.kt index 4eedb528d1..9deae0970b 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeDetailFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeDetailFragment.kt @@ -133,7 +133,7 @@ class HomeDetailFragment @Inject constructor( viewModel.onEach(HomeDetailViewState::roomGroupingMethod) { roomGroupingMethod -> when (roomGroupingMethod) { is RoomGroupingMethod.ByLegacyGroup -> onGroupChange(roomGroupingMethod.groupSummary) - is RoomGroupingMethod.BySpace -> onSpaceChange(roomGroupingMethod.spaceSummary) + is RoomGroupingMethod.BySpace -> onSpaceChange(roomGroupingMethod.spaceSummary) } } @@ -147,9 +147,9 @@ class HomeDetailFragment @Inject constructor( viewModel.observeViewEvents { viewEvent -> when (viewEvent) { - HomeDetailViewEvents.CallStarted -> handleCallStarted() + HomeDetailViewEvents.CallStarted -> handleCallStarted() is HomeDetailViewEvents.FailToCall -> showFailure(viewEvent.failure) - HomeDetailViewEvents.Loading -> showLoadingDialog() + HomeDetailViewEvents.Loading -> showLoadingDialog() } } @@ -229,8 +229,8 @@ class HomeDetailFragment @Inject constructor( private fun refreshSpaceState() { when (val roomGroupingMethod = appStateHandler.getCurrentRoomGroupingMethod()) { is RoomGroupingMethod.ByLegacyGroup -> onGroupChange(roomGroupingMethod.groupSummary) - is RoomGroupingMethod.BySpace -> onSpaceChange(roomGroupingMethod.spaceSummary) - else -> Unit + is RoomGroupingMethod.BySpace -> onSpaceChange(roomGroupingMethod.spaceSummary) + else -> Unit } } @@ -313,10 +313,10 @@ class HomeDetailFragment @Inject constructor( serverBackupStatusViewModel .onEach { when (val banState = it.bannerState.invoke()) { - is BannerState.Setup -> views.homeKeysBackupBanner.render(KeysBackupBanner.State.Setup(banState.numberOfKeys), false) + is BannerState.Setup -> views.homeKeysBackupBanner.render(KeysBackupBanner.State.Setup(banState.numberOfKeys), false) BannerState.BackingUp -> views.homeKeysBackupBanner.render(KeysBackupBanner.State.BackingUp, false) null, - BannerState.Hidden -> views.homeKeysBackupBanner.render(KeysBackupBanner.State.Hidden, false) + BannerState.Hidden -> views.homeKeysBackupBanner.render(KeysBackupBanner.State.Hidden, false) } } views.homeKeysBackupBanner.delegate = this @@ -340,7 +340,7 @@ class HomeDetailFragment @Inject constructor( is RoomGroupingMethod.ByLegacyGroup -> { // do nothing } - is RoomGroupingMethod.BySpace -> { + is RoomGroupingMethod.BySpace -> { it.roomGroupingMethod.spaceSummary?.let { spaceSummary -> sharedActionViewModel.post(HomeActivitySharedAction.ShowSpaceSettings(spaceSummary.roomId)) } @@ -354,10 +354,10 @@ class HomeDetailFragment @Inject constructor( views.bottomNavigationView.menu.findItem(R.id.bottom_action_notification).isVisible = vectorPreferences.labAddNotificationTab() views.bottomNavigationView.setOnItemSelectedListener { val tab = when (it.itemId) { - R.id.bottom_action_people -> HomeTab.RoomList(RoomListDisplayMode.PEOPLE) - R.id.bottom_action_rooms -> HomeTab.RoomList(RoomListDisplayMode.ROOMS) + R.id.bottom_action_people -> HomeTab.RoomList(RoomListDisplayMode.PEOPLE) + R.id.bottom_action_rooms -> HomeTab.RoomList(RoomListDisplayMode.ROOMS) R.id.bottom_action_notification -> HomeTab.RoomList(RoomListDisplayMode.NOTIFICATIONS) - else -> HomeTab.DialPad + else -> HomeTab.DialPad } viewModel.handle(HomeDetailAction.SwitchTab(tab)) true @@ -388,7 +388,7 @@ class HomeDetailFragment @Inject constructor( val params = RoomListParams(tab.displayMode) add(R.id.roomListContainer, RoomListFragment::class.java, params.toMvRxBundle(), fragmentTag) } - is HomeTab.DialPad -> { + is HomeTab.DialPad -> { add(R.id.roomListContainer, createDialPadFragment(), fragmentTag) } } @@ -444,7 +444,7 @@ class HomeDetailFragment @Inject constructor( views.bottomNavigationView.getOrCreateBadge(R.id.bottom_action_notification).render(it.notificationCountCatchup, it.notificationHighlightCatchup) views.syncStateView.render( it.syncState, - it.incrementalSyncStatus, + it.incrementalSyncRequestState, it.pushCounter, vectorPreferences.developerShowDebugInfo() ) @@ -465,11 +465,11 @@ class HomeDetailFragment @Inject constructor( } private fun HomeTab.toMenuId() = when (this) { - is HomeTab.DialPad -> R.id.bottom_action_dial_pad + is HomeTab.DialPad -> R.id.bottom_action_dial_pad is HomeTab.RoomList -> when (displayMode) { RoomListDisplayMode.PEOPLE -> R.id.bottom_action_people - RoomListDisplayMode.ROOMS -> R.id.bottom_action_rooms - else -> R.id.bottom_action_notification + RoomListDisplayMode.ROOMS -> R.id.bottom_action_rooms + else -> R.id.bottom_action_notification } } diff --git a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt index b8a9e5744d..485d1e33ec 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt @@ -50,10 +50,10 @@ import org.matrix.android.sdk.api.query.SpaceFilter import org.matrix.android.sdk.api.query.toActiveSpaceOrOrphanRooms import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.NewSessionListener -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.room.RoomSortOrder import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.util.toMatrixItem import org.matrix.android.sdk.flow.flow import timber.log.Timber @@ -126,8 +126,8 @@ class HomeDetailViewModel @AssistedInject constructor( override fun handle(action: HomeDetailAction) { when (action) { - is HomeDetailAction.SwitchTab -> handleSwitchTab(action) - HomeDetailAction.MarkAllRoomsRead -> handleMarkAllRoomsRead() + is HomeDetailAction.SwitchTab -> handleSwitchTab(action) + HomeDetailAction.MarkAllRoomsRead -> handleMarkAllRoomsRead() is HomeDetailAction.StartCallWithPhoneNumber -> handleStartCallWithPhoneNumber(action) } } @@ -199,11 +199,11 @@ class HomeDetailViewModel @AssistedInject constructor( copy(syncState = syncState) } - session.syncStatusService().getSyncStatusLive() + session.syncService().getSyncRequestStateLive() .asFlow() - .filterIsInstance() + .filterIsInstance() .setOnEach { - copy(incrementalSyncStatus = it) + copy(incrementalSyncRequestState = it) } } @@ -233,7 +233,7 @@ class HomeDetailViewModel @AssistedInject constructor( is RoomGroupingMethod.ByLegacyGroup -> { // TODO!! } - is RoomGroupingMethod.BySpace -> { + is RoomGroupingMethod.BySpace -> { val activeSpaceRoomId = groupingMethod.spaceSummary?.roomId var dmInvites = 0 var roomsInvite = 0 @@ -283,7 +283,7 @@ class HomeDetailViewModel @AssistedInject constructor( ) } } - null -> Unit + null -> Unit } } .launchIn(viewModelScope) diff --git a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewState.kt b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewState.kt index fbf67cdcff..7b8319d8d1 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewState.kt @@ -22,8 +22,8 @@ import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Uninitialized import im.vector.app.R import im.vector.app.RoomGroupingMethod -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.room.model.RoomSummary +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.sync.SyncState import org.matrix.android.sdk.api.util.MatrixItem @@ -40,7 +40,7 @@ data class HomeDetailViewState( val notificationHighlightRooms: Boolean = false, val hasUnreadMessages: Boolean = false, val syncState: SyncState = SyncState.Idle, - val incrementalSyncStatus: SyncStatusService.Status.IncrementalSyncStatus = SyncStatusService.Status.IncrementalSyncIdle, + val incrementalSyncRequestState: SyncRequestState.IncrementalSyncRequestState = SyncRequestState.IncrementalSyncIdle, val pushCounter: Int = 0, val pstnSupportFlag: Boolean = false, val forceDialPadTab: Boolean = false diff --git a/vector/src/main/java/im/vector/app/features/home/InitSyncStepFormatter.kt b/vector/src/main/java/im/vector/app/features/home/InitSyncStepFormatter.kt index 51ca96341e..884b4266cd 100644 --- a/vector/src/main/java/im/vector/app/features/home/InitSyncStepFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/InitSyncStepFormatter.kt @@ -18,25 +18,25 @@ package im.vector.app.features.home import im.vector.app.R import im.vector.app.core.resources.StringProvider -import org.matrix.android.sdk.api.session.initsync.InitSyncStep +import org.matrix.android.sdk.api.session.sync.InitialSyncStep import javax.inject.Inject class InitSyncStepFormatter @Inject constructor( private val stringProvider: StringProvider ) { - fun format(initSyncStep: InitSyncStep): String { + fun format(initialSyncStep: InitialSyncStep): String { return stringProvider.getString( - when (initSyncStep) { - InitSyncStep.ServerComputing -> R.string.initial_sync_start_server_computing - InitSyncStep.Downloading -> R.string.initial_sync_start_downloading - InitSyncStep.ImportingAccount -> R.string.initial_sync_start_importing_account - InitSyncStep.ImportingAccountCrypto -> R.string.initial_sync_start_importing_account_crypto - InitSyncStep.ImportingAccountRoom -> R.string.initial_sync_start_importing_account_rooms - InitSyncStep.ImportingAccountGroups -> R.string.initial_sync_start_importing_account_groups - InitSyncStep.ImportingAccountData -> R.string.initial_sync_start_importing_account_data - InitSyncStep.ImportingAccountJoinedRooms -> R.string.initial_sync_start_importing_account_joined_rooms - InitSyncStep.ImportingAccountInvitedRooms -> R.string.initial_sync_start_importing_account_invited_rooms - InitSyncStep.ImportingAccountLeftRooms -> R.string.initial_sync_start_importing_account_left_rooms + when (initialSyncStep) { + InitialSyncStep.ServerComputing -> R.string.initial_sync_start_server_computing + InitialSyncStep.Downloading -> R.string.initial_sync_start_downloading + InitialSyncStep.ImportingAccount -> R.string.initial_sync_start_importing_account + InitialSyncStep.ImportingAccountCrypto -> R.string.initial_sync_start_importing_account_crypto + InitialSyncStep.ImportingAccountRoom -> R.string.initial_sync_start_importing_account_rooms + InitialSyncStep.ImportingAccountGroups -> R.string.initial_sync_start_importing_account_groups + InitialSyncStep.ImportingAccountData -> R.string.initial_sync_start_importing_account_data + InitialSyncStep.ImportingAccountJoinedRooms -> R.string.initial_sync_start_importing_account_joined_rooms + InitialSyncStep.ImportingAccountInvitedRooms -> R.string.initial_sync_start_importing_account_invited_rooms + InitialSyncStep.ImportingAccountLeftRooms -> R.string.initial_sync_start_importing_account_left_rooms } ) } diff --git a/vector/src/main/java/im/vector/app/features/home/ShortcutCreator.kt b/vector/src/main/java/im/vector/app/features/home/ShortcutCreator.kt index 082d318cc7..23cbe3dfa2 100644 --- a/vector/src/main/java/im/vector/app/features/home/ShortcutCreator.kt +++ b/vector/src/main/java/im/vector/app/features/home/ShortcutCreator.kt @@ -63,7 +63,7 @@ class ShortcutCreator @Inject constructor( val glideRequests = GlideApp.with(context) val matrixItem = roomSummary.toMatrixItem() when (useAdaptiveIcon) { - true -> avatarRenderer.adaptiveShortcutDrawable(glideRequests, matrixItem, iconSize, adaptiveIconSize, adaptiveIconOuterSides.toFloat()) + true -> avatarRenderer.adaptiveShortcutDrawable(glideRequests, matrixItem, iconSize, adaptiveIconSize, adaptiveIconOuterSides.toFloat()) false -> avatarRenderer.shortcutDrawable(glideRequests, matrixItem, iconSize) } } catch (failure: Throwable) { diff --git a/vector/src/main/java/im/vector/app/features/home/UnreadMessagesSharedViewModel.kt b/vector/src/main/java/im/vector/app/features/home/UnreadMessagesSharedViewModel.kt index 09e2d11f84..723ca7caae 100644 --- a/vector/src/main/java/im/vector/app/features/home/UnreadMessagesSharedViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/UnreadMessagesSharedViewModel.kt @@ -55,11 +55,13 @@ data class CountInfo( val otherCount: RoomAggregateNotificationCount ) -class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initialState: UnreadMessagesState, - session: Session, - private val vectorPreferences: VectorPreferences, - appStateHandler: AppStateHandler, - private val autoAcceptInvites: AutoAcceptInvites) : +class UnreadMessagesSharedViewModel @AssistedInject constructor( + @Assisted initialState: UnreadMessagesState, + session: Session, + private val vectorPreferences: VectorPreferences, + appStateHandler: AppStateHandler, + private val autoAcceptInvites: AutoAcceptInvites +) : VectorViewModel(initialState) { @AssistedFactory @@ -126,7 +128,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia RoomAggregateNotificationCount(0, 0) ) } - is RoomGroupingMethod.BySpace -> { + is RoomGroupingMethod.BySpace -> { val selectedSpace = appStateHandler.safeActiveSpaceId() val inviteCount = if (autoAcceptInvites.hideInvites) { @@ -178,7 +180,7 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia ) ) } - null -> { + null -> { CountInfo( RoomAggregateNotificationCount(0, 0), RoomAggregateNotificationCount(0, 0) diff --git a/vector/src/main/java/im/vector/app/features/home/room/breadcrumbs/BreadcrumbsViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/breadcrumbs/BreadcrumbsViewModel.kt index 112b7e8574..651c323c86 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/breadcrumbs/BreadcrumbsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/breadcrumbs/BreadcrumbsViewModel.kt @@ -31,8 +31,10 @@ import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.flow.flow -class BreadcrumbsViewModel @AssistedInject constructor(@Assisted initialState: BreadcrumbsViewState, - private val session: Session) : +class BreadcrumbsViewModel @AssistedInject constructor( + @Assisted initialState: BreadcrumbsViewState, + private val session: Session +) : VectorViewModel(initialState) { @AssistedFactory diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt index 65d18105fe..68053ed890 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt @@ -134,12 +134,12 @@ class AutoCompleter @AssistedInject constructor( .with(object : AutocompleteCallback { override fun onPopupItemClicked(editable: Editable, item: AutocompleteMemberItem): Boolean { return when (item) { - is AutocompleteMemberItem.Header -> false // do nothing header is not clickable + is AutocompleteMemberItem.Header -> false // do nothing header is not clickable is AutocompleteMemberItem.RoomMember -> { insertMatrixItem(editText, editable, TRIGGER_AUTO_COMPLETE_MEMBERS, item.roomMemberSummary.toMatrixItem()) true } - is AutocompleteMemberItem.Everyone -> { + is AutocompleteMemberItem.Everyone -> { insertMatrixItem(editText, editable, TRIGGER_AUTO_COMPLETE_MEMBERS, item.roomSummary.toEveryoneInRoomMatrixItem()) true } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/ChatEffectManager.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/ChatEffectManager.kt index fa19e39ae7..69ee6fe4fc 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/ChatEffectManager.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/ChatEffectManager.kt @@ -117,17 +117,17 @@ class ChatEffectManager @Inject constructor( MessageType.MSGTYPE_CONFETTI -> ChatEffect.CONFETTI MessageType.MSGTYPE_SNOWFALL -> ChatEffect.SNOWFALL MessageType.MSGTYPE_EMOTE, - MessageType.MSGTYPE_TEXT -> { + MessageType.MSGTYPE_TEXT -> { event.root.getClearContent().toModel()?.body ?.let { text -> when { EMOJIS_FOR_CONFETTI.any { text.contains(it) } -> ChatEffect.CONFETTI EMOJIS_FOR_SNOWFALL.any { text.contains(it) } -> ChatEffect.SNOWFALL - else -> null + else -> null } } } - else -> null + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/JoinReplacementRoomBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/JoinReplacementRoomBottomSheet.kt index ce2903a6fa..ed8135371a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/JoinReplacementRoomBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/JoinReplacementRoomBottomSheet.kt @@ -70,7 +70,7 @@ class JoinReplacementRoomBottomSheet : views.roomUpgradeButton.render(ButtonStateView.State.Loaded) dismiss() } - is Fail -> { + is Fail -> { // display the error message views.descriptionText.text = errorFormatter.toHumanReadable(joinState.error) views.roomUpgradeButton.render(ButtonStateView.State.Error) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/JumpToBottomViewVisibilityManager.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/JumpToBottomViewVisibilityManager.kt index 7c0dcbb0d2..0f7dc251ae 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/JumpToBottomViewVisibilityManager.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/JumpToBottomViewVisibilityManager.kt @@ -31,7 +31,8 @@ class JumpToBottomViewVisibilityManager( private val jumpToBottomView: FloatingActionButton, private val debouncer: Debouncer, recyclerView: RecyclerView, - private val layoutManager: LinearLayoutManager) { + private val layoutManager: LinearLayoutManager +) { init { recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { @@ -49,7 +50,7 @@ class JumpToBottomViewVisibilityManager( override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { when (newState) { - RecyclerView.SCROLL_STATE_IDLE -> { + RecyclerView.SCROLL_STATE_IDLE -> { maybeShowJumpToBottomViewVisibilityWithDelay() } RecyclerView.SCROLL_STATE_DRAGGING, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailAction.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailAction.kt index f6ea8b76ef..64670c73ac 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailAction.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailAction.kt @@ -60,7 +60,8 @@ sealed class RoomDetailAction : VectorViewModelAction { val senderId: String?, val reason: String, val spam: Boolean = false, - val inappropriate: Boolean = false) : RoomDetailAction() + val inappropriate: Boolean = false + ) : RoomDetailAction() data class IgnoreUser(val userId: String?) : RoomDetailAction() @@ -86,9 +87,11 @@ sealed class RoomDetailAction : VectorViewModelAction { object JoinJitsiCall : RoomDetailAction() object LeaveJitsiCall : RoomDetailAction() - data class EnsureNativeWidgetAllowed(val widget: Widget, - val userJustAccepted: Boolean, - val grantedEvents: RoomDetailViewEvents) : RoomDetailAction() + data class EnsureNativeWidgetAllowed( + val widget: Widget, + val userJustAccepted: Boolean, + val grantedEvents: RoomDetailViewEvents + ) : RoomDetailAction() data class UpdateJoinJitsiCallStatus(val conferenceEvent: ConferenceEvent) : RoomDetailAction() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailActivity.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailActivity.kt index ac4df411a8..f1e06dd5ef 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailActivity.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailActivity.kt @@ -79,7 +79,7 @@ class RoomDetailActivity : private val playbackActivityListener = AudioMessagePlaybackTracker.ActivityListener { isPlayingOrRecording -> if (lastKnownPlayingOrRecordingState == isPlayingOrRecording) return@ActivityListener when (isPlayingOrRecording) { - true -> keepScreenOn() + true -> keepScreenOn() false -> endKeepScreenOn() } lastKnownPlayingOrRecordingState = isPlayingOrRecording diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt index b168bfea97..4d57647a1d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt @@ -75,9 +75,11 @@ sealed class RoomDetailViewEvents : VectorViewEvents { object OpenIntegrationManager : RoomDetailViewEvents() object OpenActiveWidgetBottomSheet : RoomDetailViewEvents() - data class RequestNativeWidgetPermission(val widget: Widget, - val domain: String, - val grantedEvents: RoomDetailViewEvents) : RoomDetailViewEvents() + data class RequestNativeWidgetPermission( + val widget: Widget, + val domain: String, + val grantedEvents: RoomDetailViewEvents + ) : RoomDetailViewEvents() data class StartChatEffect(val type: ChatEffect) : RoomDetailViewEvents() object StopChatEffects : RoomDetailViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt index e01c5ba3b7..47db50d0d4 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt @@ -22,11 +22,11 @@ import com.airbnb.mvrx.Uninitialized import im.vector.app.features.home.room.detail.arguments.TimelineArgs import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState import org.matrix.android.sdk.api.session.room.model.RoomMemberSummary import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.sender.SenderInfo +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.sync.SyncState import org.matrix.android.sdk.api.session.threads.ThreadNotificationBadgeState import org.matrix.android.sdk.api.session.widgets.model.Widget @@ -59,7 +59,7 @@ data class RoomDetailViewState( val tombstoneEvent: Event? = null, val joinUpgradedRoomAsync: Async = Uninitialized, val syncState: SyncState = SyncState.Idle, - val incrementalSyncStatus: SyncStatusService.Status.IncrementalSyncStatus = SyncStatusService.Status.IncrementalSyncIdle, + val incrementalSyncRequestState: SyncRequestState.IncrementalSyncRequestState = SyncRequestState.IncrementalSyncIdle, val pushCounter: Int = 0, val highlightedEventId: String? = null, val unreadState: UnreadState = UnreadState.Unknown, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomMessageTouchHelperCallback.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomMessageTouchHelperCallback.kt index 1f1124b8c0..5a1342b7da 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomMessageTouchHelperCallback.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomMessageTouchHelperCallback.kt @@ -98,13 +98,15 @@ class RoomMessageTouchHelperCallback( return super.convertToAbsoluteDirection(flags, layoutDirection) } - override fun onChildDraw(c: Canvas, - recyclerView: RecyclerView, - viewHolder: EpoxyViewHolder, - dX: Float, - dY: Float, - actionState: Int, - isCurrentlyActive: Boolean) { + override fun onChildDraw( + c: Canvas, + recyclerView: RecyclerView, + viewHolder: EpoxyViewHolder, + dX: Float, + dY: Float, + actionState: Int, + isCurrentlyActive: Boolean + ) { if (actionState == ACTION_STATE_SWIPE) { setTouchListener(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } @@ -119,13 +121,15 @@ class RoomMessageTouchHelperCallback( @Suppress("UNUSED_PARAMETER") @SuppressLint("ClickableViewAccessibility") - private fun setTouchListener(c: Canvas, - recyclerView: RecyclerView, - viewHolder: EpoxyViewHolder, - dX: Float, - dY: Float, - actionState: Int, - isCurrentlyActive: Boolean) { + private fun setTouchListener( + c: Canvas, + recyclerView: RecyclerView, + viewHolder: EpoxyViewHolder, + dX: Float, + dY: Float, + actionState: Int, + isCurrentlyActive: Boolean + ) { // TODO can this interfere with other interactions? should i remove it recyclerView.setOnTouchListener { _, event -> swipeBack = event.action == MotionEvent.ACTION_CANCEL || event.action == MotionEvent.ACTION_UP diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnHighlightedEventCallback.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnHighlightedEventCallback.kt index 7f652a2eea..3f9d7beb74 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnHighlightedEventCallback.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnHighlightedEventCallback.kt @@ -25,9 +25,11 @@ import java.util.concurrent.atomic.AtomicReference /** * This handles scrolling to an event which wasn't yet loaded when scheduled. */ -class ScrollOnHighlightedEventCallback(private val recyclerView: RecyclerView, - private val layoutManager: LinearLayoutManager, - private val timelineEventController: TimelineEventController) : DefaultListUpdateCallback { +class ScrollOnHighlightedEventCallback( + private val recyclerView: RecyclerView, + private val layoutManager: LinearLayoutManager, + private val timelineEventController: TimelineEventController +) : DefaultListUpdateCallback { private val scheduledEventId = AtomicReference() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnNewMessageCallback.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnNewMessageCallback.kt index 249618e12f..467906ac59 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnNewMessageCallback.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/ScrollOnNewMessageCallback.kt @@ -23,8 +23,10 @@ import im.vector.app.features.home.room.detail.timeline.item.ItemWithEvents import org.matrix.android.sdk.api.extensions.tryOrNull import java.util.concurrent.CopyOnWriteArrayList -class ScrollOnNewMessageCallback(private val layoutManager: LinearLayoutManager, - private val timelineEventController: TimelineEventController) : DefaultListUpdateCallback { +class ScrollOnNewMessageCallback( + private val layoutManager: LinearLayoutManager, + private val timelineEventController: TimelineEventController +) : DefaultListUpdateCallback { private val newTimelineEventIds = CopyOnWriteArrayList() private var forceScroll = false diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/StartCallActionsHandler.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/StartCallActionsHandler.kt index d75b9ff69d..ba691de5d2 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/StartCallActionsHandler.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/StartCallActionsHandler.kt @@ -35,7 +35,8 @@ class StartCallActionsHandler( private val timelineViewModel: TimelineViewModel, private val startCallActivityResultLauncher: ActivityResultLauncher>, private val showDialogWithMessage: (String) -> Unit, - private val onTapToReturnToCall: () -> Unit) { + private val onTapToReturnToCall: () -> Unit +) { fun onVideoCallClicked() { handleCallRequest(true) @@ -48,7 +49,7 @@ class StartCallActionsHandler( private fun handleCallRequest(isVideoCall: Boolean) = withState(timelineViewModel) { state -> val roomSummary = state.asyncRoomSummary.invoke() ?: return@withState when (roomSummary.joinedMembersCount) { - 1 -> { + 1 -> { val pendingInvite = roomSummary.invitedMembersCount ?: 0 > 0 if (pendingInvite) { // wait for other to join @@ -58,7 +59,7 @@ class StartCallActionsHandler( showDialogWithMessage(fragment.getString(R.string.cannot_call_yourself)) } } - 2 -> { + 2 -> { val currentCall = callManager.getCurrentCall() if (currentCall?.signalingRoomId == roomId) { onTapToReturnToCall() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt index 3120decd0c..2b99bc67ef 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt @@ -68,6 +68,7 @@ import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.vanniktech.emoji.EmojiPopup +import im.vector.app.BuildConfig import im.vector.app.R import im.vector.app.core.animations.play import im.vector.app.core.dialogs.ConfirmationDialogBuilder @@ -421,16 +422,16 @@ class TimelineFragment @Inject constructor( } when (mode) { is SendMode.Regular -> renderRegularMode(mode.text) - is SendMode.Edit -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_edit, R.string.edit, mode.text) - is SendMode.Quote -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_quote, R.string.action_quote, mode.text) - is SendMode.Reply -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_reply, R.string.reply, mode.text) - is SendMode.Voice -> renderVoiceMessageMode(mode.text) + is SendMode.Edit -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_edit, R.string.edit, mode.text) + is SendMode.Quote -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_quote, R.string.action_quote, mode.text) + is SendMode.Reply -> renderSpecialMode(mode.timelineEvent, R.drawable.ic_reply, R.string.reply, mode.text) + is SendMode.Voice -> renderVoiceMessageMode(mode.text) } } timelineViewModel.onEach( RoomDetailViewState::syncState, - RoomDetailViewState::incrementalSyncStatus, + RoomDetailViewState::incrementalSyncRequestState, RoomDetailViewState::pushCounter ) { syncState, incrementalSyncStatus, pushCounter -> views.syncStateView.render( @@ -443,13 +444,13 @@ class TimelineFragment @Inject constructor( messageComposerViewModel.observeViewEvents { when (it) { - is MessageComposerViewEvents.JoinRoomCommandSuccess -> handleJoinedToAnotherRoom(it) + is MessageComposerViewEvents.JoinRoomCommandSuccess -> handleJoinedToAnotherRoom(it) is MessageComposerViewEvents.SlashCommandConfirmationRequest -> handleSlashCommandConfirmationRequest(it) - is MessageComposerViewEvents.SendMessageResult -> renderSendMessageResult(it) - is MessageComposerViewEvents.ShowMessage -> showSnackWithMessage(it.message) - is MessageComposerViewEvents.ShowRoomUpgradeDialog -> handleShowRoomUpgradeDialog(it) - is MessageComposerViewEvents.AnimateSendButtonVisibility -> handleSendButtonVisibilityChanged(it) - is MessageComposerViewEvents.OpenRoomMemberProfile -> openRoomMemberProfile(it.userId) + is MessageComposerViewEvents.SendMessageResult -> renderSendMessageResult(it) + is MessageComposerViewEvents.ShowMessage -> showSnackWithMessage(it.message) + is MessageComposerViewEvents.ShowRoomUpgradeDialog -> handleShowRoomUpgradeDialog(it) + is MessageComposerViewEvents.AnimateSendButtonVisibility -> handleSendButtonVisibilityChanged(it) + is MessageComposerViewEvents.OpenRoomMemberProfile -> openRoomMemberProfile(it.userId) is MessageComposerViewEvents.VoicePlaybackOrRecordingFailure -> { if (it.throwable is VoiceFailure.UnableToRecord) { onCannotRecord() @@ -461,39 +462,39 @@ class TimelineFragment @Inject constructor( timelineViewModel.observeViewEvents { when (it) { - is RoomDetailViewEvents.Failure -> displayErrorMessage(it) - is RoomDetailViewEvents.OnNewTimelineEvents -> scrollOnNewMessageCallback.addNewTimelineEventIds(it.eventIds) - is RoomDetailViewEvents.ActionSuccess -> displayRoomDetailActionSuccess(it) - is RoomDetailViewEvents.ActionFailure -> displayRoomDetailActionFailure(it) - is RoomDetailViewEvents.ShowMessage -> showSnackWithMessage(it.message) - is RoomDetailViewEvents.NavigateToEvent -> navigateToEvent(it) - is RoomDetailViewEvents.DownloadFileState -> handleDownloadFileState(it) - is RoomDetailViewEvents.ShowE2EErrorMessage -> displayE2eError(it.withHeldCode) - RoomDetailViewEvents.DisplayPromptForIntegrationManager -> displayPromptForIntegrationManager() - is RoomDetailViewEvents.OpenStickerPicker -> openStickerPicker(it) + is RoomDetailViewEvents.Failure -> displayErrorMessage(it) + is RoomDetailViewEvents.OnNewTimelineEvents -> scrollOnNewMessageCallback.addNewTimelineEventIds(it.eventIds) + is RoomDetailViewEvents.ActionSuccess -> displayRoomDetailActionSuccess(it) + is RoomDetailViewEvents.ActionFailure -> displayRoomDetailActionFailure(it) + is RoomDetailViewEvents.ShowMessage -> showSnackWithMessage(it.message) + is RoomDetailViewEvents.NavigateToEvent -> navigateToEvent(it) + is RoomDetailViewEvents.DownloadFileState -> handleDownloadFileState(it) + is RoomDetailViewEvents.ShowE2EErrorMessage -> displayE2eError(it.withHeldCode) + RoomDetailViewEvents.DisplayPromptForIntegrationManager -> displayPromptForIntegrationManager() + is RoomDetailViewEvents.OpenStickerPicker -> openStickerPicker(it) is RoomDetailViewEvents.DisplayEnableIntegrationsWarning -> displayDisabledIntegrationDialog() - is RoomDetailViewEvents.OpenIntegrationManager -> openIntegrationManager() - is RoomDetailViewEvents.OpenFile -> startOpenFileIntent(it) - RoomDetailViewEvents.OpenActiveWidgetBottomSheet -> onViewWidgetsClicked() - is RoomDetailViewEvents.ShowInfoOkDialog -> showDialogWithMessage(it.message) - is RoomDetailViewEvents.JoinJitsiConference -> joinJitsiRoom(it.widget, it.withVideo) - RoomDetailViewEvents.LeaveJitsiConference -> leaveJitsiConference() - RoomDetailViewEvents.ShowWaitingView -> vectorBaseActivity.showWaitingView() - RoomDetailViewEvents.HideWaitingView -> vectorBaseActivity.hideWaitingView() - is RoomDetailViewEvents.RequestNativeWidgetPermission -> requestNativeWidgetPermission(it) - is RoomDetailViewEvents.OpenRoom -> handleOpenRoom(it) - RoomDetailViewEvents.OpenInvitePeople -> navigator.openInviteUsersToRoom(requireContext(), timelineArgs.roomId) - RoomDetailViewEvents.OpenSetRoomAvatarDialog -> galleryOrCameraDialogHelper.show() - RoomDetailViewEvents.OpenRoomSettings -> handleOpenRoomSettings(RoomProfileActivity.EXTRA_DIRECT_ACCESS_ROOM_SETTINGS) - RoomDetailViewEvents.OpenRoomProfile -> handleOpenRoomSettings() - is RoomDetailViewEvents.ShowRoomAvatarFullScreen -> it.matrixItem?.let { item -> + is RoomDetailViewEvents.OpenIntegrationManager -> openIntegrationManager() + is RoomDetailViewEvents.OpenFile -> startOpenFileIntent(it) + RoomDetailViewEvents.OpenActiveWidgetBottomSheet -> onViewWidgetsClicked() + is RoomDetailViewEvents.ShowInfoOkDialog -> showDialogWithMessage(it.message) + is RoomDetailViewEvents.JoinJitsiConference -> joinJitsiRoom(it.widget, it.withVideo) + RoomDetailViewEvents.LeaveJitsiConference -> leaveJitsiConference() + RoomDetailViewEvents.ShowWaitingView -> vectorBaseActivity.showWaitingView() + RoomDetailViewEvents.HideWaitingView -> vectorBaseActivity.hideWaitingView() + is RoomDetailViewEvents.RequestNativeWidgetPermission -> requestNativeWidgetPermission(it) + is RoomDetailViewEvents.OpenRoom -> handleOpenRoom(it) + RoomDetailViewEvents.OpenInvitePeople -> navigator.openInviteUsersToRoom(requireContext(), timelineArgs.roomId) + RoomDetailViewEvents.OpenSetRoomAvatarDialog -> galleryOrCameraDialogHelper.show() + RoomDetailViewEvents.OpenRoomSettings -> handleOpenRoomSettings(RoomProfileActivity.EXTRA_DIRECT_ACCESS_ROOM_SETTINGS) + RoomDetailViewEvents.OpenRoomProfile -> handleOpenRoomSettings() + is RoomDetailViewEvents.ShowRoomAvatarFullScreen -> it.matrixItem?.let { item -> navigator.openBigImageViewer(requireActivity(), it.view, item) } - is RoomDetailViewEvents.StartChatEffect -> handleChatEffect(it.type) - RoomDetailViewEvents.StopChatEffects -> handleStopChatEffects() - is RoomDetailViewEvents.DisplayAndAcceptCall -> acceptIncomingCall(it) - RoomDetailViewEvents.RoomReplacementStarted -> handleRoomReplacement() - is RoomDetailViewEvents.ChangeLocationIndicator -> handleChangeLocationIndicator(it) + is RoomDetailViewEvents.StartChatEffect -> handleChatEffect(it.type) + RoomDetailViewEvents.StopChatEffects -> handleStopChatEffects() + is RoomDetailViewEvents.DisplayAndAcceptCall -> acceptIncomingCall(it) + RoomDetailViewEvents.RoomReplacementStarted -> handleRoomReplacement() + is RoomDetailViewEvents.ChangeLocationIndicator -> handleChangeLocationIndicator(it) } } @@ -506,7 +507,7 @@ class TimelineFragment @Inject constructor( private fun handleSlashCommandConfirmationRequest(action: MessageComposerViewEvents.SlashCommandConfirmationRequest) { when (action.parsedCommand) { is ParsedCommand.UnignoreUser -> promptUnignoreUser(action.parsedCommand) - else -> TODO("Add case for ${action.parsedCommand.javaClass.simpleName}") + else -> TODO("Add case for ${action.parsedCommand.javaClass.simpleName}") } lockSendButton = false } @@ -937,14 +938,14 @@ class TimelineFragment @Inject constructor( private fun handleShareData() { when (val sharedData = timelineArgs.sharedData) { - is SharedData.Text -> { + is SharedData.Text -> { messageComposerViewModel.handle(MessageComposerAction.EnterRegularMode(sharedData.text, fromSharing = true)) } is SharedData.Attachments -> { // open share edition onContentAttachmentsReady(sharedData.attachmentData) } - null -> Timber.v("No share data to process") + null -> Timber.v("No share data to process") } } @@ -1087,8 +1088,8 @@ class TimelineFragment @Inject constructor( // Set the visual state of the call buttons (voice/video) to enabled/disabled according to user permissions val hasCallInRoom = callManager.getCallsByRoomId(state.roomId).isNotEmpty() || state.jitsiState.hasJoined val callButtonsEnabled = !hasCallInRoom && when (state.asyncRoomSummary.invoke()?.joinedMembersCount) { - 1 -> false - 2 -> state.isAllowedToStartWebRTCCall + 1 -> false + 2 -> state.isAllowedToStartWebRTCCall else -> state.isAllowedToManageWidgets } setOf(R.id.voice_call, R.id.video_call).forEach { @@ -1122,39 +1123,39 @@ class TimelineFragment @Inject constructor( override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { - R.id.invite -> { + R.id.invite -> { navigator.openInviteUsersToRoom(requireActivity(), timelineArgs.roomId) true } - R.id.timeline_setting -> { + R.id.timeline_setting -> { navigator.openRoomProfile(requireActivity(), timelineArgs.roomId) true } - R.id.open_matrix_apps -> { + R.id.open_matrix_apps -> { timelineViewModel.handle(RoomDetailAction.ManageIntegrations) true } - R.id.voice_call -> { + R.id.voice_call -> { callActionsHandler.onVoiceCallClicked() true } - R.id.video_call -> { + R.id.video_call -> { callActionsHandler.onVideoCallClicked() true } - R.id.menu_timeline_thread_list -> { + R.id.menu_timeline_thread_list -> { navigateToThreadList() true } - R.id.search -> { + R.id.search -> { handleSearchAction() true } - R.id.dev_tools -> { + R.id.dev_tools -> { navigator.openDevTools(requireContext(), timelineArgs.roomId) true } - R.id.menu_thread_timeline_copy_link -> { + R.id.menu_thread_timeline_copy_link -> { getRootThreadEventId()?.let { val permalink = session.permalinkService().createPermalink(timelineArgs.roomId, it) copyToClipboard(requireContext(), permalink, false) @@ -1166,14 +1167,14 @@ class TimelineFragment @Inject constructor( handleViewInRoomAction() true } - R.id.menu_thread_timeline_share -> { + R.id.menu_thread_timeline_share -> { getRootThreadEventId()?.let { val permalink = session.permalinkService().createPermalink(timelineArgs.roomId, it) shareText(requireContext(), permalink) } true } - else -> super.onOptionsItemSelected(item) + else -> super.onOptionsItemSelected(item) } } @@ -1241,10 +1242,12 @@ class TimelineFragment @Inject constructor( views.composerLayout.views.sendButton.contentDescription = getString(R.string.action_send) } - private fun renderSpecialMode(event: TimelineEvent, - @DrawableRes iconRes: Int, - @StringRes descriptionRes: Int, - defaultContent: String) { + private fun renderSpecialMode( + event: TimelineEvent, + @DrawableRes iconRes: Int, + @StringRes descriptionRes: Int, + defaultContent: String + ) { autoCompleter.enterSpecialMode() // switch to expanded bar views.composerLayout.views.composerRelatedMessageTitle.apply { @@ -1255,8 +1258,8 @@ class TimelineFragment @Inject constructor( val messageContent: MessageContent? = event.getLastMessageContent() val nonFormattedBody = when (messageContent) { is MessageAudioContent -> getAudioContentBodyText(messageContent) - is MessagePollContent -> messageContent.getBestPollCreationInfo()?.question?.getBestQuestion() - else -> messageContent?.body.orEmpty() + is MessagePollContent -> messageContent.getBestPollCreationInfo()?.question?.getBestQuestion() + else -> messageContent?.body.orEmpty() } var formattedBody: CharSequence? = null if (messageContent is MessageTextContent && messageContent.format == MessageFormat.FORMAT_MATRIX_HTML) { @@ -1318,9 +1321,9 @@ class TimelineFragment @Inject constructor( when (roomDetailPendingAction) { is RoomDetailPendingAction.JumpToReadReceipt -> timelineViewModel.handle(RoomDetailAction.JumpToReadReceipt(roomDetailPendingAction.userId)) - is RoomDetailPendingAction.MentionUser -> + is RoomDetailPendingAction.MentionUser -> insertUserDisplayNameInTextEditor(roomDetailPendingAction.userId) - is RoomDetailPendingAction.OpenRoom -> + is RoomDetailPendingAction.OpenRoom -> handleOpenRoom(RoomDetailViewEvents.OpenRoom(roomDetailPendingAction.roomId, roomDetailPendingAction.closeCurrentRoom)) } } @@ -1462,7 +1465,7 @@ class TimelineFragment @Inject constructor( is MessageTextItem -> { return (model as AbsMessageItem).attributes.informationData.sendState == SendState.SYNCED } - else -> false + else -> false } } } @@ -1488,9 +1491,9 @@ class TimelineFragment @Inject constructor( val state = timelineViewModel.awaitState() val showJumpToUnreadBanner = when (state.unreadState) { UnreadState.Unknown, - UnreadState.HasNoUnread -> false + UnreadState.HasNoUnread -> false is UnreadState.ReadMarkerNotLoaded -> true - is UnreadState.HasUnread -> { + is UnreadState.HasUnread -> { if (state.canShowJumpToReadMarker) { val lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition() val positionOfReadMarker = withContext(Dispatchers.Default) { @@ -1550,7 +1553,7 @@ class TimelineFragment @Inject constructor( attachmentTypeSelector = AttachmentTypeSelectorView(vectorBaseActivity, vectorBaseActivity.layoutInflater, this@TimelineFragment) attachmentTypeSelector.setAttachmentVisibility( AttachmentTypeSelectorView.Type.LOCATION, - vectorPreferences.isLocationSharingEnabled() + BuildConfig.enableLocationSharing ) attachmentTypeSelector.setAttachmentVisibility( AttachmentTypeSelectorView.Type.POLL, !isThreadTimeLine() @@ -1645,10 +1648,10 @@ class TimelineFragment @Inject constructor( views.composerLayout.setRoomEncrypted(summary.isEncrypted) // views.composerLayout.alwaysShowSendButton = false when (messageComposerState.canSendMessage) { - CanSendStatus.Allowed -> { + CanSendStatus.Allowed -> { NotificationAreaView.State.Hidden } - CanSendStatus.NoPermission -> { + CanSendStatus.NoPermission -> { NotificationAreaView.State.NoPermissionToPost } is CanSendStatus.UnSupportedE2eAlgorithm -> { @@ -1722,23 +1725,23 @@ class TimelineFragment @Inject constructor( private fun renderSendMessageResult(sendMessageResult: MessageComposerViewEvents.SendMessageResult) { when (sendMessageResult) { - is MessageComposerViewEvents.SlashCommandLoading -> { + is MessageComposerViewEvents.SlashCommandLoading -> { showLoading(null) } - is MessageComposerViewEvents.SlashCommandError -> { + is MessageComposerViewEvents.SlashCommandError -> { displayCommandError(getString(R.string.command_problem_with_parameters, sendMessageResult.command.command)) } - is MessageComposerViewEvents.SlashCommandUnknown -> { + is MessageComposerViewEvents.SlashCommandUnknown -> { displayCommandError(getString(R.string.unrecognized_command, sendMessageResult.command)) } - is MessageComposerViewEvents.SlashCommandResultOk -> { + is MessageComposerViewEvents.SlashCommandResultOk -> { handleSlashCommandResultOk(sendMessageResult.parsedCommand) } - is MessageComposerViewEvents.SlashCommandResultError -> { + is MessageComposerViewEvents.SlashCommandResultError -> { dismissLoadingDialog() displayCommandError(errorFormatter.toHumanReadable(sendMessageResult.throwable)) } - is MessageComposerViewEvents.SlashCommandNotImplemented -> { + is MessageComposerViewEvents.SlashCommandNotImplemented -> { displayCommandError(getString(R.string.not_implemented)) } is MessageComposerViewEvents.SlashCommandNotSupportedInThreads -> { @@ -1756,7 +1759,7 @@ class TimelineFragment @Inject constructor( is ParsedCommand.SetMarkdown -> { showSnackWithMessage(getString(if (parsedCommand.enable) R.string.markdown_has_been_enabled else R.string.markdown_has_been_disabled)) } - else -> Unit + else -> Unit } } @@ -1771,10 +1774,10 @@ class TimelineFragment @Inject constructor( private fun displayE2eError(withHeldCode: WithHeldCode?) { val msgId = when (withHeldCode) { WithHeldCode.BLACKLISTED -> R.string.crypto_error_withheld_blacklisted - WithHeldCode.UNVERIFIED -> R.string.crypto_error_withheld_unverified + WithHeldCode.UNVERIFIED -> R.string.crypto_error_withheld_unverified WithHeldCode.UNAUTHORISED, WithHeldCode.UNAVAILABLE -> R.string.crypto_error_withheld_generic - else -> R.string.notice_crypto_unable_to_decrypt_friendly_desc + else -> R.string.notice_crypto_unable_to_decrypt_friendly_desc } MaterialAlertDialogBuilder(requireActivity()) .setMessage(msgId) @@ -1822,9 +1825,9 @@ class TimelineFragment @Inject constructor( private fun displayRoomDetailActionSuccess(result: RoomDetailViewEvents.ActionSuccess) { when (val data = result.action) { - is RoomDetailAction.ReportContent -> { + is RoomDetailAction.ReportContent -> { when { - data.spam -> { + data.spam -> { MaterialAlertDialogBuilder(requireActivity(), R.style.ThemeOverlay_Vector_MaterialAlertDialog_NegativeDestructive) .setTitle(R.string.content_reported_as_spam_title) .setMessage(R.string.content_reported_as_spam_content) @@ -1844,7 +1847,7 @@ class TimelineFragment @Inject constructor( } .show() } - else -> { + else -> { MaterialAlertDialogBuilder(requireActivity(), R.style.ThemeOverlay_Vector_MaterialAlertDialog_NegativeDestructive) .setTitle(R.string.content_reported_title) .setMessage(R.string.content_reported_content) @@ -1856,7 +1859,7 @@ class TimelineFragment @Inject constructor( } } } - is RoomDetailAction.RequestVerification -> { + is RoomDetailAction.RequestVerification -> { Timber.v("## SAS RequestVerification action") VerificationBottomSheet.withArgs( timelineArgs.roomId, @@ -1871,7 +1874,7 @@ class TimelineFragment @Inject constructor( data.transactionId ).show(parentFragmentManager, "REQ") } - is RoomDetailAction.ResumeVerification -> { + is RoomDetailAction.ResumeVerification -> { val otherUserId = data.otherUserId ?: return VerificationBottomSheet.withArgs( roomId = timelineArgs.roomId, @@ -1879,7 +1882,7 @@ class TimelineFragment @Inject constructor( transactionId = data.transactionId, ).show(parentFragmentManager, "REQ") } - else -> Unit + else -> Unit } } @@ -1926,7 +1929,7 @@ class TimelineFragment @Inject constructor( }) if (!isManaged) { when { - url.containsRtLOverride() -> { + url.containsRtLOverride() -> { displayUrlConfirmationDialog( seenUrl = title.ensureEndsLeftToRight(), actualUrl = url.filterDirectionOverrides(), @@ -1936,7 +1939,7 @@ class TimelineFragment @Inject constructor( title.isValidUrl() && url.isValidUrl() && URL(title).host != URL(url).host -> { displayUrlConfirmationDialog(title, url) } - else -> { + else -> { openUrlInExternalBrowser(requireContext(), url) } } @@ -1982,10 +1985,12 @@ class TimelineFragment @Inject constructor( vectorBaseActivity.notImplemented("encrypted message click") } - override fun onImageMessageClicked(messageImageContent: MessageImageInfoContent, - mediaData: ImageContentRenderer.Data, - view: View, - inMemory: List) { + override fun onImageMessageClicked( + messageImageContent: MessageImageInfoContent, + mediaData: ImageContentRenderer.Data, + view: View, + inMemory: List + ) { navigator.openMediaViewer( activity = requireActivity(), roomId = timelineArgs.roomId, @@ -2029,20 +2034,20 @@ class TimelineFragment @Inject constructor( is MessageVerificationRequestContent -> { timelineViewModel.handle(RoomDetailAction.ResumeVerification(informationData.eventId, null)) } - is MessageWithAttachmentContent -> { + is MessageWithAttachmentContent -> { val action = RoomDetailAction.DownloadOrOpen(informationData.eventId, informationData.senderId, messageContent) timelineViewModel.handle(action) } - is EncryptedEventContent -> { + is EncryptedEventContent -> { timelineViewModel.handle(RoomDetailAction.TapOnFailedToDecrypt(informationData.eventId)) } - is MessageLocationContent -> { + is MessageLocationContent -> { handleShowLocationPreview(messageContent, informationData.senderId) } - is MessageBeaconInfoContent -> { + is MessageBeaconInfoContent -> { navigateToLocationLiveMap() } - else -> { + else -> { val handled = onThreadSummaryClicked(informationData.eventId, isRootThreadEvent) if (!handled) { Timber.d("No click action defined for this message content") @@ -2179,8 +2184,8 @@ class TimelineFragment @Inject constructor( private fun onShareActionClicked(action: EventSharedAction.Share) { when (action.messageContent) { - is MessageTextContent -> shareText(requireContext(), action.messageContent.body) - is MessageLocationContent -> { + is MessageTextContent -> shareText(requireContext(), action.messageContent.body) + is MessageLocationContent -> { action.messageContent.toLocationData()?.let { openLocation(requireActivity(), it.latitude, it.longitude) } @@ -2240,52 +2245,52 @@ class TimelineFragment @Inject constructor( private fun handleActions(action: EventSharedAction) { when (action) { - is EventSharedAction.OpenUserProfile -> { + is EventSharedAction.OpenUserProfile -> { openRoomMemberProfile(action.userId) } - is EventSharedAction.AddReaction -> { + is EventSharedAction.AddReaction -> { openEmojiReactionPicker(action.eventId) } - is EventSharedAction.ViewReactions -> { + is EventSharedAction.ViewReactions -> { ViewReactionsBottomSheet.newInstance(timelineArgs.roomId, action.messageInformationData) .show(requireActivity().supportFragmentManager, "DISPLAY_REACTIONS") } - is EventSharedAction.Copy -> { + is EventSharedAction.Copy -> { // I need info about the current selected message :/ copyToClipboard(requireContext(), action.content, false) showSnackWithMessage(getString(R.string.copied_to_clipboard)) } - is EventSharedAction.Redact -> { + is EventSharedAction.Redact -> { promptConfirmationToRedactEvent(action) } - is EventSharedAction.Share -> { + is EventSharedAction.Share -> { onShareActionClicked(action) } - is EventSharedAction.Save -> { + is EventSharedAction.Save -> { onSaveActionClicked(action) } - is EventSharedAction.ViewEditHistory -> { + is EventSharedAction.ViewEditHistory -> { onEditedDecorationClicked(action.messageInformationData) } - is EventSharedAction.ViewSource -> { + is EventSharedAction.ViewSource -> { JSonViewerDialog.newInstance( action.content, -1, createJSonViewerStyleProvider(colorProvider) ).show(childFragmentManager, "JSON_VIEWER") } - is EventSharedAction.ViewDecryptedSource -> { + is EventSharedAction.ViewDecryptedSource -> { JSonViewerDialog.newInstance( action.content, -1, createJSonViewerStyleProvider(colorProvider) ).show(childFragmentManager, "JSON_VIEWER") } - is EventSharedAction.QuickReact -> { + is EventSharedAction.QuickReact -> { // eventId,ClickedOn,Add timelineViewModel.handle(RoomDetailAction.UpdateQuickReactAction(action.eventId, action.clickedOn, action.add)) } - is EventSharedAction.Edit -> { + is EventSharedAction.Edit -> { if (action.eventType in EventType.POLL_START) { navigator.openCreatePoll(requireContext(), timelineArgs.roomId, action.eventId, PollMode.EDIT) } else if (withState(messageComposerViewModel) { it.isVoiceMessageIdle }) { @@ -2294,45 +2299,45 @@ class TimelineFragment @Inject constructor( requireActivity().toast(R.string.error_voice_message_cannot_reply_or_edit) } } - is EventSharedAction.Quote -> { + is EventSharedAction.Quote -> { messageComposerViewModel.handle(MessageComposerAction.EnterQuoteMode(action.eventId, views.composerLayout.text.toString())) } - is EventSharedAction.Reply -> { + is EventSharedAction.Reply -> { if (withState(messageComposerViewModel) { it.isVoiceMessageIdle }) { messageComposerViewModel.handle(MessageComposerAction.EnterReplyMode(action.eventId, views.composerLayout.text.toString())) } else { requireActivity().toast(R.string.error_voice_message_cannot_reply_or_edit) } } - is EventSharedAction.ReplyInThread -> { + is EventSharedAction.ReplyInThread -> { if (withState(messageComposerViewModel) { it.isVoiceMessageIdle }) { onReplyInThreadClicked(action) } else { requireActivity().toast(R.string.error_voice_message_cannot_reply_or_edit) } } - is EventSharedAction.ViewInRoom -> { + is EventSharedAction.ViewInRoom -> { if (withState(messageComposerViewModel) { it.isVoiceMessageIdle }) { handleViewInRoomAction() } else { requireActivity().toast(R.string.error_voice_message_cannot_reply_or_edit) } } - is EventSharedAction.CopyPermalink -> { + is EventSharedAction.CopyPermalink -> { val permalink = session.permalinkService().createPermalink(timelineArgs.roomId, action.eventId) copyToClipboard(requireContext(), permalink, false) showSnackWithMessage(getString(R.string.copied_to_clipboard)) } - is EventSharedAction.Resend -> { + is EventSharedAction.Resend -> { timelineViewModel.handle(RoomDetailAction.ResendMessage(action.eventId)) } - is EventSharedAction.Remove -> { + is EventSharedAction.Remove -> { timelineViewModel.handle(RoomDetailAction.RemoveFailedEcho(action.eventId)) } - is EventSharedAction.Cancel -> { + is EventSharedAction.Cancel -> { handleCancelSend(action) } - is EventSharedAction.ReportContentSpam -> { + is EventSharedAction.ReportContentSpam -> { timelineViewModel.handle( RoomDetailAction.ReportContent( action.eventId, action.senderId, "This message is spam", spam = true @@ -2346,31 +2351,31 @@ class TimelineFragment @Inject constructor( ) ) } - is EventSharedAction.ReportContentCustom -> { + is EventSharedAction.ReportContentCustom -> { promptReasonToReportContent(action) } - is EventSharedAction.IgnoreUser -> { + is EventSharedAction.IgnoreUser -> { action.senderId?.let { askConfirmationToIgnoreUser(it) } } - is EventSharedAction.OnUrlClicked -> { + is EventSharedAction.OnUrlClicked -> { onUrlClicked(action.url, action.title) } - is EventSharedAction.OnUrlLongClicked -> { + is EventSharedAction.OnUrlLongClicked -> { onUrlLongClicked(action.url) } - is EventSharedAction.ReRequestKey -> { + is EventSharedAction.ReRequestKey -> { timelineViewModel.handle(RoomDetailAction.ReRequestKeys(action.eventId)) } - is EventSharedAction.UseKeyBackup -> { + is EventSharedAction.UseKeyBackup -> { context?.let { startActivity(KeysBackupRestoreActivity.intent(it)) } } - is EventSharedAction.EndPoll -> { + is EventSharedAction.EndPoll -> { askConfirmationToEndPoll(action.eventId) } - is EventSharedAction.ReportContent -> Unit /* Not clickable */ - EventSharedAction.Separator -> Unit /* Not clickable */ + is EventSharedAction.ReportContent -> Unit /* Not clickable */ + EventSharedAction.Separator -> Unit /* Not clickable */ } } @@ -2580,17 +2585,17 @@ class TimelineFragment @Inject constructor( private fun launchAttachmentProcess(type: AttachmentTypeSelectorView.Type) { when (type) { - AttachmentTypeSelectorView.Type.CAMERA -> attachmentsHelper.openCamera( + AttachmentTypeSelectorView.Type.CAMERA -> attachmentsHelper.openCamera( activity = requireActivity(), vectorPreferences = vectorPreferences, cameraActivityResultLauncher = attachmentCameraActivityResultLauncher, cameraVideoActivityResultLauncher = attachmentCameraVideoActivityResultLauncher ) - AttachmentTypeSelectorView.Type.FILE -> attachmentsHelper.selectFile(attachmentFileActivityResultLauncher) - AttachmentTypeSelectorView.Type.GALLERY -> attachmentsHelper.selectGallery(attachmentMediaActivityResultLauncher) - AttachmentTypeSelectorView.Type.CONTACT -> attachmentsHelper.selectContact(attachmentContactActivityResultLauncher) - AttachmentTypeSelectorView.Type.STICKER -> timelineViewModel.handle(RoomDetailAction.SelectStickerAttachment) - AttachmentTypeSelectorView.Type.POLL -> navigator.openCreatePoll(requireContext(), timelineArgs.roomId, null, PollMode.CREATE) + AttachmentTypeSelectorView.Type.FILE -> attachmentsHelper.selectFile(attachmentFileActivityResultLauncher) + AttachmentTypeSelectorView.Type.GALLERY -> attachmentsHelper.selectGallery(attachmentMediaActivityResultLauncher) + AttachmentTypeSelectorView.Type.CONTACT -> attachmentsHelper.selectContact(attachmentContactActivityResultLauncher) + AttachmentTypeSelectorView.Type.STICKER -> timelineViewModel.handle(RoomDetailAction.SelectStickerAttachment) + AttachmentTypeSelectorView.Type.POLL -> navigator.openCreatePoll(requireContext(), timelineArgs.roomId, null, PollMode.CREATE) AttachmentTypeSelectorView.Type.LOCATION -> { navigator .openLocationSharing( diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt index 86137b89f1..0fcc44910c 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt @@ -29,7 +29,6 @@ import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import im.vector.app.AppStateHandler -import im.vector.app.BuildConfig import im.vector.app.R import im.vector.app.core.di.MavericksAssistedViewModelFactory import im.vector.app.core.di.hiltMavericksViewModelFactory @@ -56,6 +55,8 @@ import im.vector.app.features.home.room.typing.TypingHelper import im.vector.app.features.location.LocationSharingServiceConnection import im.vector.app.features.notifications.NotificationDrawerManager import im.vector.app.features.powerlevel.PowerLevelsFlowFactory +import im.vector.app.features.raw.wellknown.getOutboundSessionKeySharingStrategyOrDefault +import im.vector.app.features.raw.wellknown.withElementWellKnown import im.vector.app.features.session.coroutineScope import im.vector.app.features.settings.VectorDataStore import im.vector.app.features.settings.VectorPreferences @@ -76,6 +77,7 @@ import kotlinx.coroutines.withContext import org.matrix.android.sdk.api.MatrixPatterns import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.query.QueryStringValue +import org.matrix.android.sdk.api.raw.RawService import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.MXCryptoError import org.matrix.android.sdk.api.session.events.model.EventType @@ -88,7 +90,6 @@ import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.file.FileService import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.api.session.initsync.SyncStatusService import org.matrix.android.sdk.api.session.room.getStateEvent import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState @@ -103,6 +104,7 @@ import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper import org.matrix.android.sdk.api.session.room.read.ReadService import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent +import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.threads.ThreadNotificationBadgeState import org.matrix.android.sdk.api.session.threads.ThreadNotificationState import org.matrix.android.sdk.api.session.widgets.model.WidgetType @@ -118,6 +120,7 @@ class TimelineViewModel @AssistedInject constructor( private val vectorDataStore: VectorDataStore, private val stringProvider: StringProvider, private val session: Session, + private val rawService: RawService, private val supportedVerificationMethodsProvider: SupportedVerificationMethodsProvider, private val stickerPickerActionHandler: StickerPickerActionHandler, private val typingHelper: TypingHelper, @@ -196,8 +199,13 @@ class TimelineViewModel @AssistedInject constructor( chatEffectManager.delegate = this // Ensure to share the outbound session keys with all members - if (OutboundSessionKeySharingStrategy.WhenEnteringRoom == BuildConfig.outboundSessionKeySharingStrategy && room.roomCryptoService().isEncrypted()) { - prepareForEncryption() + if (room.roomCryptoService().isEncrypted()) { + rawService.withElementWellKnown(viewModelScope, session.sessionParams) { + val strategy = it.getOutboundSessionKeySharingStrategyOrDefault() + if (strategy == OutboundSessionKeySharingStrategy.WhenEnteringRoom) { + prepareForEncryption() + } + } } // If the user had already accepted the invitation in the room list @@ -390,70 +398,70 @@ class TimelineViewModel @AssistedInject constructor( override fun handle(action: RoomDetailAction) { when (action) { - is RoomDetailAction.ComposerFocusChange -> handleComposerFocusChange(action) - is RoomDetailAction.SendMedia -> handleSendMedia(action) - is RoomDetailAction.SendSticker -> handleSendSticker(action) - is RoomDetailAction.TimelineEventTurnsVisible -> handleEventVisible(action) - is RoomDetailAction.TimelineEventTurnsInvisible -> handleEventInvisible(action) - is RoomDetailAction.LoadMoreTimelineEvents -> handleLoadMore(action) - is RoomDetailAction.SendReaction -> handleSendReaction(action) - is RoomDetailAction.AcceptInvite -> handleAcceptInvite() - is RoomDetailAction.RejectInvite -> handleRejectInvite() - is RoomDetailAction.RedactAction -> handleRedactEvent(action) - is RoomDetailAction.UndoReaction -> handleUndoReact(action) - is RoomDetailAction.UpdateQuickReactAction -> handleUpdateQuickReaction(action) - is RoomDetailAction.DownloadOrOpen -> handleOpenOrDownloadFile(action) - is RoomDetailAction.NavigateToEvent -> handleNavigateToEvent(action) - is RoomDetailAction.JoinAndOpenReplacementRoom -> handleJoinAndOpenReplacementRoom() - is RoomDetailAction.OnClickMisconfiguredEncryption -> handleClickMisconfiguredE2E() - is RoomDetailAction.ResendMessage -> handleResendEvent(action) - is RoomDetailAction.RemoveFailedEcho -> handleRemove(action) - is RoomDetailAction.MarkAllAsRead -> handleMarkAllAsRead() - is RoomDetailAction.ReportContent -> handleReportContent(action) - is RoomDetailAction.IgnoreUser -> handleIgnoreUser(action) + is RoomDetailAction.ComposerFocusChange -> handleComposerFocusChange(action) + is RoomDetailAction.SendMedia -> handleSendMedia(action) + is RoomDetailAction.SendSticker -> handleSendSticker(action) + is RoomDetailAction.TimelineEventTurnsVisible -> handleEventVisible(action) + is RoomDetailAction.TimelineEventTurnsInvisible -> handleEventInvisible(action) + is RoomDetailAction.LoadMoreTimelineEvents -> handleLoadMore(action) + is RoomDetailAction.SendReaction -> handleSendReaction(action) + is RoomDetailAction.AcceptInvite -> handleAcceptInvite() + is RoomDetailAction.RejectInvite -> handleRejectInvite() + is RoomDetailAction.RedactAction -> handleRedactEvent(action) + is RoomDetailAction.UndoReaction -> handleUndoReact(action) + is RoomDetailAction.UpdateQuickReactAction -> handleUpdateQuickReaction(action) + is RoomDetailAction.DownloadOrOpen -> handleOpenOrDownloadFile(action) + is RoomDetailAction.NavigateToEvent -> handleNavigateToEvent(action) + is RoomDetailAction.JoinAndOpenReplacementRoom -> handleJoinAndOpenReplacementRoom() + is RoomDetailAction.OnClickMisconfiguredEncryption -> handleClickMisconfiguredE2E() + is RoomDetailAction.ResendMessage -> handleResendEvent(action) + is RoomDetailAction.RemoveFailedEcho -> handleRemove(action) + is RoomDetailAction.MarkAllAsRead -> handleMarkAllAsRead() + is RoomDetailAction.ReportContent -> handleReportContent(action) + is RoomDetailAction.IgnoreUser -> handleIgnoreUser(action) is RoomDetailAction.EnterTrackingUnreadMessagesState -> startTrackingUnreadMessages() - is RoomDetailAction.ExitTrackingUnreadMessagesState -> stopTrackingUnreadMessages() - is RoomDetailAction.VoteToPoll -> handleVoteToPoll(action) - is RoomDetailAction.AcceptVerificationRequest -> handleAcceptVerification(action) - is RoomDetailAction.DeclineVerificationRequest -> handleDeclineVerification(action) - is RoomDetailAction.RequestVerification -> handleRequestVerification(action) - is RoomDetailAction.ResumeVerification -> handleResumeRequestVerification(action) - is RoomDetailAction.ReRequestKeys -> handleReRequestKeys(action) - is RoomDetailAction.TapOnFailedToDecrypt -> handleTapOnFailedToDecrypt(action) - is RoomDetailAction.SelectStickerAttachment -> handleSelectStickerAttachment() - is RoomDetailAction.OpenIntegrationManager -> handleOpenIntegrationManager() - is RoomDetailAction.StartCall -> handleStartCall(action) - is RoomDetailAction.AcceptCall -> handleAcceptCall(action) - is RoomDetailAction.EndCall -> handleEndCall() - is RoomDetailAction.ManageIntegrations -> handleManageIntegrations() - is RoomDetailAction.AddJitsiWidget -> handleAddJitsiConference(action) - is RoomDetailAction.UpdateJoinJitsiCallStatus -> handleJitsiCallJoinStatus(action) - is RoomDetailAction.JoinJitsiCall -> handleJoinJitsiCall() - is RoomDetailAction.LeaveJitsiCall -> handleLeaveJitsiCall() - is RoomDetailAction.RemoveWidget -> handleDeleteWidget(action.widgetId) - is RoomDetailAction.EnsureNativeWidgetAllowed -> handleCheckWidgetAllowed(action) - is RoomDetailAction.CancelSend -> handleCancel(action) - is RoomDetailAction.JumpToReadReceipt -> handleJumpToReadReceipt(action) - RoomDetailAction.QuickActionInvitePeople -> handleInvitePeople() - RoomDetailAction.QuickActionSetAvatar -> handleQuickSetAvatar() - is RoomDetailAction.SetAvatarAction -> handleSetNewAvatar(action) - RoomDetailAction.QuickActionSetTopic -> _viewEvents.post(RoomDetailViewEvents.OpenRoomSettings) - is RoomDetailAction.ShowRoomAvatarFullScreen -> { + is RoomDetailAction.ExitTrackingUnreadMessagesState -> stopTrackingUnreadMessages() + is RoomDetailAction.VoteToPoll -> handleVoteToPoll(action) + is RoomDetailAction.AcceptVerificationRequest -> handleAcceptVerification(action) + is RoomDetailAction.DeclineVerificationRequest -> handleDeclineVerification(action) + is RoomDetailAction.RequestVerification -> handleRequestVerification(action) + is RoomDetailAction.ResumeVerification -> handleResumeRequestVerification(action) + is RoomDetailAction.ReRequestKeys -> handleReRequestKeys(action) + is RoomDetailAction.TapOnFailedToDecrypt -> handleTapOnFailedToDecrypt(action) + is RoomDetailAction.SelectStickerAttachment -> handleSelectStickerAttachment() + is RoomDetailAction.OpenIntegrationManager -> handleOpenIntegrationManager() + is RoomDetailAction.StartCall -> handleStartCall(action) + is RoomDetailAction.AcceptCall -> handleAcceptCall(action) + is RoomDetailAction.EndCall -> handleEndCall() + is RoomDetailAction.ManageIntegrations -> handleManageIntegrations() + is RoomDetailAction.AddJitsiWidget -> handleAddJitsiConference(action) + is RoomDetailAction.UpdateJoinJitsiCallStatus -> handleJitsiCallJoinStatus(action) + is RoomDetailAction.JoinJitsiCall -> handleJoinJitsiCall() + is RoomDetailAction.LeaveJitsiCall -> handleLeaveJitsiCall() + is RoomDetailAction.RemoveWidget -> handleDeleteWidget(action.widgetId) + is RoomDetailAction.EnsureNativeWidgetAllowed -> handleCheckWidgetAllowed(action) + is RoomDetailAction.CancelSend -> handleCancel(action) + is RoomDetailAction.JumpToReadReceipt -> handleJumpToReadReceipt(action) + RoomDetailAction.QuickActionInvitePeople -> handleInvitePeople() + RoomDetailAction.QuickActionSetAvatar -> handleQuickSetAvatar() + is RoomDetailAction.SetAvatarAction -> handleSetNewAvatar(action) + RoomDetailAction.QuickActionSetTopic -> _viewEvents.post(RoomDetailViewEvents.OpenRoomSettings) + is RoomDetailAction.ShowRoomAvatarFullScreen -> { _viewEvents.post( RoomDetailViewEvents.ShowRoomAvatarFullScreen(action.matrixItem, action.transitionView) ) } - is RoomDetailAction.DoNotShowPreviewUrlFor -> handleDoNotShowPreviewUrlFor(action) - RoomDetailAction.RemoveAllFailedMessages -> handleRemoveAllFailedMessages() - RoomDetailAction.ResendAll -> handleResendAll() - is RoomDetailAction.RoomUpgradeSuccess -> { + is RoomDetailAction.DoNotShowPreviewUrlFor -> handleDoNotShowPreviewUrlFor(action) + RoomDetailAction.RemoveAllFailedMessages -> handleRemoveAllFailedMessages() + RoomDetailAction.ResendAll -> handleResendAll() + is RoomDetailAction.RoomUpgradeSuccess -> { setState { copy(joinUpgradedRoomAsync = Success(action.replacementRoomId)) } _viewEvents.post(RoomDetailViewEvents.OpenRoom(action.replacementRoomId, closeCurrentRoom = true)) } - is RoomDetailAction.EndPoll -> handleEndPoll(action.eventId) - RoomDetailAction.StopLiveLocationSharing -> handleStopLiveLocationSharing() + is RoomDetailAction.EndPoll -> handleEndPoll(action.eventId) + RoomDetailAction.StopLiveLocationSharing -> handleStopLiveLocationSharing() } } @@ -470,7 +478,7 @@ class TimelineViewModel @AssistedInject constructor( is ConferenceEvent.Terminated -> { setState { copy(jitsiState = jitsiState.copy(hasJoined = activeConferenceHolder.isJoined(jitsiState.confId))) } } - else -> Unit + else -> Unit } } @@ -605,7 +613,7 @@ class TimelineViewModel @AssistedInject constructor( is Success -> { Success(activeRoomWidgets.invoke().filter { it.widgetId != widgetId }) } - else -> activeRoomWidgets + else -> activeRoomWidgets } ) } @@ -667,10 +675,13 @@ class TimelineViewModel @AssistedInject constructor( private fun handleComposerFocusChange(action: RoomDetailAction.ComposerFocusChange) { // Ensure outbound session keys - if (OutboundSessionKeySharingStrategy.WhenTyping == BuildConfig.outboundSessionKeySharingStrategy && room.roomCryptoService().isEncrypted()) { - if (action.focused) { - // Should we add some rate limit here, or do it only once per model lifecycle? - prepareForEncryption() + if (room.roomCryptoService().isEncrypted()) { + rawService.withElementWellKnown(viewModelScope, session.sessionParams) { + val strategy = it.getOutboundSessionKeySharingStrategyOrDefault() + if (strategy == OutboundSessionKeySharingStrategy.WhenTyping && action.focused) { + // Should we add some rate limit here, or do it only once per model lifecycle? + prepareForEncryption() + } } } } @@ -726,21 +737,21 @@ class TimelineViewModel @AssistedInject constructor( R.id.menu_thread_timeline_view_in_room, R.id.menu_thread_timeline_copy_link, R.id.menu_thread_timeline_share -> true - else -> false + else -> false } } else { when (itemId) { - R.id.timeline_setting -> true - R.id.invite -> state.canInvite - R.id.open_matrix_apps -> true - R.id.voice_call -> state.isCallOptionAvailable() - R.id.video_call -> state.isCallOptionAvailable() || state.jitsiState.confId == null || state.jitsiState.hasJoined + R.id.timeline_setting -> true + R.id.invite -> state.canInvite + R.id.open_matrix_apps -> true + R.id.voice_call -> state.isCallOptionAvailable() + R.id.video_call -> state.isCallOptionAvailable() || state.jitsiState.confId == null || state.jitsiState.hasJoined // Show Join conference button only if there is an active conf id not joined. Otherwise fallback to default video disabled. ^ - R.id.join_conference -> !state.isCallOptionAvailable() && state.jitsiState.confId != null && !state.jitsiState.hasJoined - R.id.search -> state.isSearchAvailable() + R.id.join_conference -> !state.isCallOptionAvailable() && state.jitsiState.confId != null && !state.jitsiState.hasJoined + R.id.search -> state.isSearchAvailable() R.id.menu_timeline_thread_list -> vectorPreferences.areThreadMessagesEnabled() - R.id.dev_tools -> vectorPreferences.developerMode() - else -> false + R.id.dev_tools -> vectorPreferences.developerMode() + else -> false } } } @@ -918,9 +929,9 @@ class TimelineViewModel @AssistedInject constructor( return } when { - it.root.isTextMessage() -> room.sendService().resendTextMessage(it) + it.root.isTextMessage() -> room.sendService().resendTextMessage(it) it.root.isAttachmentMessage() -> room.sendService().resendMediaMessage(it) - else -> { + else -> { // TODO } } @@ -1089,7 +1100,7 @@ class TimelineViewModel @AssistedInject constructor( MXCryptoError.ErrorType.KEYS_WITHHELD -> { WithHeldCode.fromCode(it.root.mCryptoErrorReason) } - else -> null + else -> null } _viewEvents.post(RoomDetailViewEvents.ShowE2EErrorMessage(code)) @@ -1119,11 +1130,11 @@ class TimelineViewModel @AssistedInject constructor( copy(syncState = syncState) } - session.syncStatusService().getSyncStatusLive() + session.syncService().getSyncRequestStateLive() .asFlow() - .filterIsInstance() + .filterIsInstance() .setOnEach { - copy(incrementalSyncStatus = it) + copy(incrementalSyncRequestState = it) } } @@ -1155,9 +1166,9 @@ class TimelineViewModel @AssistedInject constructor( when { previous is UnreadState.Unknown || previous is UnreadState.ReadMarkerNotLoaded -> false previous is UnreadState.HasUnread && current is UnreadState.HasUnread && - previous.readMarkerId == current.readMarkerId -> false - current is UnreadState.HasUnread || current is UnreadState.HasNoUnread -> true - else -> false + previous.readMarkerId == current.readMarkerId -> false + current is UnreadState.HasUnread || current is UnreadState.HasNoUnread -> true + else -> false } } .setOnEach { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerView.kt index e77ad66a9f..1522960cc9 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerView.kt @@ -39,7 +39,8 @@ import im.vector.app.databinding.ComposerLayoutBinding class MessageComposerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, - defStyleAttr: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr) { + defStyleAttr: Int = 0 +) : ConstraintLayout(context, attrs, defStyleAttr) { interface Callback : ComposerEditText.Callback { fun onCloseRelatedMessage() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt index eca5c846ca..53f89603ff 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt @@ -96,26 +96,26 @@ class MessageComposerViewModel @AssistedInject constructor( override fun handle(action: MessageComposerAction) { when (action) { - is MessageComposerAction.EnterEditMode -> handleEnterEditMode(action) - is MessageComposerAction.EnterQuoteMode -> handleEnterQuoteMode(action) - is MessageComposerAction.EnterRegularMode -> handleEnterRegularMode(action) - is MessageComposerAction.EnterReplyMode -> handleEnterReplyMode(action) - is MessageComposerAction.SendMessage -> handleSendMessage(action) - is MessageComposerAction.UserIsTyping -> handleUserIsTyping(action) - is MessageComposerAction.OnTextChanged -> handleOnTextChanged(action) + is MessageComposerAction.EnterEditMode -> handleEnterEditMode(action) + is MessageComposerAction.EnterQuoteMode -> handleEnterQuoteMode(action) + is MessageComposerAction.EnterRegularMode -> handleEnterRegularMode(action) + is MessageComposerAction.EnterReplyMode -> handleEnterReplyMode(action) + is MessageComposerAction.SendMessage -> handleSendMessage(action) + is MessageComposerAction.UserIsTyping -> handleUserIsTyping(action) + is MessageComposerAction.OnTextChanged -> handleOnTextChanged(action) is MessageComposerAction.OnVoiceRecordingUiStateChanged -> handleOnVoiceRecordingUiStateChanged(action) - is MessageComposerAction.StartRecordingVoiceMessage -> handleStartRecordingVoiceMessage() - is MessageComposerAction.EndRecordingVoiceMessage -> handleEndRecordingVoiceMessage(action.isCancelled, action.rootThreadEventId) - is MessageComposerAction.PlayOrPauseVoicePlayback -> handlePlayOrPauseVoicePlayback(action) - MessageComposerAction.PauseRecordingVoiceMessage -> handlePauseRecordingVoiceMessage() - MessageComposerAction.PlayOrPauseRecordingPlayback -> handlePlayOrPauseRecordingPlayback() - is MessageComposerAction.EndAllVoiceActions -> handleEndAllVoiceActions(action.deleteRecord) - is MessageComposerAction.InitializeVoiceRecorder -> handleInitializeVoiceRecorder(action.attachmentData) - is MessageComposerAction.OnEntersBackground -> handleEntersBackground(action.composerText) - is MessageComposerAction.VoiceWaveformTouchedUp -> handleVoiceWaveformTouchedUp(action) - is MessageComposerAction.VoiceWaveformMovedTo -> handleVoiceWaveformMovedTo(action) - is MessageComposerAction.AudioSeekBarMovedTo -> handleAudioSeekBarMovedTo(action) - is MessageComposerAction.SlashCommandConfirmed -> handleSlashCommandConfirmed(action) + is MessageComposerAction.StartRecordingVoiceMessage -> handleStartRecordingVoiceMessage() + is MessageComposerAction.EndRecordingVoiceMessage -> handleEndRecordingVoiceMessage(action.isCancelled, action.rootThreadEventId) + is MessageComposerAction.PlayOrPauseVoicePlayback -> handlePlayOrPauseVoicePlayback(action) + MessageComposerAction.PauseRecordingVoiceMessage -> handlePauseRecordingVoiceMessage() + MessageComposerAction.PlayOrPauseRecordingPlayback -> handlePlayOrPauseRecordingPlayback() + is MessageComposerAction.EndAllVoiceActions -> handleEndAllVoiceActions(action.deleteRecord) + is MessageComposerAction.InitializeVoiceRecorder -> handleInitializeVoiceRecorder(action.attachmentData) + is MessageComposerAction.OnEntersBackground -> handleEntersBackground(action.composerText) + is MessageComposerAction.VoiceWaveformTouchedUp -> handleVoiceWaveformTouchedUp(action) + is MessageComposerAction.VoiceWaveformMovedTo -> handleVoiceWaveformMovedTo(action) + is MessageComposerAction.AudioSeekBarMovedTo -> handleAudioSeekBarMovedTo(action) + is MessageComposerAction.SlashCommandConfirmed -> handleSlashCommandConfirmed(action) } } @@ -205,7 +205,7 @@ class MessageComposerViewModel @AssistedInject constructor( textMessage = action.text, isInThreadTimeline = state.isInThreadTimeline() )) { - is ParsedCommand.ErrorNotACommand -> { + is ParsedCommand.ErrorNotACommand -> { // Send the text message to the room if (state.rootThreadEventId != null) { room.relationService().replyInThread( @@ -220,19 +220,19 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.MessageSent) popDraft() } - is ParsedCommand.ErrorSyntax -> { + is ParsedCommand.ErrorSyntax -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandError(parsedCommand.command)) } - is ParsedCommand.ErrorEmptySlashCommand -> { + is ParsedCommand.ErrorEmptySlashCommand -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandUnknown("/")) } - is ParsedCommand.ErrorUnknownSlashCommand -> { + is ParsedCommand.ErrorUnknownSlashCommand -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandUnknown(parsedCommand.slashCommand)) } is ParsedCommand.ErrorCommandNotSupportedInThreads -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandNotSupportedInThreads(parsedCommand.command)) } - is ParsedCommand.SendPlainText -> { + is ParsedCommand.SendPlainText -> { // Send the text message to the room, without markdown if (state.rootThreadEventId != null) { room.relationService().replyInThread( @@ -246,50 +246,50 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.MessageSent) popDraft() } - is ParsedCommand.ChangeRoomName -> { + is ParsedCommand.ChangeRoomName -> { handleChangeRoomNameSlashCommand(parsedCommand) } - is ParsedCommand.Invite -> { + is ParsedCommand.Invite -> { handleInviteSlashCommand(parsedCommand) } - is ParsedCommand.Invite3Pid -> { + is ParsedCommand.Invite3Pid -> { handleInvite3pidSlashCommand(parsedCommand) } - is ParsedCommand.SetUserPowerLevel -> { + is ParsedCommand.SetUserPowerLevel -> { handleSetUserPowerLevel(parsedCommand) } - is ParsedCommand.ClearScalarToken -> { + is ParsedCommand.ClearScalarToken -> { // TODO _viewEvents.post(MessageComposerViewEvents.SlashCommandNotImplemented) } - is ParsedCommand.SetMarkdown -> { + is ParsedCommand.SetMarkdown -> { vectorPreferences.setMarkdownEnabled(parsedCommand.enable) _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.BanUser -> { + is ParsedCommand.BanUser -> { handleBanSlashCommand(parsedCommand) } - is ParsedCommand.UnbanUser -> { + is ParsedCommand.UnbanUser -> { handleUnbanSlashCommand(parsedCommand) } - is ParsedCommand.IgnoreUser -> { + is ParsedCommand.IgnoreUser -> { handleIgnoreSlashCommand(parsedCommand) } - is ParsedCommand.UnignoreUser -> { + is ParsedCommand.UnignoreUser -> { handleUnignoreSlashCommand(parsedCommand) } - is ParsedCommand.RemoveUser -> { + is ParsedCommand.RemoveUser -> { handleRemoveSlashCommand(parsedCommand) } - is ParsedCommand.JoinRoom -> { + is ParsedCommand.JoinRoom -> { handleJoinToAnotherRoomSlashCommand(parsedCommand) popDraft() } - is ParsedCommand.PartRoom -> { + is ParsedCommand.PartRoom -> { handlePartSlashCommand(parsedCommand) } - is ParsedCommand.SendEmote -> { + is ParsedCommand.SendEmote -> { if (state.rootThreadEventId != null) { room.relationService().replyInThread( rootThreadEventId = state.rootThreadEventId, @@ -307,7 +307,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendRainbow -> { + is ParsedCommand.SendRainbow -> { val message = parsedCommand.message.toString() if (state.rootThreadEventId != null) { room.relationService().replyInThread( @@ -321,7 +321,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendRainbowEmote -> { + is ParsedCommand.SendRainbowEmote -> { val message = parsedCommand.message.toString() if (state.rootThreadEventId != null) { room.relationService().replyInThread( @@ -337,7 +337,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendSpoiler -> { + is ParsedCommand.SendSpoiler -> { val text = "[${stringProvider.getString(R.string.spoiler)}](${parsedCommand.message})" val formattedText = "${parsedCommand.message}" if (state.rootThreadEventId != null) { @@ -355,42 +355,42 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendShrug -> { + is ParsedCommand.SendShrug -> { sendPrefixedMessage("¯\\_(ツ)_/¯", parsedCommand.message, state.rootThreadEventId) _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendLenny -> { + is ParsedCommand.SendLenny -> { sendPrefixedMessage("( ͡° ͜ʖ ͡°)", parsedCommand.message, state.rootThreadEventId) _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.SendChatEffect -> { + is ParsedCommand.SendChatEffect -> { sendChatEffect(parsedCommand) _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) popDraft() } - is ParsedCommand.ChangeTopic -> { + is ParsedCommand.ChangeTopic -> { handleChangeTopicSlashCommand(parsedCommand) } - is ParsedCommand.ChangeDisplayName -> { + is ParsedCommand.ChangeDisplayName -> { handleChangeDisplayNameSlashCommand(parsedCommand) } - is ParsedCommand.ChangeDisplayNameForRoom -> { + is ParsedCommand.ChangeDisplayNameForRoom -> { handleChangeDisplayNameForRoomSlashCommand(parsedCommand) } - is ParsedCommand.ChangeRoomAvatar -> { + is ParsedCommand.ChangeRoomAvatar -> { handleChangeRoomAvatarSlashCommand(parsedCommand) } - is ParsedCommand.ChangeAvatarForRoom -> { + is ParsedCommand.ChangeAvatarForRoom -> { handleChangeAvatarForRoomSlashCommand(parsedCommand) } - is ParsedCommand.ShowUser -> { + is ParsedCommand.ShowUser -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) handleWhoisSlashCommand(parsedCommand) popDraft() } - is ParsedCommand.DiscardSession -> { + is ParsedCommand.DiscardSession -> { if (room.roomCryptoService().isEncrypted()) { session.cryptoService().discardOutboundSession(room.roomId) _viewEvents.post(MessageComposerViewEvents.SlashCommandResultOk(parsedCommand)) @@ -403,7 +403,7 @@ class MessageComposerViewModel @AssistedInject constructor( ) } } - is ParsedCommand.CreateSpace -> { + is ParsedCommand.CreateSpace -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandLoading) viewModelScope.launch(Dispatchers.IO) { try { @@ -427,7 +427,7 @@ class MessageComposerViewModel @AssistedInject constructor( } Unit } - is ParsedCommand.AddToSpace -> { + is ParsedCommand.AddToSpace -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandLoading) viewModelScope.launch(Dispatchers.IO) { try { @@ -446,7 +446,7 @@ class MessageComposerViewModel @AssistedInject constructor( } Unit } - is ParsedCommand.JoinSpace -> { + is ParsedCommand.JoinSpace -> { _viewEvents.post(MessageComposerViewEvents.SlashCommandLoading) viewModelScope.launch(Dispatchers.IO) { try { @@ -459,7 +459,7 @@ class MessageComposerViewModel @AssistedInject constructor( } Unit } - is ParsedCommand.LeaveRoom -> { + is ParsedCommand.LeaveRoom -> { viewModelScope.launch(Dispatchers.IO) { try { session.roomService().leaveRoom(parsedCommand.roomId) @@ -471,7 +471,7 @@ class MessageComposerViewModel @AssistedInject constructor( } Unit } - is ParsedCommand.UpgradeRoom -> { + is ParsedCommand.UpgradeRoom -> { _viewEvents.post( MessageComposerViewEvents.ShowRoomUpgradeDialog( parsedCommand.newVersion, @@ -483,7 +483,7 @@ class MessageComposerViewModel @AssistedInject constructor( } } } - is SendMode.Edit -> { + is SendMode.Edit -> { // is original event a reply? val relationContent = state.sendMode.timelineEvent.getRelationContent() val inReplyTo = if (state.rootThreadEventId != null) { @@ -522,7 +522,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.MessageSent) popDraft() } - is SendMode.Quote -> { + is SendMode.Quote -> { room.sendService().sendQuotedTextMessage( quotedEvent = state.sendMode.timelineEvent, text = action.text.toString(), @@ -532,7 +532,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.MessageSent) popDraft() } - is SendMode.Reply -> { + is SendMode.Reply -> { val timelineEvent = state.sendMode.timelineEvent val showInThread = state.sendMode.timelineEvent.root.isThread() && state.rootThreadEventId == null // If threads are disabled this will make the fallback replies visible to clients with threads enabled @@ -555,7 +555,7 @@ class MessageComposerViewModel @AssistedInject constructor( _viewEvents.post(MessageComposerViewEvents.MessageSent) popDraft() } - is SendMode.Voice -> { + is SendMode.Voice -> { // do nothing } } @@ -582,23 +582,23 @@ class MessageComposerViewModel @AssistedInject constructor( // Create a sendMode from a draft and retrieve the TimelineEvent sendMode = when (currentDraft) { is UserDraft.Regular -> SendMode.Regular(currentDraft.content, false) - is UserDraft.Quote -> { + is UserDraft.Quote -> { room.getTimelineEvent(currentDraft.linkedEventId)?.let { timelineEvent -> SendMode.Quote(timelineEvent, currentDraft.content) } } - is UserDraft.Reply -> { + is UserDraft.Reply -> { room.getTimelineEvent(currentDraft.linkedEventId)?.let { timelineEvent -> SendMode.Reply(timelineEvent, currentDraft.content) } } - is UserDraft.Edit -> { + is UserDraft.Edit -> { room.getTimelineEvent(currentDraft.linkedEventId)?.let { timelineEvent -> SendMode.Edit(timelineEvent, currentDraft.content) } } - is UserDraft.Voice -> SendMode.Voice(currentDraft.content) - else -> null + is UserDraft.Voice -> SendMode.Voice(currentDraft.content) + else -> null } ?: SendMode.Regular("", fromSharing = false) ) } @@ -790,7 +790,7 @@ class MessageComposerViewModel @AssistedInject constructor( private fun handleSlashCommandConfirmed(action: MessageComposerAction.SlashCommandConfirmed) { when (action.parsedCommand) { is ParsedCommand.UnignoreUser -> handleUnignoreSlashCommandConfirmed(action.parsedCommand) - else -> TODO("Not handled yet") + else -> TODO("Not handled yet") } } @@ -827,15 +827,15 @@ class MessageComposerViewModel @AssistedInject constructor( setState { copy(sendMode = it.sendMode.copy(text = draft)) } room.draftService().saveDraft(UserDraft.Regular(draft)) } - it.sendMode is SendMode.Reply -> { + it.sendMode is SendMode.Reply -> { setState { copy(sendMode = it.sendMode.copy(text = draft)) } room.draftService().saveDraft(UserDraft.Reply(it.sendMode.timelineEvent.root.eventId!!, draft)) } - it.sendMode is SendMode.Quote -> { + it.sendMode is SendMode.Quote -> { setState { copy(sendMode = it.sendMode.copy(text = draft)) } room.draftService().saveDraft(UserDraft.Quote(it.sendMode.timelineEvent.root.eventId!!, draft)) } - it.sendMode is SendMode.Edit -> { + it.sendMode is SendMode.Edit -> { setState { copy(sendMode = it.sendMode.copy(text = draft)) } room.draftService().saveDraft(UserDraft.Edit(it.sendMode.timelineEvent.root.eventId!!, draft)) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt index 75a6c1e912..5698414ab4 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt @@ -53,8 +53,8 @@ sealed interface CanSendStatus { fun CanSendStatus.boolean(): Boolean { return when (this) { - CanSendStatus.Allowed -> true - CanSendStatus.NoPermission -> false + CanSendStatus.Allowed -> true + CanSendStatus.NoPermission -> false is CanSendStatus.UnSupportedE2eAlgorithm -> false } } @@ -70,7 +70,7 @@ data class MessageComposerViewState( ) : MavericksState { val isVoiceRecording = when (voiceRecordingUiState) { - VoiceMessageRecorderView.RecordingUiState.Idle -> false + VoiceMessageRecorderView.RecordingUiState.Idle -> false is VoiceMessageRecorderView.RecordingUiState.Locked, VoiceMessageRecorderView.RecordingUiState.Draft, is VoiceMessageRecorderView.RecordingUiState.Recording -> true diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/DraggableStateProcessor.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/DraggableStateProcessor.kt index 088070ceb9..1355c89006 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/DraggableStateProcessor.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/DraggableStateProcessor.kt @@ -56,28 +56,28 @@ class DraggableStateProcessor( private fun DraggingState.nextDragState(currentX: Float, currentY: Float, distanceX: Float, distanceY: Float): DraggingState { return when (this) { - DraggingState.Ready -> { + DraggingState.Ready -> { when { isDraggingToCancel(currentX, distanceX, distanceY) -> DraggingState.Cancelling(distanceX) - isDraggingToLock(currentY, distanceX, distanceY) -> DraggingState.Locking(distanceY) - else -> DraggingState.Ready + isDraggingToLock(currentY, distanceX, distanceY) -> DraggingState.Locking(distanceY) + else -> DraggingState.Ready } } is DraggingState.Cancelling -> { when { isDraggingToLock(currentY, distanceX, distanceY) -> DraggingState.Locking(distanceY) - shouldCancelRecording(distanceX) -> DraggingState.Cancel - else -> DraggingState.Cancelling(distanceX) + shouldCancelRecording(distanceX) -> DraggingState.Cancel + else -> DraggingState.Cancelling(distanceX) } } - is DraggingState.Locking -> { + is DraggingState.Locking -> { when { isDraggingToCancel(currentX, distanceX, distanceY) -> DraggingState.Cancelling(distanceX) - shouldLockRecording(distanceY) -> DraggingState.Lock - else -> DraggingState.Locking(distanceY) + shouldLockRecording(distanceY) -> DraggingState.Lock + else -> DraggingState.Locking(distanceY) } } - else -> { + else -> { this } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt index 4350ad6a7d..536a582ec1 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt @@ -84,12 +84,12 @@ class VoiceMessageRecorderView @JvmOverloads constructor( override fun onRequestRecording() = callback.onVoiceRecordingStarted() override fun onMicButtonReleased() { when (dragState) { - DraggingState.Lock -> { + DraggingState.Lock -> { // do nothing, // onSendVoiceMessage, onDeleteVoiceMessage or onRecordingLimitReached will be triggered instead } DraggingState.Cancel -> callback.onVoiceRecordingCancelled() - else -> callback.onVoiceRecordingEnded() + else -> callback.onVoiceRecordingEnded() } } @@ -99,7 +99,7 @@ class VoiceMessageRecorderView @JvmOverloads constructor( when (lastKnownState) { is RecordingUiState.Recording, is RecordingUiState.Locked -> callback.onRecordingWaveformClicked() - else -> Unit + else -> Unit } } @@ -133,7 +133,7 @@ class VoiceMessageRecorderView @JvmOverloads constructor( fun render(recordingState: RecordingUiState) { if (lastKnownState == recordingState) return when (recordingState) { - RecordingUiState.Idle -> { + RecordingUiState.Idle -> { reset() } is RecordingUiState.Recording -> { @@ -142,7 +142,7 @@ class VoiceMessageRecorderView @JvmOverloads constructor( voiceMessageViews.showRecordingViews() dragState = DraggingState.Ready } - is RecordingUiState.Locked -> { + is RecordingUiState.Locked -> { if (lastKnownState == null) { startRecordingTicker(startFromLocked = true, startAt = recordingState.recordingStartTimestamp) } @@ -151,7 +151,7 @@ class VoiceMessageRecorderView @JvmOverloads constructor( voiceMessageViews.showRecordingLockedViews(recordingState) }, 500) } - RecordingUiState.Draft -> { + RecordingUiState.Draft -> { stopRecordingTicker() voiceMessageViews.showDraftViews() } @@ -169,16 +169,16 @@ class VoiceMessageRecorderView @JvmOverloads constructor( if (currentDragState == newDragState) return when (newDragState) { is DraggingState.Cancelling -> voiceMessageViews.renderCancelling(newDragState.distanceX) - is DraggingState.Locking -> { + is DraggingState.Locking -> { if (currentDragState is DraggingState.Cancelling) { voiceMessageViews.showRecordingViews() } voiceMessageViews.renderLocking(newDragState.distanceY) } - DraggingState.Cancel -> callback.onVoiceRecordingCancelled() - DraggingState.Lock -> callback.onVoiceRecordingLocked() + DraggingState.Cancel -> callback.onVoiceRecordingCancelled() + DraggingState.Lock -> callback.onVoiceRecordingLocked() DraggingState.Ignored, - DraggingState.Ready -> { + DraggingState.Ready -> { // do nothing } } @@ -227,11 +227,11 @@ class VoiceMessageRecorderView @JvmOverloads constructor( is AudioMessagePlaybackTracker.Listener.State.Recording -> { voiceMessageViews.renderRecordingWaveform(state.amplitudeList.toList()) } - is AudioMessagePlaybackTracker.Listener.State.Playing -> { + is AudioMessagePlaybackTracker.Listener.State.Playing -> { voiceMessageViews.renderPlaying(state) } is AudioMessagePlaybackTracker.Listener.State.Paused, - is AudioMessagePlaybackTracker.Listener.State.Idle -> { + is AudioMessagePlaybackTracker.Listener.State.Idle -> { voiceMessageViews.renderIdle() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt index 0a093221a6..1eac3b440a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt @@ -65,7 +65,7 @@ class VoiceMessageViews( MotionEvent.ACTION_DOWN -> { actions.onWaveformClicked() } - MotionEvent.ACTION_UP -> { + MotionEvent.ACTION_UP -> { val percentage = getTouchedPositionPercentage(motionEvent, view) actions.onVoiceWaveformTouchedUp(percentage) } @@ -95,7 +95,7 @@ class VoiceMessageViews( actions.onRequestRecording() true } - MotionEvent.ACTION_UP -> { + MotionEvent.ACTION_UP -> { actions.onMicButtonReleased() true } @@ -103,7 +103,7 @@ class VoiceMessageViews( actions.onMicButtonDrag { currentState -> draggableStateProcessor.process(event, currentState) } true } - else -> false + else -> false } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt index 5246906223..76f2d72456 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt @@ -28,9 +28,11 @@ import javax.inject.Inject /** * Epoxy controller for read receipt event list. */ -class DisplayReadReceiptsController @Inject constructor(private val dateFormatter: VectorDateFormatter, - private val session: Session, - private val avatarRender: AvatarRenderer) : +class DisplayReadReceiptsController @Inject constructor( + private val dateFormatter: VectorDateFormatter, + private val session: Session, + private val avatarRender: AvatarRenderer +) : TypedEpoxyController>() { var listener: Listener? = null diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt index 011258f126..de51adf05a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt @@ -92,7 +92,7 @@ class SearchFragment @Inject constructor( is Loading -> { views.stateView.state = StateView.State.Loading } - is Fail -> { + is Fail -> { views.stateView.state = StateView.State.Error(errorFormatter.toHumanReadable(state.asyncSearchRequest.error)) } is Success -> { @@ -101,7 +101,7 @@ class SearchFragment @Inject constructor( image = ContextCompat.getDrawable(requireContext(), R.drawable.ic_search_no_results) ) } - else -> Unit + else -> Unit } } else { controller.setData(state) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchViewModel.kt index 561023401f..159915ea90 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchViewModel.kt @@ -54,8 +54,8 @@ class SearchViewModel @AssistedInject constructor( override fun handle(action: SearchAction) { when (action) { is SearchAction.SearchWith -> handleSearchWith(action) - is SearchAction.LoadMore -> handleLoadMore() - is SearchAction.Retry -> handleRetry() + is SearchAction.LoadMore -> handleLoadMore() + is SearchAction.Retry -> handleRetry() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/MessageColorProvider.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/MessageColorProvider.kt index 2b39eb1e26..8b03185293 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/MessageColorProvider.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/MessageColorProvider.kt @@ -28,7 +28,8 @@ import javax.inject.Inject class MessageColorProvider @Inject constructor( private val colorProvider: ColorProvider, private val matrixItemColorProvider: MatrixItemColorProvider, - private val vectorPreferences: VectorPreferences) { + private val vectorPreferences: VectorPreferences +) { @ColorInt fun getMemberNameTextColor(matrixItem: MatrixItem): Int { @@ -41,11 +42,11 @@ class MessageColorProvider @Inject constructor( when (sendState) { // SendStates, in the classical order they will occur SendState.UNKNOWN, - SendState.UNSENT -> colorProvider.getColorFromAttribute(R.attr.vctr_sending_message_text_color) - SendState.ENCRYPTING -> colorProvider.getColorFromAttribute(R.attr.vctr_encrypting_message_text_color) - SendState.SENDING -> colorProvider.getColorFromAttribute(R.attr.vctr_sending_message_text_color) + SendState.UNSENT -> colorProvider.getColorFromAttribute(R.attr.vctr_sending_message_text_color) + SendState.ENCRYPTING -> colorProvider.getColorFromAttribute(R.attr.vctr_encrypting_message_text_color) + SendState.SENDING -> colorProvider.getColorFromAttribute(R.attr.vctr_sending_message_text_color) SendState.SENT, - SendState.SYNCED -> colorProvider.getColorFromAttribute(R.attr.vctr_message_text_color) + SendState.SYNCED -> colorProvider.getColorFromAttribute(R.attr.vctr_message_text_color) SendState.UNDELIVERED, SendState.FAILED_UNKNOWN_DEVICES -> colorProvider.getColorFromAttribute(R.attr.vctr_unsent_message_text_color) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt index a601870ae8..a02eaa3202 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt @@ -131,10 +131,12 @@ class TimelineEventController @Inject constructor( fun onEventVisible(event: TimelineEvent) fun onRoomCreateLinkClicked(url: String) fun onEncryptedMessageClicked(informationData: MessageInformationData, view: View) - fun onImageMessageClicked(messageImageContent: MessageImageInfoContent, - mediaData: ImageContentRenderer.Data, - view: View, - inMemory: List) + fun onImageMessageClicked( + messageImageContent: MessageImageInfoContent, + mediaData: ImageContentRenderer.Data, + view: View, + inMemory: List + ) fun onVideoMessageClicked(messageVideoContent: MessageVideoContent, mediaData: VideoContentRenderer.Data, view: View) @@ -474,10 +476,12 @@ class TimelineEventController @Inject constructor( ) } - private fun CacheItemData.enrichWithModels(event: TimelineEvent, - nextEvent: TimelineEvent?, - position: Int, - receiptsByEvents: Map>): CacheItemData { + private fun CacheItemData.enrichWithModels( + event: TimelineEvent, + nextEvent: TimelineEvent?, + position: Int, + receiptsByEvents: Map> + ): CacheItemData { val wantsDateSeparator = wantsDateSeparator(event, nextEvent) val mergedHeaderModel = mergedHeaderItemFactory.create( event, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/EventSharedAction.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/EventSharedAction.kt index e3b10ef8c6..7bf9f536f2 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/EventSharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/EventSharedAction.kt @@ -24,9 +24,11 @@ import im.vector.app.features.home.room.detail.timeline.item.MessageInformationD import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.model.message.MessageWithAttachmentContent -sealed class EventSharedAction(@StringRes val titleRes: Int, - @DrawableRes val iconResId: Int, - val destructive: Boolean = false) : VectorSharedAction { +sealed class EventSharedAction( + @StringRes val titleRes: Int, + @DrawableRes val iconResId: Int, + val destructive: Boolean = false +) : VectorSharedAction { object Separator : EventSharedAction(0, 0) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt index ade08fdfed..d918703f95 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt @@ -126,7 +126,7 @@ class MessageActionsEpoxyController @Inject constructor( } when (state.informationData.e2eDecoration) { - E2EDecoration.WARN_IN_CLEAR -> { + E2EDecoration.WARN_IN_CLEAR -> { bottomSheetSendStateItem { id("e2e_clear") showProgress(false) @@ -143,7 +143,7 @@ class MessageActionsEpoxyController @Inject constructor( drawableStart(R.drawable.ic_shield_warning_small) } } - else -> { + else -> { // nothing } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt index 79a6dd27ff..05089cce81 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt @@ -45,6 +45,7 @@ import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.isAttachmentMessage +import org.matrix.android.sdk.api.session.events.model.isContentReportable import org.matrix.android.sdk.api.session.events.model.isTextMessage import org.matrix.android.sdk.api.session.events.model.isThread import org.matrix.android.sdk.api.session.events.model.toModel @@ -183,7 +184,7 @@ class MessageActionsViewModel @AssistedInject constructor( } else { when (timelineEvent.root.getClearType()) { EventType.MESSAGE, - EventType.STICKER -> { + EventType.STICKER -> { val messageContent: MessageContent? = timelineEvent.getLastMessageContent() if (messageContent is MessageTextContent && messageContent.format == MessageFormat.FORMAT_MATRIX_HTML) { val html = messageContent.formattedBody @@ -209,14 +210,14 @@ class MessageActionsViewModel @AssistedInject constructor( EventType.CALL_INVITE, EventType.CALL_CANDIDATES, EventType.CALL_HANGUP, - EventType.CALL_ANSWER -> { + EventType.CALL_ANSWER -> { noticeEventFormatter.format(timelineEvent, room?.roomSummary()?.isDirect.orFalse()) } in EventType.POLL_START -> { timelineEvent.root.getClearContent().toModel(catchError = true) ?.getBestPollCreationInfo()?.question?.getBestQuestion() ?: "" } - else -> null + else -> null } } } catch (failure: Throwable) { @@ -255,16 +256,16 @@ class MessageActionsViewModel @AssistedInject constructor( return arrayListOf().apply { when { - timelineEvent.root.sendState.hasFailed() -> { + timelineEvent.root.sendState.hasFailed() -> { addActionsForFailedState(timelineEvent, actionPermissions, messageContent, msgType) } - timelineEvent.root.sendState.isSending() -> { + timelineEvent.root.sendState.isSending() -> { addActionsForSendingState(timelineEvent) } timelineEvent.root.sendState == SendState.SYNCED -> { addActionsForSyncedState(timelineEvent, actionPermissions, messageContent, msgType) } - timelineEvent.root.sendState == SendState.SENT -> { + timelineEvent.root.sendState == SendState.SENT -> { addActionsForSentNotSyncedState(timelineEvent) } } @@ -280,10 +281,12 @@ class MessageActionsViewModel @AssistedInject constructor( } } - private fun ArrayList.addActionsForFailedState(timelineEvent: TimelineEvent, - actionPermissions: ActionPermissions, - messageContent: MessageContent?, - msgType: String?) { + private fun ArrayList.addActionsForFailedState( + timelineEvent: TimelineEvent, + actionPermissions: ActionPermissions, + messageContent: MessageContent?, + msgType: String? + ) { val eventId = timelineEvent.eventId if (canRetry(timelineEvent, actionPermissions)) { add(EventSharedAction.Resend(eventId)) @@ -320,10 +323,12 @@ class MessageActionsViewModel @AssistedInject constructor( // TODO sent by me or sufficient power level } - private fun ArrayList.addActionsForSyncedState(timelineEvent: TimelineEvent, - actionPermissions: ActionPermissions, - messageContent: MessageContent?, - msgType: String?) { + private fun ArrayList.addActionsForSyncedState( + timelineEvent: TimelineEvent, + actionPermissions: ActionPermissions, + messageContent: MessageContent?, + msgType: String? + ) { val eventId = timelineEvent.eventId if (!timelineEvent.root.isRedacted()) { if (canReply(timelineEvent, messageContent, actionPermissions)) { @@ -417,7 +422,7 @@ class MessageActionsViewModel @AssistedInject constructor( add(EventSharedAction.CopyPermalink(eventId)) if (session.myUserId != timelineEvent.root.senderId) { // not sent by me - if (timelineEvent.root.getClearType() == EventType.MESSAGE) { + if (timelineEvent.root.isContentReportable()) { add(EventSharedAction.ReportContent(eventId, timelineEvent.root.senderId)) } @@ -444,7 +449,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_FILE, MessageType.MSGTYPE_POLL_START, MessageType.MSGTYPE_LOCATION -> true - else -> false + else -> false } } @@ -452,9 +457,11 @@ class MessageActionsViewModel @AssistedInject constructor( * Determine whether or not the Reply In Thread bottom sheet action will be visible * to the user. */ - private fun canReplyInThread(event: TimelineEvent, - messageContent: MessageContent?, - actionPermissions: ActionPermissions): Boolean { + private fun canReplyInThread( + event: TimelineEvent, + messageContent: MessageContent?, + actionPermissions: ActionPermissions + ): Boolean { // We let reply in thread visible even if threads are not enabled, with an enhanced flow to attract users // if (!vectorPreferences.areThreadMessagesEnabled()) return false // Disable beta prompt if the homeserver do not support threads @@ -476,16 +483,18 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_FILE, MessageType.MSGTYPE_POLL_START, MessageType.MSGTYPE_STICKER_LOCAL -> true - else -> false + else -> false } } /** * Determine whether or not the view in room action will be available for the current event. */ - private fun canViewInRoom(event: TimelineEvent, - messageContent: MessageContent?, - actionPermissions: ActionPermissions): Boolean { + private fun canViewInRoom( + event: TimelineEvent, + messageContent: MessageContent?, + actionPermissions: ActionPermissions + ): Boolean { if (!vectorPreferences.areThreadMessagesEnabled()) return false if (!initialState.isFromThreadTimeline) return false if (event.root.getClearType() != EventType.MESSAGE && @@ -502,7 +511,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_FILE, MessageType.MSGTYPE_POLL_START, MessageType.MSGTYPE_STICKER_LOCAL -> event.root.threadDetails?.isRootThread ?: false - else -> false + else -> false } } @@ -517,7 +526,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_LOCATION -> { true } - else -> false + else -> false } } @@ -561,7 +570,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_NOTICE, MessageType.MSGTYPE_EMOTE, MessageType.MSGTYPE_LOCATION -> true - else -> false + else -> false } } @@ -575,7 +584,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_AUDIO, MessageType.MSGTYPE_VIDEO, MessageType.MSGTYPE_FILE -> true - else -> false + else -> false } } @@ -585,7 +594,7 @@ class MessageActionsViewModel @AssistedInject constructor( MessageType.MSGTYPE_AUDIO, MessageType.MSGTYPE_VIDEO, MessageType.MSGTYPE_FILE -> true - else -> false + else -> false } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt index b92548dd5e..52ecc6d588 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt @@ -63,7 +63,7 @@ class ViewEditHistoryEpoxyController @Inject constructor( id("Spinner") } } - is Fail -> { + is Fail -> { genericFooterItem { id("failure") text(host.stringProvider.getString(R.string.unknown_error).toEpoxyCharSequence()) @@ -127,7 +127,7 @@ class ViewEditHistoryEpoxyController @Inject constructor( textColor = colorProvider.getColor(R.color.palette_element_green) } } - else -> { + else -> { span { text = it.text } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewState.kt index dd344c4c82..fc5b58815b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryViewState.kt @@ -26,7 +26,8 @@ data class ViewEditHistoryViewState( val eventId: String, val roomId: String, val isOriginalAReply: Boolean = false, - val editList: Async> = Uninitialized) : + val editList: Async> = Uninitialized +) : MavericksState { constructor(args: TimelineEventFragmentArgs) : this(roomId = args.roomId, eventId = args.eventId) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/CallItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/CallItemFactory.kt index a5d6f75387..360dbc3fbe 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/CallItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/CallItemFactory.kt @@ -40,7 +40,8 @@ class CallItemFactory @Inject constructor( private val messageInformationDataFactory: MessageInformationDataFactory, private val messageItemAttributesFactory: MessageItemAttributesFactory, private val avatarSizeProvider: AvatarSizeProvider, - private val noticeItemFactory: NoticeItemFactory) { + private val noticeItemFactory: NoticeItemFactory +) { fun create(params: TimelineItemFactoryParams): VectorEpoxyModel<*>? { val event = params.event @@ -119,7 +120,7 @@ class CallItemFactory @Inject constructor( reactionsSummaryEvents = params.reactionsSummaryEvents ) } - else -> null + else -> null } return if (callItem == null && showHiddenEvents) { // Fallback to notice item for showing hidden events diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/DefaultItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/DefaultItemFactory.kt index db7b84ed06..d704003627 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/DefaultItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/DefaultItemFactory.kt @@ -27,15 +27,19 @@ import im.vector.app.features.home.room.detail.timeline.item.DefaultItem_ import im.vector.app.features.home.room.detail.timeline.item.MessageInformationData import javax.inject.Inject -class DefaultItemFactory @Inject constructor(private val avatarSizeProvider: AvatarSizeProvider, - private val avatarRenderer: AvatarRenderer, - private val stringProvider: StringProvider, - private val informationDataFactory: MessageInformationDataFactory) { +class DefaultItemFactory @Inject constructor( + private val avatarSizeProvider: AvatarSizeProvider, + private val avatarRenderer: AvatarRenderer, + private val stringProvider: StringProvider, + private val informationDataFactory: MessageInformationDataFactory +) { - fun create(text: String, - informationData: MessageInformationData, - highlight: Boolean, - callback: TimelineEventController.Callback?): DefaultItem { + fun create( + text: String, + informationData: MessageInformationData, + highlight: Boolean, + callback: TimelineEventController.Callback? + ): DefaultItem { val attributes = DefaultItem.Attributes( avatarRenderer = avatarRenderer, informationData = informationData, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptedItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptedItemFactory.kt index dd91f00ab9..4bc68c10aa 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptedItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptedItemFactory.kt @@ -37,13 +37,15 @@ import org.matrix.android.sdk.api.session.events.model.toModel import javax.inject.Inject // This class handles timeline events who haven't been successfully decrypted -class EncryptedItemFactory @Inject constructor(private val messageInformationDataFactory: MessageInformationDataFactory, - private val colorProvider: ColorProvider, - private val stringProvider: StringProvider, - private val avatarSizeProvider: AvatarSizeProvider, - private val drawableProvider: DrawableProvider, - private val attributesFactory: MessageItemAttributesFactory, - private val vectorPreferences: VectorPreferences) { +class EncryptedItemFactory @Inject constructor( + private val messageInformationDataFactory: MessageInformationDataFactory, + private val colorProvider: ColorProvider, + private val stringProvider: StringProvider, + private val avatarSizeProvider: AvatarSizeProvider, + private val drawableProvider: DrawableProvider, + private val attributesFactory: MessageItemAttributesFactory, + private val vectorPreferences: VectorPreferences +) { fun create(params: TimelineItemFactoryParams): VectorEpoxyModel<*>? { val event = params.event @@ -89,7 +91,7 @@ class EncryptedItemFactory @Inject constructor(private val messageInformationDat } } } - else -> { + else -> { span { drawableProvider.getDrawable(R.drawable.ic_clock, colorFromAttribute)?.let { image(it, "baseline") @@ -122,7 +124,7 @@ class EncryptedItemFactory @Inject constructor(private val messageInformationDat .message(spannableStr.toEpoxyCharSequence()) .movementMethod(createLinkMovementMethod(params.callback)) } - else -> null + else -> null } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt index 0cbd92f525..dd058197b4 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt @@ -38,7 +38,8 @@ class EncryptionItemFactory @Inject constructor( private val stringProvider: StringProvider, private val informationDataFactory: MessageInformationDataFactory, private val avatarSizeProvider: AvatarSizeProvider, - private val session: Session) { + private val session: Session +) { fun create(params: TimelineItemFactoryParams): StatusTileTimelineItem? { val event = params.event diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt index 3c7b6c32e1..7f0fff8461 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt @@ -56,10 +56,10 @@ class LiveLocationShareMessageItemFactory @Inject constructor( ): VectorEpoxyModel<*>? { val liveLocationShareSummaryData = getLiveLocationShareSummaryData(event) val item = when (val currentState = getViewState(liveLocationShareSummaryData)) { - LiveLocationShareViewState.Inactive -> buildInactiveItem(highlight, attributes) - LiveLocationShareViewState.Loading -> buildLoadingItem(highlight, attributes) + LiveLocationShareViewState.Inactive -> buildInactiveItem(highlight, attributes) + LiveLocationShareViewState.Loading -> buildLoadingItem(highlight, attributes) is LiveLocationShareViewState.Running -> buildRunningItem(highlight, attributes, currentState) - LiveLocationShareViewState.Unkwown -> null + LiveLocationShareViewState.Unkwown -> null } item?.layout(attributes.informationData.messageLayout.layoutRes) @@ -127,10 +127,10 @@ class LiveLocationShareMessageItemFactory @Inject constructor( private fun getViewState(liveLocationShareSummaryData: LiveLocationShareSummaryData?): LiveLocationShareViewState { return when { - liveLocationShareSummaryData?.isActive == null -> LiveLocationShareViewState.Unkwown - liveLocationShareSummaryData.isActive.not() -> LiveLocationShareViewState.Inactive + liveLocationShareSummaryData?.isActive == null -> LiveLocationShareViewState.Unkwown + liveLocationShareSummaryData.isActive.not() -> LiveLocationShareViewState.Inactive liveLocationShareSummaryData.isActive && liveLocationShareSummaryData.lastGeoUri.isNullOrEmpty() -> LiveLocationShareViewState.Loading - else -> + else -> LiveLocationShareViewState.Running( liveLocationShareSummaryData.lastGeoUri.orEmpty(), getEndOfLiveDateTime(liveLocationShareSummaryData) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt index 224c1cdbea..8c39584a94 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt @@ -46,10 +46,12 @@ import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import javax.inject.Inject -class MergedHeaderItemFactory @Inject constructor(private val activeSessionHolder: ActiveSessionHolder, - private val avatarRenderer: AvatarRenderer, - private val avatarSizeProvider: AvatarSizeProvider, - private val timelineEventVisibilityHelper: TimelineEventVisibilityHelper) { +class MergedHeaderItemFactory @Inject constructor( + private val activeSessionHolder: ActiveSessionHolder, + private val avatarRenderer: AvatarRenderer, + private val avatarSizeProvider: AvatarSizeProvider, + private val timelineEventVisibilityHelper: TimelineEventVisibilityHelper +) { private val collapsedEventIds = linkedSetOf() private val mergeItemCollapseStates = HashMap() @@ -65,15 +67,17 @@ class MergedHeaderItemFactory @Inject constructor(private val activeSessionHolde * @param callback callback for user event * @param requestModelBuild lambda to let the built Item request a model build when the collapse state is changed */ - fun create(event: TimelineEvent, - nextEvent: TimelineEvent?, - items: List, - partialState: TimelineEventController.PartialState, - addDaySeparator: Boolean, - currentPosition: Int, - eventIdToHighlight: String?, - callback: TimelineEventController.Callback?, - requestModelBuild: () -> Unit): BasedMergedItem<*>? { + fun create( + event: TimelineEvent, + nextEvent: TimelineEvent?, + items: List, + partialState: TimelineEventController.PartialState, + addDaySeparator: Boolean, + currentPosition: Int, + eventIdToHighlight: String?, + callback: TimelineEventController.Callback?, + requestModelBuild: () -> Unit + ): BasedMergedItem<*>? { return if (nextEvent?.root?.getClearType() == EventType.STATE_ROOM_CREATE && event.isRoomConfiguration(nextEvent.root.getClearContent()?.toModel()?.creator)) { // It's the first item before room.create @@ -86,13 +90,15 @@ class MergedHeaderItemFactory @Inject constructor(private val activeSessionHolde } } - private fun buildMembershipEventsMergedSummary(currentPosition: Int, - items: List, - partialState: TimelineEventController.PartialState, - event: TimelineEvent, - eventIdToHighlight: String?, - requestModelBuild: () -> Unit, - callback: TimelineEventController.Callback?): MergedSimilarEventsItem_? { + private fun buildMembershipEventsMergedSummary( + currentPosition: Int, + items: List, + partialState: TimelineEventController.PartialState, + event: TimelineEvent, + eventIdToHighlight: String?, + requestModelBuild: () -> Unit, + callback: TimelineEventController.Callback? + ): MergedSimilarEventsItem_? { val mergedEvents = timelineEventVisibilityHelper.prevSameTypeEvents( items, currentPosition, @@ -134,9 +140,9 @@ class MergedHeaderItemFactory @Inject constructor(private val activeSessionHolde } val mergeId = mergedEventIds.joinToString(separator = "_") { it.toString() } val summaryTitleResId = when (event.root.getClearType()) { - EventType.STATE_ROOM_MEMBER -> R.plurals.membership_changes + EventType.STATE_ROOM_MEMBER -> R.plurals.membership_changes EventType.STATE_ROOM_SERVER_ACL -> R.plurals.notice_room_server_acl_changes - else -> null + else -> null } summaryTitleResId?.let { summaryTitle -> val attributes = MergedSimilarEventsItem.Attributes( @@ -161,13 +167,15 @@ class MergedHeaderItemFactory @Inject constructor(private val activeSessionHolde } } - private fun buildRoomCreationMergedSummary(currentPosition: Int, - items: List, - partialState: TimelineEventController.PartialState, - event: TimelineEvent, - eventIdToHighlight: String?, - requestModelBuild: () -> Unit, - callback: TimelineEventController.Callback?): MergedRoomCreationItem_? { + private fun buildRoomCreationMergedSummary( + currentPosition: Int, + items: List, + partialState: TimelineEventController.PartialState, + event: TimelineEvent, + eventIdToHighlight: String?, + requestModelBuild: () -> Unit, + callback: TimelineEventController.Callback? + ): MergedRoomCreationItem_? { var prevEvent = items.prevOrNull(currentPosition) var tmpPos = currentPosition - 1 val mergedEvents = mutableListOf(event) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt index 13f783cded..54bfbdd8a0 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt @@ -200,24 +200,18 @@ class MessageItemFactory @Inject constructor( // val all = event.root.toContent() // val ev = all.toModel() val messageItem = when (messageContent) { - is MessageEmoteContent -> buildEmoteMessageItem(messageContent, informationData, highlight, callback, attributes) - is MessageTextContent -> buildItemForTextContent(messageContent, informationData, highlight, callback, attributes) - is MessageImageInfoContent -> buildImageMessageItem(messageContent, informationData, highlight, callback, attributes) - is MessageNoticeContent -> buildNoticeMessageItem(messageContent, informationData, highlight, callback, attributes) - is MessageVideoContent -> buildVideoMessageItem(messageContent, informationData, highlight, callback, attributes) - is MessageFileContent -> buildFileMessageItem(messageContent, highlight, attributes) - is MessageAudioContent -> buildAudioContent(params, messageContent, informationData, highlight, attributes) + is MessageEmoteContent -> buildEmoteMessageItem(messageContent, informationData, highlight, callback, attributes) + is MessageTextContent -> buildItemForTextContent(messageContent, informationData, highlight, callback, attributes) + is MessageImageInfoContent -> buildImageMessageItem(messageContent, informationData, highlight, callback, attributes) + is MessageNoticeContent -> buildNoticeMessageItem(messageContent, informationData, highlight, callback, attributes) + is MessageVideoContent -> buildVideoMessageItem(messageContent, informationData, highlight, callback, attributes) + is MessageFileContent -> buildFileMessageItem(messageContent, highlight, attributes) + is MessageAudioContent -> buildAudioContent(params, messageContent, informationData, highlight, attributes) is MessageVerificationRequestContent -> buildVerificationRequestMessageItem(messageContent, informationData, highlight, callback, attributes) - is MessagePollContent -> buildPollItem(messageContent, informationData, highlight, callback, attributes) - is MessageLocationContent -> { - if (vectorPreferences.labsRenderLocationsInTimeline()) { - buildLocationItem(messageContent, informationData, highlight, attributes) - } else { - buildMessageTextItem(messageContent.body, false, informationData, highlight, callback, attributes) - } - } - is MessageBeaconInfoContent -> liveLocationShareMessageItemFactory.create(params.event, highlight, attributes) - else -> buildNotHandledMessageItem(messageContent, informationData, highlight, callback, attributes) + is MessagePollContent -> buildPollItem(messageContent, informationData, highlight, callback, attributes) + is MessageLocationContent -> buildLocationItem(messageContent, informationData, highlight, attributes) + is MessageBeaconInfoContent -> liveLocationShareMessageItemFactory.create(params.event, highlight, attributes) + else -> buildNotHandledMessageItem(messageContent, informationData, highlight, callback, attributes) } return messageItem?.apply { layout(informationData.messageLayout.layoutRes) @@ -283,11 +277,11 @@ class MessageItemFactory @Inject constructor( pollResponseSummary: PollResponseData?, pollContent: MessagePollContent, ): PollState = when { - !informationData.sendState.isSent() -> Sending - pollResponseSummary?.isClosed.orFalse() -> Ended + !informationData.sendState.isSent() -> Sending + pollResponseSummary?.isClosed.orFalse() -> Ended pollContent.getBestPollCreationInfo()?.kind == PollType.UNDISCLOSED -> Undisclosed - pollResponseSummary?.myVote?.isNotEmpty().orFalse() -> Voted(pollResponseSummary?.totalVotes ?: 0) - else -> Ready + pollResponseSummary?.myVote?.isNotEmpty().orFalse() -> Voted(pollResponseSummary?.totalVotes ?: 0) + else -> Ready } private fun List.mapToOptions( @@ -305,11 +299,11 @@ class MessageItemFactory @Inject constructor( val isWinner = winnerVoteCount != 0 && voteCount == winnerVoteCount when (pollState) { - Sending -> PollSending(optionId, optionAnswer) - Ready -> PollReady(optionId, optionAnswer) - is Voted -> PollVoted(optionId, optionAnswer, voteCount, votePercentage, isMyVote) + Sending -> PollSending(optionId, optionAnswer) + Ready -> PollReady(optionId, optionAnswer) + is Voted -> PollVoted(optionId, optionAnswer, voteCount, votePercentage, isMyVote) Undisclosed -> PollUndisclosed(optionId, optionAnswer, isMyVote) - Ended -> PollEnded(optionId, optionAnswer, voteCount, votePercentage, isWinner) + Ended -> PollEnded(optionId, optionAnswer, voteCount, votePercentage, isWinner) } } @@ -329,11 +323,11 @@ class MessageItemFactory @Inject constructor( ): String { val votes = pollResponseSummary?.totalVotes ?: 0 return when { - pollState is Ended -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_after_ended, votes, votes) + pollState is Ended -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_after_ended, votes, votes) pollState is Undisclosed -> "" - pollState is Voted -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_before_ended_and_voted, votes, votes) - votes == 0 -> stringProvider.getString(R.string.poll_no_votes_cast) - else -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_before_ended_and_not_voted, votes, votes) + pollState is Voted -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_before_ended_and_voted, votes, votes) + votes == 0 -> stringProvider.getString(R.string.poll_no_votes_cast) + else -> stringProvider.getQuantityString(R.plurals.poll_total_vote_count_before_ended_and_not_voted, votes, votes) } } @@ -501,7 +495,8 @@ class MessageItemFactory @Inject constructor( informationData: MessageInformationData, highlight: Boolean, callback: TimelineEventController.Callback?, - attributes: AbsMessageItem.Attributes): MessageTextItem? { + attributes: AbsMessageItem.Attributes + ): MessageTextItem? { // For compatibility reason we should display the body return buildMessageTextItem(messageContent.body, false, informationData, highlight, callback, attributes) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/NoticeItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/NoticeItemFactory.kt index 6951c3c316..d1f2eaf607 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/NoticeItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/NoticeItemFactory.kt @@ -26,10 +26,12 @@ import im.vector.lib.core.utils.epoxy.charsequence.EpoxyCharSequence import org.matrix.android.sdk.api.extensions.orFalse import javax.inject.Inject -class NoticeItemFactory @Inject constructor(private val eventFormatter: NoticeEventFormatter, - private val avatarRenderer: AvatarRenderer, - private val informationDataFactory: MessageInformationDataFactory, - private val avatarSizeProvider: AvatarSizeProvider) { +class NoticeItemFactory @Inject constructor( + private val eventFormatter: NoticeEventFormatter, + private val avatarRenderer: AvatarRenderer, + private val informationDataFactory: MessageInformationDataFactory, + private val avatarSizeProvider: AvatarSizeProvider +) { fun create(params: TimelineItemFactoryParams): NoticeItem? { val event = params.event diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/ReadReceiptsItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/ReadReceiptsItemFactory.kt index ed3cc8df53..6a711ec2dc 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/ReadReceiptsItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/ReadReceiptsItemFactory.kt @@ -30,7 +30,8 @@ class ReadReceiptsItemFactory @Inject constructor(private val avatarRenderer: Av eventId: String, readReceipts: List, callback: TimelineEventController.Callback?, - isFromThreadTimeLine: Boolean): ReadReceiptsItem? { + isFromThreadTimeLine: Boolean + ): ReadReceiptsItem? { if (readReceipts.isEmpty()) { return null } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/RoomCreateItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/RoomCreateItemFactory.kt index fff709f346..33851c808a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/RoomCreateItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/RoomCreateItemFactory.kt @@ -28,10 +28,12 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent import javax.inject.Inject -class RoomCreateItemFactory @Inject constructor(private val stringProvider: StringProvider, - private val userPreferencesProvider: UserPreferencesProvider, - private val session: Session, - private val noticeItemFactory: NoticeItemFactory) { +class RoomCreateItemFactory @Inject constructor( + private val stringProvider: StringProvider, + private val userPreferencesProvider: UserPreferencesProvider, + private val session: Session, + private val noticeItemFactory: NoticeItemFactory +) { fun create(params: TimelineItemFactoryParams): VectorEpoxyModel<*>? { val event = params.event diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt index 07ae9d66c3..97ae3b634e 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt @@ -79,17 +79,17 @@ class TimelineItemFactory @Inject constructor( EventType.STATE_ROOM_ALIASES, EventType.STATE_SPACE_CHILD, EventType.STATE_SPACE_PARENT, - EventType.STATE_ROOM_POWER_LEVELS -> { + EventType.STATE_ROOM_POWER_LEVELS -> { noticeItemFactory.create(params) } EventType.STATE_ROOM_WIDGET_LEGACY, - EventType.STATE_ROOM_WIDGET -> widgetItemFactory.create(params) - EventType.STATE_ROOM_ENCRYPTION -> encryptionItemFactory.create(params) + EventType.STATE_ROOM_WIDGET -> widgetItemFactory.create(params) + EventType.STATE_ROOM_ENCRYPTION -> encryptionItemFactory.create(params) // State room create - EventType.STATE_ROOM_CREATE -> roomCreateItemFactory.create(params) + EventType.STATE_ROOM_CREATE -> roomCreateItemFactory.create(params) in EventType.STATE_ROOM_BEACON_INFO -> messageItemFactory.create(params) // Unhandled state event types - else -> { + else -> { // Should only happen when shouldShowHiddenEvents() settings is ON Timber.v("State event type ${event.root.type} not handled") defaultItemFactory.create(params) @@ -100,7 +100,7 @@ class TimelineItemFactory @Inject constructor( // Message itemsX EventType.STICKER, in EventType.POLL_START, - EventType.MESSAGE -> messageItemFactory.create(params) + EventType.MESSAGE -> messageItemFactory.create(params) EventType.REDACTION, EventType.KEY_VERIFICATION_ACCEPT, EventType.KEY_VERIFICATION_START, @@ -119,9 +119,9 @@ class TimelineItemFactory @Inject constructor( EventType.CALL_INVITE, EventType.CALL_HANGUP, EventType.CALL_REJECT, - EventType.CALL_ANSWER -> callItemFactory.create(params) + EventType.CALL_ANSWER -> callItemFactory.create(params) // Crypto - EventType.ENCRYPTED -> { + EventType.ENCRYPTED -> { if (event.root.isRedacted()) { // Redacted event, let the MessageItemFactory handle it messageItemFactory.create(params) @@ -130,11 +130,11 @@ class TimelineItemFactory @Inject constructor( } } EventType.KEY_VERIFICATION_CANCEL, - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { verificationConclusionItemFactory.create(params) } // Unhandled event types - else -> { + else -> { // Should only happen when shouldShowHiddenEvents() settings is ON Timber.v("Type ${event.root.getClearType()} not handled") defaultItemFactory.create(params) @@ -158,11 +158,13 @@ class TimelineItemFactory @Inject constructor( ) } - private fun buildEmptyItem(timelineEvent: TimelineEvent, - prevEvent: TimelineEvent?, - highlightedEventId: String?, - rootThreadEventId: String?, - isFromThreadTimeline: Boolean): TimelineEmptyItem { + private fun buildEmptyItem( + timelineEvent: TimelineEvent, + prevEvent: TimelineEvent?, + highlightedEventId: String?, + rootThreadEventId: String?, + isFromThreadTimeline: Boolean + ): TimelineEmptyItem { val isNotBlank = prevEvent == null || timelineEventVisibilityHelper.shouldShowEvent( timelineEvent = prevEvent, highlightedEventId = highlightedEventId, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt index e679b8d059..9a40cb6730 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt @@ -109,10 +109,10 @@ class VerificationItemFactory @Inject constructor( .highlighted(params.isHighlighted) .leftGuideline(avatarSizeProvider.leftGuideline) } - else -> return ignoredConclusion(params) + else -> return ignoredConclusion(params) } } - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { // Is the request referenced is actually really completed? if (referenceInformationData.referencesInfoData?.verificationStatus != VerificationState.DONE) { return ignoredConclusion(params) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/WidgetItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/WidgetItemFactory.kt index 647b34c626..e8017efe0b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/WidgetItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/WidgetItemFactory.kt @@ -37,7 +37,8 @@ class WidgetItemFactory @Inject constructor( private val avatarSizeProvider: AvatarSizeProvider, private val messageColorProvider: MessageColorProvider, private val avatarRenderer: AvatarRenderer, - private val userPreferencesProvider: UserPreferencesProvider) { + private val userPreferencesProvider: UserPreferencesProvider +) { fun create(params: TimelineItemFactoryParams): VectorEpoxyModel<*>? { val event = params.event @@ -47,7 +48,7 @@ class WidgetItemFactory @Inject constructor( return when (WidgetType.fromString(widgetContent.type ?: previousWidgetContent?.type ?: "")) { WidgetType.Jitsi -> createJitsiItem(params, widgetContent) // There is lot of other widget types we could improve here - else -> noticeItemFactory.create(params) + else -> noticeItemFactory.create(params) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/DisplayableEventFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/DisplayableEventFormatter.kt index 3c2bdb53ab..7b9bd4530b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/DisplayableEventFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/DisplayableEventFormatter.kt @@ -59,10 +59,10 @@ class DisplayableEventFormatter @Inject constructor( val senderName = timelineEvent.senderInfo.disambiguatedDisplayName return when (timelineEvent.root.getClearType()) { - EventType.MESSAGE -> { + EventType.MESSAGE -> { timelineEvent.getLastMessageContent()?.let { messageContent -> when (messageContent.msgType) { - MessageType.MSGTYPE_TEXT -> { + MessageType.MSGTYPE_TEXT -> { val body = messageContent.getTextDisplayableContent() if (messageContent is MessageTextContent && messageContent.matrixFormattedBody.isNullOrBlank().not()) { val localFormattedBody = htmlRenderer.get().parse(body) as Document @@ -75,42 +75,42 @@ class DisplayableEventFormatter @Inject constructor( MessageType.MSGTYPE_VERIFICATION_REQUEST -> { simpleFormat(senderName, stringProvider.getString(R.string.verification_request), appendAuthor) } - MessageType.MSGTYPE_IMAGE -> { + MessageType.MSGTYPE_IMAGE -> { simpleFormat(senderName, stringProvider.getString(R.string.sent_an_image), appendAuthor) } - MessageType.MSGTYPE_AUDIO -> { + MessageType.MSGTYPE_AUDIO -> { if ((messageContent as? MessageAudioContent)?.voiceMessageIndicator != null) { simpleFormat(senderName, stringProvider.getString(R.string.sent_a_voice_message), appendAuthor) } else { simpleFormat(senderName, stringProvider.getString(R.string.sent_an_audio_file), appendAuthor) } } - MessageType.MSGTYPE_VIDEO -> { + MessageType.MSGTYPE_VIDEO -> { simpleFormat(senderName, stringProvider.getString(R.string.sent_a_video), appendAuthor) } - MessageType.MSGTYPE_FILE -> { + MessageType.MSGTYPE_FILE -> { simpleFormat(senderName, stringProvider.getString(R.string.sent_a_file), appendAuthor) } - MessageType.MSGTYPE_LOCATION -> { + MessageType.MSGTYPE_LOCATION -> { simpleFormat(senderName, stringProvider.getString(R.string.sent_location), appendAuthor) } - else -> { + else -> { simpleFormat(senderName, messageContent.body, appendAuthor) } } } ?: span { } } - EventType.STICKER -> { + EventType.STICKER -> { simpleFormat(senderName, stringProvider.getString(R.string.send_a_sticker), appendAuthor) } - EventType.REACTION -> { + EventType.REACTION -> { timelineEvent.root.getClearContent().toModel()?.relatesTo?.let { val emojiSpanned = emojiSpanify.spanify(stringProvider.getString(R.string.sent_a_reaction, it.key)) simpleFormat(senderName, emojiSpanned, appendAuthor) } ?: span { } } EventType.KEY_VERIFICATION_CANCEL, - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { // cancel and done can appear in timeline, so should have representation simpleFormat(senderName, stringProvider.getString(R.string.sent_verification_conclusion), appendAuthor) } @@ -119,23 +119,23 @@ class DisplayableEventFormatter @Inject constructor( EventType.KEY_VERIFICATION_MAC, EventType.KEY_VERIFICATION_KEY, EventType.KEY_VERIFICATION_READY, - EventType.CALL_CANDIDATES -> { + EventType.CALL_CANDIDATES -> { span { } } - in EventType.POLL_START -> { + in EventType.POLL_START -> { timelineEvent.root.getClearContent().toModel(catchError = true)?.getBestPollCreationInfo()?.question?.getBestQuestion() ?: stringProvider.getString(R.string.sent_a_poll) } - in EventType.POLL_RESPONSE -> { + in EventType.POLL_RESPONSE -> { stringProvider.getString(R.string.poll_response_room_list_preview) } - in EventType.POLL_END -> { + in EventType.POLL_END -> { stringProvider.getString(R.string.poll_end_room_list_preview) } in EventType.STATE_ROOM_BEACON_INFO -> { simpleFormat(senderName, stringProvider.getString(R.string.sent_live_location), appendAuthor) } - else -> { + else -> { span { text = noticeEventFormatter.format(timelineEvent, isDm) ?: "" textStyle = "italic" @@ -146,7 +146,8 @@ class DisplayableEventFormatter @Inject constructor( fun formatThreadSummary( event: Event?, - latestEdition: String? = null): CharSequence { + latestEdition: String? = null + ): CharSequence { event ?: return "" // There event have been edited @@ -170,10 +171,10 @@ class DisplayableEventFormatter @Inject constructor( } return when (event.getClearType()) { - EventType.MESSAGE -> { + EventType.MESSAGE -> { (event.getClearContent().toModel() as? MessageContent)?.let { messageContent -> when (messageContent.msgType) { - MessageType.MSGTYPE_TEXT -> { + MessageType.MSGTYPE_TEXT -> { val body = messageContent.getTextDisplayableContent() if (messageContent is MessageTextContent && messageContent.matrixFormattedBody.isNullOrBlank().not()) { val localFormattedBody = htmlRenderer.get().parse(body) as Document @@ -186,53 +187,53 @@ class DisplayableEventFormatter @Inject constructor( MessageType.MSGTYPE_VERIFICATION_REQUEST -> { stringProvider.getString(R.string.verification_request) } - MessageType.MSGTYPE_IMAGE -> { + MessageType.MSGTYPE_IMAGE -> { stringProvider.getString(R.string.sent_an_image) } - MessageType.MSGTYPE_AUDIO -> { + MessageType.MSGTYPE_AUDIO -> { if ((messageContent as? MessageAudioContent)?.voiceMessageIndicator != null) { stringProvider.getString(R.string.sent_a_voice_message) } else { stringProvider.getString(R.string.sent_an_audio_file) } } - MessageType.MSGTYPE_VIDEO -> { + MessageType.MSGTYPE_VIDEO -> { stringProvider.getString(R.string.sent_a_video) } - MessageType.MSGTYPE_FILE -> { + MessageType.MSGTYPE_FILE -> { stringProvider.getString(R.string.sent_a_file) } - MessageType.MSGTYPE_LOCATION -> { + MessageType.MSGTYPE_LOCATION -> { stringProvider.getString(R.string.sent_location) } - else -> { + else -> { messageContent.body } } } ?: span { } } - EventType.STICKER -> { + EventType.STICKER -> { stringProvider.getString(R.string.send_a_sticker) } - EventType.REACTION -> { + EventType.REACTION -> { event.getClearContent().toModel()?.relatesTo?.let { emojiSpanify.spanify(stringProvider.getString(R.string.sent_a_reaction, it.key)) } ?: span { } } - in EventType.POLL_START -> { + in EventType.POLL_START -> { event.getClearContent().toModel(catchError = true)?.pollCreationInfo?.question?.question ?: stringProvider.getString(R.string.sent_a_poll) } - in EventType.POLL_RESPONSE -> { + in EventType.POLL_RESPONSE -> { stringProvider.getString(R.string.poll_response_room_list_preview) } - in EventType.POLL_END -> { + in EventType.POLL_END -> { stringProvider.getString(R.string.poll_end_room_list_preview) } in EventType.STATE_ROOM_BEACON_INFO -> { stringProvider.getString(R.string.sent_live_location) } - else -> { + else -> { span { } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt index 4c92ab0e34..2233a53eda 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt @@ -50,8 +50,8 @@ class EventDetailsFormatter @Inject constructor( event.isImageMessage() -> formatForImageMessage(event) event.isVideoMessage() -> formatForVideoMessage(event) event.isAudioMessage() -> formatForAudioMessage(event) - event.isFileMessage() -> formatForFileMessage(event) - else -> null + event.isFileMessage() -> formatForFileMessage(event) + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt index 8e06b3ee5d..19f9fc17a3 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt @@ -67,29 +67,29 @@ class NoticeEventFormatter @Inject constructor( fun format(timelineEvent: TimelineEvent, isDm: Boolean): CharSequence? { return when (val type = timelineEvent.root.getClearType()) { - EventType.STATE_ROOM_JOIN_RULES -> formatJoinRulesEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) - EventType.STATE_ROOM_CREATE -> formatRoomCreateEvent(timelineEvent.root, isDm) - EventType.STATE_ROOM_NAME -> formatRoomNameEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_TOPIC -> formatRoomTopicEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_AVATAR -> formatRoomAvatarEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_MEMBER -> formatRoomMemberEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) + EventType.STATE_ROOM_JOIN_RULES -> formatJoinRulesEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) + EventType.STATE_ROOM_CREATE -> formatRoomCreateEvent(timelineEvent.root, isDm) + EventType.STATE_ROOM_NAME -> formatRoomNameEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_TOPIC -> formatRoomTopicEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_AVATAR -> formatRoomAvatarEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_MEMBER -> formatRoomMemberEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) EventType.STATE_ROOM_THIRD_PARTY_INVITE -> formatRoomThirdPartyInvite(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) - EventType.STATE_ROOM_ALIASES -> formatRoomAliasesEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_CANONICAL_ALIAS -> formatRoomCanonicalAliasEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_ALIASES -> formatRoomAliasesEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_CANONICAL_ALIAS -> formatRoomCanonicalAliasEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) EventType.STATE_ROOM_HISTORY_VISIBILITY -> formatRoomHistoryVisibilityEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) - EventType.STATE_ROOM_SERVER_ACL -> formatRoomServerAclEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_GUEST_ACCESS -> formatRoomGuestAccessEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) - EventType.STATE_ROOM_ENCRYPTION -> formatRoomEncryptionEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_SERVER_ACL -> formatRoomServerAclEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_GUEST_ACCESS -> formatRoomGuestAccessEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) + EventType.STATE_ROOM_ENCRYPTION -> formatRoomEncryptionEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) EventType.STATE_ROOM_WIDGET, - EventType.STATE_ROOM_WIDGET_LEGACY -> formatWidgetEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) - EventType.STATE_ROOM_TOMBSTONE -> formatRoomTombstoneEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) - EventType.STATE_ROOM_POWER_LEVELS -> formatRoomPowerLevels(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_WIDGET_LEGACY -> formatWidgetEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.STATE_ROOM_TOMBSTONE -> formatRoomTombstoneEvent(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName, isDm) + EventType.STATE_ROOM_POWER_LEVELS -> formatRoomPowerLevels(timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) EventType.CALL_INVITE, EventType.CALL_CANDIDATES, EventType.CALL_HANGUP, EventType.CALL_REJECT, - EventType.CALL_ANSWER -> formatCallEvent(type, timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) + EventType.CALL_ANSWER -> formatCallEvent(type, timelineEvent.root, timelineEvent.senderInfo.disambiguatedDisplayName) EventType.CALL_NEGOTIATE, EventType.CALL_SELECT_ANSWER, EventType.CALL_REPLACES, @@ -108,8 +108,8 @@ class NoticeEventFormatter @Inject constructor( EventType.STICKER, in EventType.POLL_RESPONSE, in EventType.POLL_END, - in EventType.BEACON_LOCATION_DATA -> formatDebug(timelineEvent.root) - else -> { + in EventType.BEACON_LOCATION_DATA -> formatDebug(timelineEvent.root) + else -> { Timber.v("Type $type not handled by this formatter") null } @@ -177,19 +177,19 @@ class NoticeEventFormatter @Inject constructor( fun format(event: Event, senderName: String?, isDm: Boolean): CharSequence? { return when (val type = event.getClearType()) { - EventType.STATE_ROOM_JOIN_RULES -> formatJoinRulesEvent(event, senderName, isDm) - EventType.STATE_ROOM_NAME -> formatRoomNameEvent(event, senderName) - EventType.STATE_ROOM_TOPIC -> formatRoomTopicEvent(event, senderName) - EventType.STATE_ROOM_AVATAR -> formatRoomAvatarEvent(event, senderName) - EventType.STATE_ROOM_MEMBER -> formatRoomMemberEvent(event, senderName, isDm) + EventType.STATE_ROOM_JOIN_RULES -> formatJoinRulesEvent(event, senderName, isDm) + EventType.STATE_ROOM_NAME -> formatRoomNameEvent(event, senderName) + EventType.STATE_ROOM_TOPIC -> formatRoomTopicEvent(event, senderName) + EventType.STATE_ROOM_AVATAR -> formatRoomAvatarEvent(event, senderName) + EventType.STATE_ROOM_MEMBER -> formatRoomMemberEvent(event, senderName, isDm) EventType.STATE_ROOM_THIRD_PARTY_INVITE -> formatRoomThirdPartyInvite(event, senderName, isDm) EventType.STATE_ROOM_HISTORY_VISIBILITY -> formatRoomHistoryVisibilityEvent(event, senderName, isDm) EventType.CALL_INVITE, EventType.CALL_HANGUP, EventType.CALL_REJECT, - EventType.CALL_ANSWER -> formatCallEvent(type, event, senderName) - EventType.STATE_ROOM_TOMBSTONE -> formatRoomTombstoneEvent(event, senderName, isDm) - else -> { + EventType.CALL_ANSWER -> formatCallEvent(type, event, senderName) + EventType.STATE_ROOM_TOMBSTONE -> formatRoomTombstoneEvent(event, senderName, isDm) + else -> { Timber.v("Type $type not handled by this formatter") null } @@ -312,7 +312,7 @@ class NoticeEventFormatter @Inject constructor( ) } } - content != null -> { + content != null -> { // Invitation case if (event.isSentByCurrentUser()) { sp.getString( @@ -326,13 +326,13 @@ class NoticeEventFormatter @Inject constructor( ) } } - else -> null + else -> null } } private fun formatCallEvent(type: String, event: Event, senderName: String?): CharSequence? { return when (type) { - EventType.CALL_INVITE -> { + EventType.CALL_INVITE -> { val content = event.getClearContent().toModel() ?: return null val isVideoCall = content.isVideo() return if (isVideoCall) { @@ -349,13 +349,13 @@ class NoticeEventFormatter @Inject constructor( } } } - EventType.CALL_ANSWER -> + EventType.CALL_ANSWER -> if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_answered_call_by_you) } else { sp.getString(R.string.notice_answered_call, senderName) } - EventType.CALL_HANGUP -> + EventType.CALL_HANGUP -> if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_ended_call_by_you) } else { @@ -367,13 +367,13 @@ class NoticeEventFormatter @Inject constructor( } else { sp.getString(R.string.notice_call_candidates, senderName) } - EventType.CALL_REJECT -> + EventType.CALL_REJECT -> if (event.isSentByCurrentUser()) { sp.getString(R.string.call_tile_you_declined_this_call) } else { sp.getString(R.string.call_tile_other_declined, senderName) } - else -> null + else -> null } } @@ -403,19 +403,19 @@ class NoticeEventFormatter @Inject constructor( } else { sp.getString(R.string.notice_room_aliases_added_and_removed, senderName, addedAliases.joinToString(), removedAliases.joinToString()) } - addedAliases.isNotEmpty() -> + addedAliases.isNotEmpty() -> if (event.isSentByCurrentUser()) { sp.getQuantityString(R.plurals.notice_room_aliases_added_by_you, addedAliases.size, addedAliases.joinToString()) } else { sp.getQuantityString(R.plurals.notice_room_aliases_added, addedAliases.size, senderName, addedAliases.joinToString()) } - removedAliases.isNotEmpty() -> + removedAliases.isNotEmpty() -> if (event.isSentByCurrentUser()) { sp.getQuantityString(R.plurals.notice_room_aliases_removed_by_you, removedAliases.size, removedAliases.joinToString()) } else { sp.getQuantityString(R.plurals.notice_room_aliases_removed, removedAliases.size, senderName, removedAliases.joinToString()) } - else -> { + else -> { Timber.w("Alias event without any change...") null } @@ -516,7 +516,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_canonical_alias_no_change, senderName) } } - added.isEmpty() && removed.isEmpty() -> { + added.isEmpty() && removed.isEmpty() -> { // Canonical has changed if (canonicalAlias != null) { if (event.isSentByCurrentUser()) { @@ -532,7 +532,7 @@ class NoticeEventFormatter @Inject constructor( } } } - added.isEmpty() && canonicalAlias == prevCanonicalAlias -> { + added.isEmpty() && canonicalAlias == prevCanonicalAlias -> { // Some alternative has been removed if (event.isSentByCurrentUser()) { sp.getQuantityString(R.plurals.notice_room_canonical_alias_alternative_removed_by_you, removed.size, removed.joinToString()) @@ -540,7 +540,7 @@ class NoticeEventFormatter @Inject constructor( sp.getQuantityString(R.plurals.notice_room_canonical_alias_alternative_removed, removed.size, senderName, removed.joinToString()) } } - removed.isEmpty() && canonicalAlias == prevCanonicalAlias -> { + removed.isEmpty() && canonicalAlias == prevCanonicalAlias -> { // Some alternative has been added if (event.isSentByCurrentUser()) { sp.getQuantityString(R.plurals.notice_room_canonical_alias_alternative_added_by_you, added.size, added.joinToString()) @@ -548,7 +548,7 @@ class NoticeEventFormatter @Inject constructor( sp.getQuantityString(R.plurals.notice_room_canonical_alias_alternative_added, added.size, senderName, added.joinToString()) } } - canonicalAlias == prevCanonicalAlias -> { + canonicalAlias == prevCanonicalAlias -> { // Alternative added and removed if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_room_canonical_alias_alternative_changed_by_you) @@ -556,7 +556,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_canonical_alias_alternative_changed, senderName) } } - else -> { + else -> { // Main and removed, or main and added, or main and added and removed if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_room_canonical_alias_main_and_alternative_changed_by_you) @@ -570,7 +570,7 @@ class NoticeEventFormatter @Inject constructor( private fun formatRoomGuestAccessEvent(event: Event, senderName: String?, isDm: Boolean): String? { val eventContent: RoomGuestAccessContent? = event.content.toModel() return when (eventContent?.guestAccess) { - GuestAccess.CanJoin -> + GuestAccess.CanJoin -> if (event.isSentByCurrentUser()) { sp.getString( if (isDm) R.string.notice_direct_room_guest_access_can_join_by_you else R.string.notice_room_guest_access_can_join_by_you @@ -592,7 +592,7 @@ class NoticeEventFormatter @Inject constructor( senderName ) } - else -> null + else -> null } } @@ -608,7 +608,7 @@ class NoticeEventFormatter @Inject constructor( } else { sp.getString(R.string.notice_end_to_end_ok, senderName) } - else -> + else -> if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_end_to_end_unknown_algorithm_by_you, content.algorithm) } else { @@ -628,13 +628,13 @@ class NoticeEventFormatter @Inject constructor( } else { sp.getString(R.string.notice_display_name_set, event.senderId, eventContent?.displayName) } - eventContent?.displayName.isNullOrEmpty() -> + eventContent?.displayName.isNullOrEmpty() -> if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_display_name_removed_by_you, prevEventContent?.displayName) } else { sp.getString(R.string.notice_display_name_removed, event.senderId, prevEventContent?.displayName) } - else -> + else -> if (event.isSentByCurrentUser()) { sp.getString(R.string.notice_display_name_changed_from_by_you, prevEventContent?.displayName, eventContent?.displayName) } else { @@ -669,11 +669,13 @@ class NoticeEventFormatter @Inject constructor( return displayText.toString() } - private fun buildMembershipNotice(event: Event, - senderName: String?, - eventContent: RoomMemberContent?, - prevEventContent: RoomMemberContent?, - isDm: Boolean): String? { + private fun buildMembershipNotice( + event: Event, + senderName: String?, + eventContent: RoomMemberContent?, + prevEventContent: RoomMemberContent?, + isDm: Boolean + ): String? { val senderDisplayName = senderName ?: event.senderId ?: "" val targetDisplayName = eventContent?.displayName ?: prevEventContent?.displayName ?: event.stateKey ?: "" return when (eventContent?.membership) { @@ -694,11 +696,11 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_third_party_registered_invite, userWhoHasAccepted, threePidDisplayName) } } - event.stateKey == currentUserId -> + event.stateKey == currentUserId -> eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_invite_you_with_reason, senderDisplayName, reason) } ?: sp.getString(R.string.notice_room_invite_you, senderDisplayName) - event.stateKey.isNullOrEmpty() -> + event.stateKey.isNullOrEmpty() -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_invite_no_invitee_with_reason_by_you, reason) @@ -708,7 +710,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_invite_no_invitee_with_reason, senderDisplayName, reason) } ?: sp.getString(R.string.notice_room_invite_no_invitee, senderDisplayName) } - else -> + else -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_invite_with_reason_by_you, targetDisplayName, reason) @@ -720,7 +722,7 @@ class NoticeEventFormatter @Inject constructor( } } } - Membership.JOIN -> + Membership.JOIN -> eventContent.safeReason?.let { reason -> if (event.isSentByCurrentUser()) { sp.getString( @@ -743,7 +745,7 @@ class NoticeEventFormatter @Inject constructor( ) } } - Membership.LEAVE -> + Membership.LEAVE -> // 2 cases here: this member may have left voluntarily or they may have been "left" by someone else ie. kicked if (event.senderId == event.stateKey) { when (prevEventContent?.membership) { @@ -757,7 +759,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_reject_with_reason, senderDisplayName, reason) } ?: sp.getString(R.string.notice_room_reject, senderDisplayName) } - else -> + else -> eventContent.safeReason?.let { reason -> if (event.isSentByCurrentUser()) { sp.getString( @@ -798,7 +800,7 @@ class NoticeEventFormatter @Inject constructor( } ?: sp.getString(R.string.notice_room_withdraw, senderDisplayName, targetDisplayName) } Membership.LEAVE, - Membership.JOIN -> + Membership.JOIN -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_remove_with_reason_by_you, targetDisplayName, reason) @@ -808,7 +810,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_remove_with_reason, senderDisplayName, targetDisplayName, reason) } ?: sp.getString(R.string.notice_room_remove, senderDisplayName, targetDisplayName) } - Membership.BAN -> + Membership.BAN -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_unban_with_reason_by_you, targetDisplayName, reason) @@ -818,10 +820,10 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_unban_with_reason, senderDisplayName, targetDisplayName, reason) } ?: sp.getString(R.string.notice_room_unban, senderDisplayName, targetDisplayName) } - else -> null + else -> null } } - Membership.BAN -> + Membership.BAN -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { sp.getString(R.string.notice_room_ban_with_reason_by_you, targetDisplayName, it) @@ -831,7 +833,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_ban_with_reason, senderDisplayName, targetDisplayName, it) } ?: sp.getString(R.string.notice_room_ban, senderDisplayName, targetDisplayName) } - Membership.KNOCK -> + Membership.KNOCK -> if (event.isSentByCurrentUser()) { eventContent.safeReason?.let { reason -> sp.getString(R.string.notice_room_remove_with_reason_by_you, targetDisplayName, reason) @@ -841,7 +843,7 @@ class NoticeEventFormatter @Inject constructor( sp.getString(R.string.notice_room_remove_with_reason, senderDisplayName, targetDisplayName, reason) } ?: sp.getString(R.string.notice_room_remove, senderDisplayName, targetDisplayName) } - else -> null + else -> null } } @@ -863,7 +865,7 @@ class NoticeEventFormatter @Inject constructor( } else { sp.getString(R.string.room_join_rules_public, senderName) } - else -> null + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/RoomHistoryVisibilityFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/RoomHistoryVisibilityFormatter.kt index c1ba085fd7..76b303775a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/RoomHistoryVisibilityFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/RoomHistoryVisibilityFormatter.kt @@ -28,9 +28,9 @@ class RoomHistoryVisibilityFormatter @Inject constructor( return stringProvider.getString( when (roomHistoryVisibility) { RoomHistoryVisibility.WORLD_READABLE -> R.string.notice_room_visibility_world_readable - RoomHistoryVisibility.SHARED -> R.string.notice_room_visibility_shared - RoomHistoryVisibility.INVITED -> R.string.notice_room_visibility_invited - RoomHistoryVisibility.JOINED -> R.string.notice_room_visibility_joined + RoomHistoryVisibility.SHARED -> R.string.notice_room_visibility_shared + RoomHistoryVisibility.INVITED -> R.string.notice_room_visibility_invited + RoomHistoryVisibility.JOINED -> R.string.notice_room_visibility_joined } ) } @@ -39,9 +39,9 @@ class RoomHistoryVisibilityFormatter @Inject constructor( return stringProvider.getString( when (roomHistoryVisibility) { RoomHistoryVisibility.WORLD_READABLE -> R.string.room_settings_read_history_entry_anyone - RoomHistoryVisibility.SHARED -> R.string.room_settings_read_history_entry_members_only_option_time_shared - RoomHistoryVisibility.INVITED -> R.string.room_settings_read_history_entry_members_only_invited - RoomHistoryVisibility.JOINED -> R.string.room_settings_read_history_entry_members_only_joined + RoomHistoryVisibility.SHARED -> R.string.room_settings_read_history_entry_members_only_option_time_shared + RoomHistoryVisibility.INVITED -> R.string.room_settings_read_history_entry_members_only_invited + RoomHistoryVisibility.JOINED -> R.string.room_settings_read_history_entry_members_only_joined } ) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt index 44387759c8..6937cd3a46 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt @@ -121,18 +121,18 @@ class AudioMessagePlaybackTracker @Inject constructor() { fun getPlaybackTime(id: String): Int { return when (val state = states[id]) { is Listener.State.Playing -> state.playbackTime - is Listener.State.Paused -> state.playbackTime + is Listener.State.Paused -> state.playbackTime /* Listener.State.Idle, */ - else -> 0 + else -> 0 } } private fun getPercentage(id: String): Float { return when (val state = states[id]) { is Listener.State.Playing -> state.percentage - is Listener.State.Paused -> state.percentage + is Listener.State.Paused -> state.percentage /* Listener.State.Idle, */ - else -> 0f + else -> 0f } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AvatarSizeProvider.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AvatarSizeProvider.kt index a34c216fad..99b42a8c61 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AvatarSizeProvider.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AvatarSizeProvider.kt @@ -21,8 +21,10 @@ import im.vector.app.features.home.room.detail.timeline.style.TimelineLayoutSett import im.vector.app.features.home.room.detail.timeline.style.TimelineLayoutSettingsProvider import javax.inject.Inject -class AvatarSizeProvider @Inject constructor(private val dimensionConverter: DimensionConverter, - private val layoutSettingsProvider: TimelineLayoutSettingsProvider) { +class AvatarSizeProvider @Inject constructor( + private val dimensionConverter: DimensionConverter, + private val layoutSettingsProvider: TimelineLayoutSettingsProvider +) { private val avatarStyle by lazy { when (layoutSettingsProvider.getLayoutSettings()) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentDownloadStateTrackerBinder.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentDownloadStateTrackerBinder.kt index 8f5f80c834..a4907c1099 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentDownloadStateTrackerBinder.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentDownloadStateTrackerBinder.kt @@ -31,8 +31,10 @@ class ContentDownloadStateTrackerBinder @Inject constructor(private val activeSe private val updateListeners = mutableMapOf() - fun bind(mxcUrl: String, - holder: MessageFileItem.Holder) { + fun bind( + mxcUrl: String, + holder: MessageFileItem.Holder + ) { activeSessionHolder.getSafeActiveSession()?.also { session -> val downloadStateTracker = session.contentDownloadProgressTracker() val updateListener = ContentDownloadUpdater(holder) @@ -62,11 +64,11 @@ private class ContentDownloadUpdater(private val holder: MessageFileItem.Holder) override fun onDownloadStateUpdate(state: ContentDownloadStateTracker.State) { when (state) { - ContentDownloadStateTracker.State.Idle -> handleIdle() + ContentDownloadStateTracker.State.Idle -> handleIdle() is ContentDownloadStateTracker.State.Downloading -> handleProgress(state) - ContentDownloadStateTracker.State.Decrypting -> handleDecrypting() - ContentDownloadStateTracker.State.Success -> handleSuccess() - is ContentDownloadStateTracker.State.Failure -> handleFailure() + ContentDownloadStateTracker.State.Decrypting -> handleDecrypting() + ContentDownloadStateTracker.State.Success -> handleSuccess() + is ContentDownloadStateTracker.State.Failure -> handleFailure() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentUploadStateTrackerBinder.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentUploadStateTrackerBinder.kt index b8882b3f47..cda4af89ce 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentUploadStateTrackerBinder.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/ContentUploadStateTrackerBinder.kt @@ -33,15 +33,19 @@ import org.matrix.android.sdk.api.session.room.send.SendState import javax.inject.Inject @ActivityScoped -class ContentUploadStateTrackerBinder @Inject constructor(private val activeSessionHolder: ActiveSessionHolder, - private val messageColorProvider: MessageColorProvider, - private val errorFormatter: ErrorFormatter) { +class ContentUploadStateTrackerBinder @Inject constructor( + private val activeSessionHolder: ActiveSessionHolder, + private val messageColorProvider: MessageColorProvider, + private val errorFormatter: ErrorFormatter +) { private val updateListeners = mutableMapOf() - fun bind(eventId: String, - isLocalFile: Boolean, - progressLayout: ViewGroup) { + fun bind( + eventId: String, + isLocalFile: Boolean, + progressLayout: ViewGroup + ) { activeSessionHolder.getSafeActiveSession()?.also { session -> val uploadStateTracker = session.contentUploadProgressTracker() val updateListener = ContentMediaProgressUpdater(progressLayout, isLocalFile, messageColorProvider, errorFormatter) @@ -66,25 +70,27 @@ class ContentUploadStateTrackerBinder @Inject constructor(private val activeSess } } -private class ContentMediaProgressUpdater(private val progressLayout: ViewGroup, - private val isLocalFile: Boolean, - private val messageColorProvider: MessageColorProvider, - private val errorFormatter: ErrorFormatter) : ContentUploadStateTracker.UpdateListener { +private class ContentMediaProgressUpdater( + private val progressLayout: ViewGroup, + private val isLocalFile: Boolean, + private val messageColorProvider: MessageColorProvider, + private val errorFormatter: ErrorFormatter +) : ContentUploadStateTracker.UpdateListener { private val progressBar: ProgressBar = progressLayout.findViewById(R.id.mediaProgressBar) private val progressTextView: TextView = progressLayout.findViewById(R.id.mediaProgressTextView) override fun onUpdate(state: ContentUploadStateTracker.State) { when (state) { - is ContentUploadStateTracker.State.Idle -> handleIdle() + is ContentUploadStateTracker.State.Idle -> handleIdle() is ContentUploadStateTracker.State.EncryptingThumbnail -> handleEncryptingThumbnail() - is ContentUploadStateTracker.State.UploadingThumbnail -> handleProgressThumbnail(state) - is ContentUploadStateTracker.State.Encrypting -> handleEncrypting(state) - is ContentUploadStateTracker.State.Uploading -> handleProgress(state) - is ContentUploadStateTracker.State.Failure -> handleFailure(/*state*/) - is ContentUploadStateTracker.State.Success -> handleSuccess() - is ContentUploadStateTracker.State.CompressingImage -> handleCompressingImage() - is ContentUploadStateTracker.State.CompressingVideo -> handleCompressingVideo(state) + is ContentUploadStateTracker.State.UploadingThumbnail -> handleProgressThumbnail(state) + is ContentUploadStateTracker.State.Encrypting -> handleEncrypting(state) + is ContentUploadStateTracker.State.Uploading -> handleProgress(state) + is ContentUploadStateTracker.State.Failure -> handleFailure(/*state*/) + is ContentUploadStateTracker.State.Success -> handleSuccess() + is ContentUploadStateTracker.State.CompressingImage -> handleCompressingImage() + is ContentUploadStateTracker.State.CompressingVideo -> handleCompressingVideo(state) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MatrixItemColorProvider.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MatrixItemColorProvider.kt index 1c64082f65..e23e003768 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MatrixItemColorProvider.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MatrixItemColorProvider.kt @@ -40,7 +40,7 @@ class MatrixItemColorProvider @Inject constructor( colorProvider.getColor( when (matrixItem) { is MatrixItem.UserItem -> getColorFromUserId(matrixItem.id) - else -> getColorFromRoomId(matrixItem.id) + else -> getColorFromRoomId(matrixItem.id) } ) } @@ -96,13 +96,13 @@ class MatrixItemColorProvider @Inject constructor( @ColorRes private fun getUserColorByIndex(index: Int): Int { return when (index % 8) { - 1 -> R.color.element_name_02 - 2 -> R.color.element_name_03 - 3 -> R.color.element_name_04 - 4 -> R.color.element_name_05 - 5 -> R.color.element_name_06 - 6 -> R.color.element_name_07 - 7 -> R.color.element_name_08 + 1 -> R.color.element_name_02 + 2 -> R.color.element_name_03 + 3 -> R.color.element_name_04 + 4 -> R.color.element_name_05 + 5 -> R.color.element_name_06 + 6 -> R.color.element_name_07 + 7 -> R.color.element_name_08 else -> R.color.element_name_01 } } @@ -110,8 +110,8 @@ class MatrixItemColorProvider @Inject constructor( @ColorRes private fun getColorFromRoomId(roomId: String?): Int { return when ((roomId?.toList()?.sumOf { it.code } ?: 0) % 3) { - 1 -> R.color.element_room_02 - 2 -> R.color.element_room_03 + 1 -> R.color.element_room_02 + 2 -> R.color.element_room_03 else -> R.color.element_room_01 } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt index 7e4ec75783..e86d3b2ec6 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt @@ -47,10 +47,12 @@ import javax.inject.Inject /** * This class is responsible of building extra information data associated to a given event. */ -class MessageInformationDataFactory @Inject constructor(private val session: Session, - private val dateFormatter: VectorDateFormatter, - private val messageLayoutFactory: TimelineMessageLayoutFactory, - private val reactionsSummaryFactory: ReactionsSummaryFactory) { +class MessageInformationDataFactory @Inject constructor( + private val session: Session, + private val dateFormatter: VectorDateFormatter, + private val messageLayoutFactory: TimelineMessageLayoutFactory, + private val reactionsSummaryFactory: ReactionsSummaryFactory +) { fun create(params: TimelineItemFactoryParams): MessageInformationData { val event = params.event @@ -124,9 +126,11 @@ class MessageInformationDataFactory @Inject constructor(private val session: Ses ) } - private fun getSendStateDecoration(event: TimelineEvent, - lastSentEventWithoutReadReceipts: String?, - isMedia: Boolean): SendStateDecoration { + private fun getSendStateDecoration( + event: TimelineEvent, + lastSentEventWithoutReadReceipts: String?, + isMedia: Boolean + ): SendStateDecoration { val eventSendState = event.root.sendState return if (eventSendState.isSending()) { if (isMedia) SendStateDecoration.SENDING_MEDIA else SendStateDecoration.SENDING_NON_MEDIA @@ -159,18 +163,18 @@ class MessageInformationDataFactory @Inject constructor(private val session: Ses session.cryptoService().getDeviceInfo(event.root.senderId ?: "", deviceId) } when { - sendingDevice == null -> { + sendingDevice == null -> { // For now do not decorate this with warning // maybe it's a deleted session E2EDecoration.NONE } - sendingDevice.trustLevel == null -> { + sendingDevice.trustLevel == null -> { E2EDecoration.WARN_SENT_BY_UNKNOWN } sendingDevice.trustLevel?.isVerified().orFalse() -> { E2EDecoration.NONE } - else -> { + else -> { E2EDecoration.WARN_SENT_BY_UNVERIFIED } } @@ -197,10 +201,10 @@ class MessageInformationDataFactory @Inject constructor(private val session: Ses return when (event?.root?.getClearType()) { EventType.KEY_VERIFICATION_DONE, EventType.KEY_VERIFICATION_CANCEL -> true - EventType.MESSAGE -> { + EventType.MESSAGE -> { event.getLastMessageContent() is MessageVerificationRequestContent } - else -> false + else -> false } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt index dad0e3e4ed..ad7482d9a5 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt @@ -36,13 +36,16 @@ class MessageItemAttributesFactory @Inject constructor( private val stringProvider: StringProvider, private val displayableEventFormatter: DisplayableEventFormatter, private val preferencesProvider: UserPreferencesProvider, - private val emojiCompatFontProvider: EmojiCompatFontProvider) { + private val emojiCompatFontProvider: EmojiCompatFontProvider +) { - fun create(messageContent: Any?, - informationData: MessageInformationData, - callback: TimelineEventController.Callback?, - reactionsSummaryEvents: ReactionsSummaryEvents?, - threadDetails: ThreadDetails? = null): AbsMessageItem.Attributes { + fun create( + messageContent: Any?, + informationData: MessageInformationData, + callback: TimelineEventController.Callback?, + reactionsSummaryEvents: ReactionsSummaryEvents?, + threadDetails: ThreadDetails? = null + ): AbsMessageItem.Attributes { return AbsMessageItem.Attributes( avatarSize = avatarSizeProvider.avatarSize, informationData = informationData, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineControllerInterceptorHelper.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineControllerInterceptorHelper.kt index e9361e564c..6739eff010 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineControllerInterceptorHelper.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineControllerInterceptorHelper.kt @@ -30,8 +30,9 @@ import kotlin.reflect.KMutableProperty0 private const val DEFAULT_PREFETCH_THRESHOLD = 30 -class TimelineControllerInterceptorHelper(private val positionOfReadMarker: KMutableProperty0, - private val adapterPositionMapping: MutableMap +class TimelineControllerInterceptorHelper( + private val positionOfReadMarker: KMutableProperty0, + private val adapterPositionMapping: MutableMap ) { private var previousModelsSize = 0 diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineDisplayableEvents.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineDisplayableEvents.kt index 1736b20d44..85ffd7295c 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineDisplayableEvents.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineDisplayableEvents.kt @@ -71,11 +71,11 @@ fun TimelineEvent.isRoomConfiguration(roomCreatorUserId: String?): Boolean { EventType.STATE_ROOM_CANONICAL_ALIAS, EventType.STATE_ROOM_POWER_LEVELS, EventType.STATE_ROOM_ENCRYPTION -> true - EventType.STATE_ROOM_MEMBER -> { + EventType.STATE_ROOM_MEMBER -> { // Keep only room member events regarding the room creator (when he joined the room), // but exclude events where the room creator invite others, or where others join roomCreatorUserId != null && root.stateKey == roomCreatorUserId } - else -> false + else -> false } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventDiffUtilCallback.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventDiffUtilCallback.kt index 7aa43a4513..c2569b038b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventDiffUtilCallback.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventDiffUtilCallback.kt @@ -19,8 +19,10 @@ package im.vector.app.features.home.room.detail.timeline.helper import androidx.recyclerview.widget.DiffUtil import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent -class TimelineEventDiffUtilCallback(private val oldList: List, - private val newList: List) : DiffUtil.Callback() { +class TimelineEventDiffUtilCallback( + private val oldList: List, + private val newList: List +) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldList.size diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt index 8ca999309a..e4e0ea8352 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt @@ -47,7 +47,8 @@ class TimelineEventVisibilityHelper @Inject constructor(private val userPreferen minSize: Int, eventIdToHighlight: String?, rootThreadEventId: String?, - isFromThreadTimeline: Boolean): List { + isFromThreadTimeline: Boolean + ): List { if (index >= timelineEvents.size - 1) { return emptyList() } @@ -99,7 +100,8 @@ class TimelineEventVisibilityHelper @Inject constructor(private val userPreferen minSize: Int, eventIdToHighlight: String?, rootThreadEventId: String?, - isFromThreadTimeline: Boolean): List { + isFromThreadTimeline: Boolean + ): List { val prevSub = timelineEvents.subList(0, index + 1) return prevSub .reversed() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineMediaSizeProvider.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineMediaSizeProvider.kt index 53c2f6c0d4..107873b776 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineMediaSizeProvider.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineMediaSizeProvider.kt @@ -25,8 +25,10 @@ import javax.inject.Inject import kotlin.math.roundToInt @ActivityScoped -class TimelineMediaSizeProvider @Inject constructor(private val resources: Resources, - private val vectorPreferences: VectorPreferences) { +class TimelineMediaSizeProvider @Inject constructor( + private val resources: Resources, + private val vectorPreferences: VectorPreferences +) { var recyclerView: RecyclerView? = null private var cachedSize: Pair? = null diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineVisibilityStateChangedListeners.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineVisibilityStateChangedListeners.kt index 95feef83c0..61a7557906 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineVisibilityStateChangedListeners.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineVisibilityStateChangedListeners.kt @@ -31,8 +31,10 @@ class ReadMarkerVisibilityStateChangedListener(private val callback: TimelineEve } } -class TimelineEventVisibilityStateChangedListener(private val callback: TimelineEventController.Callback?, - private val event: TimelineEvent) : +class TimelineEventVisibilityStateChangedListener( + private val callback: TimelineEventController.Callback?, + private val event: TimelineEvent +) : VectorEpoxyModel.OnVisibilityStateChangedListener { override fun onVisibilityStateChanged(visibilityState: Int) { @@ -44,8 +46,10 @@ class TimelineEventVisibilityStateChangedListener(private val callback: Timeline } } -class MergedTimelineEventVisibilityStateChangedListener(private val callback: TimelineEventController.Callback?, - private val events: List) : +class MergedTimelineEventVisibilityStateChangedListener( + private val callback: TimelineEventController.Callback?, + private val events: List +) : VectorEpoxyModel.OnVisibilityStateChangedListener { override fun onVisibilityStateChanged(visibilityState: Int) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/image/ImageContentRendererFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/image/ImageContentRendererFactory.kt index 26cab4d863..91bbd584e1 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/image/ImageContentRendererFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/image/ImageContentRendererFactory.kt @@ -60,6 +60,6 @@ fun TimelineEvent.buildImageContentRendererData(maxHeight: Int): ImageContentRen allowNonMxcUrls = false ) } - else -> null + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsBaseMessageItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsBaseMessageItem.kt index c21cb5319e..e3471b22f8 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsBaseMessageItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsBaseMessageItem.kt @@ -80,7 +80,7 @@ abstract class AbsBaseMessageItem : BaseEventItem super.bind(holder) renderReactions(holder, baseAttributes.informationData.reactionsSummary) when (baseAttributes.informationData.e2eDecoration) { - E2EDecoration.NONE -> { + E2EDecoration.NONE -> { holder.e2EDecorationView.render(null) } E2EDecoration.WARN_IN_CLEAR, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt index e7823845fa..ee3a9f6746 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt @@ -77,25 +77,31 @@ abstract class AbsMessageLocationItem : AbsMe .apply(RequestOptions.centerCropTransform()) .placeholder(holder.staticMapImageView.drawable) .listener(object : RequestListener { - override fun onLoadFailed(e: GlideException?, - model: Any?, - target: Target?, - isFirstResource: Boolean): Boolean { + override fun onLoadFailed( + e: GlideException?, + model: Any?, + target: Target?, + isFirstResource: Boolean + ): Boolean { holder.staticMapPinImageView.setImageResource(R.drawable.ic_location_pin_failed) holder.staticMapErrorTextView.isVisible = true + holder.staticMapCopyrightTextView.isVisible = false return false } - override fun onResourceReady(resource: Drawable?, - model: Any?, - target: Target?, - dataSource: DataSource?, - isFirstResource: Boolean): Boolean { + override fun onResourceReady( + resource: Drawable?, + model: Any?, + target: Target?, + dataSource: DataSource?, + isFirstResource: Boolean + ): Boolean { locationPinProvider?.create(locationUserId) { pinDrawable -> // we are not using Glide since it does not display it correctly when there is no user photo holder.staticMapPinImageView.setImageDrawable(pinDrawable) } holder.staticMapErrorTextView.isVisible = false + holder.staticMapCopyrightTextView.isVisible = true return false } }) @@ -107,5 +113,6 @@ abstract class AbsMessageLocationItem : AbsMe val staticMapImageView by bind(R.id.staticMapImageView) val staticMapPinImageView by bind(R.id.staticMapPinImageView) val staticMapErrorTextView by bind(R.id.staticMapErrorTextView) + val staticMapCopyrightTextView by bind(R.id.staticMapCopyrightTextView) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/CallTileTimelineItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/CallTileTimelineItem.kt index b56f5264e6..228e0181d2 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/CallTileTimelineItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/CallTileTimelineItem.kt @@ -60,11 +60,11 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem renderInvitedStatus(holder) - CallStatus.IN_CALL -> renderInCallStatus(holder) + CallStatus.INVITED -> renderInvitedStatus(holder) + CallStatus.IN_CALL -> renderInCallStatus(holder) CallStatus.REJECTED -> renderRejectedStatus(holder) - CallStatus.ENDED -> renderEndedStatus(holder) - CallStatus.MISSED -> renderMissedStatus(holder) + CallStatus.ENDED -> renderEndedStatus(holder) + CallStatus.MISSED -> renderMissedStatus(holder) } renderSendState(holder.view, null, holder.failedToSendIndicator) } @@ -97,11 +97,11 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { + CallKind.VIDEO -> { val endCallStatus = holder.resources.getString(R.string.call_tile_video_call_has_ended, attributes.formattedDuration) holder.statusView.setStatus(endCallStatus) } - CallKind.AUDIO -> { + CallKind.AUDIO -> { val endCallStatus = holder.resources.getString(R.string.call_tile_voice_call_has_ended, attributes.formattedDuration) holder.statusView.setStatus(endCallStatus) } @@ -148,7 +148,7 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { + attributes.isStillActive -> { holder.rejectView.isVisible = true holder.rejectView.setText(R.string.call_notification_hangup) holder.rejectView.setLeftDrawable(R.drawable.ic_call_hangup, R.attr.colorOnPrimary) @@ -156,7 +156,7 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { + else -> { holder.acceptRejectViewGroup.isVisible = false } } @@ -169,7 +169,7 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { + attributes.callKind == CallKind.CONFERENCE -> { holder.acceptRejectViewGroup.isVisible = true holder.acceptView.onClick { attributes.callback?.onTimelineItemAction(RoomDetailAction.JoinJitsiCall) @@ -200,7 +200,7 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { + else -> { holder.acceptRejectViewGroup.isVisible = false } } @@ -209,13 +209,13 @@ abstract class CallTileTimelineItem : AbsBaseMessageItem { holder.statusView.setStatus(R.string.call_tile_video_active) } - attributes.informationData.sentByMe -> { + attributes.informationData.sentByMe -> { holder.statusView.setStatus(R.string.call_ringing) } - attributes.callKind.isVoiceCall -> { + attributes.callKind.isVoiceCall -> { holder.statusView.setStatus(R.string.call_tile_voice_incoming) } - else -> { + else -> { holder.statusView.setStatus(R.string.call_tile_video_incoming) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageAudioItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageAudioItem.kt index f574dcfdcb..a3c09960c9 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageAudioItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageAudioItem.kt @@ -144,9 +144,9 @@ abstract class MessageAudioItem : AbsMessageItem() { audioMessagePlaybackTracker.track(attributes.informationData.eventId, object : AudioMessagePlaybackTracker.Listener { override fun onUpdate(state: AudioMessagePlaybackTracker.Listener.State) { when (state) { - is AudioMessagePlaybackTracker.Listener.State.Idle -> renderIdleState(holder) - is AudioMessagePlaybackTracker.Listener.State.Playing -> renderPlayingState(holder, state) - is AudioMessagePlaybackTracker.Listener.State.Paused -> renderPausedState(holder, state) + is AudioMessagePlaybackTracker.Listener.State.Idle -> renderIdleState(holder) + is AudioMessagePlaybackTracker.Listener.State.Playing -> renderPlayingState(holder, state) + is AudioMessagePlaybackTracker.Listener.State.Paused -> renderPausedState(holder, state) is AudioMessagePlaybackTracker.Listener.State.Recording -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt index 838fbd46de..795bd21cb2 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt @@ -72,13 +72,13 @@ abstract class MessageLiveLocationItem : AbsMessageLocationItem + messageLayout is TimelineMessageLayout.Bubble -> LocationLiveMessageBannerViewState.Watcher( bottomStartCornerRadiusInDp = messageLayout.cornersRadius.bottomStartRadius, bottomEndCornerRadiusInDp = messageLayout.cornersRadius.bottomEndRadius, formattedLocalTimeOfEndOfLive = getFormattedLocalTimeEndOfLive(), ) - isEmitter -> { + isEmitter -> { val cornerRadius = getBannerCornerRadiusForDefaultLayout(holder) LocationLiveMessageBannerViewState.Emitter( remainingTimeInMillis = getRemainingTimeOfLiveInMillis(), @@ -87,7 +87,7 @@ abstract class MessageLiveLocationItem : AbsMessageLocationItem { + else -> { val cornerRadius = getBannerCornerRadiusForDefaultLayout(holder) LocationLiveMessageBannerViewState.Watcher( bottomStartCornerRadiusInDp = cornerRadius, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageVoiceItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageVoiceItem.kt index 82860da886..e8f1762963 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageVoiceItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageVoiceItem.kt @@ -111,7 +111,7 @@ abstract class MessageVoiceItem : AbsMessageItem() { holder.voicePlaybackWaveform.setOnTouchListener { view, motionEvent -> when (motionEvent.action) { - MotionEvent.ACTION_UP -> { + MotionEvent.ACTION_UP -> { val percentage = getTouchedPositionPercentage(motionEvent, view) waveformTouchListener?.onWaveformTouchedUp(percentage) } @@ -126,9 +126,9 @@ abstract class MessageVoiceItem : AbsMessageItem() { audioMessagePlaybackTracker.track(attributes.informationData.eventId, object : AudioMessagePlaybackTracker.Listener { override fun onUpdate(state: AudioMessagePlaybackTracker.Listener.State) { when (state) { - is AudioMessagePlaybackTracker.Listener.State.Idle -> renderIdleState(holder, waveformColorIdle, waveformColorPlayed) - is AudioMessagePlaybackTracker.Listener.State.Playing -> renderPlayingState(holder, state, waveformColorIdle, waveformColorPlayed) - is AudioMessagePlaybackTracker.Listener.State.Paused -> renderPausedState(holder, state, waveformColorIdle, waveformColorPlayed) + is AudioMessagePlaybackTracker.Listener.State.Idle -> renderIdleState(holder, waveformColorIdle, waveformColorPlayed) + is AudioMessagePlaybackTracker.Listener.State.Playing -> renderPlayingState(holder, state, waveformColorIdle, waveformColorPlayed) + is AudioMessagePlaybackTracker.Listener.State.Paused -> renderPausedState(holder, state, waveformColorIdle, waveformColorPlayed) is AudioMessagePlaybackTracker.Listener.State.Recording -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/NoticeItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/NoticeItem.kt index 7ca5166542..9d865e6dad 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/NoticeItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/NoticeItem.kt @@ -44,7 +44,7 @@ abstract class NoticeItem : BaseEventItem() { holder.avatarImageView.onClick(attributes.avatarClickListener) when (attributes.informationData.e2eDecoration) { - E2EDecoration.NONE -> { + E2EDecoration.NONE -> { holder.e2EDecorationView.render(null) } E2EDecoration.WARN_IN_CLEAR, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionView.kt index 80daa595b6..b21b1a152d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionView.kt @@ -43,10 +43,10 @@ class PollOptionView @JvmOverloads constructor( views.optionNameTextView.text = state.optionAnswer when (state) { - is PollOptionViewState.PollSending -> renderPollSending() - is PollOptionViewState.PollEnded -> renderPollEnded(state) - is PollOptionViewState.PollReady -> renderPollReady() - is PollOptionViewState.PollVoted -> renderPollVoted(state) + is PollOptionViewState.PollSending -> renderPollSending() + is PollOptionViewState.PollEnded -> renderPollEnded(state) + is PollOptionViewState.PollReady -> renderPollReady() + is PollOptionViewState.PollVoted -> renderPollVoted(state) is PollOptionViewState.PollUndisclosed -> renderPollUndisclosed(state) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt index fe17f9e9e7..826c6c5395 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt @@ -16,47 +16,54 @@ package im.vector.app.features.home.room.detail.timeline.item -sealed class PollOptionViewState(open val optionId: String, - open val optionAnswer: String) { +sealed class PollOptionViewState( + open val optionId: String, + open val optionAnswer: String +) { /** * Represents a poll that is not sent to the server yet. */ - data class PollSending(override val optionId: String, - override val optionAnswer: String + data class PollSending( + override val optionId: String, + override val optionAnswer: String ) : PollOptionViewState(optionId, optionAnswer) /** * Represents a poll that is sent but not voted by the user. */ - data class PollReady(override val optionId: String, - override val optionAnswer: String + data class PollReady( + override val optionId: String, + override val optionAnswer: String ) : PollOptionViewState(optionId, optionAnswer) /** * Represents a poll that user already voted. */ - data class PollVoted(override val optionId: String, - override val optionAnswer: String, - val voteCount: Int, - val votePercentage: Double, - val isSelected: Boolean + data class PollVoted( + override val optionId: String, + override val optionAnswer: String, + val voteCount: Int, + val votePercentage: Double, + val isSelected: Boolean ) : PollOptionViewState(optionId, optionAnswer) /** * Represents a poll that is ended. */ - data class PollEnded(override val optionId: String, - override val optionAnswer: String, - val voteCount: Int, - val votePercentage: Double, - val isWinner: Boolean + data class PollEnded( + override val optionId: String, + override val optionAnswer: String, + val voteCount: Int, + val votePercentage: Double, + val isWinner: Boolean ) : PollOptionViewState(optionId, optionAnswer) /** * Represent a poll that is undisclosed, votes will be hidden until the poll is ended. */ - data class PollUndisclosed(override val optionId: String, - override val optionAnswer: String, - val isSelected: Boolean + data class PollUndisclosed( + override val optionId: String, + override val optionAnswer: String, + val isSelected: Boolean ) : PollOptionViewState(optionId, optionAnswer) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/StatusTileTimelineItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/StatusTileTimelineItem.kt index 3810f1cb6f..e4c68a7a5b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/StatusTileTimelineItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/StatusTileTimelineItem.kt @@ -56,7 +56,7 @@ abstract class StatusTileTimelineItem : AbsBaseMessageItem R.drawable.ic_shield_trusted ShieldUIState.BLACK -> R.drawable.ic_shield_black - ShieldUIState.RED -> R.drawable.ic_shield_warning + ShieldUIState.RED -> R.drawable.ic_shield_warning ShieldUIState.ERROR -> R.drawable.ic_warning_badge } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/VerificationRequestItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/VerificationRequestItem.kt index fc4c55d1f3..395b5fa308 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/VerificationRequestItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/VerificationRequestItem.kt @@ -78,7 +78,7 @@ abstract class VerificationRequestItem : AbsBaseMessageItem { + null -> { holder.buttonBar.isVisible = !attributes.informationData.sentByMe holder.statusTextView.text = null holder.statusTextView.isVisible = false @@ -89,17 +89,17 @@ abstract class VerificationRequestItem : AbsBaseMessageItem { + VerificationState.CANCELED_BY_ME -> { holder.buttonBar.isVisible = false holder.statusTextView.text = holder.view.context.getString(R.string.verification_request_you_cancelled) holder.statusTextView.isVisible = true } - VerificationState.WAITING -> { + VerificationState.WAITING -> { holder.buttonBar.isVisible = false holder.statusTextView.text = holder.view.context.getString(R.string.verification_request_waiting) holder.statusTextView.isVisible = true } - VerificationState.DONE -> { + VerificationState.DONE -> { holder.buttonBar.isVisible = false holder.statusTextView.text = if (attributes.informationData.sentByMe) { holder.view.context.getString(R.string.verification_request_other_accepted, attributes.otherUserName) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/merged/MergedTimelines.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/merged/MergedTimelines.kt index a517aab720..58ad08f026 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/merged/MergedTimelines.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/merged/MergedTimelines.kt @@ -35,7 +35,8 @@ import kotlin.reflect.KMutableProperty0 class MergedTimelines( private val coroutineScope: CoroutineScope, private val mainTimeline: Timeline, - private val secondaryTimelineParams: SecondaryTimelineParams) : Timeline by mainTimeline { + private val secondaryTimelineParams: SecondaryTimelineParams +) : Timeline by mainTimeline { data class SecondaryTimelineParams( val timeline: Timeline, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt index a4677da1d9..7f619d3838 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt @@ -34,7 +34,8 @@ import javax.inject.Inject */ class ViewReactionsEpoxyController @Inject constructor( private val stringProvider: StringProvider, - private val emojiSpanify: EmojiSpanify) : + private val emojiSpanify: EmojiSpanify +) : TypedEpoxyController() { var listener: Listener? = null @@ -48,7 +49,7 @@ class ViewReactionsEpoxyController @Inject constructor( id("Spinner") } } - is Fail -> { + is Fail -> { genericFooterItem { id("failure") text(host.stringProvider.getString(R.string.unknown_error).toEpoxyCharSequence()) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt index 1c9127aa1e..1ce4341167 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt @@ -41,7 +41,8 @@ import org.matrix.android.sdk.flow.unwrap data class DisplayReactionsViewState( val eventId: String, val roomId: String, - val mapReactionKeyToMemberList: Async> = Uninitialized) : + val mapReactionKeyToMemberList: Async> = Uninitialized +) : MavericksState { constructor(args: TimelineEventFragmentArgs) : this(roomId = args.roomId, eventId = args.eventId) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/render/EventTextRenderer.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/render/EventTextRenderer.kt index 83cffc4279..920f3e3b80 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/render/EventTextRenderer.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/render/EventTextRenderer.kt @@ -30,10 +30,12 @@ import im.vector.app.features.html.PillImageSpan import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.util.MatrixItem -class EventTextRenderer @AssistedInject constructor(@Assisted private val roomId: String?, - private val context: Context, - private val avatarRenderer: AvatarRenderer, - private val sessionHolder: ActiveSessionHolder) { +class EventTextRenderer @AssistedInject constructor( + @Assisted private val roomId: String?, + private val context: Context, + private val avatarRenderer: AvatarRenderer, + private val sessionHolder: ActiveSessionHolder +) { /* ========================================================================================== * Public api diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt index a0d10a8a75..e1707decc9 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt @@ -34,11 +34,13 @@ import org.matrix.android.sdk.api.session.room.timeline.isEdition import org.matrix.android.sdk.api.session.room.timeline.isRootThread import javax.inject.Inject -class TimelineMessageLayoutFactory @Inject constructor(private val session: Session, - private val layoutSettingsProvider: TimelineLayoutSettingsProvider, - private val localeProvider: LocaleProvider, - private val resources: Resources, - private val vectorPreferences: VectorPreferences) { +class TimelineMessageLayoutFactory @Inject constructor( + private val session: Session, + private val layoutSettingsProvider: TimelineLayoutSettingsProvider, + private val localeProvider: LocaleProvider, + private val resources: Resources, + private val vectorPreferences: VectorPreferences +) { companion object { // Can be rendered in bubbles, other types will fallback to default @@ -60,16 +62,15 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess MessageType.MSGTYPE_STICKER_LOCAL, MessageType.MSGTYPE_EMOTE, MessageType.MSGTYPE_BEACON_INFO, + MessageType.MSGTYPE_LOCATION, + MessageType.MSGTYPE_BEACON_LOCATION_DATA, ) private val MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE = setOf( MessageType.MSGTYPE_IMAGE, MessageType.MSGTYPE_VIDEO, MessageType.MSGTYPE_BEACON_INFO, - ) - - private val MSG_TYPES_WITH_LOCATION_DATA = setOf( MessageType.MSGTYPE_LOCATION, - MessageType.MSGTYPE_BEACON_LOCATION_DATA + MessageType.MSGTYPE_BEACON_LOCATION_DATA, ) } @@ -145,23 +146,20 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess private fun MessageContent?.isPseudoBubble(): Boolean { if (this == null) return false - if (msgType == MessageType.MSGTYPE_LOCATION) return vectorPreferences.labsRenderLocationsInTimeline() return this.msgType in MSG_TYPES_WITH_PSEUDO_BUBBLE_LAYOUT } private fun MessageContent?.timestampInsideMessage(): Boolean { return when { - this == null -> false - msgType in MSG_TYPES_WITH_LOCATION_DATA -> vectorPreferences.labsRenderLocationsInTimeline() - else -> msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE + this == null -> false + else -> msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE } } private fun MessageContent?.shouldAddMessageOverlay(): Boolean { return when { this == null || msgType == MessageType.MSGTYPE_BEACON_INFO -> false - msgType == MessageType.MSGTYPE_LOCATION -> vectorPreferences.labsRenderLocationsInTimeline() - else -> msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE + else -> msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE } } @@ -182,9 +180,11 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess ) } - private fun buildCornersRadius(isIncoming: Boolean, - isFirstFromThisSender: Boolean, - isLastFromThisSender: Boolean): TimelineMessageLayout.Bubble.CornersRadius { + private fun buildCornersRadius( + isIncoming: Boolean, + isFirstFromThisSender: Boolean, + isLastFromThisSender: Boolean + ): TimelineMessageLayout.Bubble.CornersRadius { return if ((isIncoming && !isRTL) || (!isIncoming && isRTL)) { TimelineMessageLayout.Bubble.CornersRadius( topStartRadius = if (isFirstFromThisSender) cornerRadius else 0f, @@ -210,10 +210,10 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess return when (event?.root?.getClearType()) { EventType.KEY_VERIFICATION_DONE, EventType.KEY_VERIFICATION_CANCEL -> true - EventType.MESSAGE -> { + EventType.MESSAGE -> { event.getLastMessageContent() is MessageVerificationRequestContent } - else -> false + else -> false } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlRetriever.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlRetriever.kt index c97fae055d..eef649dbc0 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlRetriever.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlRetriever.kt @@ -25,8 +25,10 @@ import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.getLatestEventId -class PreviewUrlRetriever(session: Session, - private val coroutineScope: CoroutineScope) { +class PreviewUrlRetriever( + session: Session, + private val coroutineScope: CoroutineScope +) { private val mediaService = session.mediaService() private data class EventIdPreviewUrlUiState( diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt index 29a314d1b3..e0df5c466f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt @@ -35,7 +35,9 @@ sealed class PreviewUrlUiState { data class Error(val throwable: Throwable) : PreviewUrlUiState() // PreviewUrl data - data class Data(val eventId: String, - val url: String, - val previewUrlData: PreviewUrlData) : PreviewUrlUiState() + data class Data( + val eventId: String, + val url: String, + val previewUrlData: PreviewUrlData + ) : PreviewUrlUiState() } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt index 69455c767e..0e2429d45a 100755 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt @@ -62,9 +62,11 @@ class PreviewUrlView @JvmOverloads constructor( * @param imageContentRenderer the tool to render the image * @param force true to force refresh */ - fun render(newState: PreviewUrlUiState, - imageContentRenderer: ImageContentRenderer, - force: Boolean = false) { + fun render( + newState: PreviewUrlUiState, + imageContentRenderer: ImageContentRenderer, + force: Boolean = false + ) { if (newState == state && !force) { return } @@ -74,10 +76,10 @@ class PreviewUrlView @JvmOverloads constructor( hideAll() when (newState) { PreviewUrlUiState.Unknown, - PreviewUrlUiState.NoUrl -> renderHidden() - PreviewUrlUiState.Loading -> renderLoading() + PreviewUrlUiState.NoUrl -> renderHidden() + PreviewUrlUiState.Loading -> renderLoading() is PreviewUrlUiState.Error -> renderHidden() - is PreviewUrlUiState.Data -> renderData(newState.previewUrlData, imageContentRenderer) + is PreviewUrlUiState.Data -> renderData(newState.previewUrlData, imageContentRenderer) } } @@ -89,7 +91,7 @@ class PreviewUrlView @JvmOverloads constructor( val guidelineBegin = DimensionConverter(resources).dpToPx(8) views.urlPreviewStartGuideline.setGuidelineBegin(guidelineBegin) } - is TimelineMessageLayout.Bubble -> { + is TimelineMessageLayout.Bubble -> { setCardBackgroundColor(Color.TRANSPARENT) rippleColor = ColorStateList.valueOf(Color.TRANSPARENT) views.urlPreviewStartGuideline.setGuidelineBegin(0) @@ -100,7 +102,7 @@ class PreviewUrlView @JvmOverloads constructor( override fun onClick(v: View?) { when (val finalState = state) { is PreviewUrlUiState.Data -> delegate?.onPreviewUrlClicked(finalState.url) - else -> Unit + else -> Unit } } @@ -113,14 +115,14 @@ class PreviewUrlView @JvmOverloads constructor( title = finalState.previewUrlData.title ) } - else -> Unit + else -> Unit } } private fun onCloseClick() { when (val finalState = state) { is PreviewUrlUiState.Data -> delegate?.onPreviewUrlCloseClicked(finalState.eventId, finalState.url) - else -> Unit + else -> Unit } } @@ -152,8 +154,8 @@ class PreviewUrlView @JvmOverloads constructor( views.urlPreviewDescription.setTextOrHide(previewUrlData.description) views.urlPreviewDescription.maxLines = when { previewUrlData.mxcUrl != null -> 2 - previewUrlData.title != null -> 3 - else -> 5 + previewUrlData.title != null -> 3 + else -> 5 } views.urlPreviewSite.setTextOrHide(previewUrlData.siteName.takeIf { it != previewUrlData.title }) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomBottomSheet.kt index 03a0e64d9b..31662abd83 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomBottomSheet.kt @@ -92,17 +92,17 @@ class MigrateRoomBottomSheet : when (val result = state.upgradingStatus.invoke()) { is UpgradeRoomViewModelTask.Result.Failure -> { val errorText = when (result) { - is UpgradeRoomViewModelTask.Result.UnknownRoom -> { + is UpgradeRoomViewModelTask.Result.UnknownRoom -> { // should not happen getString(R.string.unknown_error) } - is UpgradeRoomViewModelTask.Result.NotAllowed -> { + is UpgradeRoomViewModelTask.Result.NotAllowed -> { getString(R.string.upgrade_room_no_power_to_manage) } is UpgradeRoomViewModelTask.Result.ErrorFailure -> { errorFormatter.toHumanReadable(result.throwable) } - else -> null + else -> null } views.inlineError.setTextOrHide(errorText) views.button.isVisible = true @@ -116,7 +116,7 @@ class MigrateRoomBottomSheet : } } } - else -> { + else -> { views.button.isVisible = true views.button.text = getString(R.string.upgrade) } @@ -149,9 +149,10 @@ class MigrateRoomBottomSheet : const val REQUEST_KEY = "MigrateRoomBottomSheetRequest" const val BUNDLE_KEY_REPLACEMENT_ROOM = "BUNDLE_KEY_REPLACEMENT_ROOM" - fun newInstance(roomId: String, newVersion: String, - reason: MigrationReason = MigrationReason.MANUAL, - customDescription: CharSequence? = null + fun newInstance( + roomId: String, newVersion: String, + reason: MigrationReason = MigrationReason.MANUAL, + customDescription: CharSequence? = null ): MigrateRoomBottomSheet { return MigrateRoomBottomSheet().apply { setArguments(Args(roomId, newVersion, reason, customDescription)) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomViewModel.kt index 50eecb90fb..0a49c2c775 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/upgrade/MigrateRoomViewModel.kt @@ -35,7 +35,8 @@ import org.matrix.android.sdk.api.session.getRoomSummary class MigrateRoomViewModel @AssistedInject constructor( @Assisted initialState: MigrateRoomViewState, private val session: Session, - private val upgradeRoomViewModelTask: UpgradeRoomViewModelTask) : + private val upgradeRoomViewModelTask: UpgradeRoomViewModelTask +) : VectorViewModel(initialState) { init { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt index 0f91f7b7c6..ef122509a4 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt @@ -31,7 +31,8 @@ import javax.inject.Inject */ class RoomWidgetsController @Inject constructor( val stringProvider: StringProvider, - val colorProvider: ColorProvider) : + val colorProvider: ColorProvider +) : TypedEpoxyController>() { var listener: Listener? = null diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/AlphabeticalRoomComparator.kt b/vector/src/main/java/im/vector/app/features/home/room/list/AlphabeticalRoomComparator.kt index 03b4b24726..2997bbf0eb 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/AlphabeticalRoomComparator.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/AlphabeticalRoomComparator.kt @@ -24,8 +24,8 @@ class AlphabeticalRoomComparator @Inject constructor() : Comparator override fun compare(leftRoomSummary: RoomSummary?, rightRoomSummary: RoomSummary?): Int { return when { rightRoomSummary?.displayName == null -> -1 - leftRoomSummary?.displayName == null -> 1 - else -> leftRoomSummary.displayName.compareTo(rightRoomSummary.displayName) + leftRoomSummary?.displayName == null -> 1 + else -> leftRoomSummary.displayName.compareTo(rightRoomSummary.displayName) } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/ChronologicalRoomComparator.kt b/vector/src/main/java/im/vector/app/features/home/room/list/ChronologicalRoomComparator.kt index 06616683bc..4fba8a422d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/ChronologicalRoomComparator.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/ChronologicalRoomComparator.kt @@ -24,8 +24,8 @@ class ChronologicalRoomComparator @Inject constructor() : Comparator -1 - leftRoomSummary?.latestPreviewableEvent?.root == null -> 1 - else -> { + leftRoomSummary?.latestPreviewableEvent?.root == null -> 1 + else -> { val rightTimestamp = rightRoomSummary.latestPreviewableEvent?.root?.originServerTs ?: 0 val leftTimestamp = leftRoomSummary.latestPreviewableEvent?.root?.originServerTs ?: 0 @@ -34,7 +34,7 @@ class ChronologicalRoomComparator @Inject constructor() : Comparator 0 -> 1 deltaTimestamp < 0 -> -1 - else -> 0 + else -> 0 } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFooterController.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFooterController.kt index 00d59f4c37..df009e8d6b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFooterController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFooterController.kt @@ -45,7 +45,7 @@ class RoomListFooterController @Inject constructor( inSpace(data.currentRoomGrouping.invoke()?.space() != null) } } - else -> { + else -> { if (userPreferencesProvider.shouldShowLongClickOnRoomHelp()) { helpFooterItem { id("long_click_help") diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt index 674f5022f2..5539986118 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt @@ -110,8 +110,8 @@ class RoomListFragment @Inject constructor( super.onCreate(savedInstanceState) analyticsScreenName = when (roomListParams.displayMode) { RoomListDisplayMode.PEOPLE -> MobileScreen.ScreenName.People - RoomListDisplayMode.ROOMS -> MobileScreen.ScreenName.Rooms - else -> null + RoomListDisplayMode.ROOMS -> MobileScreen.ScreenName.Rooms + else -> null } } @@ -124,10 +124,10 @@ class RoomListFragment @Inject constructor( sharedActionViewModel = activityViewModelProvider.get(RoomListQuickActionsSharedActionViewModel::class.java) roomListViewModel.observeViewEvents { when (it) { - is RoomListViewEvents.Loading -> showLoading(it.message) - is RoomListViewEvents.Failure -> showFailure(it.throwable) - is RoomListViewEvents.SelectRoom -> handleSelectRoom(it, it.isInviteAlreadyAccepted) - is RoomListViewEvents.Done -> Unit + is RoomListViewEvents.Loading -> showLoading(it.message) + is RoomListViewEvents.Failure -> showFailure(it.throwable) + is RoomListViewEvents.SelectRoom -> handleSelectRoom(it, it.isInviteAlreadyAccepted) + is RoomListViewEvents.Done -> Unit is RoomListViewEvents.NavigateToMxToBottomSheet -> handleShowMxToLink(it.link) } } @@ -209,9 +209,9 @@ class RoomListFragment @Inject constructor( private fun setupCreateRoomButton() { when (roomListParams.displayMode) { RoomListDisplayMode.NOTIFICATIONS -> views.createChatFabMenu.isVisible = true - RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.isVisible = true - RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.isVisible = true - RoomListDisplayMode.FILTERED -> Unit // No button in this mode + RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.isVisible = true + RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.isVisible = true + RoomListDisplayMode.FILTERED -> Unit // No button in this mode } views.createChatRoomButton.debouncedClicks { @@ -228,16 +228,16 @@ class RoomListFragment @Inject constructor( views.createChatFabMenu.removeCallbacks(showFabRunnable) when (newState) { - RecyclerView.SCROLL_STATE_IDLE -> { + RecyclerView.SCROLL_STATE_IDLE -> { views.createChatFabMenu.postDelayed(showFabRunnable, 250) } RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING -> { when (roomListParams.displayMode) { RoomListDisplayMode.NOTIFICATIONS -> views.createChatFabMenu.hide() - RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.hide() - RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.hide() - RoomListDisplayMode.FILTERED -> Unit + RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.hide() + RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.hide() + RoomListDisplayMode.FILTERED -> Unit } } } @@ -293,7 +293,7 @@ class RoomListFragment @Inject constructor( } val contentAdapter = when { - section.livePages != null -> { + section.livePages != null -> { pagedControllerFactory.createRoomSummaryPagedController(roomListParams.displayMode) .also { controller -> section.livePages.observe(viewLifecycleOwner) { pl -> @@ -343,7 +343,7 @@ class RoomListFragment @Inject constructor( controller.listener = this } } - else -> { + else -> { pagedControllerFactory.createRoomSummaryListController(roomListParams.displayMode) .also { controller -> section.liveList?.observe(viewLifecycleOwner) { list -> @@ -400,9 +400,9 @@ class RoomListFragment @Inject constructor( if (isAdded) { when (roomListParams.displayMode) { RoomListDisplayMode.NOTIFICATIONS -> views.createChatFabMenu.show() - RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.show() - RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.show() - RoomListDisplayMode.FILTERED -> Unit + RoomListDisplayMode.PEOPLE -> views.createChatRoomButton.show() + RoomListDisplayMode.ROOMS -> views.createGroupRoomButton.show() + RoomListDisplayMode.FILTERED -> Unit } } } @@ -422,28 +422,28 @@ class RoomListFragment @Inject constructor( private fun handleQuickActions(quickAction: RoomListQuickActionsSharedAction) { when (quickAction) { - is RoomListQuickActionsSharedAction.NotificationsAllNoisy -> { + is RoomListQuickActionsSharedAction.NotificationsAllNoisy -> { roomListViewModel.handle(RoomListAction.ChangeRoomNotificationState(quickAction.roomId, RoomNotificationState.ALL_MESSAGES_NOISY)) } - is RoomListQuickActionsSharedAction.NotificationsAll -> { + is RoomListQuickActionsSharedAction.NotificationsAll -> { roomListViewModel.handle(RoomListAction.ChangeRoomNotificationState(quickAction.roomId, RoomNotificationState.ALL_MESSAGES)) } is RoomListQuickActionsSharedAction.NotificationsMentionsOnly -> { roomListViewModel.handle(RoomListAction.ChangeRoomNotificationState(quickAction.roomId, RoomNotificationState.MENTIONS_ONLY)) } - is RoomListQuickActionsSharedAction.NotificationsMute -> { + is RoomListQuickActionsSharedAction.NotificationsMute -> { roomListViewModel.handle(RoomListAction.ChangeRoomNotificationState(quickAction.roomId, RoomNotificationState.MUTE)) } - is RoomListQuickActionsSharedAction.Settings -> { + is RoomListQuickActionsSharedAction.Settings -> { navigator.openRoomProfile(requireActivity(), quickAction.roomId) } - is RoomListQuickActionsSharedAction.Favorite -> { + is RoomListQuickActionsSharedAction.Favorite -> { roomListViewModel.handle(RoomListAction.ToggleTag(quickAction.roomId, RoomTag.ROOM_TAG_FAVOURITE)) } - is RoomListQuickActionsSharedAction.LowPriority -> { + is RoomListQuickActionsSharedAction.LowPriority -> { roomListViewModel.handle(RoomListAction.ToggleTag(quickAction.roomId, RoomTag.ROOM_TAG_LOW_PRIORITY)) } - is RoomListQuickActionsSharedAction.Leave -> { + is RoomListQuickActionsSharedAction.Leave -> { promptLeaveRoom(quickAction.roomId) } } @@ -484,21 +484,21 @@ class RoomListFragment @Inject constructor( message = getString(R.string.room_list_catchup_empty_body) ) } - RoomListDisplayMode.PEOPLE -> + RoomListDisplayMode.PEOPLE -> StateView.State.Empty( title = getString(R.string.room_list_people_empty_title), image = ContextCompat.getDrawable(requireContext(), R.drawable.empty_state_dm), isBigImage = true, message = getString(R.string.room_list_people_empty_body) ) - RoomListDisplayMode.ROOMS -> + RoomListDisplayMode.ROOMS -> StateView.State.Empty( title = getString(R.string.room_list_rooms_empty_title), image = ContextCompat.getDrawable(requireContext(), R.drawable.empty_state_room), isBigImage = true, message = getString(R.string.room_list_rooms_empty_body) ) - RoomListDisplayMode.FILTERED -> + RoomListDisplayMode.FILTERED -> // Always display the content in this mode, because if the footer StateView.State.Content } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderGroup.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderGroup.kt index 2847bc12f0..a8a30349c7 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderGroup.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderGroup.kt @@ -55,15 +55,15 @@ class RoomListSectionBuilderGroup( val actualGroupId = appStateHandler.safeActiveGroupId() when (mode) { - RoomListDisplayMode.PEOPLE -> { + RoomListDisplayMode.PEOPLE -> { // 4 sections Invites / Fav / Dms / Low Priority buildPeopleSections(sections, activeGroupAwareQueries, actualGroupId) } - RoomListDisplayMode.ROOMS -> { + RoomListDisplayMode.ROOMS -> { // 5 sections invites / Fav / Rooms / Low Priority / Server notice buildRoomsSections(sections, activeGroupAwareQueries, actualGroupId) } - RoomListDisplayMode.FILTERED -> { + RoomListDisplayMode.FILTERED -> { // Used when searching for rooms withQueryParams( { @@ -126,9 +126,11 @@ class RoomListSectionBuilderGroup( return sections } - private fun buildRoomsSections(sections: MutableList, - activeSpaceAwareQueries: MutableList, - actualGroupId: String?) { + private fun buildRoomsSections( + sections: MutableList, + activeSpaceAwareQueries: MutableList, + actualGroupId: String? + ) { if (autoAcceptInvites.showInvites()) { addSection( sections, @@ -246,11 +248,13 @@ class RoomListSectionBuilderGroup( } } - private fun addSection(sections: MutableList, - activeSpaceUpdaters: MutableList, - @StringRes nameRes: Int, - notifyOfLocalEcho: Boolean = false, - query: (RoomSummaryQueryParams.Builder) -> Unit) { + private fun addSection( + sections: MutableList, + activeSpaceUpdaters: MutableList, + @StringRes nameRes: Int, + notifyOfLocalEcho: Boolean = false, + query: (RoomSummaryQueryParams.Builder) -> Unit + ) { withQueryParams(query) { roomQueryParams -> val name = stringProvider.getString(nameRes) session.roomService().getFilteredPagedRoomSummariesLive(roomQueryParams) diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderSpace.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderSpace.kt index 445ae7d4f5..47a1df3ed0 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderSpace.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListSectionBuilderSpace.kt @@ -78,15 +78,15 @@ class RoomListSectionBuilderSpace( val sections = mutableListOf() val activeSpaceAwareQueries = mutableListOf() when (mode) { - RoomListDisplayMode.PEOPLE -> { + RoomListDisplayMode.PEOPLE -> { // 4 sections Invites / Fav / Dms / Low Priority buildDmSections(sections, activeSpaceAwareQueries) } - RoomListDisplayMode.ROOMS -> { + RoomListDisplayMode.ROOMS -> { // 6 sections invites / Fav / Rooms / Low Priority / Server notice / Suggested rooms buildRoomsSections(sections, activeSpaceAwareQueries) } - RoomListDisplayMode.FILTERED -> { + RoomListDisplayMode.FILTERED -> { // Used when searching for rooms buildFilteredSection(sections) } @@ -107,8 +107,10 @@ class RoomListSectionBuilderSpace( return sections } - private fun buildRoomsSections(sections: MutableList, - activeSpaceAwareQueries: MutableList) { + private fun buildRoomsSections( + sections: MutableList, + activeSpaceAwareQueries: MutableList + ) { if (autoAcceptInvites.showInvites()) { addSection( sections = sections, @@ -230,8 +232,10 @@ class RoomListSectionBuilderSpace( ) } - private fun buildDmSections(sections: MutableList, - activeSpaceAwareQueries: MutableList) { + private fun buildDmSections( + sections: MutableList, + activeSpaceAwareQueries: MutableList + ) { if (autoAcceptInvites.showInvites()) { addSection( sections = sections, @@ -283,8 +287,10 @@ class RoomListSectionBuilderSpace( } } - private fun buildNotificationsSection(sections: MutableList, - activeSpaceAwareQueries: MutableList) { + private fun buildNotificationsSection( + sections: MutableList, + activeSpaceAwareQueries: MutableList + ) { if (autoAcceptInvites.showInvites()) { addSection( sections = sections, @@ -344,13 +350,15 @@ class RoomListSectionBuilderSpace( ) } - private fun addSection(sections: MutableList, - activeSpaceUpdaters: MutableList, - @StringRes nameRes: Int, - notifyOfLocalEcho: Boolean = false, - spaceFilterStrategy: RoomListViewModel.SpaceFilterStrategy = RoomListViewModel.SpaceFilterStrategy.NONE, - countRoomAsNotif: Boolean = false, - query: (RoomSummaryQueryParams.Builder) -> Unit) { + private fun addSection( + sections: MutableList, + activeSpaceUpdaters: MutableList, + @StringRes nameRes: Int, + notifyOfLocalEcho: Boolean = false, + spaceFilterStrategy: RoomListViewModel.SpaceFilterStrategy = RoomListViewModel.SpaceFilterStrategy.NONE, + countRoomAsNotif: Boolean = false, + query: (RoomSummaryQueryParams.Builder) -> Unit + ) { withQueryParams(query) { roomQueryParams -> val updatedQueryParams = roomQueryParams.process(spaceFilterStrategy, appStateHandler.safeActiveSpaceId()) val liveQueryParams = MutableStateFlow(updatedQueryParams) @@ -377,7 +385,7 @@ class RoomListSectionBuilderSpace( } }) } - RoomListViewModel.SpaceFilterStrategy.ALL_IF_SPACE_NULL -> { + RoomListViewModel.SpaceFilterStrategy.ALL_IF_SPACE_NULL -> { activeSpaceUpdaters.add(object : RoomListViewModel.ActiveSpaceQueryUpdater { override fun updateForSpaceId(roomId: String?) { if (roomId != null) { @@ -393,7 +401,7 @@ class RoomListSectionBuilderSpace( } }) } - RoomListViewModel.SpaceFilterStrategy.NONE -> { + RoomListViewModel.SpaceFilterStrategy.NONE -> { // we ignore current space for this one } } @@ -440,12 +448,12 @@ class RoomListSectionBuilderSpace( spaceFilter = currentSpace.toActiveSpaceOrOrphanRooms() ) } - RoomListViewModel.SpaceFilterStrategy.ALL_IF_SPACE_NULL -> { + RoomListViewModel.SpaceFilterStrategy.ALL_IF_SPACE_NULL -> { copy( spaceFilter = currentSpace?.let { SpaceFilter.ActiveSpace(it) } ) } - RoomListViewModel.SpaceFilterStrategy.NONE -> this + RoomListViewModel.SpaceFilterStrategy.NONE -> this } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt index 73540ac76a..49467c0531 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt @@ -156,16 +156,16 @@ class RoomListViewModel @AssistedInject constructor( override fun handle(action: RoomListAction) { when (action) { - is RoomListAction.SelectRoom -> handleSelectRoom(action) - is RoomListAction.AcceptInvitation -> handleAcceptInvitation(action) - is RoomListAction.RejectInvitation -> handleRejectInvitation(action) - is RoomListAction.FilterWith -> handleFilter(action) - is RoomListAction.LeaveRoom -> handleLeaveRoom(action) + is RoomListAction.SelectRoom -> handleSelectRoom(action) + is RoomListAction.AcceptInvitation -> handleAcceptInvitation(action) + is RoomListAction.RejectInvitation -> handleRejectInvitation(action) + is RoomListAction.FilterWith -> handleFilter(action) + is RoomListAction.LeaveRoom -> handleLeaveRoom(action) is RoomListAction.ChangeRoomNotificationState -> handleChangeNotificationMode(action) - is RoomListAction.ToggleTag -> handleToggleTag(action) - is RoomListAction.ToggleSection -> handleToggleSection(action.section) - is RoomListAction.JoinSuggestedRoom -> handleJoinSuggestedRoom(action) - is RoomListAction.ShowRoomDetails -> handleShowRoomDetails(action) + is RoomListAction.ToggleTag -> handleToggleTag(action) + is RoomListAction.ToggleSection -> handleToggleSection(action.section) + is RoomListAction.JoinSuggestedRoom -> handleJoinSuggestedRoom(action) + is RoomListAction.ShowRoomDetails -> handleShowRoomDetails(action) } } @@ -316,9 +316,9 @@ class RoomListViewModel @AssistedInject constructor( private fun String.otherTag(): String? { return when (this) { - RoomTag.ROOM_TAG_FAVOURITE -> RoomTag.ROOM_TAG_LOW_PRIORITY + RoomTag.ROOM_TAG_FAVOURITE -> RoomTag.ROOM_TAG_LOW_PRIORITY RoomTag.ROOM_TAG_LOW_PRIORITY -> RoomTag.ROOM_TAG_FAVOURITE - else -> null + else -> null } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItem.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItem.kt index 5452b03992..046d90c512 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItem.kt @@ -128,7 +128,7 @@ abstract class RoomSummaryItem : VectorEpoxyModel() { RoomListDisplayMode.ROOMS, RoomListDisplayMode.PEOPLE, RoomListDisplayMode.NOTIFICATIONS -> renderForDefaultDisplayMode(holder) - RoomListDisplayMode.FILTERED -> renderForFilteredDisplayMode(holder) + RoomListDisplayMode.FILTERED -> renderForFilteredDisplayMode(holder) } private fun renderForDefaultDisplayMode(holder: Holder) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItemFactory.kt index 733addb6b0..f50cec5149 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomSummaryItemFactory.kt @@ -37,32 +37,38 @@ import org.matrix.android.sdk.api.session.room.model.SpaceChildInfo import org.matrix.android.sdk.api.util.toMatrixItem import javax.inject.Inject -class RoomSummaryItemFactory @Inject constructor(private val displayableEventFormatter: DisplayableEventFormatter, - private val dateFormatter: VectorDateFormatter, - private val stringProvider: StringProvider, - private val typingHelper: TypingHelper, - private val avatarRenderer: AvatarRenderer, - private val errorFormatter: ErrorFormatter) { +class RoomSummaryItemFactory @Inject constructor( + private val displayableEventFormatter: DisplayableEventFormatter, + private val dateFormatter: VectorDateFormatter, + private val stringProvider: StringProvider, + private val typingHelper: TypingHelper, + private val avatarRenderer: AvatarRenderer, + private val errorFormatter: ErrorFormatter +) { - fun create(roomSummary: RoomSummary, - roomChangeMembershipStates: Map, - selectedRoomIds: Set, - displayMode: RoomListDisplayMode, - listener: RoomListListener?): VectorEpoxyModel<*> { + fun create( + roomSummary: RoomSummary, + roomChangeMembershipStates: Map, + selectedRoomIds: Set, + displayMode: RoomListDisplayMode, + listener: RoomListListener? + ): VectorEpoxyModel<*> { return when (roomSummary.membership) { Membership.INVITE -> { val changeMembershipState = roomChangeMembershipStates[roomSummary.roomId] ?: ChangeMembershipState.Unknown createInvitationItem(roomSummary, changeMembershipState, listener) } - else -> createRoomItem( + else -> createRoomItem( roomSummary, selectedRoomIds, displayMode, listener?.let { it::onRoomClicked }, listener?.let { it::onRoomLongClicked } ) } } - fun createSuggestion(spaceChildInfo: SpaceChildInfo, - suggestedRoomJoiningStates: Map>, - listener: RoomListListener?): VectorEpoxyModel<*> { + fun createSuggestion( + spaceChildInfo: SpaceChildInfo, + suggestedRoomJoiningStates: Map>, + listener: RoomListListener? + ): VectorEpoxyModel<*> { val error = (suggestedRoomJoiningStates[spaceChildInfo.childRoomId] as? Fail)?.error return SpaceChildInfoItem_() .id("sug_${spaceChildInfo.childRoomId}") @@ -84,9 +90,11 @@ class RoomSummaryItemFactory @Inject constructor(private val displayableEventFor .itemClickListener { listener?.onSuggestedRoomClicked(spaceChildInfo) } } - private fun createInvitationItem(roomSummary: RoomSummary, - changeMembershipState: ChangeMembershipState, - listener: RoomListListener?): VectorEpoxyModel<*> { + private fun createInvitationItem( + roomSummary: RoomSummary, + changeMembershipState: ChangeMembershipState, + listener: RoomListListener? + ): VectorEpoxyModel<*> { val secondLine = if (roomSummary.isDirect) { roomSummary.inviterId } else { diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt index a6b1a0de52..b629ca8bac 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt @@ -107,8 +107,8 @@ class RoomListQuickActionsBottomSheet : // Do not dismiss for all the actions when (quickAction) { is RoomListQuickActionsSharedAction.LowPriority -> Unit - is RoomListQuickActionsSharedAction.Favorite -> Unit - else -> dismiss() + is RoomListQuickActionsSharedAction.Favorite -> Unit + else -> dismiss() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt index 7f0de584cf..e1837a32de 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt @@ -83,9 +83,9 @@ class RoomListQuickActionsEpoxyController @Inject constructor( @StringRes private fun titleForNotificationState(notificationState: RoomNotificationState): Int? = when (notificationState) { RoomNotificationState.ALL_MESSAGES_NOISY -> R.string.room_settings_all_messages - RoomNotificationState.MENTIONS_ONLY -> R.string.room_settings_mention_and_keyword_only - RoomNotificationState.MUTE -> R.string.room_settings_none - else -> null + RoomNotificationState.MENTIONS_ONLY -> R.string.room_settings_mention_and_keyword_only + RoomNotificationState.MUTE -> R.string.room_settings_none + else -> null } private fun RoomListQuickActionsSharedAction.Leave.toBottomSheetItem() { diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedAction.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedAction.kt index 21fbd8b914..0423a8fffc 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedAction.kt @@ -24,7 +24,8 @@ import im.vector.app.core.platform.VectorSharedAction sealed class RoomListQuickActionsSharedAction( @StringRes val titleRes: Int, @DrawableRes val iconResId: Int?, - val destructive: Boolean = false) : + val destructive: Boolean = false +) : VectorSharedAction { data class NotificationsAllNoisy(val roomId: String) : RoomListQuickActionsSharedAction( diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/widget/NotifsFabMenuView.kt b/vector/src/main/java/im/vector/app/features/home/room/list/widget/NotifsFabMenuView.kt index 72b58fc7ca..1487c30957 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/widget/NotifsFabMenuView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/widget/NotifsFabMenuView.kt @@ -24,8 +24,10 @@ import com.google.android.material.floatingactionbutton.FloatingActionButton import im.vector.app.R import im.vector.app.databinding.MotionNotifsFabMenuMergeBinding -class NotifsFabMenuView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, - defStyleAttr: Int = 0) : MotionLayout(context, attrs, defStyleAttr) { +class NotifsFabMenuView @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null, + defStyleAttr: Int = 0 +) : MotionLayout(context, attrs, defStyleAttr) { private val views: MotionNotifsFabMenuMergeBinding diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt index 1ddd665ef4..71a24da5ae 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt @@ -59,13 +59,13 @@ class ThreadsActivity : VectorBaseActivity() { private fun initFragment() { if (isFirstCreation()) { when (val fragment = fragmentToNavigate()) { - is DisplayFragment.ThreadList -> { + is DisplayFragment.ThreadList -> { initThreadListFragment(fragment.threadListArgs) } is DisplayFragment.ThreadTimeLine -> { initThreadTimelineFragment(fragment.threadTimelineArgs) } - is DisplayFragment.ErrorFragment -> { + is DisplayFragment.ErrorFragment -> { finish() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/model/ThreadListItem.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/model/ThreadListItem.kt index 385bb226a1..d5a6b72a1b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/model/ThreadListItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/model/ThreadListItem.kt @@ -81,7 +81,7 @@ abstract class ThreadListItem : VectorEpoxyModel() { private fun renderNotificationState(holder: Holder) { when (threadNotificationState) { - ThreadNotificationState.NEW_MESSAGE -> { + ThreadNotificationState.NEW_MESSAGE -> { holder.unreadImageView.isVisible = true holder.unreadImageView.setColorFilter(ContextCompat.getColor(holder.view.context, R.color.palette_gray_200)) } @@ -89,7 +89,7 @@ abstract class ThreadListItem : VectorEpoxyModel() { holder.unreadImageView.isVisible = true holder.unreadImageView.setColorFilter(ContextCompat.getColor(holder.view.context, R.color.palette_vermilion)) } - else -> { + else -> { holder.unreadImageView.isVisible = false } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt index d7dd03cbbd..14098fd8b0 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt @@ -50,7 +50,7 @@ class ThreadListController @Inject constructor( override fun buildModels() = when (session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) { - true -> buildThreadSummaries() + true -> buildThreadSummaries() false -> buildThreadList() } diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt index d038b14491..4b7af330fb 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt @@ -37,9 +37,11 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.threads.ThreadTimelineEvent import org.matrix.android.sdk.flow.flow -class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState: ThreadListViewState, - private val analyticsTracker: AnalyticsTracker, - private val session: Session) : +class ThreadListViewModel @AssistedInject constructor( + @Assisted val initialState: ThreadListViewState, + private val analyticsTracker: AnalyticsTracker, + private val session: Session +) : VectorViewModel(initialState) { private val room = session.getRoom(initialState.roomId) @@ -69,7 +71,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState */ private fun fetchAndObserveThreads() { when (session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) { - true -> { + true -> { fetchThreadList() observeThreadSummaries() } diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt index 8e762fda96..13bf056301 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt @@ -87,7 +87,7 @@ class ThreadListFragment @Inject constructor( ThreadListBottomSheet().show(childFragmentManager, "Filtering") true } - else -> super.onOptionsItemSelected(item) + else -> super.onOptionsItemSelected(item) } } @@ -97,7 +97,7 @@ class ThreadListFragment @Inject constructor( val filterBadge = filterIcon.findViewById(R.id.threadListFilterBadge) filterBadge.isVisible = state.shouldFilterThreads when (threadListViewModel.canHomeserverUseThreading()) { - true -> menu.findItem(R.id.menu_thread_list_filter).isVisible = !state.threadSummaryList.invoke().isNullOrEmpty() + true -> menu.findItem(R.id.menu_thread_list_filter).isVisible = !state.threadSummaryList.invoke().isNullOrEmpty() false -> menu.findItem(R.id.menu_thread_list_filter).isVisible = !state.rootThreadEventList.invoke().isNullOrEmpty() } } @@ -182,7 +182,7 @@ class ThreadListFragment @Inject constructor( private fun renderEmptyStateIfNeeded(state: ThreadListViewState) { when (threadListViewModel.canHomeserverUseThreading()) { - true -> views.threadListEmptyConstraintLayout.isVisible = state.threadSummaryList.invoke().isNullOrEmpty() + true -> views.threadListEmptyConstraintLayout.isVisible = state.threadSummaryList.invoke().isNullOrEmpty() false -> views.threadListEmptyConstraintLayout.isVisible = state.rootThreadEventList.invoke().isNullOrEmpty() } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/typing/TypingHelper.kt b/vector/src/main/java/im/vector/app/features/home/room/typing/TypingHelper.kt index 6cc72a4045..8f5f57b86b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/typing/TypingHelper.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/typing/TypingHelper.kt @@ -38,7 +38,7 @@ class TypingHelper @Inject constructor(private val stringProvider: StringProvide typingUsers[0].disambiguatedDisplayName, typingUsers[1].disambiguatedDisplayName ) - else -> + else -> stringProvider.getString( R.string.room_many_users_are_typing, typingUsers[0].disambiguatedDisplayName, @@ -55,7 +55,7 @@ class TypingHelper @Inject constructor(private val stringProvider: StringProvide R.string.room_notification_two_users_are_typing, typingUsers[0].disambiguatedDisplayName, typingUsers[1].disambiguatedDisplayName ) - else -> stringProvider.getString( + else -> stringProvider.getString( R.string.room_notification_more_than_two_users_are_typing, typingUsers[0].disambiguatedDisplayName, typingUsers[1].disambiguatedDisplayName ) diff --git a/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt b/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt index 5327d70ec9..16f678f098 100644 --- a/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt +++ b/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt @@ -51,23 +51,23 @@ class FontTagHandler : SimpleTagHandler() { } catch (e: Exception) { // try other w3c colors? return when (colorName) { - "white" -> Color.WHITE - "yellow" -> Color.YELLOW + "white" -> Color.WHITE + "yellow" -> Color.YELLOW "fuchsia" -> Color.parseColor("#FF00FF") - "red" -> Color.RED - "silver" -> Color.parseColor("#C0C0C0") - "gray" -> Color.GRAY - "olive" -> Color.parseColor("#808000") - "purple" -> Color.parseColor("#800080") - "maroon" -> Color.parseColor("#800000") - "aqua" -> Color.parseColor("#00FFFF") - "lime" -> Color.parseColor("#00FF00") - "teal" -> Color.parseColor("#008080") - "green" -> Color.GREEN - "blue" -> Color.BLUE - "orange" -> Color.parseColor("#FFA500") - "navy" -> Color.parseColor("#000080") - else -> failResult + "red" -> Color.RED + "silver" -> Color.parseColor("#C0C0C0") + "gray" -> Color.GRAY + "olive" -> Color.parseColor("#808000") + "purple" -> Color.parseColor("#800080") + "maroon" -> Color.parseColor("#800000") + "aqua" -> Color.parseColor("#00FFFF") + "lime" -> Color.parseColor("#00FF00") + "teal" -> Color.parseColor("#008080") + "green" -> Color.GREEN + "blue" -> Color.BLUE + "orange" -> Color.parseColor("#FFA500") + "navy" -> Color.parseColor("#000080") + else -> failResult } } } diff --git a/vector/src/main/java/im/vector/app/features/html/PillImageSpan.kt b/vector/src/main/java/im/vector/app/features/html/PillImageSpan.kt index ae285b074c..b285bef9ec 100644 --- a/vector/src/main/java/im/vector/app/features/html/PillImageSpan.kt +++ b/vector/src/main/java/im/vector/app/features/html/PillImageSpan.kt @@ -43,10 +43,11 @@ import java.lang.ref.WeakReference * It's needed to call [bind] method to start requesting avatar, otherwise only the placeholder icon will be displayed if not already cached. * Implements MatrixItemSpan so that it could be automatically transformed in matrix links and displayed as pills. */ -class PillImageSpan(private val glideRequests: GlideRequests, - private val avatarRenderer: AvatarRenderer, - private val context: Context, - override val matrixItem: MatrixItem +class PillImageSpan( + private val glideRequests: GlideRequests, + private val avatarRenderer: AvatarRenderer, + private val context: Context, + override val matrixItem: MatrixItem ) : ReplacementSpan(), MatrixItemSpan { private val pillDrawable = createChipDrawable() @@ -61,10 +62,12 @@ class PillImageSpan(private val glideRequests: GlideRequests, // ReplacementSpan ***************************************************************************** - override fun getSize(paint: Paint, text: CharSequence, - start: Int, - end: Int, - fm: Paint.FontMetricsInt?): Int { + override fun getSize( + paint: Paint, text: CharSequence, + start: Int, + end: Int, + fm: Paint.FontMetricsInt? + ): Int { val rect = pillDrawable.bounds if (fm != null) { val fmPaint = paint.fontMetricsInt @@ -80,14 +83,16 @@ class PillImageSpan(private val glideRequests: GlideRequests, return rect.right } - override fun draw(canvas: Canvas, text: CharSequence, - start: Int, - end: Int, - x: Float, - top: Int, - y: Int, - bottom: Int, - paint: Paint) { + override fun draw( + canvas: Canvas, text: CharSequence, + start: Int, + end: Int, + x: Float, + top: Int, + y: Int, + bottom: Int, + paint: Paint + ) { canvas.save() val fm = paint.fontMetricsInt val transY: Int = y + (fm.descent + fm.ascent - pillDrawable.bounds.bottom) / 2 diff --git a/vector/src/main/java/im/vector/app/features/html/PillsPostProcessor.kt b/vector/src/main/java/im/vector/app/features/html/PillsPostProcessor.kt index 2d63d69c35..13a33cf30d 100644 --- a/vector/src/main/java/im/vector/app/features/html/PillsPostProcessor.kt +++ b/vector/src/main/java/im/vector/app/features/html/PillsPostProcessor.kt @@ -34,10 +34,12 @@ import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.util.MatrixItem import org.matrix.android.sdk.api.util.toMatrixItem -class PillsPostProcessor @AssistedInject constructor(@Assisted private val roomId: String?, - private val context: Context, - private val avatarRenderer: AvatarRenderer, - private val sessionHolder: ActiveSessionHolder) : +class PillsPostProcessor @AssistedInject constructor( + @Assisted private val roomId: String?, + private val context: Context, + private val avatarRenderer: AvatarRenderer, + private val sessionHolder: ActiveSessionHolder +) : EventHtmlRenderer.PostProcessor { /* ========================================================================================== @@ -90,10 +92,10 @@ class PillsPostProcessor @AssistedInject constructor(@Assisted private val roomI private fun LinkSpan.createPillSpan(roomId: String?): PillImageSpan? { val matrixItem = when (val permalinkData = PermalinkParser.parse(url)) { - is PermalinkData.UserLink -> permalinkData.toMatrixItem(roomId) - is PermalinkData.RoomLink -> permalinkData.toMatrixItem() + is PermalinkData.UserLink -> permalinkData.toMatrixItem(roomId) + is PermalinkData.RoomLink -> permalinkData.toMatrixItem() is PermalinkData.GroupLink -> permalinkData.toMatrixItem() - else -> null + else -> null } ?: return null return createPillImageSpan(matrixItem) } @@ -110,7 +112,7 @@ class PillsPostProcessor @AssistedInject constructor(@Assisted private val roomI val room: RoomSummary? = sessionHolder.getSafeActiveSession()?.getRoomSummary(roomIdOrAlias) when { isRoomAlias -> MatrixItem.RoomAliasItem(roomIdOrAlias, room?.displayName, room?.avatarUrl) - else -> MatrixItem.RoomItem(roomIdOrAlias, room?.displayName, room?.avatarUrl) + else -> MatrixItem.RoomItem(roomIdOrAlias, room?.displayName, room?.avatarUrl) } } else { // Exclude event link (used in reply events, we do not want to pill the "in reply to") diff --git a/vector/src/main/java/im/vector/app/features/invite/InviteButtonStateBinder.kt b/vector/src/main/java/im/vector/app/features/invite/InviteButtonStateBinder.kt index 43763cdf37..024fb5aebb 100644 --- a/vector/src/main/java/im/vector/app/features/invite/InviteButtonStateBinder.kt +++ b/vector/src/main/java/im/vector/app/features/invite/InviteButtonStateBinder.kt @@ -32,9 +32,9 @@ object InviteButtonStateBinder { val requestInProgress = changeMembershipState.isInProgress() || changeMembershipState.isSuccessful() when { - requestInProgress -> acceptView.render(ButtonStateView.State.Loading) + requestInProgress -> acceptView.render(ButtonStateView.State.Loading) changeMembershipState is ChangeMembershipState.FailedJoining -> acceptView.render(ButtonStateView.State.Error) - else -> acceptView.render(ButtonStateView.State.Button) + else -> acceptView.render(ButtonStateView.State.Button) } // ButtonStateView.State.Loaded not used because roomSummary will not be displayed as a room invitation anymore @@ -42,7 +42,7 @@ object InviteButtonStateBinder { when (changeMembershipState) { is ChangeMembershipState.FailedLeaving -> rejectView.render(ButtonStateView.State.Error) - else -> rejectView.render(ButtonStateView.State.Button) + else -> rejectView.render(ButtonStateView.State.Button) } } } diff --git a/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomActivity.kt b/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomActivity.kt index 7bb6670e96..304ec72ce2 100644 --- a/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomActivity.kt +++ b/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomActivity.kt @@ -69,12 +69,12 @@ class InviteUsersToRoomActivity : SimpleFragmentActivity() { .stream() .onEach { sharedAction -> when (sharedAction) { - UserListSharedAction.Close -> finish() - UserListSharedAction.GoBack -> onBackPressed() + UserListSharedAction.Close -> finish() + UserListSharedAction.GoBack -> onBackPressed() is UserListSharedAction.OnMenuItemSelected -> onMenuItemSelected(sharedAction) - UserListSharedAction.OpenPhoneBook -> openPhoneBook() + UserListSharedAction.OpenPhoneBook -> openPhoneBook() // not exhaustive because it's a sharedAction - else -> Unit + else -> Unit } } .launchIn(lifecycleScope) diff --git a/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomViewModel.kt index 63cf666f30..68b0329a86 100644 --- a/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/invite/InviteUsersToRoomViewModel.kt @@ -60,18 +60,18 @@ class InviteUsersToRoomViewModel @AssistedInject constructor( selections.asFlow() .map { user -> when (user) { - is PendingSelection.UserPendingSelection -> room.membershipService().invite(user.user.userId, null) + is PendingSelection.UserPendingSelection -> room.membershipService().invite(user.user.userId, null) is PendingSelection.ThreePidPendingSelection -> room.membershipService().invite3pid(user.threePid) } }.onCompletion { error -> if (error != null) return@onCompletion val successMessage = when (selections.size) { - 1 -> stringProvider.getString( + 1 -> stringProvider.getString( R.string.invitation_sent_to_one_user, selections.first().getBestName() ) - 2 -> stringProvider.getString( + 2 -> stringProvider.getString( R.string.invitations_sent_to_two_users, selections.first().getBestName(), selections.last().getBestName() diff --git a/vector/src/main/java/im/vector/app/features/lifecycle/VectorActivityLifecycleCallbacks.kt b/vector/src/main/java/im/vector/app/features/lifecycle/VectorActivityLifecycleCallbacks.kt index e453a347f5..32b4bf3f12 100644 --- a/vector/src/main/java/im/vector/app/features/lifecycle/VectorActivityLifecycleCallbacks.kt +++ b/vector/src/main/java/im/vector/app/features/lifecycle/VectorActivityLifecycleCallbacks.kt @@ -66,7 +66,7 @@ class VectorActivityLifecycleCallbacks constructor(private val popupAlertManager } catch (failure: Throwable) { when (failure) { // The task was not found. We can ignore it. - is IllegalArgumentException -> { + is IllegalArgumentException -> { Timber.e("The task was not found: ${failure.localizedMessage}") false } @@ -74,7 +74,7 @@ class VectorActivityLifecycleCallbacks constructor(private val popupAlertManager Timber.e("Package manager error: ${failure.localizedMessage}") true } - else -> throw failure + else -> throw failure } } diff --git a/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt b/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt index a51491e85b..6de73cb20f 100644 --- a/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt +++ b/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt @@ -59,16 +59,16 @@ class LinkHandlerActivity : VectorBaseActivity() { private fun handleIntent() { val uri = intent.data when { - uri == null -> { + uri == null -> { // Should not happen Timber.w("Uri is null") finish() } - uri.getQueryParameter(LoginConfig.CONFIG_HS_PARAMETER) != null -> handleConfigUrl(uri) - uri.toString().startsWith(PermalinkService.MATRIX_TO_URL_BASE) -> handleSupportedHostUrl() - uri.toString().startsWith(PermalinkHandler.MATRIX_TO_CUSTOM_SCHEME_URL_BASE) -> handleSupportedHostUrl() + uri.getQueryParameter(LoginConfig.CONFIG_HS_PARAMETER) != null -> handleConfigUrl(uri) + uri.toString().startsWith(PermalinkService.MATRIX_TO_URL_BASE) -> handleSupportedHostUrl() + uri.toString().startsWith(PermalinkHandler.MATRIX_TO_CUSTOM_SCHEME_URL_BASE) -> handleSupportedHostUrl() resources.getStringArray(R.array.permalink_supported_hosts).contains(uri.host) -> handleSupportedHostUrl() - else -> { + else -> { // Other links are not yet handled, but should not come here (manifest configuration error?) toast(R.string.universal_link_malformed) finish() diff --git a/vector/src/main/java/im/vector/app/features/location/LocationSharingActivity.kt b/vector/src/main/java/im/vector/app/features/location/LocationSharingActivity.kt index 10c271727b..169af4a5a2 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationSharingActivity.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationSharingActivity.kt @@ -57,7 +57,7 @@ class LocationSharingActivity : VectorBaseActivity { + LocationSharingMode.PREVIEW -> { addFragment( views.fragmentContainer, LocationPreviewFragment::class.java, diff --git a/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt b/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt index 89aedf3aa9..1b25f3fcec 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt @@ -89,9 +89,9 @@ class LocationSharingFragment @Inject constructor( viewModel.observeViewEvents { when (it) { - LocationSharingViewEvents.Close -> locationSharingNavigator.quit() - LocationSharingViewEvents.LocationNotAvailableError -> handleLocationNotAvailableError() - is LocationSharingViewEvents.ZoomToUserLocation -> handleZoomToUserLocationEvent(it) + LocationSharingViewEvents.Close -> locationSharingNavigator.quit() + LocationSharingViewEvents.LocationNotAvailableError -> handleLocationNotAvailableError() + is LocationSharingViewEvents.ZoomToUserLocation -> handleZoomToUserLocationEvent(it) is LocationSharingViewEvents.StartLiveLocationService -> handleStartLiveLocationService(it) } } @@ -223,7 +223,7 @@ class LocationSharingFragment @Inject constructor( private fun updateMap(state: LocationSharingViewState) { // first, update the options view val options: Set = when (state.areTargetAndUserLocationEqual) { - true -> { + true -> { if (vectorPreferences.labsEnableLiveLocation()) { setOf(LocationSharingOption.USER_CURRENT, LocationSharingOption.USER_LIVE) } else { @@ -231,7 +231,7 @@ class LocationSharingFragment @Inject constructor( } } false -> setOf(LocationSharingOption.PINNED) - else -> emptySet() + else -> emptySet() } views.shareLocationOptionsPicker.render(options) diff --git a/vector/src/main/java/im/vector/app/features/location/LocationSharingViewModel.kt b/vector/src/main/java/im/vector/app/features/location/LocationSharingViewModel.kt index 231de00094..9ca340f098 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationSharingViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationSharingViewModel.kt @@ -118,10 +118,10 @@ class LocationSharingViewModel @AssistedInject constructor( override fun handle(action: LocationSharingAction) { when (action) { - LocationSharingAction.CurrentUserLocationSharing -> handleCurrentUserLocationSharingAction() - is LocationSharingAction.PinnedLocationSharing -> handlePinnedLocationSharingAction(action) - is LocationSharingAction.LocationTargetChange -> handleLocationTargetChangeAction(action) - LocationSharingAction.ZoomToUserLocation -> handleZoomToUserLocationAction() + LocationSharingAction.CurrentUserLocationSharing -> handleCurrentUserLocationSharingAction() + is LocationSharingAction.PinnedLocationSharing -> handlePinnedLocationSharingAction(action) + is LocationSharingAction.LocationTargetChange -> handleLocationTargetChangeAction(action) + LocationSharingAction.ZoomToUserLocation -> handleZoomToUserLocationAction() is LocationSharingAction.StartLiveLocationSharing -> handleStartLiveLocationSharingAction(action.durationMillis) } } diff --git a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt index 4e56e7954c..1913f4202d 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt @@ -129,7 +129,7 @@ class LocationTracker @Inject constructor( LocationManager.GPS_PROVIDER -> { hasGpsProviderLiveLocation = isLive } - else -> { + else -> { if (hasGpsProviderLiveLocation) { // Ignore this update Timber.d("## LocationTracker. ignoring location from ${location.provider}, we have gps live location") diff --git a/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt b/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt index dd2a56fb3a..1f9cb44c91 100644 --- a/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt +++ b/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt @@ -33,6 +33,7 @@ import com.mapbox.mapboxsdk.plugins.annotation.SymbolManager import com.mapbox.mapboxsdk.plugins.annotation.SymbolOptions import com.mapbox.mapboxsdk.style.layers.Property import im.vector.app.R +import im.vector.app.core.utils.DimensionConverter import timber.log.Timber class MapTilerMapView @JvmOverloads constructor( @@ -56,6 +57,7 @@ class MapTilerMapView @JvmOverloads constructor( private var mapRefs: MapRefs? = null private var initZoomDone = false private var showLocationButton = false + private var dimensionConverter: DimensionConverter? = null init { context.theme.obtainStyledAttributes( @@ -70,6 +72,7 @@ class MapTilerMapView @JvmOverloads constructor( recycle() } } + dimensionConverter = DimensionConverter(resources) } private fun setLocateButtonVisibility(typedArray: TypedArray) { @@ -151,7 +154,12 @@ class MapTilerMapView @JvmOverloads constructor( pendingState = state } - safeMapRefs.map.uiSettings.setLogoMargins(0, 0, 0, state.logoMarginBottom) + safeMapRefs.map.uiSettings.apply { + setLogoMargins(0, 0, 0, state.logoMarginBottom) + dimensionConverter?.let { + setAttributionMargins(it.dpToPx(88), 0, 0, state.logoMarginBottom) + } + } val pinDrawable = state.pinDrawable ?: userLocationDrawable pinDrawable?.let { drawable -> diff --git a/vector/src/main/java/im/vector/app/features/location/UrlMapProvider.kt b/vector/src/main/java/im/vector/app/features/location/UrlMapProvider.kt index 3e4e16861e..f043006d70 100644 --- a/vector/src/main/java/im/vector/app/features/location/UrlMapProvider.kt +++ b/vector/src/main/java/im/vector/app/features/location/UrlMapProvider.kt @@ -17,8 +17,6 @@ package im.vector.app.features.location import im.vector.app.BuildConfig -import im.vector.app.core.resources.LocaleProvider -import im.vector.app.core.resources.isRTL import im.vector.app.features.raw.wellknown.getElementWellknown import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.raw.RawService @@ -26,7 +24,6 @@ import org.matrix.android.sdk.api.session.Session import javax.inject.Inject class UrlMapProvider @Inject constructor( - private val localeProvider: LocaleProvider, private val session: Session, private val rawService: RawService ) { @@ -44,10 +41,12 @@ class UrlMapProvider @Inject constructor( return upstreamMapUrl ?: fallbackMapUrl } - fun buildStaticMapUrl(locationData: LocationData, - zoom: Double, - width: Int, - height: Int): String { + fun buildStaticMapUrl( + locationData: LocationData, + zoom: Double, + width: Int, + height: Int + ): String { return buildString { append(STATIC_MAP_BASE_URL) append(locationData.longitude) @@ -61,10 +60,8 @@ class UrlMapProvider @Inject constructor( append(height) append(".png") append(keyParam) - if (!localeProvider.isRTL()) { - // On LTR languages we want the legal mentions to be displayed on the bottom left of the image - append("&attribution=bottomleft") - } + // Since the default copyright font is too small we put a custom one on map + append("&attribution=false") } } } diff --git a/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt index 8cb552e3c4..51c7caed3a 100644 --- a/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt +++ b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt @@ -70,6 +70,7 @@ class LocationLiveMessageBannerView @JvmOverloads constructor( GlideApp.with(context) .load(ColorDrawable(ThemeUtils.getColor(context, android.R.attr.colorBackground))) + .placeholder(binding.locationLiveMessageBannerBackground.drawable) .transform(GranularRoundedCorners(0f, 0f, viewState.bottomEndCornerRadiusInDp, viewState.bottomStartCornerRadiusInDp)) .into(background) } diff --git a/vector/src/main/java/im/vector/app/features/location/live/duration/ChooseLiveDurationBottomSheet.kt b/vector/src/main/java/im/vector/app/features/location/live/duration/ChooseLiveDurationBottomSheet.kt index 36165d4524..5cde84a2d9 100644 --- a/vector/src/main/java/im/vector/app/features/location/live/duration/ChooseLiveDurationBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/location/live/duration/ChooseLiveDurationBottomSheet.kt @@ -72,7 +72,7 @@ class ChooseLiveDurationBottomSheet : R.id.liveLocShareChooseDurationOption1 -> DURATION_IN_MS_OPTION_1 R.id.liveLocShareChooseDurationOption2 -> DURATION_IN_MS_OPTION_2 R.id.liveLocShareChooseDurationOption3 -> DURATION_IN_MS_OPTION_3 - else -> DURATION_IN_MS_OPTION_1 + else -> DURATION_IN_MS_OPTION_1 } } diff --git a/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewFragment.kt b/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewFragment.kt index 9a4975e2e0..5f2410d697 100644 --- a/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewFragment.kt +++ b/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewFragment.kt @@ -25,6 +25,7 @@ import androidx.core.graphics.drawable.toBitmap import androidx.lifecycle.lifecycleScope import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState +import com.google.android.material.bottomsheet.BottomSheetBehavior import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.geometry.LatLngBounds import com.mapbox.mapboxsdk.maps.MapView @@ -40,6 +41,7 @@ import im.vector.app.R import im.vector.app.core.extensions.addChildFragment import im.vector.app.core.extensions.configureWith import im.vector.app.core.platform.VectorBaseFragment +import im.vector.app.core.utils.DimensionConverter import im.vector.app.databinding.FragmentLocationLiveMapViewBinding import im.vector.app.features.location.UrlMapProvider import im.vector.app.features.location.zoomToBounds @@ -58,6 +60,7 @@ class LocationLiveMapViewFragment @Inject constructor() : VectorBaseFragment + val bottomSheetHeight = BottomSheetBehavior.from(views.bottomSheet).peekHeight + mapboxMap.uiSettings.apply { + // Place copyright above the user list bottom sheet + setLogoMargins(dimensionConverter.dpToPx(8), 0, 0, bottomSheetHeight + dimensionConverter.dpToPx(8)) + setAttributionMargins(dimensionConverter.dpToPx(96), 0, 0, bottomSheetHeight + dimensionConverter.dpToPx(8)) + } + lifecycleScope.launch { mapboxMap.setStyle(urlMapProvider.getMapUrl()) { style -> mapStyle = style diff --git a/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewModel.kt b/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewModel.kt index 64802c7090..eb5bccff0f 100644 --- a/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/location/live/map/LocationLiveMapViewModel.kt @@ -49,9 +49,9 @@ class LocationLiveMapViewModel @AssistedInject constructor( override fun handle(action: LocationLiveMapAction) { when (action) { - is LocationLiveMapAction.AddMapSymbol -> handleAddMapSymbol(action) + is LocationLiveMapAction.AddMapSymbol -> handleAddMapSymbol(action) is LocationLiveMapAction.RemoveMapSymbol -> handleRemoveMapSymbol(action) - LocationLiveMapAction.StopSharing -> handleStopSharing() + LocationLiveMapAction.StopSharing -> handleStopSharing() } } diff --git a/vector/src/main/java/im/vector/app/features/location/live/map/UserLiveLocationViewStateMapper.kt b/vector/src/main/java/im/vector/app/features/location/live/map/UserLiveLocationViewStateMapper.kt index 09922b77d4..77f8c30fd3 100644 --- a/vector/src/main/java/im/vector/app/features/location/live/map/UserLiveLocationViewStateMapper.kt +++ b/vector/src/main/java/im/vector/app/features/location/live/map/UserLiveLocationViewStateMapper.kt @@ -42,7 +42,7 @@ class UserLiveLocationViewStateMapper @Inject constructor( userId.isNullOrEmpty() || locationData == null -> continuation.resume(null) { // do nothing on cancellation } - else -> { + else -> { locationPinProvider.create(userId) { pinDrawable -> val session = activeSessionHolder.getActiveSession() session.getUser(userId)?.toMatrixItem()?.let { matrixItem -> diff --git a/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt b/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt index 2308f2c544..9512a518e8 100644 --- a/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt @@ -65,7 +65,7 @@ abstract class AbstractLoginFragment : VectorBaseFragment( private fun handleLoginViewEvents(loginViewEvents: LoginViewEvents) { when (loginViewEvents) { is LoginViewEvents.Failure -> showFailure(loginViewEvents.throwable) - else -> + else -> // This is handled by the Activity Unit } @@ -78,10 +78,10 @@ abstract class AbstractLoginFragment : VectorBaseFragment( } when (throwable) { - is CancellationException -> + is CancellationException -> /* Ignore this error, user has cancelled the action */ Unit - is Failure.ServerError -> + is Failure.ServerError -> if (throwable.error.code == MatrixError.M_FORBIDDEN && throwable.httpCode == HttpsURLConnection.HTTP_FORBIDDEN /* 403 */) { MaterialAlertDialogBuilder(requireActivity()) @@ -94,7 +94,7 @@ abstract class AbstractLoginFragment : VectorBaseFragment( } is Failure.UnrecognizedCertificateFailure -> showUnrecognizedCertificateFailure(throwable) - else -> + else -> onError(throwable) } } @@ -140,7 +140,7 @@ abstract class AbstractLoginFragment : VectorBaseFragment( true } - displayCancelDialog && isResetPasswordStarted -> { + displayCancelDialog && isResetPasswordStarted -> { // Ask for confirmation before cancelling the reset password MaterialAlertDialogBuilder(requireActivity()) .setTitle(R.string.login_reset_password_cancel_confirmation_title) @@ -154,7 +154,7 @@ abstract class AbstractLoginFragment : VectorBaseFragment( true } - else -> { + else -> { resetViewModel() // Do not consume the Back event false diff --git a/vector/src/main/java/im/vector/app/features/login/LoginAction.kt b/vector/src/main/java/im/vector/app/features/login/LoginAction.kt index 800df32b9d..5947fa0cb5 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginAction.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginAction.kt @@ -66,9 +66,11 @@ sealed class LoginAction : VectorViewModelAction { object ClearHomeServerHistory : LoginAction() // For the soft logout case - data class SetupSsoForSessionRecovery(val homeServerUrl: String, - val deviceId: String, - val ssoIdentityProviders: List?) : LoginAction() + data class SetupSsoForSessionRecovery( + val homeServerUrl: String, + val deviceId: String, + val ssoIdentityProviders: List? + ) : LoginAction() data class PostViewEvent(val viewEvent: LoginViewEvents) : LoginAction() diff --git a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt index 42a9b18558..722133f585 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt @@ -42,6 +42,7 @@ import im.vector.app.features.analytics.plan.MobileScreen import im.vector.app.features.home.HomeActivity import im.vector.app.features.login.terms.LoginTermsFragment import im.vector.app.features.login.terms.LoginTermsFragmentArgument +import im.vector.app.features.onboarding.AuthenticationDescription import im.vector.app.features.pin.UnlockedActivity import org.matrix.android.sdk.api.auth.registration.FlowResult import org.matrix.android.sdk.api.auth.registration.Stage @@ -106,7 +107,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA private fun handleLoginViewEvents(loginViewEvents: LoginViewEvents) { when (loginViewEvents) { - is LoginViewEvents.RegistrationFlowResult -> { + is LoginViewEvents.RegistrationFlowResult -> { // Check that all flows are supported by the application if (loginViewEvents.flowResult.missingStages.any { !it.isSupported() }) { // Display a popup to propose use web fallback @@ -128,7 +129,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA } } } - is LoginViewEvents.OutdatedHomeserver -> { + is LoginViewEvents.OutdatedHomeserver -> { MaterialAlertDialogBuilder(this) .setTitle(R.string.login_error_outdated_homeserver_title) .setMessage(R.string.login_error_outdated_homeserver_warning_content) @@ -136,7 +137,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA .show() Unit } - is LoginViewEvents.OpenServerSelection -> + is LoginViewEvents.OpenServerSelection -> addFragmentToBackstack(views.loginFragmentContainer, LoginServerSelectionFragment::class.java, option = { ft -> @@ -148,22 +149,22 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // TODO Disabled because it provokes a flickering // ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim) }) - is LoginViewEvents.OnServerSelectionDone -> onServerSelectionDone(loginViewEvents) - is LoginViewEvents.OnSignModeSelected -> onSignModeSelected(loginViewEvents) - is LoginViewEvents.OnLoginFlowRetrieved -> + is LoginViewEvents.OnServerSelectionDone -> onServerSelectionDone(loginViewEvents) + is LoginViewEvents.OnSignModeSelected -> onSignModeSelected(loginViewEvents) + is LoginViewEvents.OnLoginFlowRetrieved -> addFragmentToBackstack( views.loginFragmentContainer, LoginSignUpSignInSelectionFragment::class.java, option = commonOption ) - is LoginViewEvents.OnWebLoginError -> onWebLoginError(loginViewEvents) - is LoginViewEvents.OnForgetPasswordClicked -> + is LoginViewEvents.OnWebLoginError -> onWebLoginError(loginViewEvents) + is LoginViewEvents.OnForgetPasswordClicked -> addFragmentToBackstack( views.loginFragmentContainer, LoginResetPasswordFragment::class.java, option = commonOption ) - is LoginViewEvents.OnResetPasswordSendThreePidDone -> { + is LoginViewEvents.OnResetPasswordSendThreePidDone -> { supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) addFragmentToBackstack( views.loginFragmentContainer, @@ -171,7 +172,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA option = commonOption ) } - is LoginViewEvents.OnResetPasswordMailConfirmationSuccess -> { + is LoginViewEvents.OnResetPasswordMailConfirmationSuccess -> { supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) addFragmentToBackstack( views.loginFragmentContainer, @@ -183,7 +184,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // Go back to the login fragment supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) } - is LoginViewEvents.OnSendEmailSuccess -> { + is LoginViewEvents.OnSendEmailSuccess -> { // Pop the enter email Fragment supportFragmentManager.popBackStack(FRAGMENT_REGISTRATION_STAGE_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE) addFragmentToBackstack( @@ -194,7 +195,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA option = commonOption ) } - is LoginViewEvents.OnSendMsisdnSuccess -> { + is LoginViewEvents.OnSendMsisdnSuccess -> { // Pop the enter Msisdn Fragment supportFragmentManager.popBackStack(FRAGMENT_REGISTRATION_STAGE_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE) addFragmentToBackstack( @@ -206,7 +207,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA ) } is LoginViewEvents.Failure, - is LoginViewEvents.Loading -> + is LoginViewEvents.Loading -> // This is handled by the Fragments Unit } @@ -218,10 +219,8 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // change the screen name analyticsScreenName = MobileScreen.ScreenName.Register } - val intent = HomeActivity.newIntent( - this, - accountCreation = loginViewState.signMode == SignMode.SignUp - ) + val authDescription = inferAuthDescription(loginViewState) + val intent = HomeActivity.newIntent(this, authenticationDescription = authDescription) startActivity(intent) finish() return @@ -231,6 +230,13 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA views.loginLoading.isVisible = loginViewState.isLoading() } + private fun inferAuthDescription(loginViewState: LoginViewState) = when (loginViewState.signMode) { + SignMode.Unknown -> null + SignMode.SignUp -> AuthenticationDescription.Register(type = AuthenticationDescription.AuthenticationType.Other) + SignMode.SignIn -> AuthenticationDescription.Login + SignMode.SignInWithMatrixId -> AuthenticationDescription.Login + } + private fun onWebLoginError(onWebLoginError: LoginViewEvents.OnWebLoginError) { // Pop the backstack supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) @@ -247,29 +253,29 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA when (loginViewEvents.serverType) { ServerType.MatrixOrg -> Unit // In this case, we wait for the login flow ServerType.EMS, - ServerType.Other -> addFragmentToBackstack( + ServerType.Other -> addFragmentToBackstack( views.loginFragmentContainer, LoginServerUrlFormFragment::class.java, option = commonOption ) - ServerType.Unknown -> Unit /* Should not happen */ + ServerType.Unknown -> Unit /* Should not happen */ } } private fun onSignModeSelected(loginViewEvents: LoginViewEvents.OnSignModeSelected) = withState(loginViewModel) { state -> // state.signMode could not be ready yet. So use value from the ViewEvent when (loginViewEvents.signMode) { - SignMode.Unknown -> error("Sign mode has to be set before calling this method") - SignMode.SignUp -> { + SignMode.Unknown -> error("Sign mode has to be set before calling this method") + SignMode.SignUp -> { // This is managed by the LoginViewEvents } - SignMode.SignIn -> { + SignMode.SignIn -> { // It depends on the LoginMode when (state.loginMode) { LoginMode.Unknown, - is LoginMode.Sso -> error("Developer error") + is LoginMode.Sso -> error("Developer error") is LoginMode.SsoAndPassword, - LoginMode.Password -> addFragmentToBackstack( + LoginMode.Password -> addFragmentToBackstack( views.loginFragmentContainer, LoginFragment::class.java, tag = FRAGMENT_LOGIN_TAG, @@ -361,28 +367,28 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA tag = FRAGMENT_REGISTRATION_STAGE_TAG, option = commonOption ) - is Stage.Email -> addFragmentToBackstack( + is Stage.Email -> addFragmentToBackstack( views.loginFragmentContainer, LoginGenericTextInputFormFragment::class.java, LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetEmail, stage.mandatory), tag = FRAGMENT_REGISTRATION_STAGE_TAG, option = commonOption ) - is Stage.Msisdn -> addFragmentToBackstack( + is Stage.Msisdn -> addFragmentToBackstack( views.loginFragmentContainer, LoginGenericTextInputFormFragment::class.java, LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetMsisdn, stage.mandatory), tag = FRAGMENT_REGISTRATION_STAGE_TAG, option = commonOption ) - is Stage.Terms -> addFragmentToBackstack( + is Stage.Terms -> addFragmentToBackstack( views.loginFragmentContainer, LoginTermsFragment::class.java, LoginTermsFragmentArgument(stage.policies.toLocalizedLoginTerms(getString(R.string.resources_language))), tag = FRAGMENT_REGISTRATION_STAGE_TAG, option = commonOption ) - else -> Unit // Should not happen + else -> Unit // Should not happen } } diff --git a/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt index e8c0b25027..9c598c400b 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt @@ -37,6 +37,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import org.matrix.android.sdk.api.auth.data.SsoIdentityProvider import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.failure.MatrixError import org.matrix.android.sdk.api.failure.isInvalidPassword @@ -85,8 +86,8 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment= Build.VERSION_CODES.O) { when (state.signMode) { - SignMode.Unknown -> error("developer error") - SignMode.SignUp -> { + SignMode.Unknown -> error("developer error") + SignMode.SignUp -> { views.loginField.setAutofillHints(HintConstants.AUTOFILL_HINT_NEW_USERNAME) views.passwordField.setAutofillHints(HintConstants.AUTOFILL_HINT_NEW_PASSWORD) } @@ -101,8 +102,8 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment error("developer error") - SignMode.SignUp -> SocialLoginButtonsView.Mode.MODE_SIGN_UP + SignMode.Unknown -> error("developer error") + SignMode.SignUp -> SocialLoginButtonsView.Mode.MODE_SIGN_UP SignMode.SignIn, SignMode.SignInWithMatrixId -> SocialLoginButtonsView.Mode.MODE_SIGN_IN } @@ -155,9 +156,9 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment error("developer error") - SignMode.SignUp -> R.string.login_signup_username_hint - SignMode.SignIn -> R.string.login_signin_username_hint + SignMode.Unknown -> error("developer error") + SignMode.SignUp -> R.string.login_signup_username_hint + SignMode.SignIn -> R.string.login_signin_username_hint SignMode.SignInWithMatrixId -> R.string.login_signin_matrix_id_hint } ) @@ -170,9 +171,9 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment error("developer error") - SignMode.SignUp -> R.string.login_signup_to - SignMode.SignIn -> R.string.login_connect_to + SignMode.Unknown -> error("developer error") + SignMode.SignUp -> R.string.login_signup_to + SignMode.SignIn -> R.string.login_connect_to SignMode.SignInWithMatrixId -> R.string.login_connect_to } @@ -183,18 +184,18 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment { + ServerType.EMS -> { views.loginServerIcon.isVisible = true views.loginServerIcon.setImageResource(R.drawable.ic_logo_element_matrix_services) views.loginTitle.text = getString(resId, "Element Matrix Services") views.loginNotice.text = getString(R.string.login_server_modular_text) } - ServerType.Other -> { + ServerType.Other -> { views.loginServerIcon.isVisible = false views.loginTitle.text = getString(resId, state.homeServerUrlFromUser.toReducedUrl()) views.loginNotice.text = getString(R.string.login_server_other_text) } - ServerType.Unknown -> Unit /* Should not happen */ + ServerType.Unknown -> Unit /* Should not happen */ } views.loginPasswordNotice.isVisible = false @@ -202,11 +203,11 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment error("developer error") - SignMode.SignUp -> R.string.login_signup_submit + SignMode.Unknown -> error("developer error") + SignMode.SignUp -> R.string.login_signup_submit SignMode.SignIn, SignMode.SignInWithMatrixId -> R.string.login_signin } @@ -279,7 +280,7 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment