diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 00000000..5e6c6f35
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,12 @@
+*
+
+!.git/
+!Lagrange.Codec/
+!Lagrange.Core/
+!Lagrange.Milky/
+!Lagrange.Milky.Implementation.Api.Generator/
+!Lagrange.Proto/
+!Lagrange.Proto.Generator/
+
+*/bin/
+*/obj/
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 00000000..9bdbe82d
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,380 @@
+root = true
+
+# All files
+[*]
+indent_style = space
+
+# Xml files
+[*.xml]
+indent_size = 2
+
+# C# files
+[*.cs]
+
+#### Core EditorConfig Options ####
+
+# Indentation and spacing
+indent_size = 4
+tab_width = 4
+
+# New line preferences
+insert_final_newline = false
+
+#### .NET Coding Conventions ####
+[*.{cs,vb}]
+
+# Organize usings
+dotnet_separate_import_directive_groups = false
+dotnet_sort_system_directives_first = true
+file_header_template = unset
+
+# this. and Me. preferences
+dotnet_style_qualification_for_event = false:silent
+dotnet_style_qualification_for_field = false:silent
+dotnet_style_qualification_for_method = false:silent
+dotnet_style_qualification_for_property = false:silent
+
+# Language keywords vs BCL types preferences
+dotnet_style_predefined_type_for_locals_parameters_members = true:silent
+dotnet_style_predefined_type_for_member_access = true:silent
+
+# Parentheses preferences
+dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
+
+# Modifier preferences
+dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
+
+# Expression-level preferences
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_namespace_match_folder = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_operator_placement_when_wrapping = beginning_of_line
+dotnet_style_prefer_auto_properties = true:suggestion
+dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
+dotnet_style_prefer_compound_assignment = true:suggestion
+dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
+dotnet_style_prefer_conditional_expression_over_return = true:suggestion
+dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed:suggestion
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
+dotnet_style_prefer_inferred_tuple_names = true:suggestion
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
+dotnet_style_prefer_simplified_interpolation = true:suggestion
+
+# Field preferences
+dotnet_style_readonly_field = true:warning
+
+# Parameter preferences
+dotnet_code_quality_unused_parameters = all:suggestion
+
+# Suppression preferences
+dotnet_remove_unnecessary_suppression_exclusions = none
+
+#### C# Coding Conventions ####
+[*.cs]
+
+# LWX like var
+# but doesn't like the built-in type
+# var preferences
+csharp_style_var_elsewhere = true:warning
+csharp_style_var_for_built_in_types = false:warning
+csharp_style_var_when_type_is_apparent = true:warning
+
+# Expression-bodied members
+csharp_style_expression_bodied_accessors = true:silent
+csharp_style_expression_bodied_constructors = false:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_lambdas = true:suggestion
+csharp_style_expression_bodied_local_functions = false:silent
+csharp_style_expression_bodied_methods = false:silent
+csharp_style_expression_bodied_operators = false:silent
+csharp_style_expression_bodied_properties = true:silent
+
+# Pattern matching preferences
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+csharp_style_prefer_extended_property_pattern = true:suggestion
+csharp_style_prefer_not_pattern = true:suggestion
+csharp_style_prefer_pattern_matching = true:silent
+csharp_style_prefer_switch_expression = true:suggestion
+
+# Null-checking preferences
+csharp_style_conditional_delegate_call = true:suggestion
+
+# Modifier preferences
+csharp_prefer_static_anonymous_function = true:suggestion
+csharp_prefer_static_local_function = true:warning
+csharp_preferred_modifier_order = public,private,protected,internal,file,const,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion
+csharp_style_prefer_readonly_struct = true:suggestion
+csharp_style_prefer_readonly_struct_member = true:suggestion
+
+# Code-block preferences
+csharp_prefer_braces = true:silent
+csharp_prefer_simple_using_statement = true:suggestion
+csharp_style_namespace_declarations = file_scoped:suggestion
+csharp_style_prefer_method_group_conversion = true:silent
+csharp_style_prefer_primary_constructors = true:suggestion
+csharp_style_prefer_top_level_statements = true:silent
+
+# Expression-level preferences
+csharp_prefer_simple_default_expression = true:suggestion
+csharp_style_deconstructed_variable_declaration = true:suggestion
+csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
+csharp_style_inlined_variable_declaration = true:suggestion
+csharp_style_prefer_index_operator = true:suggestion
+csharp_style_prefer_local_over_anonymous_function = true:suggestion
+csharp_style_prefer_null_check_over_type_check = true:suggestion
+csharp_style_prefer_range_operator = true:suggestion
+csharp_style_prefer_tuple_swap = true:suggestion
+csharp_style_prefer_utf8_string_literals = true:suggestion
+csharp_style_throw_expression = true:suggestion
+csharp_style_unused_value_assignment_preference = discard_variable:suggestion
+csharp_style_unused_value_expression_statement_preference = discard_variable:silent
+
+# 'using' directive preferences
+csharp_using_directive_placement = outside_namespace:silent
+
+#### C# Formatting Rules ####
+
+# New line preferences
+csharp_new_line_before_catch = true
+csharp_new_line_before_else = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_open_brace = all
+csharp_new_line_between_query_expression_clauses = true
+
+# Indentation preferences
+csharp_indent_block_contents = true
+csharp_indent_braces = false
+csharp_indent_case_contents = true
+csharp_indent_case_contents_when_block = false
+csharp_indent_labels = one_less_than_current
+csharp_indent_switch_labels = true
+
+# Space preferences
+csharp_space_after_cast = false
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_after_comma = true
+csharp_space_after_dot = false
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_after_semicolon_in_for_statement = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_around_declaration_statements = false
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_before_comma = false
+csharp_space_before_dot = false
+csharp_space_before_open_square_brackets = false
+csharp_space_before_semicolon_in_for_statement = false
+csharp_space_between_empty_square_brackets = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_between_method_call_parameter_list_parentheses = false
+csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+csharp_space_between_method_declaration_name_and_open_parenthesis = false
+csharp_space_between_method_declaration_parameter_list_parentheses = false
+csharp_space_between_parentheses = false
+csharp_space_between_square_brackets = false
+
+# Wrapping preferences
+csharp_preserve_single_line_blocks = true
+csharp_preserve_single_line_statements = true
+
+#### Naming styles ####
+[*.{cs,vb}]
+
+# Naming rules
+
+dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces
+dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion
+dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces
+dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase
+
+dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion
+dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters
+dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase
+
+dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods
+dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties
+dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.events_should_be_pascalcase.symbols = events
+dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion
+dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables
+dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase
+
+dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion
+dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants
+dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase
+
+dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion
+dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters
+dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase
+
+dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields
+dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion
+dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields
+dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase
+
+dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion
+dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields
+dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase
+
+dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields
+dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields
+dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields
+dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields
+dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums
+dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions
+dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase
+
+dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion
+dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members
+dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase
+
+# Symbol specifications
+
+dotnet_naming_symbols.interfaces.applicable_kinds = interface
+dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.interfaces.required_modifiers =
+
+dotnet_naming_symbols.enums.applicable_kinds = enum
+dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.enums.required_modifiers =
+
+dotnet_naming_symbols.events.applicable_kinds = event
+dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.events.required_modifiers =
+
+dotnet_naming_symbols.methods.applicable_kinds = method
+dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.methods.required_modifiers =
+
+dotnet_naming_symbols.properties.applicable_kinds = property
+dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.properties.required_modifiers =
+
+dotnet_naming_symbols.public_fields.applicable_kinds = field
+dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal
+dotnet_naming_symbols.public_fields.required_modifiers =
+
+dotnet_naming_symbols.private_fields.applicable_kinds = field
+dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
+dotnet_naming_symbols.private_fields.required_modifiers =
+
+dotnet_naming_symbols.private_static_fields.applicable_kinds = field
+dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
+dotnet_naming_symbols.private_static_fields.required_modifiers = static
+
+dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum
+dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.types_and_namespaces.required_modifiers =
+
+dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
+dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.non_field_members.required_modifiers =
+
+dotnet_naming_symbols.type_parameters.applicable_kinds = namespace
+dotnet_naming_symbols.type_parameters.applicable_accessibilities = *
+dotnet_naming_symbols.type_parameters.required_modifiers =
+
+dotnet_naming_symbols.private_constant_fields.applicable_kinds = field
+dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
+dotnet_naming_symbols.private_constant_fields.required_modifiers = const
+
+dotnet_naming_symbols.local_variables.applicable_kinds = local
+dotnet_naming_symbols.local_variables.applicable_accessibilities = local
+dotnet_naming_symbols.local_variables.required_modifiers =
+
+dotnet_naming_symbols.local_constants.applicable_kinds = local
+dotnet_naming_symbols.local_constants.applicable_accessibilities = local
+dotnet_naming_symbols.local_constants.required_modifiers = const
+
+dotnet_naming_symbols.parameters.applicable_kinds = parameter
+dotnet_naming_symbols.parameters.applicable_accessibilities = *
+dotnet_naming_symbols.parameters.required_modifiers =
+
+dotnet_naming_symbols.public_constant_fields.applicable_kinds = field
+dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal
+dotnet_naming_symbols.public_constant_fields.required_modifiers = const
+
+dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field
+dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal
+dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static
+
+dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field
+dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
+dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static
+
+dotnet_naming_symbols.local_functions.applicable_kinds = local_function
+dotnet_naming_symbols.local_functions.applicable_accessibilities = *
+dotnet_naming_symbols.local_functions.required_modifiers =
+
+# Naming styles
+
+dotnet_naming_style.pascalcase.required_prefix =
+dotnet_naming_style.pascalcase.required_suffix =
+dotnet_naming_style.pascalcase.word_separator =
+dotnet_naming_style.pascalcase.capitalization = pascal_case
+
+dotnet_naming_style.ipascalcase.required_prefix = I
+dotnet_naming_style.ipascalcase.required_suffix =
+dotnet_naming_style.ipascalcase.word_separator =
+dotnet_naming_style.ipascalcase.capitalization = pascal_case
+
+dotnet_naming_style.tpascalcase.required_prefix = T
+dotnet_naming_style.tpascalcase.required_suffix =
+dotnet_naming_style.tpascalcase.word_separator =
+dotnet_naming_style.tpascalcase.capitalization = pascal_case
+
+dotnet_naming_style._camelcase.required_prefix = _
+dotnet_naming_style._camelcase.required_suffix =
+dotnet_naming_style._camelcase.word_separator =
+dotnet_naming_style._camelcase.capitalization = camel_case
+
+dotnet_naming_style.camelcase.required_prefix =
+dotnet_naming_style.camelcase.required_suffix =
+dotnet_naming_style.camelcase.word_separator =
+dotnet_naming_style.camelcase.capitalization = camel_case
+
+dotnet_naming_style.s_camelcase.required_prefix = s_
+dotnet_naming_style.s_camelcase.required_suffix =
+dotnet_naming_style.s_camelcase.word_separator =
+dotnet_naming_style.s_camelcase.capitalization = camel_case
+
diff --git a/.github/workflows/milky-build.yaml b/.github/workflows/milky-build.yaml
new file mode 100644
index 00000000..b375e46f
--- /dev/null
+++ b/.github/workflows/milky-build.yaml
@@ -0,0 +1,72 @@
+name: Build Lagrange.Milky
+
+on:
+ push:
+ branches: [ main ]
+ paths:
+ - .github/workflows/milky-build.yaml
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Milky/**
+ - Lagrange.Milky.Implementation.Api.Generator/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ pull_request:
+ branches: [ main ]
+ paths:
+ - .github/workflows/milky-build.yaml
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Milky/**
+ - Lagrange.Milky.Implementation.Api.Generator/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ workflow_dispatch:
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ include:
+ - os: windows-latest
+ rid: win-x64
+ binary-extension: '.exe'
+ - os: macos-latest
+ rid: osx-arm64
+ binary-extension: ''
+ - os: ubuntu-latest
+ rid: linux-x64
+ binary-extension: ''
+
+ env:
+ RUNTIME_IDENTIFIER: ${{ matrix.rid }}
+
+ steps:
+ - name: Install Linux Dependencies
+ if: matrix.os == 'ubuntu-latest'
+ run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev
+
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: '10'
+
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Publish
+ run: dotnet publish Lagrange.Milky -c Release -r ${{ matrix.rid }}
+
+ - if: github.event_name != 'pull_request'
+ uses: actions/upload-artifact@v4
+ with:
+ name: Lagrange.Milky-${{ matrix.rid }}
+ path: Lagrange.Milky/bin/Release/net10.0/${{ matrix.rid }}/publish/Lagrange.Milky${{ matrix.binary-extension }}
+ - if: github.event_name != 'pull_request'
+ uses: actions/upload-artifact@v4
+ with:
+ name: Lagrange.Milky-${{ matrix.rid }}-symbol-files
+ path: |
+ Lagrange.Milky/bin/Release/net10.0/${{ matrix.rid }}/publish/*
+ !Lagrange.Milky/bin/Release/net10.0/${{ matrix.rid }}/publish/Lagrange.Milky${{ matrix.binary-extension }}
diff --git a/.github/workflows/milky-docker.yaml b/.github/workflows/milky-docker.yaml
new file mode 100644
index 00000000..5a13cdc7
--- /dev/null
+++ b/.github/workflows/milky-docker.yaml
@@ -0,0 +1,132 @@
+name: Build Lagrange.Milky image
+
+on:
+ push:
+ branches: [ main ]
+ paths:
+ - .github/workflows/milky-docker.yaml
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Milky/**
+ - Lagrange.Milky.Implementation.Api.Generator/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ pull_request:
+ branches: [ main ]
+ paths:
+ - .github/workflows/milky-docker.yaml
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Milky/**
+ - Lagrange.Milky.Implementation.Api.Generator/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ workflow_dispatch:
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - platform: linux/amd64
+ runner: ubuntu-24.04
+ - platform: linux/arm64
+ runner: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runner }}
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Prepare
+ run: |
+ platform=${{ matrix.platform }}
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
+ echo "REGISTRY_IMAGE=ghcr.io/${GITHUB_REPOSITORY_OWNER@L}/lagrange.milky" >> $GITHUB_ENV
+
+ - name: Docker meta
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ${{ env.REGISTRY_IMAGE }}
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.repository_owner }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build and push by digest
+ id: build
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: Lagrange.Milky/Resources/Dockerfile
+ platforms: ${{ matrix.platform }}
+ labels: ${{ steps.meta.outputs.labels }}
+ tags: ${{ env.REGISTRY_IMAGE }}
+ outputs: type=image,push-by-digest=true,name-canonical=true,push=true
+
+ - name: Export digest
+ run: |
+ mkdir -p ${{ runner.temp }}/digests
+ digest="${{ steps.build.outputs.digest }}"
+ touch "${{ runner.temp }}/digests/${digest#sha256:}"
+
+ - name: Upload digest
+ uses: actions/upload-artifact@v4
+ with:
+ name: digests-${{ env.PLATFORM_PAIR }}
+ path: ${{ runner.temp }}/digests/*
+ if-no-files-found: error
+ retention-days: 1
+
+ merge:
+ runs-on: ubuntu-latest
+ needs:
+ - build
+ steps:
+ - name: Prepare
+ run: |
+ echo "REGISTRY_IMAGE=ghcr.io/${GITHUB_REPOSITORY_OWNER@L}/lagrange.milky" >> $GITHUB_ENV
+
+ - name: Download digests
+ uses: actions/download-artifact@v4
+ with:
+ path: ${{ runner.temp }}/digests
+ pattern: digests-*
+ merge-multiple: true
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.repository_owner }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Docker meta
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ${{ env.REGISTRY_IMAGE }}
+ tags: |
+ type=ref,event=branch
+ type=ref,event=pr
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+
+ - name: Create manifest list and push
+ working-directory: ${{ runner.temp }}/digests
+ run: |
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
+ $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
+
+ - name: Inspect image
+ run: |
+ docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }}
diff --git a/.github/workflows/native-api-build.yaml b/.github/workflows/native-api-build.yaml
new file mode 100644
index 00000000..a3cbff8c
--- /dev/null
+++ b/.github/workflows/native-api-build.yaml
@@ -0,0 +1,73 @@
+name: Build Lagrange.Core.NativeAPI
+
+on:
+ push:
+ branches: [ main ]
+ paths:
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ - Lagrange.Core.NativeAPI/**
+ pull_request:
+ branches: [ main ]
+ paths:
+ - Lagrange.Codec/**
+ - Lagrange.Core/**
+ - Lagrange.Proto/**
+ - Lagrange.Proto.Generator/**
+ - Lagrange.Core.NativeAPI/**
+ workflow_dispatch:
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ include:
+ - os: windows-latest
+ rid: win-x64
+ binary-extension: '.dll'
+ - os: windows-latest
+ rid: win-arm64
+ binary-extension: '.dll'
+ - os: macos-latest
+ rid: osx-x64
+ binary-extension: '.dylib'
+ - os: macos-latest
+ rid: osx-arm64
+ binary-extension: '.dylib'
+ - os: ubuntu-latest
+ rid: linux-x64
+ binary-extension: '.so'
+ - os: ubuntu-22.04-arm
+ rid: linux-arm64
+ binary-extension: '.so'
+
+ env:
+ RUNTIME_IDENTIFIER: ${{ matrix.rid }}
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: '10'
+
+ - name: Install Linux Dependencies
+ if: matrix.os == 'ubuntu-latest' || matrix.os == 'ubuntu-22.04-arm'
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y clang zlib1g-dev
+
+ - name: Publish with Native AOT
+ run: dotnet publish Lagrange.Core.NativeAPI -c Release -r ${{ matrix.rid }}
+
+ - name: Upload artifacts
+ if: github.event_name != 'pull_request'
+ uses: actions/upload-artifact@v4
+ with:
+ name: Lagrange.Core.NativeAPI-${{ matrix.rid }}
+ path: Lagrange.Core.NativeAPI/bin/Release/net9.0/${{ matrix.rid }}/publish/Lagrange.Core.NativeAPI${{ matrix.binary-extension }}
\ No newline at end of file
diff --git a/.github/workflows/nuget-push-lagrange-core.yaml b/.github/workflows/nuget-push-lagrange-core.yaml
new file mode 100644
index 00000000..b05d8b73
--- /dev/null
+++ b/.github/workflows/nuget-push-lagrange-core.yaml
@@ -0,0 +1,57 @@
+name: Nuget push Lagrange.Core
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - "Lagrange.Core/Lagrange.Core.csproj"
+ workflow_dispatch:
+
+jobs:
+ nuget-push:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ # Check Version
+ - shell: pwsh
+ run: |
+ $lversion = ([xml](Get-Content .\Lagrange.Core\Lagrange.Core.csproj)).Project.PropertyGroup.Version
+ echo "Local version: $lversion"
+
+ try {
+ $response = Invoke-WebRequest -Uri "https://api.nuget.org/v3-flatcontainer/lagrange.core/index.json"
+ } catch {
+ if ($_.Exception.Response.StatusCode.value__ -eq 404) {
+ echo "No remote version"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+ } else {
+ throw
+ }
+ }
+
+ $rversions = ($response.Content | ConvertFrom-Json).versions
+ echo "Remote version: $rversions"
+ if ($lversion -in $rversions) {
+ echo "Version($lversion) already exists"
+ echo "continued=false" >> $env:GITHUB_ENV
+ exit 0
+ }
+
+ echo "Version($lversion) does not exist"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+
+ - if: env.continued == 'true'
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: '10'
+
+ - if: env.continued == 'true'
+ run: dotnet pack -c Release -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg Lagrange.Core
+
+ - if: env.continued == 'true'
+ run: dotnet nuget push ./Lagrange.Core/bin/Release/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_TOKEN }}
\ No newline at end of file
diff --git a/.github/workflows/nuget-push-lagrange-proto-codegen.yaml b/.github/workflows/nuget-push-lagrange-proto-codegen.yaml
new file mode 100644
index 00000000..ae03cae0
--- /dev/null
+++ b/.github/workflows/nuget-push-lagrange-proto-codegen.yaml
@@ -0,0 +1,57 @@
+name: Nuget push Lagrange.Proto.Generator
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - "Lagrange.Proto.Generator/Lagrange.Proto.Generator.csproj"
+ workflow_dispatch:
+
+jobs:
+ nuget-push:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ # Check Version
+ - shell: pwsh
+ run: |
+ $lversion = ([xml](Get-Content .\Lagrange.Proto.Generator\Lagrange.Proto.Generator.csproj)).Project.PropertyGroup.Version
+ echo "Local version: $lversion"
+
+ try {
+ $response = Invoke-WebRequest -Uri "https://api.nuget.org/v3-flatcontainer/lagrange.proto.generator/index.json"
+ } catch {
+ if ($_.Exception.Response.StatusCode.value__ -eq 404) {
+ echo "No remote version"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+ } else {
+ throw
+ }
+ }
+
+ $rversions = ($response.Content | ConvertFrom-Json).versions
+ echo "Remote version: $rversions"
+ if ($lversion -in $rversions) {
+ echo "Version($lversion) already exists"
+ echo "continued=false" >> $env:GITHUB_ENV
+ exit 0
+ }
+
+ echo "Version($lversion) does not exist"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+
+ - if: env.continued == 'true'
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: '10'
+
+ - if: env.continued == 'true'
+ run: dotnet pack -c Release -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg Lagrange.Proto.Generator
+
+ - if: env.continued == 'true'
+ run: dotnet nuget push ./Lagrange.Proto.Generator/bin/Release/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_TOKEN }}
\ No newline at end of file
diff --git a/.github/workflows/nuget-push-lagrange-proto.yaml b/.github/workflows/nuget-push-lagrange-proto.yaml
new file mode 100644
index 00000000..d7904a56
--- /dev/null
+++ b/.github/workflows/nuget-push-lagrange-proto.yaml
@@ -0,0 +1,57 @@
+name: Nuget push Lagrange.Proto
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - "Lagrange.Proto/Lagrange.Proto.csproj"
+ workflow_dispatch:
+
+jobs:
+ nuget-push:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ # Check Version
+ - shell: pwsh
+ run: |
+ $lversion = ([xml](Get-Content .\Lagrange.Proto\Lagrange.Proto.csproj)).Project.PropertyGroup.Version
+ echo "Local version: $lversion"
+
+ try {
+ $response = Invoke-WebRequest -Uri "https://api.nuget.org/v3-flatcontainer/lagrange.proto/index.json"
+ } catch {
+ if ($_.Exception.Response.StatusCode.value__ -eq 404) {
+ echo "No remote version"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+ } else {
+ throw
+ }
+ }
+
+ $rversions = ($response.Content | ConvertFrom-Json).versions
+ echo "Remote version: $rversions"
+ if ($lversion -in $rversions) {
+ echo "Version($lversion) already exists"
+ echo "continued=false" >> $env:GITHUB_ENV
+ exit 0
+ }
+
+ echo "Version($lversion) does not exist"
+ echo "continued=true" >> $env:GITHUB_ENV
+ exit 0
+
+ - if: env.continued == 'true'
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: '10'
+
+ - if: env.continued == 'true'
+ run: dotnet pack -c Release -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg Lagrange.Proto
+
+ - if: env.continued == 'true'
+ run: dotnet nuget push ./Lagrange.Proto/bin/Release/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_TOKEN }}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..04130647
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
+# VSCode
+/.vscode
+
+# Dev Container
+/.devcontainer
+
+# CSharp
+/*/bin
+/*/obj
+
+# VS
+/.vs
+
+# Rider (and other IDEs that use .idea)
+/.idea
+/global.json
\ No newline at end of file
diff --git a/Lagrange.Codec/Lagrange.Codec.csproj b/Lagrange.Codec/Lagrange.Codec.csproj
index b846a6e4..2c5fb061 100644
--- a/Lagrange.Codec/Lagrange.Codec.csproj
+++ b/Lagrange.Codec/Lagrange.Codec.csproj
@@ -1,7 +1,7 @@
- net9.0
+ net10.0
enable
enable
true
diff --git a/Lagrange.Core.NativeAPI.Test/Lagrange.Core.NativeAPI.Test.csproj b/Lagrange.Core.NativeAPI.Test/Lagrange.Core.NativeAPI.Test.csproj
new file mode 100644
index 00000000..6c1dc922
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/Lagrange.Core.NativeAPI.Test.csproj
@@ -0,0 +1,10 @@
+
+
+
+ Exe
+ net10.0
+ enable
+ enable
+
+
+
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/BotConfigStruct.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/BotConfigStruct.cs
new file mode 100644
index 00000000..e60358ae
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/BotConfigStruct.cs
@@ -0,0 +1,28 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotConfigStruct
+ {
+ public BotConfigStruct()
+ {
+ }
+
+ public byte Protocol { get; set; } = 0b00000100;
+
+ public bool AutoReconnect { get; set; } = true;
+
+ public bool UseIPv6Network { get; set; } = false;
+
+ public bool GetOptimumServer { get; set; } = true;
+
+ public uint HighwayChunkSize { get; set; } = 1024 * 1024;
+
+ public uint HighwayConcurrent { get; set; } = 4;
+
+ public bool AutoReLogin { get; set; } = true;
+
+ public ByteArrayNative addr { get; set; } = new();
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/BotLogEventStruct.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/BotLogEventStruct.cs
new file mode 100644
index 00000000..181e8674
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/BotLogEventStruct.cs
@@ -0,0 +1,14 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotLogEventStruct
+ {
+ public BotLogEventStruct() { }
+
+ public int Level = 0;
+ public ByteArrayNative Tag = new();
+ public ByteArrayNative Message = new();
+ }
+}
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/BotQrCodeEventStruct.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/BotQrCodeEventStruct.cs
new file mode 100644
index 00000000..227cd96c
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/BotQrCodeEventStruct.cs
@@ -0,0 +1,14 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotQrCodeEventStruct
+ {
+ public BotQrCodeEventStruct() { }
+
+ public ByteArrayNative Url = new();
+
+ public ByteArrayNative Image = new();
+ }
+}
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/ByteArrayNative.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/ByteArrayNative.cs
new file mode 100644
index 00000000..56302a45
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/ByteArrayNative.cs
@@ -0,0 +1,45 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct ByteArrayNative
+ {
+ public int Length;
+ public IntPtr Data;
+
+ public static implicit operator ByteArrayNative(byte[] bytes)
+ {
+ IntPtr ptr = Marshal.AllocHGlobal(bytes.Length);
+ Marshal.Copy(bytes, 0, ptr, bytes.Length);
+
+ return new ByteArrayNative { Length = bytes.Length, Data = ptr };
+ }
+
+ public static implicit operator byte[](ByteArrayNative byteArray)
+ {
+ if (byteArray.Data == IntPtr.Zero)
+ {
+ return [];
+ }
+ byte[] bytes = new byte[byteArray.Length];
+ Marshal.Copy(byteArray.Data, bytes, 0, byteArray.Length);
+
+ Marshal.FreeHGlobal(byteArray.Data);
+
+ return bytes;
+ }
+
+ public byte[] ToByteArrayWithoutFree()
+ {
+ byte[] bytes = new byte[Length];
+ Marshal.Copy(Data, bytes, 0, Length);
+ return bytes;
+ }
+
+ public bool IsEmpty()
+ {
+ return Length == 0 || Data == IntPtr.Zero;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/EventArrayStruct.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/EventArrayStruct.cs
new file mode 100644
index 00000000..c4cab992
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/EventArrayStruct.cs
@@ -0,0 +1,10 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct EventArrayStruct
+{
+ public IntPtr Events;
+ public int Count;
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI.Test/NativeModel/ReverseEventCountStruct.cs b/Lagrange.Core.NativeAPI.Test/NativeModel/ReverseEventCountStruct.cs
new file mode 100644
index 00000000..2a3fff2d
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/NativeModel/ReverseEventCountStruct.cs
@@ -0,0 +1,27 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test.NativeModel;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct ReverseEventCountStruct
+{
+ public ReverseEventCountStruct() { }
+
+ public int BotCaptchaEventCount = 0;
+ public int BotFriendRequestEventCount = 0;
+ public int BotGroupInviteNotificationEventCount = 0;
+ public int BotGroupInviteSelfEventCount = 0;
+ public int BotGroupJoinNotificationEventCount = 0;
+ public int BotGroupMemberDecreaseEventCount = 0;
+ public int BotGroupNudgeEventCount = 0;
+ public int BotGroupReactionEventCount = 0;
+ public int BotLoginEventCount = 0;
+ public int BotLogEventCount = 0;
+ public int BotMessageEventCount = 0;
+ public int BotNewDeviceVerifyEventCount = 0;
+ public int BotOnlineEventCount = 0;
+ public int BotQrCodeEventCount = 0;
+ public int BotQrCodeQueryEventCount = 0;
+ public int BotRefreshKeystoreEventCount = 0;
+ public int BotSMSEventCount = 0;
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI.Test/Program.cs b/Lagrange.Core.NativeAPI.Test/Program.cs
new file mode 100644
index 00000000..1a4c7094
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/Program.cs
@@ -0,0 +1,124 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.NativeAPI.Test.NativeModel;
+
+namespace Lagrange.Core.NativeAPI.Test;
+
+class Program
+{
+ static int _index = 0;
+
+ static TaskCompletionSource _tcs = new();
+
+ static async Task Main(string[] args)
+ {
+ var botConfig = new BotConfigStruct { };
+ botConfig.addr = Encoding.UTF8.GetBytes("");
+
+ IntPtr keystorePtr = IntPtr.Zero;
+ IntPtr botConfigPtr = Marshal.AllocHGlobal(Marshal.SizeOf(botConfig));
+ Marshal.StructureToPtr(botConfig, botConfigPtr, false);
+ _index = Wrapper.Initialize(botConfigPtr, keystorePtr, IntPtr.Zero);
+ Console.WriteLine($"Bot initialized with index: {_index}");
+ int status = Wrapper.Start(_index);
+ Console.WriteLine($"Bot started with status: {status}");
+ Marshal.FreeHGlobal(botConfigPtr);
+
+ var timer = new System.Timers.Timer(100);
+ timer.Elapsed += PollingProcesser;
+ timer.Start();
+ await _tcs.Task;
+ }
+
+ static async void PollingProcesser(Object? source, System.Timers.ElapsedEventArgs e)
+ {
+ try
+ {
+ // await GetEventCount();
+ await GetQrCodeEvent();
+ await GetLogEvent();
+ }
+ catch (Exception exception)
+ {
+ Console.WriteLine(exception);
+ }
+ }
+
+ static async Task GetEventCount()
+ {
+ await Task.Run(() =>
+ {
+ IntPtr ptr = Wrapper.GetEventCount(_index);
+ if (ptr == IntPtr.Zero)
+ {
+ return;
+ }
+
+ var eventCount = Marshal.PtrToStructure(ptr);
+ Console.WriteLine($"BotCaptchaEventCount: {eventCount.BotCaptchaEventCount}");
+ Console.WriteLine($"BotLoginEventCount: {eventCount.BotLoginEventCount}");
+ Console.WriteLine($"BotLogEventCount: {eventCount.BotLogEventCount}");
+ Console.WriteLine($"BotMessageEventCount: {eventCount.BotMessageEventCount}");
+ Console.WriteLine($"BotNewDeviceVerifyEventCount: {eventCount.BotNewDeviceVerifyEventCount}");
+ Console.WriteLine($"BotOnlineEventCount: {eventCount.BotOnlineEventCount}");
+ Console.WriteLine($"BotQrCodeEventCount: {eventCount.BotQrCodeEventCount}");
+ Console.WriteLine($"BotQrCodeQueryEventCount: {eventCount.BotQrCodeQueryEventCount}");
+ Console.WriteLine($"BotRefreshKeystoreEventCount: {eventCount.BotRefreshKeystoreEventCount}");
+ Console.WriteLine($"BotSMSEventCount: {eventCount.BotSMSEventCount}");
+ Wrapper.FreeMemory(ptr);
+ });
+ }
+
+ static async Task GetLogEvent()
+ {
+ await Task.Run(() =>
+ {
+ IntPtr ptr = Wrapper.GetBotLogEvent(_index);
+ if (ptr == IntPtr.Zero)
+ {
+ return;
+ }
+
+ var logEventArray = Marshal.PtrToStructure(ptr);
+
+ for (int i = 0; i < logEventArray.Count; i++)
+ {
+ // 计算当前结构体的指针位置
+ IntPtr currentStructPtr = logEventArray.Events + i * Marshal.SizeOf();
+
+ // 将指针转换为结构体
+ var logEvent = Marshal.PtrToStructure(currentStructPtr);
+
+ // 处理日志事件
+ Console.WriteLine($"Log: {Encoding.UTF8.GetString(logEvent.Message.ToByteArrayWithoutFree())}");
+ }
+
+ Wrapper.FreeMemory(ptr);
+ });
+ }
+
+ static async Task GetQrCodeEvent()
+ {
+ await Task.Run(() =>
+ {
+ IntPtr ptr = Wrapper.GetQrCodeEvent(_index);
+ if (ptr == IntPtr.Zero)
+ {
+ return;
+ }
+
+ var qrCodeEventArray = Marshal.PtrToStructure(ptr);
+
+ for (int i = 0; i < qrCodeEventArray.Count; i++)
+ {
+ IntPtr currentStructPtr = qrCodeEventArray.Events + i * Marshal.SizeOf();
+
+ var qrCodeEvent = Marshal.PtrToStructure(currentStructPtr);
+
+ Console.WriteLine($"QrCodeUrl: {Encoding.UTF8.GetString(qrCodeEvent.Url.ToByteArrayWithoutFree())}");
+ }
+
+ Wrapper.FreeMemory(ptr);
+ });
+ }
+}
diff --git a/Lagrange.Core.NativeAPI.Test/Wrapper.cs b/Lagrange.Core.NativeAPI.Test/Wrapper.cs
new file mode 100644
index 00000000..1c448479
--- /dev/null
+++ b/Lagrange.Core.NativeAPI.Test/Wrapper.cs
@@ -0,0 +1,29 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.Test;
+
+public static class Wrapper
+{
+ public const string DLL_NAME = "Lagrange.Core.NativeAPI.dll";
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int Initialize(IntPtr botConfigPtr, IntPtr keystorePtr, IntPtr appConfigPtr);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int Start(int index);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int Stop(int index);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int FreeMemory(IntPtr ptr);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern IntPtr GetQrCodeEvent(int index);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern IntPtr GetEventCount(int index);
+
+ [DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
+ public static extern IntPtr GetBotLogEvent(int index);
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/Context.cs b/Lagrange.Core.NativeAPI/Context.cs
new file mode 100644
index 00000000..2b23b8ba
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/Context.cs
@@ -0,0 +1,17 @@
+using Lagrange.Core.NativeAPI.ReverseEvent;
+
+namespace Lagrange.Core.NativeAPI
+{
+ public class Context
+ {
+ public Context(BotContext botContext)
+ {
+ BotContext = botContext;
+ EventInvoker = new ReverseEventInvoker(BotContext);
+ SendMessageContext = new SendMessageContext(BotContext);
+ }
+ public BotContext BotContext { get; set; }
+ public ReverseEventInvoker EventInvoker { get; set; }
+ public SendMessageContext SendMessageContext { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/Lagrange.Core.NativeAPI.csproj b/Lagrange.Core.NativeAPI/Lagrange.Core.NativeAPI.csproj
new file mode 100644
index 00000000..9a643a05
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/Lagrange.Core.NativeAPI.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net10.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotAppInfoStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotAppInfoStruct.cs
new file mode 100644
index 00000000..f2ab0c2f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotAppInfoStruct.cs
@@ -0,0 +1,114 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common
+{
+ [StructLayout(LayoutKind.Sequential)]
+ struct BotAppInfoStruct
+ {
+ public BotAppInfoStruct() { }
+
+ public ByteArrayNative Os = new();
+
+ public ByteArrayNative VendorOs = new();
+
+ public ByteArrayNative Kernel = new();
+
+ public ByteArrayNative CurrentVersion = new();
+
+ public ByteArrayNative PtVersion = new();
+
+ public int SsoVersion = 0;
+
+ public ByteArrayNative PackageName = new();
+
+ public ByteArrayNative ApkSignatureMd5 = new();
+
+ public WtLoginSdkInfoStruct SdkInfo = new();
+
+ public int AppId = 0;
+
+ public int SubAppId = 0;
+
+ public ushort AppClientVersion = 0;
+
+ public static implicit operator BotAppInfo(BotAppInfoStruct info)
+ {
+ return new BotAppInfo()
+ {
+ Os = Encoding.UTF8.GetString(info.Os.ToByteArrayWithoutFree()),
+ VendorOs = Encoding.UTF8.GetString(info.VendorOs.ToByteArrayWithoutFree()),
+ Kernel = Encoding.UTF8.GetString(info.Kernel.ToByteArrayWithoutFree()),
+ CurrentVersion = Encoding.UTF8.GetString(info.CurrentVersion.ToByteArrayWithoutFree()),
+ PtVersion = Encoding.UTF8.GetString(info.PtVersion.ToByteArrayWithoutFree()),
+ SsoVersion = info.SsoVersion,
+ PackageName = Encoding.UTF8.GetString(info.PackageName.ToByteArrayWithoutFree()),
+ ApkSignatureMd5 = info.ApkSignatureMd5.ToByteArrayWithoutFree(),
+ SdkInfo = info.SdkInfo,
+ AppId = info.AppId,
+ SubAppId = info.SubAppId,
+ AppClientVersion = info.AppClientVersion
+ };
+ }
+
+ public static implicit operator BotAppInfoStruct(BotAppInfo info)
+ {
+ return new BotAppInfoStruct()
+ {
+ Os = Encoding.UTF8.GetBytes(info.Os),
+ VendorOs = Encoding.UTF8.GetBytes(info.VendorOs),
+ Kernel = Encoding.UTF8.GetBytes(info.Kernel),
+ CurrentVersion = Encoding.UTF8.GetBytes(info.CurrentVersion),
+ PtVersion = Encoding.UTF8.GetBytes(info.PtVersion),
+ SsoVersion = info.SsoVersion,
+ PackageName = Encoding.UTF8.GetBytes(info.PackageName),
+ ApkSignatureMd5 = info.ApkSignatureMd5,
+ SdkInfo = info.SdkInfo,
+ AppId = info.AppId,
+ SubAppId = info.SubAppId,
+ AppClientVersion = info.AppClientVersion
+ };
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct WtLoginSdkInfoStruct
+ {
+ public WtLoginSdkInfoStruct() { }
+
+ public uint SdkBuildTime = 0;
+
+ public ByteArrayNative SdkVersion = new();
+
+ public uint MiscBitMap = 0;
+
+ public uint SubSigMap = 0;
+
+ public int MainSigMap = 0;
+
+ public static implicit operator WtLoginSdkInfo(WtLoginSdkInfoStruct info)
+ {
+ return new WtLoginSdkInfo()
+ {
+ SdkBuildTime = info.SdkBuildTime,
+ SdkVersion = Encoding.UTF8.GetString(info.SdkVersion.ToByteArrayWithoutFree()),
+ MiscBitMap = info.MiscBitMap,
+ SubSigMap = info.SubSigMap,
+ MainSigMap = (Sig)info.MainSigMap,
+ };
+ }
+
+ public static implicit operator WtLoginSdkInfoStruct(WtLoginSdkInfo info)
+ {
+ return new WtLoginSdkInfoStruct()
+ {
+ SdkBuildTime = info.SdkBuildTime,
+ SdkVersion = Encoding.UTF8.GetBytes(info.SdkVersion),
+ MiscBitMap = info.MiscBitMap,
+ SubSigMap = info.SubSigMap,
+ MainSigMap = (int)info.MainSigMap,
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotConfigStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotConfigStruct.cs
new file mode 100644
index 00000000..f104bf5a
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotConfigStruct.cs
@@ -0,0 +1,65 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotConfigStruct
+ {
+ public BotConfigStruct() { }
+
+ public byte Protocol { get; set; } = 0b00000100;
+
+ public bool AutoReconnect { get; set; } = true;
+
+ public bool UseIPv6Network { get; set; } = false;
+
+ public bool GetOptimumServer { get; set; } = true;
+
+ public uint HighwayChunkSize { get; set; } = 1024 * 1024;
+
+ public uint HighwayConcurrent { get; set; } = 4;
+
+ public bool AutoReLogin { get; set; } = true;
+
+ public ByteArrayNative SignAddress { get; set; } = new();
+
+ public static implicit operator BotConfig(BotConfigStruct config)
+ {
+ return new BotConfig()
+ {
+ Protocol = (Protocols)config.Protocol,
+ AutoReconnect = config.AutoReconnect,
+ UseIPv6Network = config.UseIPv6Network,
+ GetOptimumServer = config.GetOptimumServer,
+ HighwayChunkSize = config.HighwayChunkSize,
+ HighwayConcurrent = config.HighwayConcurrent,
+ AutoReLogin = config.AutoReLogin,
+ SignProvider = (Protocols)config.Protocol switch
+ {
+ Protocols.Windows => throw new NotSupportedException("Windows is not supported"),
+ Protocols.MacOs => throw new NotSupportedException("MacOs is not supported"),
+ Protocols.Linux => new LinuxSignProvider(Encoding.UTF8.GetString(config.SignAddress.ToByteArrayWithoutFree())),
+ Protocols.AndroidPhone => new AndroidSignProvider(Encoding.UTF8.GetString(config.SignAddress.ToByteArrayWithoutFree())),
+ Protocols.AndroidPad => new AndroidSignProvider(Encoding.UTF8.GetString(config.SignAddress.ToByteArrayWithoutFree())),
+ _ => throw new ArgumentOutOfRangeException()
+ }
+ };
+ }
+
+ public static implicit operator BotConfigStruct(BotConfig config)
+ {
+ return new BotConfigStruct()
+ {
+ Protocol = (byte)config.Protocol,
+ AutoReconnect = config.AutoReconnect,
+ UseIPv6Network = config.UseIPv6Network,
+ GetOptimumServer = config.GetOptimumServer,
+ HighwayChunkSize = config.HighwayChunkSize,
+ HighwayConcurrent = config.HighwayConcurrent,
+ AutoReLogin = config.AutoReLogin,
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotFriendCategoryStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotFriendCategoryStruct.cs
new file mode 100644
index 00000000..2f20e998
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotFriendCategoryStruct.cs
@@ -0,0 +1,39 @@
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common
+{
+ public struct BotFriendCategoryStruct
+ {
+ public BotFriendCategoryStruct() { }
+
+ public int Id = 0;
+
+ public ByteArrayNative Name = new();
+
+ public int Count = 0;
+
+ public int SortId = 0;
+
+ public static implicit operator BotFriendCategoryStruct(BotFriendCategory category)
+ {
+ return new BotFriendCategoryStruct()
+ {
+ Id = category.Id,
+ Name = Encoding.UTF8.GetBytes(category.Name),
+ Count = category.Count,
+ SortId = category.SortId
+ };
+ }
+
+ public static implicit operator BotFriendCategory(BotFriendCategoryStruct category)
+ {
+ return new BotFriendCategory(
+ category.Id,
+ Encoding.UTF8.GetString(category.Name),
+ category.Count,
+ category.SortId
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupExitNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupExitNotificationStruct.cs
new file mode 100644
index 00000000..d05887ab
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupExitNotificationStruct.cs
@@ -0,0 +1,13 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupExitNotificationStruct(BotGroupExitNotification e) : BotGroupNotificationBaseStruct(e)
+{
+ public static implicit operator BotGroupExitNotificationStruct(BotGroupExitNotification e)
+ {
+ return new BotGroupExitNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupInviteNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupInviteNotificationStruct.cs
new file mode 100644
index 00000000..61962f8b
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupInviteNotificationStruct.cs
@@ -0,0 +1,25 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupInviteNotificationStruct(BotGroupInviteNotification e) : BotGroupNotificationBaseStruct(e)
+{
+ public int State = (int)e.State;
+
+ public long OperatorUin = e.OperatorUin ?? 0;
+
+ public ByteArrayNative OperatorUid = Encoding.UTF8.GetBytes(e.OperatorUid ?? "");
+
+ public long InviterUin = e.InviterUin;
+
+ public ByteArrayNative InviterUid = Encoding.UTF8.GetBytes(e.InviterUid);
+
+ public bool IsFiltered = e.IsFiltered;
+
+ public static implicit operator BotGroupInviteNotificationStruct(BotGroupInviteNotification e)
+ {
+ return new BotGroupInviteNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupJoinNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupJoinNotificationStruct.cs
new file mode 100644
index 00000000..2c07ae27
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupJoinNotificationStruct.cs
@@ -0,0 +1,23 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupJoinNotificationStruct(BotGroupJoinNotification notification) : BotGroupNotificationBaseStruct(notification)
+{
+ public int State = (int)notification.State;
+
+ public long OperatorUin = notification.OperatorUin ?? 0;
+
+ public ByteArrayNative OperatorUid { get; } = Encoding.UTF8.GetBytes(notification.OperatorUid ?? "");
+
+ public ByteArrayNative Comment { get; } = Encoding.UTF8.GetBytes(notification.Comment);
+
+ public bool IsFiltered { get; } = notification.IsFiltered;
+
+ public static implicit operator BotGroupJoinNotificationStruct(BotGroupJoinNotification e)
+ {
+ return new BotGroupJoinNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupKickNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupKickNotificationStruct.cs
new file mode 100644
index 00000000..f132b77f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupKickNotificationStruct.cs
@@ -0,0 +1,17 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupKickNotificationStruct(BotGroupKickNotification notification) : BotGroupNotificationBaseStruct(notification)
+{
+ public long OperatorUin = notification.OperatorUin;
+
+ public ByteArrayNative OperatorUid { get; } = Encoding.UTF8.GetBytes(notification.OperatorUid);
+
+ public static implicit operator BotGroupKickNotificationStruct(BotGroupKickNotification e)
+ {
+ return new BotGroupKickNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupNotificationBaseStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupNotificationBaseStruct.cs
new file mode 100644
index 00000000..f2d453ea
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupNotificationBaseStruct.cs
@@ -0,0 +1,18 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public abstract class BotGroupNotificationBaseStruct(BotGroupNotificationBase e)
+{
+ public long GroupUin = e.GroupUin;
+
+ public ulong Sequence = e.Sequence;
+
+ public int Type = (int)e.Type;
+
+ public long TargetUin = e.TargetUin;
+
+ public ByteArrayNative TargetUid = Encoding.UTF8.GetBytes(e.TargetUid);
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupSetAdminNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupSetAdminNotificationStruct.cs
new file mode 100644
index 00000000..66b3ecad
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupSetAdminNotificationStruct.cs
@@ -0,0 +1,17 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupSetAdminNotificationStruct(BotGroupSetAdminNotification notification) : BotGroupNotificationBaseStruct(notification)
+{
+ public long OperatorUin = notification.OperatorUin;
+
+ public ByteArrayNative OperatorUid { get; } = Encoding.UTF8.GetBytes(notification.OperatorUid);
+
+ public static implicit operator BotGroupSetAdminNotificationStruct(BotGroupSetAdminNotification e)
+ {
+ return new BotGroupSetAdminNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupUnsetAdminNotificationStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupUnsetAdminNotificationStruct.cs
new file mode 100644
index 00000000..48c4907f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotGroupUnsetAdminNotificationStruct.cs
@@ -0,0 +1,17 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+[StructLayout(LayoutKind.Sequential)]
+public class BotGroupUnsetAdminNotificationStruct(BotGroupUnsetAdminNotification notification) : BotGroupNotificationBaseStruct(notification)
+{
+ public long OperatorUin = notification.OperatorUin;
+
+ public ByteArrayNative OperatorUid { get; } = Encoding.UTF8.GetBytes(notification.OperatorUid);
+
+ public static implicit operator BotGroupUnsetAdminNotificationStruct(BotGroupUnsetAdminNotification e)
+ {
+ return new BotGroupUnsetAdminNotificationStruct(e);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotKeystoreStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotKeystoreStruct.cs
new file mode 100644
index 00000000..645bc352
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotKeystoreStruct.cs
@@ -0,0 +1,181 @@
+using System.Text;
+using Lagrange.Core.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common
+{
+ public struct BotKeystoreStruct
+ {
+ public BotKeystoreStruct() { }
+
+ public long Uin = 0;
+
+ public ByteArrayNative Uid = new();
+
+ public ByteArrayNative Guid = new();
+
+ public ByteArrayNative AndroidId = new();
+
+ public ByteArrayNative Qimei = new();
+
+ public ByteArrayNative DeviceName = new();
+
+ // WLoginSigs
+
+ public ByteArrayNative A2 = new();
+
+ public ByteArrayNative A2Key = new byte[16];
+
+ public ByteArrayNative D2 = new();
+
+ public ByteArrayNative D2Key = new byte[16];
+
+ public ByteArrayNative A1 = new();
+
+ public ByteArrayNative A1Key = new byte[16];
+
+ public ByteArrayNative NoPicSig = new();
+
+ public ByteArrayNative TgtgtKey = new();
+
+ public ByteArrayNative Ksid = new();
+
+ public ByteArrayNative SuperKey = new();
+
+ public ByteArrayNative StKey = new();
+
+ public ByteArrayNative StWeb = new();
+
+ public ByteArrayNative St = new();
+
+ public ByteArrayNative WtSessionTicket = new();
+
+ public ByteArrayNative WtSessionTicketKey = new();
+
+ public ByteArrayNative RandomKey = new byte[16];
+
+ public ByteArrayNative SKey = new();
+
+ public ByteArrayDictNative PsKey = new();
+
+ public static implicit operator BotKeystore(BotKeystoreStruct keystore)
+ {
+ var psKey = new Dictionary();
+ foreach (var kvp in (ByteArrayKVPNative[])keystore.PsKey)
+ {
+ psKey[Encoding.UTF8.GetString(kvp.Key)] = Encoding.UTF8.GetString(kvp.Value);
+ }
+
+ return new BotKeystore()
+ {
+ Uin = keystore.Uin,
+ Uid = Encoding.UTF8.GetString(keystore.Uid),
+ Guid = keystore.Guid,
+ AndroidId = Encoding.UTF8.GetString(keystore.AndroidId),
+ Qimei = Encoding.UTF8.GetString(keystore.Qimei),
+ DeviceName = Encoding.UTF8.GetString(keystore.DeviceName),
+ WLoginSigs = new WLoginSigs()
+ {
+ A2 = keystore.A2,
+ A2Key = keystore.A2Key,
+ D2 = keystore.D2,
+ D2Key = keystore.D2Key,
+ A1 = keystore.A1,
+ A1Key = keystore.A1Key,
+ NoPicSig = keystore.NoPicSig,
+ TgtgtKey = keystore.TgtgtKey,
+ Ksid = keystore.Ksid,
+ SuperKey = keystore.SuperKey,
+ StKey = keystore.StKey,
+ StWeb = keystore.StWeb,
+ St = keystore.St,
+ WtSessionTicket = keystore.WtSessionTicket,
+ WtSessionTicketKey = keystore.WtSessionTicketKey,
+ RandomKey = keystore.RandomKey,
+ SKey = keystore.SKey,
+ PsKey = psKey
+ }
+ };
+ }
+
+ public static implicit operator BotKeystoreStruct(BotKeystore keystore)
+ {
+ var bytePsKey = new ByteArrayKVPNative[keystore.WLoginSigs.PsKey.Count];
+ int i = 0;
+ foreach (var kvp in keystore.WLoginSigs.PsKey)
+ {
+ bytePsKey[i++] = new ByteArrayKVPNative
+ {
+ Key = Encoding.UTF8.GetBytes(kvp.Key), Value = Encoding.UTF8.GetBytes(kvp.Value)
+ };
+ }
+
+ return new BotKeystoreStruct()
+ {
+ Uin = keystore.Uin,
+ Uid = Encoding.UTF8.GetBytes(keystore.Uid),
+ Guid = keystore.Guid,
+ AndroidId = Encoding.UTF8.GetBytes(keystore.AndroidId),
+ Qimei = Encoding.UTF8.GetBytes(keystore.Qimei),
+ DeviceName = Encoding.UTF8.GetBytes(keystore.DeviceName),
+ A2 = keystore.WLoginSigs.A2,
+ A2Key = keystore.WLoginSigs.A2Key,
+ D2 = keystore.WLoginSigs.D2,
+ D2Key = keystore.WLoginSigs.D2Key,
+ A1 = keystore.WLoginSigs.A1,
+ A1Key = keystore.WLoginSigs.A1Key,
+ NoPicSig = keystore.WLoginSigs.NoPicSig,
+ TgtgtKey = keystore.WLoginSigs.TgtgtKey,
+ Ksid = keystore.WLoginSigs.Ksid,
+ SuperKey = keystore.WLoginSigs.SuperKey,
+ StKey = keystore.WLoginSigs.StKey,
+ StWeb = keystore.WLoginSigs.StWeb,
+ St = keystore.WLoginSigs.St,
+ WtSessionTicket = keystore.WLoginSigs.WtSessionTicket,
+ WtSessionTicketKey = keystore.WLoginSigs.WtSessionTicketKey,
+ RandomKey = keystore.WLoginSigs.RandomKey,
+ SKey = keystore.WLoginSigs.SKey,
+ PsKey = bytePsKey
+ };
+ }
+
+ public BotKeystore ToKeystoreWithoutFree()
+ {
+ var psKey = new Dictionary();
+ foreach (var kvp in (ByteArrayKVPNative[])PsKey)
+ {
+ psKey[Encoding.UTF8.GetString(kvp.Key)] = Encoding.UTF8.GetString(kvp.Value);
+ }
+
+ return new BotKeystore()
+ {
+ Uin = Uin,
+ Uid = Encoding.UTF8.GetString(Uid.ToByteArrayWithoutFree()),
+ Guid = Guid.ToByteArrayWithoutFree(),
+ AndroidId = Encoding.UTF8.GetString(AndroidId.ToByteArrayWithoutFree()),
+ Qimei = Encoding.UTF8.GetString(Qimei.ToByteArrayWithoutFree()),
+ DeviceName = Encoding.UTF8.GetString(DeviceName.ToByteArrayWithoutFree()),
+ WLoginSigs = new WLoginSigs()
+ {
+ A2 = A2.ToByteArrayWithoutFree(),
+ A2Key = A2Key.ToByteArrayWithoutFree(),
+ D2 = D2.ToByteArrayWithoutFree(),
+ D2Key = D2Key.ToByteArrayWithoutFree(),
+ A1 = A1.ToByteArrayWithoutFree(),
+ A1Key = A1Key.ToByteArrayWithoutFree(),
+ NoPicSig = NoPicSig.ToByteArrayWithoutFree(),
+ TgtgtKey = TgtgtKey.ToByteArrayWithoutFree(),
+ Ksid = Ksid.ToByteArrayWithoutFree(),
+ SuperKey = SuperKey.ToByteArrayWithoutFree(),
+ StKey = StKey.ToByteArrayWithoutFree(),
+ StWeb = StWeb.ToByteArrayWithoutFree(),
+ St = St.ToByteArrayWithoutFree(),
+ WtSessionTicket = WtSessionTicket.ToByteArrayWithoutFree(),
+ WtSessionTicketKey = WtSessionTicketKey.ToByteArrayWithoutFree(),
+ RandomKey = RandomKey.ToByteArrayWithoutFree(),
+ SKey = SKey.ToByteArrayWithoutFree(),
+ PsKey = psKey
+ }
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/BotSignProvider.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/BotSignProvider.cs
new file mode 100644
index 00000000..820ec297
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/BotSignProvider.cs
@@ -0,0 +1,392 @@
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Lagrange.Core.Common;
+using Lagrange.Core.Internal.Packets.Service;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+
+internal class LinuxSignProvider(string? signUrl) : BotSignProvider, IDisposable
+{
+ private const string Tag = nameof(LinuxSignProvider);
+
+ private readonly HttpClient _client = new();
+
+ private string Url => signUrl ?? $"https://sign.lagrangecore.org/api/sign/{Context.AppInfo.AppClientVersion}";
+
+ private static readonly HashSet WhiteListCommand =
+ [
+ "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
+ "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess",
+ "trpc.o3.report.Report.SsoReport",
+ "MessageSvc.PbSendMsg",
+ "wtlogin.trans_emp",
+ "wtlogin.login",
+ "wtlogin.exchange_emp",
+ "trpc.login.ecdh.EcdhService.SsoKeyExchange",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginNewDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshTicket",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshA2",
+ "OidbSvcTrpcTcp.0x11ec_1",
+ "OidbSvcTrpcTcp.0x758_1", // create group
+ "OidbSvcTrpcTcp.0x7c1_1",
+ "OidbSvcTrpcTcp.0x7c2_5", // request friend
+ "OidbSvcTrpcTcp.0x10db_1",
+ "OidbSvcTrpcTcp.0x8a1_7", // request group
+ "OidbSvcTrpcTcp.0x89a_0",
+ "OidbSvcTrpcTcp.0x89a_15",
+ "OidbSvcTrpcTcp.0x88d_0", // fetch group detail
+ "OidbSvcTrpcTcp.0x88d_14",
+ "OidbSvcTrpcTcp.0x112a_1",
+ "OidbSvcTrpcTcp.0x587_74",
+ "OidbSvcTrpcTcp.0x1100_1",
+ "OidbSvcTrpcTcp.0x1102_1",
+ "OidbSvcTrpcTcp.0x1103_1",
+ "OidbSvcTrpcTcp.0x1107_1",
+ "OidbSvcTrpcTcp.0x1105_1",
+ "OidbSvcTrpcTcp.0xf88_1",
+ "OidbSvcTrpcTcp.0xf89_1",
+ "OidbSvcTrpcTcp.0xf57_1",
+ "OidbSvcTrpcTcp.0xf57_106",
+ "OidbSvcTrpcTcp.0xf57_9",
+ "OidbSvcTrpcTcp.0xf55_1",
+ "OidbSvcTrpcTcp.0xf67_1",
+ "OidbSvcTrpcTcp.0xf67_5",
+ "OidbSvcTrpcTcp.0x6d9_4"
+ ];
+
+ public override bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
+
+ public override async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
+ {
+ try
+ {
+ var payload = new JsonObject
+ {
+ ["cmd"] = cmd,
+ ["seq"] = seq,
+ ["src"] = Convert.ToHexString(body.Span),
+ };
+
+ var response = await _client.PostAsync(Url, new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return null;
+
+ var content = JsonHelper.Deserialize(await response.Content.ReadAsStringAsync());
+ if (content == null) return null;
+
+ return new SsoSecureInfo
+ {
+ SecSign = Convert.FromHexString(content.Value.Sign),
+ SecToken = Convert.FromHexString(content.Value.Token),
+ SecExtra = Convert.FromHexString(content.Value.Extra)
+ };
+ }
+ catch (Exception e)
+ {
+ Context.LogWarning(Tag, $"Failed to get sign: {e.Message}");
+ return null;
+ }
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+
+ [Serializable]
+ internal class Root
+ {
+ [JsonPropertyName("value")] public Response Value { get; set; } = new();
+ }
+
+ [Serializable]
+ internal class Response
+ {
+ [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
+
+ [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
+
+ [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
+ }
+}
+
+internal class AndroidSignProvider(string? signUrl) : AndroidBotSignProvider, IDisposable
+{
+ private const string Tag = nameof(AndroidSignProvider);
+
+ private readonly HttpClient _client = new();
+
+ private readonly string _url = signUrl ?? "http://127.0.0.1:8081";
+
+ private static readonly HashSet WhiteListCommand =
+ [
+ "OidbSvcTrpcTcp.0xf88_1", "OidbSvcTrpcTcp.0x1105_1", "oidb_0xf7e_1",
+ "trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg", "OidbSvcTrpcTcp.0x92eb_0", "qzoneh5.h5.wnshtml",
+ "OidbSvc.0x580_1", "trpc.commercial.dataworks.UserActionReport_sso.SsoReport", "OidbSvcTrpcTcp.0xe37_1200",
+ "OidbSvcTrpcTcp.0xf67_5", "OidbSvcTrpcTcp.0x55f_0",
+ "MQUpdateSvc_com_qq_qzone_act.web.OidbSvcTrpcJsapiTcp.0x9377_0",
+ "trpc.down.intercept.Intercept.SsoGetInterceptFile", "wtlogin.device_lock", "qidianservice.207",
+ "SQQzoneSvc.addReply", "ResourceConfig.GetResourceReq", "wtlogin.name2uin",
+ "trpc.passwd.manager.PasswdManager.SetPasswd", "trpc.qqva.vipdata.Vipdata.SsoGetUserData",
+ "OidbSvc.0x8a1_0", "OidbSvcTrpcTcp.0x101e_2", "OidbSvcTrpcTcp.0xf67_1", "trpc.qpay.sso.web.Do",
+ "OidbSvcTrpcTcp.0xf6e_1", "OidbSvcTcp.0x102a", "trpc.o3.ecdh_access.EcdhAccess.SsoSecureA2Access",
+ "OidbSvcTrpcTcp.0x88d_0", "OidbSvcTrpcTcp.0x1258_1", "OidbSvcTrpcTcp.0x11ec_1", "OidbSvcTrpcTcp.0x899_9",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoComment", "SQQzoneSvc.like",
+ "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess", "OidbSvc.0x787_11", "OidbSvcTrpcTcp.0x1100_1",
+ "SQQzoneSvc.Custom.getFacade", "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
+ "ProfileService.Pb.ReqSystemMsgAction.Group", "OidbSvcTrpcTcp.0xf57_1", "OidbSvcTrpcTcp.0x12a9_200",
+ "wtlogin.exchange_emp", "OidbSvc.0x56c_6", "QChannelSvr.trpc.qchannel.commwriter.ComWriter.PublishFeed",
+ "OidbSvcTrpcTcp.0x6d9_4", "trpc.lplan.feed_svr.StatusWrite.SsoPostStatus",
+ "QChannelSvr.trpc.qchannel.commwriter.ComWriter.DoComment", "OidbSvc.0x592_15", "OidbSvc.0x592_8",
+ "OidbSvc.0x5eb_42261", "SummaryCard.ReqSummaryCard", "QQStranger.InteractiveMsgSvr.SsoSendInterMsg",
+ "ProfileService.GroupMngReq", "OidbSvcTrpcTcp.0xf89_1", "OidbSvc.0xe27", "ConnAuthSvr.get_app_info",
+ "qidianservice.135", "OidbSvc.0x5eb_96", "OidbSvc.0x592_5", "trpc.group_pro.msgproxy.sendmsg",
+ "oidb_0x43c_4", "OidbSvc.0x787_0", "ConnAuthSvr.get_app_info_emp", "OidbSvc.0xb3c_1",
+ "QQStranger.login_svr.SsoLoginInfoReport", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoBarrage",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetMainPageCommData", "QQConnectLogin.get_promote_page",
+ "trpc.springfestival.redpacket.LuckyBag.SsoSubmitGrade", "OidbSvc.0xb3c_6", "OidbSvc.0x89b_1",
+ "wtlogin.login", "OidbSvcTrpcTcp.0x7c2_5", "oidb_0xcf3_0", "gcbindgroupsso.get_appid",
+ "SQQzoneSvc.getVisitorNotify", "qidianservice.290", "trpc.qlive.word_svr.WordSvr.NewPublicChat",
+ "wtlogin.register", "OidbSvcTrpcTcp.0xf57_9", "friendlist.GetMultiTroopInfoReq", "StatSvc.GetOnlineStatus",
+ "OidbSvcTrpcTcp.0x10db_1", "OidbSvc.0x9fa", "OidbSvcTrpcTcp.0xe37_800", "qidianservice.269",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetCommentList", "OidbSvcTrpcTcp.0xf65_1",
+ "OidbSvcTrpcTcp.0x9127_1", "QQStranger.FeedPlazaSvr.SsoFeedPublish", "OidbSvc.0xb3c_get_by_id",
+ "OidbSvcTrpcTcp.0x11c5_100", "SQQzoneSvc.mobileqboss.get", "GDCTrpcProxy.down",
+ "trpc.login.ecdh.EcdhService.SsoQRLoginGenQr", "OidbSvcTrpcTcp.0xf59_2", "OidbSvc.0x592_10",
+ "OidbSvcTrpcTcp.0xfe7_3", "OidbSvc.0x592_18", "OidbSvc.0x88d_0", "trpc.qpay.red_pack_skin.Skin.SsoAddSkin",
+ "MsgProxy.SendMsg", "OidbSvcTrpcTcp.0x899_1", "trpc.lplan.user_manager_svr.User.SsoSetProfile",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
+ "QChannelSvr.trpc.qchannel.commwriter.ComWriter.DoReply", "OidbSvc.0x5eb_43",
+ "trpc.passwd.manager.PasswdManager.VerifyPasswd", "OidbSvc.0xb3c_update_5", "OidbSvc.0x592_17",
+ "trpc.login.ecdh.EcdhService.SsoQRLoginScanQr", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoLike",
+ "SQQzoneSvc.getProfileFeeds", "OidbSvc.0x6d6_0", "WalletGestureSvc.GetSignV2", "OidbSvcTrpcTcp.0x88d_14",
+ "friendlist.ModifyGroupInfoReq", "OidbSvc.oidb_0x758", "OidbSvcTrpcTcp.0xf57_106",
+ "QQConnectLogin.submit_promote_page_emp", "OidbSvcTrpcTcp.0x1107_1", "ProfileService.getGroupInfoReq",
+ "OidbSvcTrpcTcp.0x8a1_7", "OidbSvc.0x42d_4", "QQConnectLogin.auth", "OidbSvcTrpcTcp.0x8fc_3",
+ "ConnAuthSvr.get_auth_api_list_emp", "QQConnectLogin.auth_emp", "trpc.o3.report.Report.SsoReport",
+ "ConnAuthSvr.get_auth_api_list", "PushService.settoken", "trpc.lplan.feed_svr.StatusWrite.SsoComment",
+ "trpc.lplan.feed_svr.StatusWrite.SsoReply", "trpc.lplan.like_svr.Like.SsoDoLike", "OidbSvcTrpcTcp.0xf5d_11",
+ "miniapp.trpc.minigame.sdk_qgroup_svr.sdk_qgroup_svr.JoinGroup", "QQStranger.FeedSvr.SsoFeedPublish",
+ "OidbSvcTrpcTcp.0x9176_1", "OidbSvc.0x592_6", "LightAppSvc.mini_app_userapp.GetDropdownAppList",
+ "OidbSvc.0xb3c_add", "OidbSvc.0xb3c_get_undone", "OidbSvc.0x758_0", "OidbSvcTrpcTcp.0x10ed_1",
+ "OidbSvc.0xb3c_get_done", "OidbSvc.0xb3c_update", "OidbSvc.0xc26_0", "SQQzoneSvc.GetCate",
+ "OidbSvc.0xb3c_delete", "OidbSvc.0xb3c_share",
+ "FeedCloudSvr.trpc.videocircle.circleprofile.CircleProfile.SetProfile", "OidbSvc.0xb3c_get_done_count",
+ "OidbSvc.0x592_19", "OidbSvc.0xb3c", "OidbSvcTcp.0x88d_0", "OidbSvc.0xb3c_2",
+ "trpc.qlive.relationchain_svr.RelationchainSvr.Follow", "OidbSvc.0xe72", "OidbSvc.0xb3c_5",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoReply", "OidbSvc.0xb3c_4",
+ "trpc.qqstranger.common_proxy.CommonProxy.SsoHandle", "QQStranger.UserInfo.SsoSetMiniUserInfo",
+ "OidbSvcTrpcTcp.0xfe7_4", "oidb_0xd9c_11", "wtlogin_device.login", "OidbSvc.0x4ff_9", "OidbSvc.0xef0_1",
+ "OidbSvc.0xb3c_7", "OidbSvc.0x4ff_9_IMCore", "OidbSvcTrpcTcp.0x1250_0", "OidbSvcTrpcTcp.0xa80_1",
+ "OidbSvc.0x89a_0", "OidbSvc.0xb3c_8", "OidbSvcTrpcTcp.0x930e_0", "SQQzoneSvc.get", "OidbSvc.0x592",
+ "ConnAuthSvr.sdk_auth_api", "OidbSvc.0xcd5", "oidb_0xcf4_0", "OidbSvcTrpcTcp.0x5cf_11", "OidbSvc.0x899_0",
+ "OidbSvc.0x592_2", "OidbSvcTrpcTcp.0xf65_10", "OidbSvcTrpcTcp.0x92e4_0", "OidbSvc.0x592_7",
+ "ConnAuthSvr.fast_qq_login", "OidbSvc.0x758", "trpc.QQService.CommonLogic.StatusService.SsoGetLikeList",
+ "OidbSvc.0x592_11", "OidbSvc.0x592_12", "wtlogin_device.tran_sim_emp", "MessageSvc.PbGetGroupMsg",
+ "OidbSvc.0x8ba", "account.RequestQueryQQMobileContactsV3", "OidbSvcTrpcTcp.0x758_1",
+ "FeedCloudSvr.trpc.circlesearch.exhibition.ExhibitionSvr.ExhibitionSuggestion",
+ "trpc.msg.msg_svc.MsgService.SsoGetPeerSeq", "SQQzoneSvc.addComment", "WalletGestureSvc.GetPassword",
+ "OidbSvc.0x592_3", "OidbSvcTrpcTcp.0xf55_1", "WalletGestureSvc.SetPassword",
+ "friendlist.GetTroopMemberList", "OidbSvcTrpcTcp.0xfd4_1", "OidbSvcTrpcTcp.0xfa5_1",
+ "OidbSvcTrpcTcp.0x787_1", "trpc.qpay.encryptedtransfer.Encryption.SsoUINEncrypt", "oidb_0xeb1_1",
+ "gcbindgroupsso.unbind_group", "oidb_0xdc2_34", "trpc.qlive.qlive_proxy_svr.TrpcProxy.*", "OidbSvc.0x592_4",
+ "OidbSvcTrpcTcp.0xfe1_2", "SQQzoneSvc.publishmood", "trpc.down.intercept.Intercept.SsoGetDownloadTips",
+ "LightAppSvc.mini_app_cloudstorage.GetUserCloudStorage",
+ "trpc.down.joint_operation_game_intercept.JointOperationGameIntercept.SsoQueryConfig",
+ "GDCTrpcProxy.service", "SQQzoneSvc.forward", "OidbSvc.0x5eb_cn_switch", "OidbSvcTrpcTcp.0x930d_0",
+ "OidbSvc.0x6d7_0", "OidbSvcTrpcTcp.0xcd5", "trpc.o3.ecdh_access.EcdhAccess.SsoSecureA2Establish",
+ "OidbSvcTrpcTcp.0x102a_1", "OidbSvcTrpcTcp.0x89a_0", "trpc.msg.register_proxy.RegisterProxy.PushParams",
+ "QQConnectLogin.get_promote_page_emp", "QQStranger.UserInfo.SsoGetMiniUserInfo", "oidb_0xfd4_1",
+ "QQConnectLogin.submit_promote_page", "oidb_0xe37_800", "OidbSvcTrpcTcp.0x1102_1", "oidb_0x9045_1",
+ "oidb_0x7c4_0", "OidbSvcTrpcTcp.0xfe5_2", "oidb_0x7a2_0", "oidb_0x42e_3",
+ "friendlist.GetTroopAppointRemarkReq", "trpc.lplan.map_svr.Map.SsoReportLocation",
+ "OidbSvcTrpcTcp.0x125b_500", "friendlist.GetLastLoginInfoReq", "friendlist.GetFriendListReq",
+ "oidb_0xe37_1200", "OidbSvcTrpcTcp.0x9124_0", "VisitorSvc.ReqFavorite", "SQQzoneSvc.get_all_feedsphoto_ex",
+ "StatSvc.register", "SQQzoneSvc.getPhotoComment", "oidb_0x7df_3", "SQQzoneSvc.getActiveFeeds",
+ "SQQzoneSvc.preGetPassiveFeeds", "SQQzoneSvc.getAIONewestFeeds", "ResourceConfig.ClientReq",
+ "friendlist.getFriendGroupList", "SQQzoneSvc.photo", "OidbSvc.0xc33_42220",
+ "trpc.qmeta.mob_proxy_svr.MobProxy.SsoHandle", "OidbSvcTrpcTcp.0x102a_0",
+ "QQStranger.UserInfo.SsoBatchGetMiniUserInfo", "ProfileService.SimpleInfo", "PbMessageSvc.PbUnReadMsgSeq",
+ "OidbSvc_device.0x9f5", "OidbSvcTrpcTcp.0xf5d_1", "OidbSvcTcp.0xef0_1", "OidbSvcTrpcTcp.0xf5b_1",
+ "OidbSvcTrpcTcp.0xe37_1700", "OidbSvcTrpcTcp.0x972_6", "OidbSvc.0x758_1",
+ "trpc.g_qqrtc.qq_mav_room_state_read.GetRoomState.SsoGetInfoByUin", "OidbSvcTrpcTcp.0x901f_1",
+ "OidbSvc.0x5eb_99", "OidbSvcTrpcTcp.0x899_0", "OidbSvc.0x6d9_4", "OidbSvc.0x787_1",
+ "OidbSvcTrpcTcp.0x88d_111", "friendlist.addFriend", "OidbSvcTrpcTcp.0x6d9_2", "OidbSvcTrpcTcp.0x6d6_3",
+ "OidbSvcTrpcTcp.0x127a_0", "oidb_0xe61_1", "OidbSvc.0x88d_1_2", "OidbSvc.0x592_1",
+ "OidbSvcTrpcTcp.0x126e_200", "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetFeedList",
+ "OidbSvc.0xe61", "OidbSvcTrpcTcp.0x6d6_2", "OidbSvc.0x53c_2", "SQQzoneSvc.shuoshuo",
+ "OidbSvcTrpcTcp.0x126d_200", "OidbSvcTrpcTcp.0x1225_0", "OidbSvcTrpcTcp.0x11e9_200", "OidbSvc.0x852_48",
+ "OidbSvc.0xbcb", "OidbSvc.0x42d", "OidbSvc.0x515_2", "OidbSvcTrpcTcp.0x11c5_200",
+ "OidbSvcTrpcTcp.0x11c4_200", "trpc.qqhb.qqhb_proxy.Handler.sso_handle", "OidbSvcTrpcTcp.0x11c4_100",
+ "OidbSvc.0x852_35", "OidbSvcTrpcTcp.0x1194_1", "OidbSvcTrpcTcp.0x10c0_1", "OidbSvc.0x88d_7",
+ "OidbSvcTrpcTcp.0x110d_1", "OidbSvcTrpcTcp.0x10f4_1", "friendlist.AddFriendReq", "OidbSvcTrpcTcp.0xfe1",
+ "OidbSvcTrpcTcp.0x902e_1", "OidbSvcTrpcTcp.0x10c0_2", "QSec.AVEng", "SecuritySvc.GetConfig",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoFollow", "group_member_card.get_group_member_card_info",
+ "OidbSvc.0x570_8", "OidbSvc.0xe63_1", "OidbSvcTrpcTcp.0x8f9_14", "OidbSvc.0x7df_3",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetReplyList", "OidbSvc.0x58b", "OidbSvcTrpcTcp.0x9a2_12",
+ "OidbSvcTrpcTcp.0xfe7_2", "OidbSvc.0xe3e", "OidbSvc.0x592_16",
+ "CertifiedAccountSvc.certified_account_read.GetFollowList",
+ "QChannelSvr.trpc.qchannel.commreader.ComReader.BatchGetFeedDetail", "oidb_0x5d0_1", "OidbSvc.0xf7e_1",
+ "OidbSvcTrpcTcp.0x644_1", "oidb_0x43c_5", "OidbSvc.0xbe8", "OidbSvcTrpcTcp.0xfe1_8",
+ "OidbSvcTrpcTcp.0x101e_1", "OidbSvc.0x5d0_1", "OidbSvc.0x8a1_7", "MessageSvc.PbGetRoamMsg", "oidb_0xe8c_0",
+ "OidbSvcTrpcTcp.0x10d8_1", "OidbSvc.0x8a0_0", "OidbSvcTrpcTcp.0xe37_700", "OidbSvc.0x587_normalNightSet",
+ "OidbSvc.0x899_9", "OidbSvc.0x587_123", "QQRTCSvc.RoomManager-GetRoomInfo", "friendlist.GetTroopListReqV2",
+ "OidbSvc.0x592_13", "MessageSvc.PbSendMsg", "wtlogin.qrlogin", "oidb_0x9072_0", "OidbSvc.0x592_9",
+ "OidbSvcTrpcTcp.0x11ea_200", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.PublishFeed",
+ "OidbSvc.0x7a2_0", "OidbSvc.0x8a4", "OidbSvc.0x88d_1", "oidb_0x5d6_21", "oidb_0x5d6_19", "OidbSvc.0x8f1",
+ "OidbSvcTrpcTcp.0x11e9_100", "OidbSvcTrpcTcp.0x1017_1", "OidbSvc.0xb3c_3",
+ "trpc.qpay.midas_order.Order.SsoMakeOrder", "OidbSvcTrpcTcp.0x116c_1", "OidbSvc.0x5eb_ForTheme",
+ "SQQzoneSvc.getPhotoWall", "OidbSvc.0x5eb_22", "OidbSvc.0x5eb_42073", "ConnAuthSvr.sdk_auth_api_emp",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetRelationGroupList", "NowSummaryCard.NearbyMiniCardReq",
+ "OidbSvc.0x5eb_15", "OidbSvcTrpcTcp.0x116d_1", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoPush",
+ "group_member_statistic.get_group_member_statistic", "SQQzoneSvc.getMainPage", "OidbSvc.0x6d6_3",
+ "OidbSvcTrpcTcp.0x1224_0", "QQConnectLogin.pre_auth", "GameCenterMsg.GetUserInfo", "MessageSvc.PbGetMsg",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetBusiInfo", "OidbSvc.0xc6b",
+ "friendlist.GetTroopMemberListReq", "OidbSvc.0x6d6_2", "friendlist.getTroopMemberList",
+ "trpc.down.joint_operation_game_intercept.JointOperationGameIntercept.SsoCheck",
+ "SsoSnsSession.Cmd0x3_SubCmd0x1_FuncGetBlockList", "OidbSvcTrpcTcp.0x1262_19", "OidbSvcTrpcTcp.0x105b_1",
+ "friendlist.GetSimpleOnlineFriendInfoReq", "OidbSvc.0xbbb", "OidbSvcTrpcTcp.0x1130_1",
+ "OidbSvc_device.0x633", "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetRerankedFeedList",
+ "SQQzoneSvc.getProfile", "QQConnectLogin.pre_auth_emp", "OidbSvc.0xcdd", "MessageSvc.PbBindUinGetMsg",
+ "OidbSvc.0x480_9", "AvatarInfoSvr.QQHeadUrlReq", "OidbSvc.0x480_9_IMCore", "OidbSvcTrpcTcp.0x10c8_1",
+ "OidbSvcTcp.0x88d_1", "OidbSvcTrpcTcp.0x1289_1", "LightAppSvc.mini_app_privacy.GetPrivacyInfo",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetMainPageBasicData", "OidbSvc.0x5eb_common",
+ "OidbSvcTrpcTcp.0xaf6_0", "IncreaseURLSvr.QQHeadUrlReq"
+ ];
+
+ public override bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
+
+ public override async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
+ {
+ try
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["cmd"] = cmd,
+ ["seq"] = seq,
+ ["buffer"] = Convert.ToHexString(body.Span),
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["version"] = Context.AppInfo.PtVersion
+ };
+
+ var response = await _client.PostAsync($"{_url}/sign", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return null;
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ if (content == null) return null;
+
+ return new SsoSecureInfo
+ {
+ SecSign = Convert.FromHexString(content.Value.Sign),
+ SecToken = Convert.FromHexString(content.Value.Token),
+ SecExtra = Convert.FromHexString(content.Value.Extra)
+ };
+ }
+ catch (Exception e)
+ {
+ Context.LogWarning(Tag, "Failed to get sign: {0}", e, e.Message);
+ return null;
+ }
+ }
+
+ public override async Task GetEnergy(long uin, string data)
+ {
+ try
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["data"] = data,
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["ver"] = Context.AppInfo.SdkInfo.SdkVersion,
+ ["version"] = Context.AppInfo.PtVersion
+ };
+
+ var response = await _client.PostAsync($"{_url}/energy", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return [];
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ return content == null ? [] : Convert.FromHexString(content.Value);
+ }
+ catch (Exception e)
+ {
+ Context.LogWarning(Tag, "Failed to get energy: {0}", e, e.Message);
+ return [];
+ }
+ }
+
+ public override async Task GetDebugXwid(long uin, string data)
+ {
+ try
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["data"] = data,
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["version"] = Context.AppInfo.PtVersion
+ };
+
+ var response = await _client.PostAsync($"{_url}/get_tlv553", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return [];
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ return content == null ? [] : Convert.FromHexString(content.Value);
+ }
+ catch (Exception e)
+ {
+ Context.LogWarning(Tag, "Failed to get debug_xwid: {0}", e, e.Message);
+ return [];
+ }
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+
+ [Serializable]
+ internal class ResponseRoot
+ {
+ [JsonPropertyName("data")] public T Value { get; set; } = default!;
+ }
+
+ [Serializable]
+ internal class SignResponse
+ {
+ [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
+
+ [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
+
+ [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
+ }
+}
+
+internal static partial class JsonHelper
+{
+ [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Default, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
+
+ [JsonSerializable(typeof(AndroidSignProvider.ResponseRoot))]
+ [JsonSerializable(typeof(AndroidSignProvider.ResponseRoot))]
+ [JsonSerializable(typeof(LinuxSignProvider.Root))]
+ [JsonSerializable(typeof(LinuxSignProvider.Response))]
+
+ [JsonSerializable(typeof(JsonObject))]
+ [JsonSerializable(typeof(LightApp))]
+ private partial class CoreSerializerContext : JsonSerializerContext;
+
+ public static T? Deserialize(string json) where T : class =>
+ JsonSerializer.Deserialize(json, typeof(T), CoreSerializerContext.Default) as T;
+
+ public static string Serialize(T value) =>
+ JsonSerializer.Serialize(value, typeof(T), CoreSerializerContext.Default);
+
+ public static ReadOnlyMemory SerializeToUtf8Bytes(T value) =>
+ JsonSerializer.SerializeToUtf8Bytes(value, typeof(T), CoreSerializerContext.Default);
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayDictNative.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayDictNative.cs
new file mode 100644
index 00000000..13390d19
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayDictNative.cs
@@ -0,0 +1,40 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+
+public struct ByteArrayDictNative
+{
+ public int Length;
+ public IntPtr Data;
+
+ public static implicit operator ByteArrayDictNative(ByteArrayKVPNative[] dict)
+ {
+ int size = Marshal.SizeOf();
+ IntPtr ptr = Marshal.AllocHGlobal(size * dict.Length);
+ for (int i = 0; i < dict.Length; i++)
+ {
+ Marshal.StructureToPtr(dict[i], ptr + i * size, false);
+ }
+
+ return new ByteArrayDictNative { Length = dict.Length, Data = ptr };
+ }
+
+ public static implicit operator ByteArrayKVPNative[](ByteArrayDictNative dict)
+ {
+ if (dict.Data == IntPtr.Zero || dict.Length == 0)
+ {
+ return [];
+ }
+
+ ByteArrayKVPNative[] result = new ByteArrayKVPNative[dict.Length];
+ int size = Marshal.SizeOf();
+ for (int i = 0; i < dict.Length; i++)
+ {
+ result[i] = Marshal.PtrToStructure(dict.Data + i * size);
+ }
+
+ Marshal.FreeHGlobal(dict.Data);
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayKVPNative.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayKVPNative.cs
new file mode 100644
index 00000000..66fcfa6d
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayKVPNative.cs
@@ -0,0 +1,11 @@
+using System.Runtime.InteropServices;
+// ReSharper disable InconsistentNaming
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct ByteArrayKVPNative
+{
+ public ByteArrayNative Key;
+ public ByteArrayNative Value;
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayNative.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayNative.cs
new file mode 100644
index 00000000..71b4a439
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/ByteArrayNative.cs
@@ -0,0 +1,45 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct ByteArrayNative
+ {
+ public int Length;
+ public IntPtr Data;
+
+ public static implicit operator ByteArrayNative(byte[] bytes)
+ {
+ IntPtr ptr = Marshal.AllocHGlobal(bytes.Length);
+ Marshal.Copy(bytes, 0, ptr, bytes.Length);
+
+ return new ByteArrayNative { Length = bytes.Length, Data = ptr };
+ }
+
+ public static implicit operator byte[](ByteArrayNative byteArray)
+ {
+ if (byteArray.Data == IntPtr.Zero)
+ {
+ return [];
+ }
+ byte[] bytes = new byte[byteArray.Length];
+ Marshal.Copy(byteArray.Data, bytes, 0, byteArray.Length);
+
+ Marshal.FreeHGlobal(byteArray.Data);
+
+ return bytes;
+ }
+
+ public byte[] ToByteArrayWithoutFree()
+ {
+ byte[] bytes = new byte[Length];
+ Marshal.Copy(Data, bytes, 0, Length);
+ return bytes;
+ }
+
+ public bool IsEmpty()
+ {
+ return Length == 0 || Data == IntPtr.Zero;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Common/KeyValuePairNative.cs b/Lagrange.Core.NativeAPI/NativeModel/Common/KeyValuePairNative.cs
new file mode 100644
index 00000000..8a9b98d0
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Common/KeyValuePairNative.cs
@@ -0,0 +1,12 @@
+// using System.Runtime.InteropServices;
+//
+// // 这东西疑似用不了,搁置
+// namespace Lagrange.Core.NativeAPI.NativeModel.Common
+// {
+// [StructLayout(LayoutKind.Sequential)]
+// public struct KeyValuePairNative
+// {
+// public T1 Key;
+// public T2 Value;
+// }
+// }
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotCaptchaEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotCaptchaEventStruct.cs
new file mode 100644
index 00000000..4af3c176
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotCaptchaEventStruct.cs
@@ -0,0 +1,26 @@
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ public struct BotCaptchaEventStruct : IEventStruct
+ {
+ public BotCaptchaEventStruct() { }
+
+ public ByteArrayNative CaptchaUrl = new();
+
+ public static implicit operator BotCaptchaEventStruct(BotCaptchaEvent e)
+ {
+ return new BotCaptchaEventStruct()
+ {
+ CaptchaUrl = Encoding.UTF8.GetBytes(e.CaptchaUrl)
+ };
+ }
+
+ public static implicit operator BotCaptchaEvent(BotCaptchaEventStruct e)
+ {
+ return new BotCaptchaEvent(Encoding.UTF8.GetString(e.CaptchaUrl));
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRecallEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRecallEventStruct.cs
new file mode 100644
index 00000000..68c1e4de
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRecallEventStruct.cs
@@ -0,0 +1,32 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotFriendRecallEventStruct : IEventStruct
+ {
+ public BotFriendRecallEventStruct() { }
+
+ public long PeerUin = 0;
+
+ public long AuthorUin = 0;
+
+ public ulong Sequence = 0;
+
+ public ByteArrayNative Tip = new();
+
+ public static implicit operator BotFriendRecallEventStruct(BotFriendRecallEvent e)
+ {
+ return new BotFriendRecallEventStruct()
+ {
+ PeerUin = e.PeerUin,
+ AuthorUin = e.AuthorUin,
+ Sequence = e.Sequence,
+ Tip = Encoding.UTF8.GetBytes(e.Tip)
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRequestEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRequestEventStruct.cs
new file mode 100644
index 00000000..f55d0a67
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotFriendRequestEventStruct.cs
@@ -0,0 +1,40 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotFriendRequestEventStruct : IEventStruct
+ {
+ public BotFriendRequestEventStruct() { }
+
+ public ByteArrayNative InitiatorUid = new();
+
+ public long InitiatorUin = 0;
+
+ public ByteArrayNative Message = new();
+
+ public ByteArrayNative Source = new();
+
+ //public static implicit operator BotGroupMemberDecreaseEvent(BotGroupMemberDecreaseEventStruct e)
+ //{
+ // return new BotGroupMemberDecreaseEvent(
+ // e.GroupUin, e.UserUin, e.OperatorUin
+ // );
+ //}
+
+ public static implicit operator BotFriendRequestEventStruct(BotFriendRequestEvent e)
+ {
+ return new BotFriendRequestEventStruct()
+ {
+ InitiatorUid = Encoding.UTF8.GetBytes(e.InitiatorUid),
+ InitiatorUin = e.InitiatorUin,
+ Message = Encoding.UTF8.GetBytes(e.Message),
+ Source = Encoding.UTF8.GetBytes(e.Source)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupInviteNotificationEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupInviteNotificationEventStruct.cs
new file mode 100644
index 00000000..1a15c81f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupInviteNotificationEventStruct.cs
@@ -0,0 +1,16 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event;
+[StructLayout(LayoutKind.Sequential)]
+public struct BotGroupInviteNotificationEventStruct(BotGroupInviteNotification notification) : IEventStruct
+{
+ public BotGroupInviteNotificationStruct Notification = notification;
+
+ public static implicit operator BotGroupInviteNotificationEventStruct(BotGroupInviteNotificationEvent e)
+ {
+ return new BotGroupInviteNotificationEventStruct(e.Notification);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupJoinNotificationEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupJoinNotificationEventStruct.cs
new file mode 100644
index 00000000..5683f8a8
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupJoinNotificationEventStruct.cs
@@ -0,0 +1,18 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupJoinNotificationEventStruct(BotGroupJoinNotification notification) : IEventStruct
+ {
+ public BotGroupJoinNotificationStruct Notification = notification;
+
+ public static implicit operator BotGroupJoinNotificationEventStruct(BotGroupJoinNotificationEvent e)
+ {
+ return new BotGroupJoinNotificationEventStruct(e.Notification);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberDecreaseEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberDecreaseEventStruct.cs
new file mode 100644
index 00000000..e444b8dd
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberDecreaseEventStruct.cs
@@ -0,0 +1,27 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupMemberDecreaseEventStruct : IEventStruct
+ {
+ public BotGroupMemberDecreaseEventStruct() { }
+
+ public long GroupUin = 0;
+
+ public long UserUin = 0;
+
+ public long OperatorUin = 0;
+
+ public static implicit operator BotGroupMemberDecreaseEventStruct(BotGroupMemberDecreaseEvent e)
+ {
+ return new BotGroupMemberDecreaseEventStruct()
+ {
+ GroupUin = e.GroupUin,
+ UserUin = e.UserUin,
+ OperatorUin = e.OperatorUin ?? 0
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberIncreaseEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberIncreaseEventStruct.cs
new file mode 100644
index 00000000..68d08886
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupMemberIncreaseEventStruct.cs
@@ -0,0 +1,33 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupMemberIncreaseEventStruct : IEventStruct
+ {
+ public BotGroupMemberIncreaseEventStruct() { }
+
+ public long GroupUin = 0;
+
+ public long MemberUin = 0;
+
+ public long InvitorUin = 0;
+
+ public uint Type = 0;
+
+ public long OperatorUin = 0;
+
+ public static implicit operator BotGroupMemberIncreaseEventStruct(BotGroupMemberIncreaseEvent e)
+ {
+ return new BotGroupMemberIncreaseEventStruct()
+ {
+ GroupUin = e.GroupUin,
+ MemberUin = e.MemberUin,
+ InvitorUin = e.InvitorUin,
+ Type = e.Type,
+ OperatorUin = e.OperatorUin
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupNudgeEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupNudgeEventStruct.cs
new file mode 100644
index 00000000..9d7adb13
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupNudgeEventStruct.cs
@@ -0,0 +1,50 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupNudgeEventStruct : IEventStruct
+ {
+ public BotGroupNudgeEventStruct() { }
+
+ public long GroupUin = 0;
+
+ public long OperatorUin = 0;
+
+ public ByteArrayNative Action = new();
+
+ public ByteArrayNative ActionImgUrl = new();
+
+ public long TargetUin = 0;
+
+ public ByteArrayNative Suffix = new();
+
+ public static implicit operator BotGroupNudgeEvent(BotGroupNudgeEventStruct e)
+ {
+ return new BotGroupNudgeEvent(
+ e.GroupUin,
+ e.OperatorUin,
+ Encoding.UTF8.GetString(e.Action),
+ Encoding.UTF8.GetString(e.ActionImgUrl),
+ e.TargetUin,
+ Encoding.UTF8.GetString(e.Suffix)
+ );
+ }
+
+ public static implicit operator BotGroupNudgeEventStruct(BotGroupNudgeEvent e)
+ {
+ return new BotGroupNudgeEventStruct()
+ {
+ GroupUin = e.GroupUin,
+ OperatorUin = e.OperatorUin,
+ Action = Encoding.UTF8.GetBytes(e.Action),
+ ActionImgUrl = Encoding.UTF8.GetBytes(e.ActionImageUrl),
+ TargetUin = e.TargetUin,
+ Suffix = Encoding.UTF8.GetBytes(e.Suffix)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupReactionEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupReactionEventStruct.cs
new file mode 100644
index 00000000..aef6ae42
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupReactionEventStruct.cs
@@ -0,0 +1,38 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupReactionEventStruct : IEventStruct
+ {
+ public BotGroupReactionEventStruct() { }
+
+ public long TargetGroupUin = 0;
+
+ public ulong TargetSequence = 0;
+
+ public long OperatorUin = 0;
+
+ public bool IsAdd = false;
+
+ public ByteArrayNative Code = new();
+
+ public ulong CurrentCount = 0;
+
+ public static implicit operator BotGroupReactionEventStruct(BotGroupReactionEvent e)
+ {
+ return new BotGroupReactionEventStruct()
+ {
+ TargetGroupUin = e.TargetGroupUin,
+ TargetSequence = e.TargetSequence,
+ OperatorUin = e.OperatorUin,
+ IsAdd = e.IsAdd,
+ Code = Encoding.UTF8.GetBytes(e.Code),
+ CurrentCount = e.CurrentCount
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupRecallEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupRecallEventStruct.cs
new file mode 100644
index 00000000..c6e8843c
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotGroupRecallEventStruct.cs
@@ -0,0 +1,35 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupRecallEventStruct : IEventStruct
+ {
+ public BotGroupRecallEventStruct() { }
+
+ public long GroupUin = 0;
+
+ public ulong Sequence = 0;
+
+ public long AuthorUin = 0;
+
+ public long OperatorUin = 0;
+
+ public ByteArrayNative Tip = new();
+
+ public static implicit operator BotGroupRecallEventStruct(BotGroupRecallEvent e)
+ {
+ return new BotGroupRecallEventStruct()
+ {
+ GroupUin = e.GroupUin,
+ Sequence = e.Sequence,
+ AuthorUin = e.AuthorUin,
+ OperatorUin = e.OperatorUin,
+ Tip = Encoding.UTF8.GetBytes(e.Tip)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotLogEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotLogEventStruct.cs
new file mode 100644
index 00000000..5a60ff54
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotLogEventStruct.cs
@@ -0,0 +1,37 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotLogEventStruct : IEventStruct
+ {
+ public BotLogEventStruct() { }
+
+ public int Level = 0;
+ public ByteArrayNative Tag = new();
+ public ByteArrayNative Message = new();
+
+ public static implicit operator BotLogEventStruct(BotLogEvent e)
+ {
+ return new BotLogEventStruct()
+ {
+ Level = (int)e.Level,
+ Tag = Encoding.UTF8.GetBytes(e.Tag),
+ Message = Encoding.UTF8.GetBytes(e.Message)
+ };
+ }
+
+ public static implicit operator BotLogEvent(BotLogEventStruct e)
+ {
+ return new BotLogEvent(
+ Encoding.UTF8.GetString(e.Tag),
+ (LogLevel)e.Level,
+ Encoding.UTF8.GetString(e.Message),
+ null // TODO: Handle exception if needed
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotLoginEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotLoginEventStruct.cs
new file mode 100644
index 00000000..962b42d1
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotLoginEventStruct.cs
@@ -0,0 +1,34 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotLoginEventStruct : IEventStruct
+ {
+ public BotLoginEventStruct() { }
+ public int State = 0;
+ public ByteArrayNative Tag = new();
+ public ByteArrayNative Message = new();
+
+ public static implicit operator BotLoginEvent(BotLoginEventStruct e)
+ {
+ return new BotLoginEvent(
+ e.State,
+ (Encoding.UTF8.GetString(e.Tag), Encoding.UTF8.GetString(e.Message))
+ );
+ }
+
+ public static implicit operator BotLoginEventStruct(BotLoginEvent e)
+ {
+ return new BotLoginEventStruct()
+ {
+ State = e.State,
+ Tag = Encoding.UTF8.GetBytes(e.Error?.Tag ?? string.Empty),
+ Message = Encoding.UTF8.GetBytes(e.Error?.Message ?? string.Empty)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotMessageEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotMessageEventStruct.cs
new file mode 100644
index 00000000..25f11f79
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotMessageEventStruct.cs
@@ -0,0 +1,29 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.NativeAPI.NativeModel.Message;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotMessageEventStruct : IEventStruct
+ {
+ public BotMessageEventStruct() { }
+
+ public BotMessageStruct Message = new();
+
+ // 懒得写了,没意义
+ // public static BotMessageEvent ToEvent(this BotMessageEventStruct e)
+ // {
+ // return new BotMessageEvent(
+ // e.Message.ToMessage(),
+ // Encoding.UTF8.GetString(e.RawMessage)
+ // );
+ // }
+
+ public static implicit operator BotMessageEventStruct(BotMessageEvent e)
+ {
+ return new BotMessageEventStruct() { Message = e.Message };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotNewDeviceVerifyEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotNewDeviceVerifyEventStruct.cs
new file mode 100644
index 00000000..d79829d2
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotNewDeviceVerifyEventStruct.cs
@@ -0,0 +1,25 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotNewDeviceVerifyEventStruct : IEventStruct
+ {
+ public BotNewDeviceVerifyEventStruct() { }
+
+ public ByteArrayNative Url = new();
+
+ public static implicit operator BotNewDeviceVerifyEvent(BotNewDeviceVerifyEventStruct e)
+ {
+ return new BotNewDeviceVerifyEvent(Encoding.UTF8.GetString(e.Url));
+ }
+
+ public static implicit operator BotNewDeviceVerifyEventStruct(BotNewDeviceVerifyEvent e)
+ {
+ return new BotNewDeviceVerifyEventStruct() { Url = Encoding.UTF8.GetBytes(e.Url) };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotOfflineEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotOfflineEventStruct.cs
new file mode 100644
index 00000000..af777935
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotOfflineEventStruct.cs
@@ -0,0 +1,36 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotOfflineEventStruct : IEventStruct
+ {
+ public BotOfflineEventStruct() { }
+
+ public int Reason = 0;
+
+ ByteArrayNative Tag = new();
+
+ ByteArrayNative Message = new();
+
+ public static implicit operator BotOfflineEvent(BotOfflineEventStruct e)
+ {
+ return new BotOfflineEvent((BotOfflineEvent.Reasons)e.Reason, (
+ Encoding.UTF8.GetString(e.Tag), Encoding.UTF8.GetString(e.Message)
+ ));
+ }
+
+ public static implicit operator BotOfflineEventStruct(BotOfflineEvent e)
+ {
+ return new BotOfflineEventStruct()
+ {
+ Reason = (int)e.Reason,
+ Tag = Encoding.UTF8.GetBytes(e.Tips?.Tag ?? ""),
+ Message = Encoding.UTF8.GetBytes(e.Tips?.Message ?? ""),
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotOnlineEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotOnlineEventStruct.cs
new file mode 100644
index 00000000..f8748d99
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotOnlineEventStruct.cs
@@ -0,0 +1,23 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotOnlineEventStruct : IEventStruct
+ {
+ public BotOnlineEventStruct() { }
+
+ public int Reason = 0;
+
+ public static implicit operator BotOnlineEvent(BotOnlineEventStruct e)
+ {
+ return new BotOnlineEvent((BotOnlineEvent.Reasons)e.Reason);
+ }
+
+ public static implicit operator BotOnlineEventStruct(BotOnlineEvent e)
+ {
+ return new BotOnlineEventStruct() { Reason = (int)e.Reason };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeEventStruct.cs
new file mode 100644
index 00000000..4bb9d8e0
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeEventStruct.cs
@@ -0,0 +1,31 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotQrCodeEventStruct : IEventStruct
+ {
+ public BotQrCodeEventStruct() { }
+
+ public ByteArrayNative Url = new();
+
+ public ByteArrayNative Image = new();
+
+ public static implicit operator BotQrCodeEvent(BotQrCodeEventStruct e)
+ {
+ return new BotQrCodeEvent(Encoding.UTF8.GetString(e.Url), e.Image);
+ }
+
+ public static implicit operator BotQrCodeEventStruct(BotQrCodeEvent e)
+ {
+ return new BotQrCodeEventStruct()
+ {
+ Url = Encoding.UTF8.GetBytes(e.Url),
+ Image = e.Image
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeQueryEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeQueryEventStruct.cs
new file mode 100644
index 00000000..d49cf93a
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotQrCodeQueryEventStruct.cs
@@ -0,0 +1,23 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotQrCodeQueryEventStruct : IEventStruct
+ {
+ public BotQrCodeQueryEventStruct() { }
+
+ public byte State = 0;
+
+ public static implicit operator BotQrCodeQueryEvent(BotQrCodeQueryEventStruct e)
+ {
+ return new BotQrCodeQueryEvent((BotQrCodeQueryEvent.TransEmpState)e.State);
+ }
+
+ public static implicit operator BotQrCodeQueryEventStruct(BotQrCodeQueryEvent e)
+ {
+ return new BotQrCodeQueryEventStruct { State = (byte)e.State };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotRefreshKeystoreEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotRefreshKeystoreEventStruct.cs
new file mode 100644
index 00000000..6b91e450
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotRefreshKeystoreEventStruct.cs
@@ -0,0 +1,24 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotRefreshKeystoreEventStruct : IEventStruct
+ {
+ public BotRefreshKeystoreEventStruct() { }
+
+ public BotKeystoreStruct Keystore = new();
+
+ public static implicit operator BotRefreshKeystoreEvent(BotRefreshKeystoreEventStruct e)
+ {
+ return new BotRefreshKeystoreEvent(e.Keystore);
+ }
+
+ public static implicit operator BotRefreshKeystoreEventStruct(BotRefreshKeystoreEvent e)
+ {
+ return new BotRefreshKeystoreEventStruct() { Keystore = e.Keystore };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/BotSMSEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/BotSMSEventStruct.cs
new file mode 100644
index 00000000..de4ec638
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/BotSMSEventStruct.cs
@@ -0,0 +1,34 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotSMSEventStruct : IEventStruct
+ {
+ public BotSMSEventStruct() { }
+
+ public ByteArrayNative Url = new();
+
+ public ByteArrayNative Phone = new();
+
+ public static implicit operator BotSMSEvent(BotSMSEventStruct e)
+ {
+ return new BotSMSEvent(
+ Encoding.UTF8.GetString(e.Url),
+ Encoding.UTF8.GetString(e.Phone)
+ );
+ }
+
+ public static implicit operator BotSMSEventStruct(BotSMSEvent e)
+ {
+ return new BotSMSEventStruct()
+ {
+ Url = Encoding.UTF8.GetBytes(e.Url ?? string.Empty),
+ Phone = Encoding.UTF8.GetBytes(e.Phone)
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/EventArrayStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/EventArrayStruct.cs
new file mode 100644
index 00000000..fb908c55
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/EventArrayStruct.cs
@@ -0,0 +1,10 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct EventArrayStruct
+{
+ public IntPtr Events;
+ public int Count;
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/IEventStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/IEventStruct.cs
new file mode 100644
index 00000000..3d9b3968
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/IEventStruct.cs
@@ -0,0 +1,6 @@
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ public interface IEventStruct
+ {
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Event/ReverseEventCountStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Event/ReverseEventCountStruct.cs
new file mode 100644
index 00000000..d0335621
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Event/ReverseEventCountStruct.cs
@@ -0,0 +1,31 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Event
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct ReverseEventCountStruct
+ {
+ public ReverseEventCountStruct() { }
+
+ public int BotCaptchaEventCount = 0;
+ public int BotFriendRequestEventCount = 0;
+ public int BotFriendRecallEventCount = 0;
+ public int BotGroupInviteNotificationEventCount = 0;
+ public int BotGroupInviteSelfEventCount = 0;
+ public int BotGroupJoinNotificationEventCount = 0;
+ public int BotGroupMemberDecreaseEventCount = 0;
+ public int BotGroupMemberIncreaseEventCount = 0;
+ public int BotGroupNudgeEventCount = 0;
+ public int BotGroupReactionEventCount = 0;
+ public int BotGroupRecallEventCount = 0;
+ public int BotLoginEventCount = 0;
+ public int BotLogEventCount = 0;
+ public int BotMessageEventCount = 0;
+ public int BotNewDeviceVerifyEventCount = 0;
+ public int BotOnlineEventCount = 0;
+ public int BotQrCodeEventCount = 0;
+ public int BotQrCodeQueryEventCount = 0;
+ public int BotRefreshKeystoreEventCount = 0;
+ public int BotSMSEventCount = 0;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/BotFriendStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/BotFriendStruct.cs
new file mode 100644
index 00000000..609b1a9b
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/BotFriendStruct.cs
@@ -0,0 +1,62 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotFriendStruct
+ {
+ public BotFriendStruct() { }
+
+ public long Uin = 0;
+
+ public ByteArrayNative Nickname = new();
+
+ public ByteArrayNative Uid = new();
+
+ public int Age = 0;
+
+ public int Gender = 0;
+
+ public ByteArrayNative Remarks = new();
+
+ public ByteArrayNative PersonalSign = new();
+
+ public ByteArrayNative Qid = new();
+
+ public BotFriendCategoryStruct Category = new();
+
+ public static implicit operator BotFriend(BotFriendStruct friend)
+ {
+ return new BotFriend(
+ friend.Uin,
+ Encoding.UTF8.GetString(friend.Nickname),
+ Encoding.UTF8.GetString(friend.Uid),
+ Encoding.UTF8.GetString(friend.Remarks),
+ Encoding.UTF8.GetString(friend.PersonalSign),
+ Encoding.UTF8.GetString(friend.Qid),
+ friend.Category
+ );
+ }
+
+ public static implicit operator BotFriendStruct(BotFriend friend)
+ {
+ return new BotFriendStruct()
+ {
+ Uin = friend.Uin,
+ Nickname = Encoding.UTF8.GetBytes(friend.Nickname),
+ Uid = Encoding.UTF8.GetBytes(friend.Uid),
+ Age = friend.Age,
+ Gender = (int)friend.Gender,
+ Remarks = Encoding.UTF8.GetBytes(friend.Remarks),
+ PersonalSign = Encoding.UTF8.GetBytes(friend.PersonalSign),
+ Qid = Encoding.UTF8.GetBytes(friend.Qid),
+ Category = friend.Category
+ };
+ }
+
+
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupMemberStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupMemberStruct.cs
new file mode 100644
index 00000000..57e3076a
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupMemberStruct.cs
@@ -0,0 +1,90 @@
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupMemberStruct
+ {
+ public BotGroupMemberStruct() { }
+
+ public BotGroupStruct BotGroup = new();
+
+ public long Uin = 0;
+
+ public ByteArrayNative Uid = new();
+
+ public ByteArrayNative Nickname = new();
+
+ public int Age = 0;
+
+ public int Gender = 0;
+
+ public int Permission = 0;
+
+ public int GroupLevel = 0;
+
+ public ByteArrayNative MemberCard = new();
+
+ public ByteArrayNative SpecialTitle = new();
+
+ public ByteArrayNative JoinTime = new();
+
+ public ByteArrayNative LastMsgTime = new();
+
+ public ByteArrayNative ShutUpTimestamp = new();
+
+
+ public static implicit operator BotGroupMember(BotGroupMemberStruct member)
+ {
+ return new BotGroupMember(
+ member.BotGroup,
+ member.Uin,
+ Encoding.UTF8.GetString(member.Uid),
+ Encoding.UTF8.GetString(member.Nickname),
+ (GroupMemberPermission)member.Permission,
+ member.GroupLevel,
+ Encoding.UTF8.GetString(member.MemberCard),
+ Encoding.UTF8.GetString(member.SpecialTitle),
+ DateTime.ParseExact(
+ Encoding.UTF8.GetString(member.JoinTime),
+ "O",
+ CultureInfo.InvariantCulture
+ ),
+ DateTime.ParseExact(
+ Encoding.UTF8.GetString(member.LastMsgTime),
+ "O",
+ CultureInfo.InvariantCulture
+ ),
+ DateTime.ParseExact(
+ Encoding.UTF8.GetString(member.ShutUpTimestamp),
+ "O",
+ CultureInfo.InvariantCulture
+ )
+ );
+ }
+
+ public static implicit operator BotGroupMemberStruct(BotGroupMember member)
+ {
+ return new BotGroupMemberStruct()
+ {
+ BotGroup = member.Group,
+ Uin = member.Uin,
+ Uid = Encoding.UTF8.GetBytes(member.Uid),
+ Nickname = Encoding.UTF8.GetBytes(member.Nickname),
+ Age = member.Age,
+ Gender = (int)member.Gender,
+ Permission = (int)member.Permission,
+ GroupLevel = member.GroupLevel,
+ MemberCard = Encoding.UTF8.GetBytes(member.MemberCard ?? string.Empty),
+ SpecialTitle = Encoding.UTF8.GetBytes(member.SpecialTitle ?? string.Empty),
+ JoinTime = Encoding.UTF8.GetBytes(member.JoinTime.ToString("O")),
+ LastMsgTime = Encoding.UTF8.GetBytes(member.LastMsgTime.ToString("O")),
+ ShutUpTimestamp = Encoding.UTF8.GetBytes(member.ShutUpTimestamp.ToString("O"))
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupStruct.cs
new file mode 100644
index 00000000..397eab60
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/BotGroupStruct.cs
@@ -0,0 +1,60 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotGroupStruct
+ {
+ public BotGroupStruct() { }
+
+ public long GroupUin = 0;
+
+ public ByteArrayNative GroupName = new();
+
+ public int MemberCount = 0;
+
+ public int MaxMember = 0;
+
+ public long CreateTime = 0;
+
+ public ByteArrayNative Description = new();
+
+ public ByteArrayNative Question = new();
+
+ public ByteArrayNative Announcement = new();
+
+ public static implicit operator BotGroup(BotGroupStruct group)
+ {
+ return new BotGroup(
+ group.GroupUin,
+ Encoding.UTF8.GetString(group.GroupName),
+ group.MemberCount,
+ group.MaxMember,
+ group.CreateTime,
+ Encoding.UTF8.GetString(group.Description),
+ Encoding.UTF8.GetString(group.Question),
+ Encoding.UTF8.GetString(group.Announcement)
+ );
+ }
+
+ public static implicit operator BotGroupStruct(BotGroup group)
+ {
+ return new BotGroupStruct()
+ {
+ GroupUin = group.GroupUin,
+ GroupName = Encoding.UTF8.GetBytes(group.GroupName),
+ MemberCount = group.MemberCount,
+ MaxMember = group.MaxMember,
+ CreateTime = group.CreateTime,
+ Description = Encoding.UTF8.GetBytes(group.Description ?? string.Empty),
+ Question = Encoding.UTF8.GetBytes(group.Question ?? string.Empty),
+ Announcement = Encoding.UTF8.GetBytes(group.Announcement ?? string.Empty)
+ };
+ }
+
+
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/BotMessageStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/BotMessageStruct.cs
new file mode 100644
index 00000000..bb07fb37
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/BotMessageStruct.cs
@@ -0,0 +1,174 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Message;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.NativeAPI.NativeModel.Message.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotMessageStruct
+ {
+ public BotMessageStruct() { }
+
+ //需要手动释放
+ public IntPtr Contact = IntPtr.Zero;
+ public IntPtr Receiver = IntPtr.Zero;
+
+ public BotGroupStruct Group = new();
+
+ public int Type = 0;
+
+ public ByteArrayNative Time = new();
+
+ public IntPtr Entities = IntPtr.Zero;
+
+ public int EntityLength = 0;
+
+ public ulong Sequence = 0;
+
+ public ulong ClientSequence = 0;
+
+ public static implicit operator BotMessageStruct(BotMessage message)
+ {
+ int type = 0;
+ IntPtr contact = IntPtr.Zero;
+ IntPtr receiver = IntPtr.Zero;
+ switch (message.Type)
+ {
+ case MessageType.Group:
+ type = (int)MessageType.Group;
+ contact = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotGroupMemberStruct)(BotGroupMember)message.Contact, contact, false);
+
+ switch (message.Receiver)
+ {
+ case BotGroup group:
+ receiver = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotGroupStruct)group, receiver, false);
+ break;
+ case BotGroupMember member:
+ receiver = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotGroupMemberStruct)member, receiver, false);
+ break;
+ }
+
+ break;
+ case MessageType.Private:
+ type = (int)MessageType.Private;
+ contact = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotFriendStruct)(BotFriend)message.Contact, contact, false);
+ receiver = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotFriendStruct)(BotFriend)message.Receiver, receiver, false);
+ break;
+ case MessageType.Temp:
+ type = (int)MessageType.Temp;
+ contact = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotStrangerStruct)(BotStranger)message.Contact, contact, false);
+ receiver = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotStrangerStruct)(BotStranger)message.Receiver, receiver, false);
+ break;
+ }
+
+ TypedEntityStruct[] entities = new TypedEntityStruct[message.Entities.Count];
+ for (int i = 0; i < message.Entities.Count; i++)
+ {
+ switch (message.Entities[i])
+ {
+ case ImageEntity imageEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.ImageEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((ImageEntityStruct)imageEntity, entities[i].Entity, false);
+ break;
+ case MentionEntity mentionEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.MentionEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((MentionEntityStruct)mentionEntity, entities[i].Entity, false);
+ break;
+ case RecordEntity recordEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.RecordEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((RecordEntityStruct)recordEntity, entities[i].Entity, false);
+ break;
+ case ReplyEntity replyEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.ReplyEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((ReplyEntityStruct)replyEntity, entities[i].Entity, false);
+ break;
+ case TextEntity textEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.TextEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((TextEntityStruct)textEntity, entities[i].Entity, false);
+ break;
+ case VideoEntity videoEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.VideoEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((VideoEntityStruct)videoEntity, entities[i].Entity, false);
+ break;
+ case MultiMsgEntity multiMsgEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.MultiMsgEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((MultiMsgEntityStruct)multiMsgEntity, entities[i].Entity, false);
+ break;
+ case GroupFileEntity groupFileEntity:
+ entities[i] = new TypedEntityStruct()
+ {
+ Type = (int)EntityType.GroupFileEntity,
+ Entity = Marshal.AllocHGlobal(Marshal.SizeOf())
+ };
+ Marshal.StructureToPtr((GroupFileEntityStruct)groupFileEntity, entities[i].Entity, false);
+ break;
+ }
+ }
+
+ int entitiesLength = entities.Length;
+ IntPtr entitiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf() * entitiesLength);
+ for (int i = 0; i < entitiesLength; i++)
+ {
+ IntPtr entityPtr = entitiesPtr + i * Marshal.SizeOf();
+ Marshal.StructureToPtr(entities[i], entityPtr, false);
+ }
+
+ return new BotMessageStruct()
+ {
+ Contact = contact,
+ Receiver = receiver,
+ Group = message.Receiver switch
+ {
+ BotGroup group => (BotGroupStruct)group,
+ BotGroupMember member => member.Group,
+ _ => new BotGroupStruct(),
+ },
+ Type = type,
+ Time = Encoding.UTF8.GetBytes(message.Time.ToString("O")),
+ Entities = entitiesPtr,
+ EntityLength = entitiesLength,
+ Sequence = message.Sequence,
+ ClientSequence = message.ClientSequence
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/BotStrangerStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/BotStrangerStruct.cs
new file mode 100644
index 00000000..10e933fe
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/BotStrangerStruct.cs
@@ -0,0 +1,70 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BotStrangerStruct
+ {
+ public BotStrangerStruct() { }
+ public long Uin = 0;
+ public ByteArrayNative Nickname = new();
+ public ByteArrayNative Uid = new();
+ public ByteArrayNative PersonalSign = new();
+ public ByteArrayNative Remark = new();
+ public ulong Level = 0;
+ public int Gender = 0;
+ public long RegistrationTime = 0;
+ public long Birthday = 0;
+ public ulong Age = 0;
+ public ByteArrayNative QID = new();
+ public long Source = 0;
+ public ByteArrayNative Country = new();
+ public ByteArrayNative City = new();
+ public ByteArrayNative School = new();
+
+ public static implicit operator BotStranger(BotStrangerStruct stranger)
+ {
+ return new BotStranger(
+ stranger.Uin,
+ Encoding.UTF8.GetString(stranger.Nickname),
+ Encoding.UTF8.GetString(stranger.Uid),
+ Encoding.UTF8.GetString(stranger.PersonalSign),
+ Encoding.UTF8.GetString(stranger.Remark),
+ stranger.Level,
+ (BotGender)stranger.Gender,
+ DateTimeOffset.FromUnixTimeSeconds(stranger.RegistrationTime).LocalDateTime,
+ DateTimeOffset.FromUnixTimeSeconds(stranger.Birthday).LocalDateTime,
+ stranger.Age,
+ Encoding.UTF8.GetString(stranger.QID),
+ Encoding.UTF8.GetString(stranger.Country),
+ Encoding.UTF8.GetString(stranger.City),
+ Encoding.UTF8.GetString(stranger.School)
+ );
+ }
+
+ public static implicit operator BotStrangerStruct(BotStranger stranger)
+ {
+ return new BotStrangerStruct()
+ {
+ Uin = stranger.Uin,
+ Nickname = Encoding.UTF8.GetBytes(stranger.Nickname),
+ Uid = Encoding.UTF8.GetBytes(stranger.Uid),
+ PersonalSign = Encoding.UTF8.GetBytes(stranger.PersonalSign),
+ Remark = Encoding.UTF8.GetBytes(stranger.Remark),
+ Level = stranger.Level,
+ Gender = (int)stranger.Gender,
+ RegistrationTime = new DateTimeOffset(stranger.RegistrationTime).ToUnixTimeSeconds(),
+ Birthday = new DateTimeOffset(stranger.Birthday ?? new()).ToUnixTimeSeconds(),
+ Age = stranger.Age,
+ QID = Encoding.UTF8.GetBytes(stranger.QID),
+ Country = Encoding.UTF8.GetBytes(stranger.Country),
+ City = Encoding.UTF8.GetBytes(stranger.City),
+ School = Encoding.UTF8.GetBytes(stranger.School ?? string.Empty)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/EntityType.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/EntityType.cs
new file mode 100644
index 00000000..9e6e4c3f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/EntityType.cs
@@ -0,0 +1,14 @@
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ public enum EntityType
+ {
+ ImageEntity = 0,
+ MentionEntity = 1,
+ RecordEntity = 2,
+ ReplyEntity = 3,
+ VideoEntity = 4,
+ TextEntity = 5,
+ MultiMsgEntity = 6,
+ GroupFileEntity = 7,
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/GroupFileEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/GroupFileEntityStruct.cs
new file mode 100644
index 00000000..de97f28f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/GroupFileEntityStruct.cs
@@ -0,0 +1,35 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct GroupFileEntityStruct : IEntityStruct
+ {
+ public GroupFileEntityStruct() { }
+
+ public ByteArrayNative FileId = new();
+
+ public ByteArrayNative FileName = new();
+
+ public long FileSize = 0;
+
+ public ByteArrayNative FileMd5 = new();
+
+ public ByteArrayNative FileUrl = new();
+
+ public static implicit operator GroupFileEntityStruct(GroupFileEntity entity)
+ {
+ return new GroupFileEntityStruct()
+ {
+ FileId = Encoding.UTF8.GetBytes(entity.FileId),
+ FileName = Encoding.UTF8.GetBytes(entity.FileName),
+ FileSize = entity.FileSize,
+ FileMd5 = Encoding.UTF8.GetBytes(entity.FileMd5),
+ FileUrl = Encoding.UTF8.GetBytes(entity.FileUrl),
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/IEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/IEntityStruct.cs
new file mode 100644
index 00000000..cf7802a8
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/IEntityStruct.cs
@@ -0,0 +1,4 @@
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ public interface IEntityStruct;
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ImageEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ImageEntityStruct.cs
new file mode 100644
index 00000000..0840fb74
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ImageEntityStruct.cs
@@ -0,0 +1,49 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct ImageEntityStruct : IEntityStruct
+ {
+ public ImageEntityStruct() { }
+
+ public ByteArrayNative FileUrl = new();
+
+ public ByteArrayNative FileName = new();
+
+ public ByteArrayNative FileSha1 = new();
+
+ public uint FileSize = 0;
+
+ public ByteArrayNative FileMd5 = new();
+
+ public float ImageWidth = 0;
+
+ public float ImageHeight = 0;
+
+ public int SubType = 0;
+
+ public ByteArrayNative Summary = new();
+
+ public uint RecordLength = 0;
+
+ public static implicit operator ImageEntityStruct(ImageEntity entity)
+ {
+ return new ImageEntityStruct()
+ {
+ FileUrl = Encoding.UTF8.GetBytes(entity.FileUrl),
+ FileName = Encoding.UTF8.GetBytes(entity.FileName),
+ FileSha1 = Encoding.UTF8.GetBytes(entity.FileSha1),
+ FileSize = entity.FileSize,
+ FileMd5 = Encoding.UTF8.GetBytes(entity.FileMd5),
+ ImageWidth = entity.ImageSize.X,
+ ImageHeight = entity.ImageSize.Y,
+ SubType = entity.SubType,
+ Summary = Encoding.UTF8.GetBytes(entity.Summary)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MentionEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MentionEntityStruct.cs
new file mode 100644
index 00000000..ac21579b
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MentionEntityStruct.cs
@@ -0,0 +1,25 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct MentionEntityStruct : IEntityStruct
+ {
+ public MentionEntityStruct() { }
+
+ public long Uin = 0;
+ public ByteArrayNative Display = new();
+
+ public static implicit operator MentionEntityStruct(MentionEntity entity)
+ {
+ return new MentionEntityStruct()
+ {
+ Uin = entity.Uin,
+ Display = Encoding.UTF8.GetBytes(entity.Display ?? string.Empty)
+ };
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MultiMsgEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MultiMsgEntityStruct.cs
new file mode 100644
index 00000000..f35a4dff
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/MultiMsgEntityStruct.cs
@@ -0,0 +1,40 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct MultiMsgEntityStruct
+{
+ public MultiMsgEntityStruct() { }
+
+ public IntPtr Messages;
+
+ public int MessageCount;
+
+ public ByteArrayNative ResId;
+
+ public static implicit operator MultiMsgEntityStruct(Lagrange.Core.Message.Entities.MultiMsgEntity entity)
+ {
+ var messagesStructs = entity.Messages
+ .Select(m => (BotMessageStruct)m)
+ .ToArray();
+
+ IntPtr messagesPtr = Marshal.AllocHGlobal(Marshal.SizeOf() * messagesStructs.Length);
+
+ for (int i = 0; i < messagesStructs.Length; i++)
+ {
+ Marshal.StructureToPtr(messagesStructs[i], messagesPtr + i * Marshal.SizeOf(), false);
+ }
+
+ return new MultiMsgEntityStruct
+ {
+ Messages = messagesPtr,
+ MessageCount = messagesStructs.Length,
+ ResId = entity.ResId != null
+ ? Encoding.UTF8.GetBytes(entity.ResId)
+ : []
+ };
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/RecordEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/RecordEntityStruct.cs
new file mode 100644
index 00000000..69c59a26
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/RecordEntityStruct.cs
@@ -0,0 +1,34 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct RecordEntityStruct : IEntityStruct
+ {
+ public RecordEntityStruct() { }
+ public ByteArrayNative FileUrl = new();
+
+ public ByteArrayNative FileName = new();
+
+ public ByteArrayNative FileSha1 = new();
+
+ public uint FileSize = 0;
+
+ public ByteArrayNative FileMd5 = new();
+
+ public static implicit operator RecordEntityStruct(RecordEntity entity)
+ {
+ return new RecordEntityStruct()
+ {
+ FileUrl = Encoding.UTF8.GetBytes(entity.FileUrl),
+ FileName = Encoding.UTF8.GetBytes(entity.FileName),
+ FileSha1 = Encoding.UTF8.GetBytes(entity.FileSha1),
+ FileSize = entity.FileSize,
+ FileMd5 = Encoding.UTF8.GetBytes(entity.FileMd5)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ReplyEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ReplyEntityStruct.cs
new file mode 100644
index 00000000..6f515b5e
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/ReplyEntityStruct.cs
@@ -0,0 +1,57 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Message.Entities;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct ReplyEntityStruct
+ {
+ public ReplyEntityStruct() { }
+
+ public ulong SrcUid;
+
+ public ulong SrcSequence;
+
+ public IntPtr Source;
+
+ public int SourceType;
+
+ public static implicit operator ReplyEntityStruct(ReplyEntity entity)
+ {
+ var type = entity.Source switch
+ {
+ BotFriend => 1,
+ BotGroupMember => 2,
+ BotStranger => 3,
+ _ => 0
+ };
+
+ var sourcePtr = type switch
+ {
+ 1 => Marshal.AllocHGlobal(Marshal.SizeOf()),
+ 2 => Marshal.AllocHGlobal(Marshal.SizeOf()),
+ 3 => Marshal.AllocHGlobal(Marshal.SizeOf()),
+ _ => IntPtr.Zero
+ };
+
+ if (entity.Source != null && sourcePtr != 0)
+ {
+ switch (type)
+ {
+ case 1: Marshal.StructureToPtr((BotFriendStruct)(BotFriend)entity.Source, sourcePtr, false); break;
+ case 2: Marshal.StructureToPtr((BotGroupMemberStruct)(BotGroupMember)entity.Source, sourcePtr, false); break;
+ case 3: Marshal.StructureToPtr((BotStrangerStruct)(BotStranger)entity.Source, sourcePtr, false); break;
+ }
+ }
+
+ return new ReplyEntityStruct
+ {
+ SrcUid = entity.SrcUid,
+ SrcSequence = entity.SrcSequence,
+ Source = sourcePtr,
+ SourceType = type
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/TextEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/TextEntityStruct.cs
new file mode 100644
index 00000000..f1b7bbcc
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/TextEntityStruct.cs
@@ -0,0 +1,20 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct TextEntityStruct : IEntityStruct
+ {
+ public TextEntityStruct() { }
+
+ public ByteArrayNative Text = new();
+
+ public static implicit operator TextEntityStruct(TextEntity entity)
+ {
+ return new TextEntityStruct() { Text = Encoding.UTF8.GetBytes(entity.Text) };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/VideoEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/VideoEntityStruct.cs
new file mode 100644
index 00000000..a51b11c4
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/Entity/VideoEntityStruct.cs
@@ -0,0 +1,35 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message.Entity
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct VideoEntityStruct : IEntityStruct
+ {
+ public VideoEntityStruct() { }
+
+ public ByteArrayNative FileUrl = new();
+
+ public ByteArrayNative FileName = new();
+
+ public ByteArrayNative FileSha1 = new();
+
+ public uint FileSize = 0;
+
+ public ByteArrayNative FileMd5 = new();
+
+ public static implicit operator VideoEntityStruct(VideoEntity entity)
+ {
+ return new VideoEntityStruct()
+ {
+ FileUrl = Encoding.UTF8.GetBytes(entity.FileUrl),
+ FileName = Encoding.UTF8.GetBytes(entity.FileName),
+ FileSha1 = Encoding.UTF8.GetBytes(entity.FileSha1),
+ FileSize = entity.FileSize,
+ FileMd5 = Encoding.UTF8.GetBytes(entity.FileMd5)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/Message/TypedEntityStruct.cs b/Lagrange.Core.NativeAPI/NativeModel/Message/TypedEntityStruct.cs
new file mode 100644
index 00000000..d98b3fde
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/Message/TypedEntityStruct.cs
@@ -0,0 +1,12 @@
+using System.Runtime.InteropServices;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Message
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public class TypedEntityStruct
+ {
+ //需要手动释放
+ public IntPtr Entity = IntPtr.Zero;
+ public int Type = 0;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/NativeModel/StructExtensions.cs b/Lagrange.Core.NativeAPI/NativeModel/StructExtensions.cs
new file mode 100644
index 00000000..91051932
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/NativeModel/StructExtensions.cs
@@ -0,0 +1,55 @@
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.Message;
+using Lagrange.Core.Message.Entities;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.NativeModel.Message;
+using Lagrange.Core.NativeAPI.NativeModel.Message.Entity;
+
+namespace Lagrange.Core.NativeAPI.NativeModel
+{
+ public static class StructExtensions
+ {
+ #region Context
+
+ #region Dictionary
+
+ // public static KeyValuePairNative[] ToDictionaryStruct(
+ // this Dictionary dict
+ // )
+ // where T1 : notnull
+ // {
+ // var result = new KeyValuePairNative[dict.Count];
+ // int i = 0;
+ // foreach (var kvp in dict)
+ // {
+ // result[i++] = new KeyValuePairNative() { Key = kvp.Key, Value = kvp.Value };
+ // }
+ //
+ // return result;
+ // }
+ //
+ // public static Dictionary ToDictionary(
+ // this KeyValuePairNative[] dict
+ // )
+ // where T1 : notnull
+ // {
+ // var result = new Dictionary(dict.Length);
+ // foreach (var kvp in dict)
+ // {
+ // result[kvp.Key] = kvp.Value;
+ // }
+ //
+ // return result;
+ // }
+
+ #endregion
+
+ #endregion
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/OperateGroupEntryPoint.cs b/Lagrange.Core.NativeAPI/OperateGroupEntryPoint.cs
new file mode 100644
index 00000000..759c8063
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/OperateGroupEntryPoint.cs
@@ -0,0 +1,298 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Common.Interface;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.NativeModel.Message;
+
+namespace Lagrange.Core.NativeAPI
+{
+ public static class OperateGroupEntryPoint
+ {
+ [UnmanagedCallersOnly(EntryPoint = "FetchGroupNotifications")]
+ public static IntPtr FetchGroupNotifications(int index, ulong count, ulong start /*= 0*/)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ var notifications = context.FetchGroupNotifications(count, start).GetAwaiter().GetResult();
+
+ return GetGroupNotificationsStructPtr(notifications);
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "FetchFilteredGroupNotifications")]
+ public static IntPtr FetchFilteredGroupNotifications(int index, ulong count, ulong start /*= 0*/)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ var notifications = context.FetchFilteredGroupNotifications(count, start).GetAwaiter().GetResult();
+
+ return GetGroupNotificationsStructPtr(notifications);
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetGroupList")]
+ public static IntPtr GetGroupList(int index, bool refresh /*= false*/)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ var groups = context.FetchGroups(refresh).GetAwaiter().GetResult();
+
+ var result = new EventArrayStruct();
+ if (groups == null || groups.Count == 0)
+ {
+ result.Events = IntPtr.Zero;
+ result.Count = 0;
+
+ IntPtr emptyResultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, emptyResultPtr, false);
+ return emptyResultPtr;
+ }
+
+ result.Events = Marshal.AllocHGlobal(Marshal.SizeOf() * groups.Count);
+ result.Count = groups.Count;
+ for (int i = 0; i < groups.Count; i++)
+ {
+ Marshal.StructureToPtr(
+ (BotGroupStruct)groups[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ }
+
+ IntPtr resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, resultPtr, false);
+ return resultPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetMemberList")]
+ public static IntPtr GetMemberList(int index, long groupUin, bool refresh /*= false*/)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ var members = context.FetchMembers(groupUin, refresh).GetAwaiter().GetResult();
+
+ var result = new EventArrayStruct();
+ if (members == null || members.Count == 0)
+ {
+ result.Events = IntPtr.Zero;
+ result.Count = 0;
+
+ IntPtr emptyResultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, emptyResultPtr, false);
+ return emptyResultPtr;
+ }
+
+ result.Events = Marshal.AllocHGlobal(Marshal.SizeOf() * members.Count);
+ result.Count = members.Count;
+ for (int i = 0; i < members.Count; i++)
+ {
+ Marshal.StructureToPtr(
+ (BotGroupMemberStruct)members[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ }
+
+ IntPtr resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, resultPtr, false);
+ return resultPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "QuitGroup")]
+ public static void QuitGroup(int index, long groupUin)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ BotContext context = Program.Contexts[index].BotContext;
+ context.GroupQuit(groupUin);
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "RenameGroup")]
+ public static void RenameGroup(int index, long groupUin, ByteArrayNative name)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ BotContext context = Program.Contexts[index].BotContext;
+ context.GroupRename(groupUin, Encoding.UTF8.GetString(name.ToByteArrayWithoutFree()));
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "RenameGroupMember")]
+ public static void RenameGroupMember(int index, long groupUin, long targetUin, ByteArrayNative name)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ BotContext context = Program.Contexts[index].BotContext;
+ context.GroupMemberRename(groupUin, targetUin, Encoding.UTF8.GetString(name.ToByteArrayWithoutFree()));
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SendGroupNudge")]
+ public static void SendGroupNudge(int index, long peerUin, long targetUin)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ BotContext context = Program.Contexts[index].BotContext;
+ context.SendGroupNudge(peerUin, targetUin);
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SetGroupSpecialTitle")]
+ public static void SetGroupSpecialTitle(int index, long groupUin, long targetUin, ByteArrayNative title)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ BotContext context = Program.Contexts[index].BotContext;
+ context.GroupSetSpecialTitle(groupUin, targetUin, Encoding.UTF8.GetString(title.ToByteArrayWithoutFree()));
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SetGroupNotification")]
+ public static void SetGroupNotification(int index, long groupUin, ulong sequence, int type, bool isFiltered, int operate, ByteArrayNative message)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ if (message.IsEmpty())
+ {
+ context.SetGroupNotification(groupUin, sequence, (BotGroupNotificationType)type, isFiltered, (GroupNotificationOperate)operate);
+ return;
+ }
+
+ context.SetGroupNotification(groupUin, sequence, (BotGroupNotificationType)type, isFiltered, (GroupNotificationOperate)operate, Encoding.UTF8.GetString(message.ToByteArrayWithoutFree()));
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SetGroupReaction")]
+ public static void SetGroupReaction(int index, long groupUin, ulong sequence, ByteArrayNative code, bool isAdd)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index].BotContext;
+ context.SetGroupReaction(groupUin, sequence, Encoding.UTF8.GetString(code.ToByteArrayWithoutFree()), isAdd);
+ }
+
+ private static IntPtr GetGroupNotificationsStructPtr(List notifications)
+ {
+ EventArrayStruct result = new EventArrayStruct();
+ if (notifications == null || notifications.Count == 0)
+ {
+ result.Events = IntPtr.Zero;
+ result.Count = 0;
+
+ IntPtr emptyResultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, emptyResultPtr, false);
+ return emptyResultPtr;
+ }
+
+ int addressLength = 0;
+ for (int i = 0; i < notifications.Count; i++)
+ {
+ addressLength += notifications[i].Type switch
+ {
+ BotGroupNotificationType.Join => Marshal.SizeOf(),
+ BotGroupNotificationType.SetAdmin => Marshal.SizeOf(),
+ BotGroupNotificationType.KickOther => Marshal.SizeOf(),
+ BotGroupNotificationType.KickSelf => Marshal.SizeOf(),
+ BotGroupNotificationType.Exit => Marshal.SizeOf(),
+ BotGroupNotificationType.UnsetAdmin => Marshal.SizeOf(),
+ BotGroupNotificationType.Invite => Marshal.SizeOf(),
+ _ => throw new ArgumentOutOfRangeException($"Out of notification of type: {notifications[i].Type}"),
+ };
+ }
+
+ result.Events = Marshal.AllocHGlobal(addressLength);
+ result.Count = notifications.Count;
+ for (int i = 0; i < notifications.Count; i++)
+ {
+ switch (notifications[i].Type)
+ {
+ case BotGroupNotificationType.Join:
+ Marshal.StructureToPtr(
+ (BotGroupJoinNotificationStruct)(BotGroupJoinNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+
+ case BotGroupNotificationType.SetAdmin:
+ Marshal.StructureToPtr(
+ (BotGroupSetAdminNotificationStruct)(BotGroupSetAdminNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+
+ case BotGroupNotificationType.KickOther:
+ case BotGroupNotificationType.KickSelf:
+ Marshal.StructureToPtr(
+ (BotGroupKickNotificationStruct)(BotGroupKickNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+
+ case BotGroupNotificationType.Exit:
+ Marshal.StructureToPtr(
+ (BotGroupExitNotificationStruct)(BotGroupExitNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+
+ case BotGroupNotificationType.UnsetAdmin:
+ Marshal.StructureToPtr(
+ (BotGroupUnsetAdminNotificationStruct)(BotGroupUnsetAdminNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+
+ case BotGroupNotificationType.Invite:
+ Marshal.StructureToPtr(
+ (BotGroupInviteNotificationStruct)(BotGroupInviteNotification)notifications[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ break;
+ }
+ }
+
+ var resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, resultPtr, false);
+ return resultPtr;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/Program.cs b/Lagrange.Core.NativeAPI/Program.cs
new file mode 100644
index 00000000..53beafe3
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/Program.cs
@@ -0,0 +1,83 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.Common;
+using Lagrange.Core.Common.Interface;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+
+namespace Lagrange.Core.NativeAPI;
+
+public static class Program
+{
+ public static List Contexts { get; set; } = [];
+
+ [UnmanagedCallersOnly(EntryPoint = "Initialize")]
+ public static int Initialize(IntPtr botConfigPtr, IntPtr keystorePtr, IntPtr appInfoPtr)
+ {
+ var botConfigStruct = Marshal.PtrToStructure(botConfigPtr);
+ var botConfig = botConfigStruct;
+
+ BotAppInfo? appInfo = null;
+ if (appInfoPtr != IntPtr.Zero)
+ {
+ var appInfoStruct = Marshal.PtrToStructure(appInfoPtr);
+ appInfo = appInfoStruct;
+ }
+
+ int index = Contexts.Count;
+ if (keystorePtr != IntPtr.Zero)
+ {
+ var keystoreStruct = Marshal.PtrToStructure(keystorePtr);
+ var keystore = keystoreStruct.ToKeystoreWithoutFree();
+ Contexts.Add(new Context(BotFactory.Create(botConfig, keystore, appInfo)));
+ }
+ else
+ {
+ Contexts.Add(new Context(BotFactory.Create(botConfig, appInfo)));
+ }
+
+ return index;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "Start")]
+ public static StatusCode Start(int index)
+ {
+ if (Contexts.Count <= index)
+ {
+ return StatusCode.InvalidIndex;
+ }
+
+ if (Contexts[index].BotContext.IsOnline)
+ {
+ return StatusCode.AlreadyStarted;
+ }
+
+ Task.Run(async () =>
+ {
+ await Contexts[index].BotContext.Login();
+ await Task.Delay(Timeout.Infinite);
+ });
+
+ return StatusCode.Success;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "Stop")]
+ public static StatusCode Stop(int index)
+ {
+ if (Contexts.Count <= index)
+ {
+ return StatusCode.InvalidIndex;
+ }
+
+ Contexts[index].BotContext.Dispose();
+ Contexts.RemoveAt(index);
+ return StatusCode.Success;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "FreeMemory")]
+ public static void FreeMemory(IntPtr ptr)
+ {
+ if (ptr != IntPtr.Zero)
+ {
+ Marshal.FreeHGlobal(ptr);
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/Abstract/ReverseEventBase.cs b/Lagrange.Core.NativeAPI/ReverseEvent/Abstract/ReverseEventBase.cs
new file mode 100644
index 00000000..256e9a88
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/Abstract/ReverseEventBase.cs
@@ -0,0 +1,10 @@
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent.Abstract
+{
+ public abstract class ReverseEventBase
+ {
+ public List Events = [];
+ public virtual void RegisterEventHandler(BotContext context) { }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotCaptchaReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotCaptchaReverseEvent.cs
new file mode 100644
index 00000000..45005253
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotCaptchaReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotCaptchaReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotCaptchaEventStruct)e)
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRecallReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRecallReverseEvent.cs
new file mode 100644
index 00000000..00733116
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRecallReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotFriendRecallReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotFriendRecallEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRequestReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRequestReverseEvent.cs
new file mode 100644
index 00000000..b4537e68
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotFriendRequestReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotFriendRequestReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotFriendRequestEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupInviteNotificationReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupInviteNotificationReverseEvent.cs
new file mode 100644
index 00000000..4471c059
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupInviteNotificationReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupInviteNotificationReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupInviteNotificationEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupJoinNotificationReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupJoinNotificationReverseEvent.cs
new file mode 100644
index 00000000..a290efad
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupJoinNotificationReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupJoinNotificationReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupJoinNotificationEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberDecreaseReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberDecreaseReverseEvent.cs
new file mode 100644
index 00000000..2bb91ede
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberDecreaseReverseEvent.cs
@@ -0,0 +1,17 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupMemberDecreaseReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupMemberDecreaseEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberIncreaseReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberIncreaseReverseEvent.cs
new file mode 100644
index 00000000..7c8137c0
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupMemberIncreaseReverseEvent.cs
@@ -0,0 +1,17 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupMemberIncreaseReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupMemberIncreaseEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupNudgeReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupNudgeReverseEvent.cs
new file mode 100644
index 00000000..28e4a7c2
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupNudgeReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupNudgeReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupNudgeEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupReactionReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupReactionReverseEvent.cs
new file mode 100644
index 00000000..b2d74811
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupReactionReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupReactionReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupReactionEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupRecallReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupRecallReverseEvent.cs
new file mode 100644
index 00000000..a35c68c9
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotGroupRecallReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotGroupRecallReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotGroupRecallEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotLogReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotLogReverseEvent.cs
new file mode 100644
index 00000000..0170d49e
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotLogReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotLogReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotLogEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotLoginReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotLoginReverseEvent.cs
new file mode 100644
index 00000000..1e86cb49
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotLoginReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotLoginReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) =>
+ {
+ Events.Add((BotLoginEventStruct)e);
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotMessageReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotMessageReverseEvent.cs
new file mode 100644
index 00000000..2d7d3093
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotMessageReverseEvent.cs
@@ -0,0 +1,18 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.NativeModel.Message;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotMessageReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent(
+ (ctx, e) => Events.Add((BotMessageEventStruct)e)
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotNewDeviceVerifyReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotNewDeviceVerifyReverseEvent.cs
new file mode 100644
index 00000000..274e68a0
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotNewDeviceVerifyReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotNewDeviceVerifyReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotNewDeviceVerifyEventStruct)e)
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotOfflineReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotOfflineReverseEvent.cs
new file mode 100644
index 00000000..737b9b89
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotOfflineReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotOfflineReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotOfflineEventStruct)e)
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotOnlineReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotOnlineReverseEvent.cs
new file mode 100644
index 00000000..1ab94438
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotOnlineReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotOnlineReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotOnlineEventStruct)e)
+ );
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeQueryReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeQueryReverseEvent.cs
new file mode 100644
index 00000000..00320f91
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeQueryReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotQrCodeQueryReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotQrCodeQueryEventStruct)e)
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeReverseEvent.cs
new file mode 100644
index 00000000..4433979a
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotQrCodeReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotQrCodeReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotQrCodeEventStruct)e)
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotRefreshKeystoreReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotRefreshKeystoreReverseEvent.cs
new file mode 100644
index 00000000..b19d81db
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotRefreshKeystoreReverseEvent.cs
@@ -0,0 +1,16 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotRefreshKeystoreReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotRefreshKeystoreEventStruct)e)
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/BotSMSReverseEvent.cs b/Lagrange.Core.NativeAPI/ReverseEvent/BotSMSReverseEvent.cs
new file mode 100644
index 00000000..74dc3f1c
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/BotSMSReverseEvent.cs
@@ -0,0 +1,15 @@
+using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.NativeAPI.NativeModel;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class BotSMSReverseEvent : ReverseEventBase
+ {
+ public override void RegisterEventHandler(BotContext context)
+ {
+ context.EventInvoker.RegisterEvent((ctx, e) => Events.Add((BotSMSEventStruct)e));
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/EventEntryPoint.cs b/Lagrange.Core.NativeAPI/ReverseEvent/EventEntryPoint.cs
new file mode 100644
index 00000000..343e9ea2
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/EventEntryPoint.cs
@@ -0,0 +1,372 @@
+using System.Runtime.InteropServices;
+using Lagrange.Core.NativeAPI.NativeModel.Event;
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public static class EventEntryPoint
+ {
+ [UnmanagedCallersOnly(EntryPoint = "GetEventCount")]
+ public static IntPtr GetEventCount(int index)
+ {
+ var eventCount = new ReverseEventCountStruct
+ {
+ BotCaptchaEventCount = Program.Contexts[index].EventInvoker.BotCaptchaEvent.Events.Count,
+ BotFriendRequestEventCount = Program.Contexts[index].EventInvoker.BotFriendRequestEvent.Events.Count,
+ BotFriendRecallEventCount = Program.Contexts[index].EventInvoker.BotFriendRecallEvent.Events.Count,
+ BotGroupInviteNotificationEventCount = Program.Contexts[index].EventInvoker.BotGroupInviteNotificationEvent.Events.Count,
+ BotGroupJoinNotificationEventCount = Program.Contexts[index].EventInvoker.BotGroupJoinNotificationEvent.Events.Count,
+ BotGroupMemberDecreaseEventCount = Program.Contexts[index].EventInvoker.BotGroupMemberDecreaseEvent.Events.Count,
+ BotGroupMemberIncreaseEventCount = Program.Contexts[index].EventInvoker.BotGroupMemberIncreaseEvent.Events.Count,
+ BotGroupNudgeEventCount = Program.Contexts[index].EventInvoker.BotGroupNudgeEvent.Events.Count,
+ BotGroupReactionEventCount = Program.Contexts[index].EventInvoker.BotGroupReactionEvent.Events.Count,
+ BotGroupRecallEventCount = Program.Contexts[index].EventInvoker.BotGroupRecallEvent.Events.Count,
+ BotLoginEventCount = Program.Contexts[index].EventInvoker.BotLoginEvent.Events.Count,
+ BotLogEventCount = Program.Contexts[index].EventInvoker.BotLogEvent.Events.Count,
+ BotMessageEventCount = Program.Contexts[index].EventInvoker.BotMessageEvent.Events.Count,
+ BotNewDeviceVerifyEventCount = Program.Contexts[index].EventInvoker.BotNewDeviceVerifyEvent.Events.Count,
+ BotOnlineEventCount = Program.Contexts[index].EventInvoker.BotOnlineEvent.Events.Count,
+ BotQrCodeEventCount = Program.Contexts[index].EventInvoker.BotQrCodeEvent.Events.Count,
+ BotQrCodeQueryEventCount = Program.Contexts[index].EventInvoker.BotQrCodeQueryEvent.Events.Count,
+ BotRefreshKeystoreEventCount = Program.Contexts[index].EventInvoker.BotRefreshKeystoreEvent.Events.Count,
+ BotSMSEventCount = Program.Contexts[index].EventInvoker.BotSMSEvent.Events.Count
+ };
+
+ IntPtr eventCountPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(eventCount, eventCountPtr, false);
+
+ return eventCountPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetCaptchaEvent")]
+ public static IntPtr GetCaptchaEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botCaptchaEvent = Program.Contexts[index].EventInvoker.BotCaptchaEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botCaptchaEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotFriendRecallEvent")]
+ public static IntPtr GetBotFriendRecallEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botFriendRecallEvent = Program.Contexts[index].EventInvoker.BotFriendRecallEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botFriendRecallEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotFriendRequestEvent")]
+ public static IntPtr GetBotFriendRequestEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botFriendRequestEvent = Program.Contexts[index].EventInvoker.BotFriendRequestEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botFriendRequestEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupInviteNotificationEvent")]
+ public static IntPtr GetBotGroupInviteNotificationEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupInviteNotificationEvent = Program.Contexts[index].EventInvoker.BotGroupInviteNotificationEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupInviteNotificationEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupJoinNotificationEvent")]
+ public static IntPtr GetBotGroupJoinNotificationEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupJoinNotificationEvent = Program.Contexts[index].EventInvoker.BotGroupJoinNotificationEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupJoinNotificationEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupMemberDecreaseEvent")]
+ public static IntPtr GetBotGroupMemberDecreaseEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupMemberDecreaseEvent = Program.Contexts[index].EventInvoker.BotGroupMemberDecreaseEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupMemberDecreaseEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupMemberIncreaseEvent")]
+ public static IntPtr GetBotGroupMemberIncreaseEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupMemberIncreaseEvent = Program.Contexts[index].EventInvoker.BotGroupMemberIncreaseEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupMemberIncreaseEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupNudgeEvent")]
+ public static IntPtr GetBotGroupNudgeEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupNudgeEvent = Program.Contexts[index].EventInvoker.BotGroupNudgeEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupNudgeEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupReactionEvent")]
+ public static IntPtr GetBotGroupReactionEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupReactionEvent = Program.Contexts[index].EventInvoker.BotGroupReactionEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupReactionEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotGroupRecallEvent")]
+ public static IntPtr GetBotGroupRecallEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botGroupRecallEvent = Program.Contexts[index].EventInvoker.BotGroupRecallEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botGroupRecallEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetLoginEvent")]
+ public static IntPtr GetLoginEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botLoginEvent = Program.Contexts[index].EventInvoker.BotLoginEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botLoginEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetBotLogEvent")]
+ public static IntPtr GetBotLogEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botLogEvent = Program.Contexts[index].EventInvoker.BotLogEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botLogEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetMessageEvent")]
+ public static IntPtr GetMessageEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botMessageEvent = Program.Contexts[index].EventInvoker.BotMessageEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botMessageEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetNewDeviceVerifyEvent")]
+ public static IntPtr GetNewDeviceVerifyEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botNewDeviceVerifyEvent = Program.Contexts[index].EventInvoker.BotNewDeviceVerifyEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botNewDeviceVerifyEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetOfflineEvent")]
+ public static IntPtr GetOfflineEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botOfflineEvent = Program.Contexts[index].EventInvoker.BotOfflineEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botOfflineEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetOnlineEvent")]
+ public static IntPtr GetOnlineEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botOnlineEvent = Program.Contexts[index].EventInvoker.BotOnlineEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botOnlineEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetQrCodeEvent")]
+ public static IntPtr GetQrCodeEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botQrCodeEvent = Program.Contexts[index].EventInvoker.BotQrCodeEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botQrCodeEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetQrCodeQueryEvent")]
+ public static IntPtr GetQrCodeQueryEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botQrCodeQueryEvent = Program.Contexts[index].EventInvoker.BotQrCodeQueryEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botQrCodeQueryEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetRefreshKeystoreEvent")]
+ public static IntPtr GetRefreshKeystoreEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botRefreshKeystoreEvent = Program.Contexts[index].EventInvoker.BotRefreshKeystoreEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botRefreshKeystoreEvent);
+
+ return eventPtr;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "GetSMSEvent")]
+ public static IntPtr GetSMSEvent(int index)
+ {
+ if (index >= Program.Contexts.Count)
+ {
+ return IntPtr.Zero;
+ }
+
+ var botSMSEvent = Program.Contexts[index].EventInvoker.BotSMSEvent;
+
+ IntPtr eventPtr = GetEventStructPtr(botSMSEvent);
+
+ return eventPtr;
+ }
+
+ private static IntPtr GetEventStructPtr(ReverseEventBase reverseEvent) where T : IEventStruct
+ {
+ EventArrayStruct result = new EventArrayStruct();
+
+ if (reverseEvent.Events.Count == 0)
+ {
+ result.Events = IntPtr.Zero;
+ result.Count = 0;
+ }
+ else
+ {
+ result.Events = Marshal.AllocHGlobal(reverseEvent.Events.Count * Marshal.SizeOf());
+ result.Count = reverseEvent.Events.Count;
+
+ for (int i = 0; i < reverseEvent.Events.Count; i++)
+ {
+ Marshal.StructureToPtr(
+ reverseEvent.Events[i],
+ result.Events + i * Marshal.SizeOf(),
+ false
+ );
+ }
+
+ reverseEvent.Events.Clear();
+ }
+
+ IntPtr resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr(result, resultPtr, false);
+ return resultPtr;
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/ReverseEvent/ReverseEventInvoker.cs b/Lagrange.Core.NativeAPI/ReverseEvent/ReverseEventInvoker.cs
new file mode 100644
index 00000000..178c64b4
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/ReverseEvent/ReverseEventInvoker.cs
@@ -0,0 +1,68 @@
+using Lagrange.Core.NativeAPI.ReverseEvent.Abstract;
+
+namespace Lagrange.Core.NativeAPI.ReverseEvent
+{
+ public class ReverseEventInvoker
+ {
+ public ReverseEventInvoker(BotContext context)
+ {
+ BotCaptchaEvent.RegisterEventHandler(context);
+ BotFriendRequestEvent.RegisterEventHandler(context);
+ BotGroupInviteNotificationEvent.RegisterEventHandler(context);
+ BotGroupJoinNotificationEvent.RegisterEventHandler(context);
+ BotGroupMemberDecreaseEvent.RegisterEventHandler(context);
+ BotGroupMemberIncreaseEvent.RegisterEventHandler(context);
+ BotGroupNudgeEvent.RegisterEventHandler(context);
+ BotGroupReactionEvent.RegisterEventHandler(context);
+ BotLoginEvent.RegisterEventHandler(context);
+ BotLogEvent.RegisterEventHandler(context);
+ BotMessageEvent.RegisterEventHandler(context);
+ BotNewDeviceVerifyEvent.RegisterEventHandler(context);
+ BotOfflineEvent.RegisterEventHandler(context);
+ BotOnlineEvent.RegisterEventHandler(context);
+ BotQrCodeEvent.RegisterEventHandler(context);
+ BotQrCodeQueryEvent.RegisterEventHandler(context);
+ BotRefreshKeystoreEvent.RegisterEventHandler(context);
+ }
+
+ public BotCaptchaReverseEvent BotCaptchaEvent { get; } = new();
+
+ public BotFriendRequestReverseEvent BotFriendRequestEvent { get; } = new();
+
+ public BotFriendRecallReverseEvent BotFriendRecallEvent { get; } = new();
+
+ public BotGroupInviteNotificationReverseEvent BotGroupInviteNotificationEvent { get; } = new();
+
+ public BotGroupJoinNotificationReverseEvent BotGroupJoinNotificationEvent { get; } = new();
+
+ public BotGroupMemberDecreaseReverseEvent BotGroupMemberDecreaseEvent { get; } = new();
+
+ public BotGroupMemberIncreaseReverseEvent BotGroupMemberIncreaseEvent { get; } = new();
+
+ public BotGroupNudgeReverseEvent BotGroupNudgeEvent { get; } = new();
+
+ public BotGroupReactionReverseEvent BotGroupReactionEvent { get; } = new();
+
+ public BotGroupRecallReverseEvent BotGroupRecallEvent { get; } = new();
+
+ public BotLoginReverseEvent BotLoginEvent { get; } = new();
+
+ public BotLogReverseEvent BotLogEvent { get; } = new();
+
+ public BotMessageReverseEvent BotMessageEvent { get; } = new();
+
+ public BotNewDeviceVerifyReverseEvent BotNewDeviceVerifyEvent { get; } = new();
+
+ public BotOfflineReverseEvent BotOfflineEvent { get; } = new();
+
+ public BotOnlineReverseEvent BotOnlineEvent { get; } = new();
+
+ public BotQrCodeReverseEvent BotQrCodeEvent { get; } = new();
+
+ public BotQrCodeQueryReverseEvent BotQrCodeQueryEvent { get; } = new();
+
+ public BotRefreshKeystoreReverseEvent BotRefreshKeystoreEvent { get; } = new();
+
+ public BotSMSReverseEvent BotSMSEvent { get; } = new();
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.NativeAPI/SendMessageContext.cs b/Lagrange.Core.NativeAPI/SendMessageContext.cs
new file mode 100644
index 00000000..10e78edf
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/SendMessageContext.cs
@@ -0,0 +1,163 @@
+using System.Runtime.CompilerServices;
+using System.Text;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Message;
+
+namespace Lagrange.Core.NativeAPI
+{
+ public class SendMessageContext
+ {
+ public SendMessageContext(BotContext context)
+ {
+ _context = context;
+ }
+
+ private BotContext _context;
+ public Dictionary MessageBuilders { get; } = new();
+
+ public int CreateMessageBuilder()
+ {
+ var random = new Random();
+ int randomNumber = random.Next(1, int.MaxValue);
+ while (MessageBuilders.ContainsKey(randomNumber))
+ {
+ randomNumber = random.Next(1, int.MaxValue);
+ }
+
+ MessageBuilders.Add(randomNumber, new MessageBuilder());
+ return randomNumber;
+ }
+
+ public void RemoveMessageBuilder(int id)
+ {
+ MessageBuilders.Remove(id);
+ }
+
+ public MessageChain? Build(int id)
+ {
+ if (!MessageBuilders.TryGetValue(id, out var builder))
+ {
+ return null;
+ }
+
+ var message = builder.Build();
+ MessageBuilders.Remove(id);
+ return message;
+ }
+
+ public void AddText(int id, byte[] text)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.Text(Encoding.UTF8.GetString(text));
+ }
+ }
+
+ public void AddImage(int id, byte[] image, byte[]? summary = null,
+ int subType = 0)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ if (summary != null)
+ {
+ builder.Image(image, Encoding.UTF8.GetString(summary), subType);
+ }
+ else
+ {
+ builder.Image(image: image, subType: subType);
+ }
+ }
+ }
+
+ public void AddLocalImage(int id, byte[] path, byte[]? summary = null,
+ int subType = 0)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ if (summary != null)
+ {
+ builder.Image(
+ Encoding.UTF8.GetString(path),
+ Encoding.UTF8.GetString(summary),
+ subType
+ );
+ }
+ else
+ {
+ builder.Image(path: Encoding.UTF8.GetString(path), subType: subType);
+ }
+ }
+ }
+
+ public void AddMention(int id, long uin, byte[]? display = null)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.Mention(uin, display is null ? null : Encoding.UTF8.GetString(display));
+ }
+ }
+
+ public void AddReply(int id /*, BotMessage messages */)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void AddMultiMsg(int id /*, List messages */)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void AddMultiMsg(int id, byte[] resId)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.MultiMsg(Encoding.UTF8.GetString(resId));
+ }
+ }
+
+ public void AddRecord(int id, byte[] record)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.Record(record);
+ }
+ }
+
+ public void AddLocalRecord(int id, byte[] path)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.Record(Encoding.UTF8.GetString(path));
+ }
+ }
+
+ public void AddVideo(int id, byte[] video, byte[]? thumbnail)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ builder.Video(video, thumbnail);
+ }
+ }
+
+ public void AddLocalVideo(int id, byte[] path, byte[]? thumbPath)
+ {
+ if (MessageBuilders.TryGetValue(id, out var builder))
+ {
+ string? thumb = thumbPath == null ? null : Encoding.UTF8.GetString(thumbPath);
+ builder.Video(Encoding.UTF8.GetString(path), thumb);
+ }
+ }
+ }
+
+ internal static class BotMessageAccessor
+ {
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "k__BackingField")]
+ public static extern ref BotContact GetContact(this BotMessage message);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "k__BackingField")]
+ public static extern ref BotContact GetReceiver(this BotMessage message);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "k__BackingField")]
+ public static extern ref ulong GetClientSequence(this BotMessage message);
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/SendMessageEntryPoint.cs b/Lagrange.Core.NativeAPI/SendMessageEntryPoint.cs
new file mode 100644
index 00000000..dd96d877
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/SendMessageEntryPoint.cs
@@ -0,0 +1,294 @@
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Common.Interface;
+using Lagrange.Core.Message;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.NativeAPI.NativeModel.Message;
+
+namespace Lagrange.Core.NativeAPI
+{
+ public static class SendMessageEntryPoint
+ {
+ [UnmanagedCallersOnly(EntryPoint = "CreateMessageBuilder")]
+ public static int CreateMessageBuilder(int index)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return 0;
+ }
+
+ var context = Program.Contexts[index];
+ return context.SendMessageContext.CreateMessageBuilder();
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddText")]
+ public static void AddText(int index, int id, ByteArrayNative byteArrayNative)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddText(id, byteArrayNative.ToByteArrayWithoutFree());
+ }
+
+ //summary可选,可以传结构内Length为0或Data为Zero的ByteArrayNative
+ [UnmanagedCallersOnly(EntryPoint = "AddImage")]
+ public static void AddImage(
+ int index,
+ int id,
+ ByteArrayNative byteArrayNative,
+ ByteArrayNative summary,
+ int subType
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ byte[]? sum = summary.IsEmpty() ? null : summary.ToByteArrayWithoutFree();
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddImage(
+ id,
+ byteArrayNative.ToByteArrayWithoutFree(),
+ sum,
+ subType
+ );
+ }
+
+ //summary可选,可以传结构内Length为0或Data为Zero的ByteArrayNative
+ [UnmanagedCallersOnly(EntryPoint = "AddLocalImage")]
+ public static void AddLocalImage(
+ int index,
+ int id,
+ ByteArrayNative byteArrayNative,
+ ByteArrayNative summary,
+ int subType
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ byte[]? sum = summary.IsEmpty() ? null : summary.ToByteArrayWithoutFree();
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddLocalImage(
+ id,
+ byteArrayNative.ToByteArrayWithoutFree(),
+ sum,
+ subType
+ );
+ }
+
+ //display可选,可以传结构内Length为0或Data为Zero的ByteArrayNative
+ [UnmanagedCallersOnly(EntryPoint = "AddMention")]
+ public static void AddMention(
+ int index,
+ int id,
+ long uin,
+ ByteArrayNative display
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ byte[]? ds = display.IsEmpty() ? null : display.ToByteArrayWithoutFree();
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddMention(
+ id, uin, ds
+ );
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddMultiMsg")]
+ public static void AddMultiMsg(
+ int index,
+ int id,
+ ByteArrayNative resId
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddMultiMsg(
+ id, resId.ToByteArrayWithoutFree()
+ );
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddRecord")]
+ public static void AddRecord(int index, int id, ByteArrayNative byteArrayNative)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddRecord(id, byteArrayNative.ToByteArrayWithoutFree());
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddLocalRecord")]
+ public static void AddLocalRecord(int index, int id, ByteArrayNative byteArrayNative)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddLocalRecord(
+ id,
+ byteArrayNative.ToByteArrayWithoutFree()
+ );
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddVideo")]
+ public static void AddVideo(
+ int index,
+ int id,
+ ByteArrayNative byteArrayNative,
+ ByteArrayNative thumbnail
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ byte[]? thumb = thumbnail.IsEmpty() ? null : thumbnail.ToByteArrayWithoutFree();
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddVideo(
+ id,
+ byteArrayNative.ToByteArrayWithoutFree(),
+ thumb
+ );
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "AddLocalVideo")]
+ public static void AddLocalVideo(
+ int index,
+ int id,
+ ByteArrayNative byteArrayNative,
+ ByteArrayNative thumbnail
+ )
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ byte[]? thumb = thumbnail.IsEmpty() ? null : thumbnail.ToByteArrayWithoutFree();
+
+ var context = Program.Contexts[index];
+ context.SendMessageContext.AddLocalVideo(
+ id,
+ byteArrayNative.ToByteArrayWithoutFree(),
+ thumb
+ );
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SendFriendMessage")]
+ public static IntPtr SendFriendMessage(int index, int id, long friendUin)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index];
+ var chain = context.SendMessageContext.Build(id);
+ if (chain == null)
+ {
+ return IntPtr.Zero;
+ }
+
+ try
+ {
+ var message = context.BotContext.SendFriendMessage(friendUin, chain).GetAwaiter().GetResult();
+
+ IntPtr messagePtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotMessageStruct)message, messagePtr, false);
+ return messagePtr;
+ }
+ catch
+ {
+ return IntPtr.Zero;
+ }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "SendGroupMessage")]
+ public static IntPtr SendGroupMessage(int index, int id, long groupUin)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return IntPtr.Zero;
+ }
+
+ var context = Program.Contexts[index];
+ var chain = context.SendMessageContext.Build(id);
+ if (chain == null)
+ {
+ return IntPtr.Zero;
+ }
+
+ try
+ {
+ var message = context.BotContext.SendGroupMessage(groupUin, chain).GetAwaiter().GetResult();
+
+ IntPtr messagePtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ Marshal.StructureToPtr((BotMessageStruct)message, messagePtr, false);
+ return messagePtr;
+ }
+ catch
+ {
+ return IntPtr.Zero;
+ }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "RecallMessage")]
+ public static void RecallMessage(int index, BotMessageStruct message)
+ {
+ if (Program.Contexts.Count <= index)
+ {
+ return;
+ }
+
+ var context = Program.Contexts[index];
+ var message1 = (BotMessage)RuntimeHelpers.GetUninitializedObject(typeof(BotMessage));
+ message1.Sequence = message.Sequence;
+ message1.GetClientSequence() = message.ClientSequence;
+
+ if ((MessageType)message.Type == MessageType.Group)
+ {
+ BotGroupMemberStruct member = new();
+ Marshal.PtrToStructure(
+ message.Contact,
+ member
+ );
+ message1.GetContact() = (BotGroupMember)member;
+ context.BotContext.RecallMessage(message1);
+ return;
+ }
+
+ BotFriendStruct contact = new();
+ BotFriendStruct receiver = new();
+ Marshal.PtrToStructure(message.Contact, contact);
+ Marshal.PtrToStructure(message.Receiver, receiver);
+ message1.GetContact() = (BotFriend)contact;
+ message1.GetReceiver() = (BotFriend)receiver;
+ context.BotContext.RecallMessage(message1);
+ }
+ }
+}
diff --git a/Lagrange.Core.NativeAPI/StatusCode.cs b/Lagrange.Core.NativeAPI/StatusCode.cs
new file mode 100644
index 00000000..639fc86f
--- /dev/null
+++ b/Lagrange.Core.NativeAPI/StatusCode.cs
@@ -0,0 +1,11 @@
+namespace Lagrange.Core.NativeAPI
+{
+ public enum StatusCode
+ {
+ Success = 0,
+ UnInitialized = 1,
+ AlreadyInitialized = 2,
+ AlreadyStarted = 3,
+ InvalidIndex = 4,
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.Runner/InteropSignProvider.cs b/Lagrange.Core.Runner/InteropSignProvider.cs
new file mode 100644
index 00000000..a61ac5de
--- /dev/null
+++ b/Lagrange.Core.Runner/InteropSignProvider.cs
@@ -0,0 +1,137 @@
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Lagrange.Core.Common;
+using Lagrange.Core.Internal.Packets.Service;
+
+namespace Lagrange.Core.NativeAPI.NativeModel.Common;
+
+public class LinuxSignProvider(string? signUrl) : BotSignProvider, IDisposable
+{
+ private const string Tag = nameof(LinuxSignProvider);
+
+ private readonly HttpClient _client = new();
+
+ private string Url => signUrl ?? $"https://sign.lagrangecore.org/api/sign/{Context.AppInfo.AppClientVersion}";
+
+ private static readonly HashSet WhiteListCommand =
+ [
+ "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
+ "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess",
+ "trpc.o3.report.Report.SsoReport",
+ "MessageSvc.PbSendMsg",
+ "wtlogin.trans_emp",
+ "wtlogin.login",
+ "wtlogin.exchange_emp",
+ "trpc.login.ecdh.EcdhService.SsoKeyExchange",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginNewDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshTicket",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshA2",
+ "OidbSvcTrpcTcp.0x11ec_1",
+ "OidbSvcTrpcTcp.0x758_1", // create group
+ "OidbSvcTrpcTcp.0x7c1_1",
+ "OidbSvcTrpcTcp.0x7c2_5", // request friend
+ "OidbSvcTrpcTcp.0x10db_1",
+ "OidbSvcTrpcTcp.0x8a1_7", // request group
+ "OidbSvcTrpcTcp.0x89a_0",
+ "OidbSvcTrpcTcp.0x89a_15",
+ "OidbSvcTrpcTcp.0x88d_0", // fetch group detail
+ "OidbSvcTrpcTcp.0x88d_14",
+ "OidbSvcTrpcTcp.0x112a_1",
+ "OidbSvcTrpcTcp.0x587_74",
+ "OidbSvcTrpcTcp.0x1100_1",
+ "OidbSvcTrpcTcp.0x1102_1",
+ "OidbSvcTrpcTcp.0x1103_1",
+ "OidbSvcTrpcTcp.0x1107_1",
+ "OidbSvcTrpcTcp.0x1105_1",
+ "OidbSvcTrpcTcp.0xf88_1",
+ "OidbSvcTrpcTcp.0xf89_1",
+ "OidbSvcTrpcTcp.0xf57_1",
+ "OidbSvcTrpcTcp.0xf57_106",
+ "OidbSvcTrpcTcp.0xf57_9",
+ "OidbSvcTrpcTcp.0xf55_1",
+ "OidbSvcTrpcTcp.0xf67_1",
+ "OidbSvcTrpcTcp.0xf67_5",
+ "OidbSvcTrpcTcp.0x6d9_4"
+ ];
+
+ public override bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
+
+ public override async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
+ {
+ try
+ {
+ var payload = new JsonObject
+ {
+ ["cmd"] = cmd,
+ ["seq"] = seq,
+ ["src"] = Convert.ToHexString(body.Span),
+ };
+
+ var response = await _client.PostAsync(Url, new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return null;
+
+ var content = JsonHelper.Deserialize(await response.Content.ReadAsStringAsync());
+ if (content == null) return null;
+
+ return new SsoSecureInfo
+ {
+ SecSign = Convert.FromHexString(content.Value.Sign),
+ SecToken = Convert.FromHexString(content.Value.Token),
+ SecExtra = Convert.FromHexString(content.Value.Extra)
+ };
+ }
+ catch (Exception e)
+ {
+ Context.LogWarning(Tag, $"Failed to get sign: {e.Message}");
+ return null;
+ }
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+
+ [Serializable]
+ internal class Root
+ {
+ [JsonPropertyName("value")] public Response Value { get; set; } = new();
+ }
+
+ [Serializable]
+ internal class Response
+ {
+ [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
+
+ [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
+
+ [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
+ }
+}
+
+internal static partial class JsonHelper
+{
+ [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Default, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
+
+ [JsonSerializable(typeof(LinuxSignProvider.Root))]
+ [JsonSerializable(typeof(LinuxSignProvider.Response))]
+
+ [JsonSerializable(typeof(JsonObject))]
+ [JsonSerializable(typeof(LightApp))]
+ private partial class CoreSerializerContext : JsonSerializerContext;
+
+ public static T? Deserialize(string json) where T : class =>
+ JsonSerializer.Deserialize(json, typeof(T), CoreSerializerContext.Default) as T;
+
+ public static string Serialize(T value) =>
+ JsonSerializer.Serialize(value, typeof(T), CoreSerializerContext.Default);
+
+ public static ReadOnlyMemory SerializeToUtf8Bytes(T value) =>
+ JsonSerializer.SerializeToUtf8Bytes(value, typeof(T), CoreSerializerContext.Default);
+}
\ No newline at end of file
diff --git a/Lagrange.Core.Runner/Lagrange.Core.Runner.csproj b/Lagrange.Core.Runner/Lagrange.Core.Runner.csproj
index 3d3fba14..31326d8f 100644
--- a/Lagrange.Core.Runner/Lagrange.Core.Runner.csproj
+++ b/Lagrange.Core.Runner/Lagrange.Core.Runner.csproj
@@ -2,13 +2,18 @@
Exe
- net9.0
+ net10.0
enable
enable
+ true
+
+
+
+
diff --git a/Lagrange.Core.Runner/Program.cs b/Lagrange.Core.Runner/Program.cs
index ed472f3b..d2a14308 100644
--- a/Lagrange.Core.Runner/Program.cs
+++ b/Lagrange.Core.Runner/Program.cs
@@ -1,6 +1,14 @@
-using Lagrange.Core.Common;
+using System.Diagnostics;
+using System.Text;
+using System.Text.Json;
+using Lagrange.Core.Common;
+using Lagrange.Core.Common.Entity;
using Lagrange.Core.Common.Interface;
using Lagrange.Core.Events.EventArgs;
+using Lagrange.Core.Internal.Packets.Message;
+using Lagrange.Core.Message;
+using Lagrange.Core.NativeAPI.NativeModel.Common;
+using Lagrange.Core.Utility;
namespace Lagrange.Core.Runner;
@@ -8,16 +16,58 @@ internal static class Program
{
private static async Task Main()
{
- var context = BotFactory.Create(new BotConfig
+ var sign = new LinuxSignProvider("");
+
+ Console.OutputEncoding = Encoding.UTF8;
+ Console.InputEncoding = Encoding.UTF8;
+
+ BotContext context;
+
+ if (File.Exists("keystore.json"))
{
-
- });
+ context = BotFactory.Create(new BotConfig
+ {
+ Protocol = Protocols.Linux,
+ SignProvider = sign,
+ LogLevel = LogLevel.Debug
+ }, JsonSerializer.Deserialize(await File.ReadAllTextAsync("keystore.json")) ?? throw new InvalidOperationException());
+ }
+ else
+ {
+ context = BotFactory.Create(new BotConfig
+ {
+ Protocol = Protocols.Linux,
+ SignProvider = sign,
+ LogLevel = LogLevel.Debug
+ });
+ }
+
+ AppDomain.CurrentDomain.ProcessExit += async (_, _) =>
+ {
+ await context.Logout();
+ };
context.EventInvoker.RegisterEvent((_, args) =>
{
Console.WriteLine(args);
});
+
+ context.EventInvoker.RegisterEvent((_, args) =>
+ {
+ Console.WriteLine(args);
+ QrCodeHelper.Output(args.Url, false);
+ });
+
+ context.EventInvoker.RegisterEvent(async (_, args) =>
+ {
+ await File.WriteAllTextAsync("keystore.json", JsonSerializer.Serialize(args.Keystore));
+ });
- await context.SocketContext.Connect();
+ await context.Login();
+
+ //var builder = new MessageBuilder().Text("Awoo");
+ //var message = await context.SendFriendMessage(1925648680, builder.Build());
+
+ await Task.Delay(-1);
}
}
\ No newline at end of file
diff --git a/Lagrange.Core.Runner/QrCodeHelper.cs b/Lagrange.Core.Runner/QrCodeHelper.cs
new file mode 100644
index 00000000..2db98960
--- /dev/null
+++ b/Lagrange.Core.Runner/QrCodeHelper.cs
@@ -0,0 +1,49 @@
+using Net.Codecrete.QrCodeGenerator;
+
+namespace Lagrange.Core.Runner;
+
+internal static class QrCodeHelper
+{
+ // This part of the code is from "https://github.com/eric2788/Lagrange.Core/blob/fd20a5aec81cacd56d60f3130cf057461300fd3f/Lagrange.OneBot/Utility/QrCodeHelper.cs#L30C52-L30C52"
+ // Thanks to "https://github.com/eric2788"
+ internal static void Output(string text, bool compatibilityMode)
+ {
+ var segments = QrSegment.MakeSegments(text);
+ var qrCode = QrCode.EncodeSegments(segments, QrCode.Ecc.Low);
+
+ var (bottomHalfBlock, topHalfBlock, emptyBlock, fullBlock) = compatibilityMode ? (".", "^", " ", "@") : ("▄", "▀", " ", "█");
+
+ for (var y = 0; y < qrCode.Size + 2; y += 2)
+ {
+ for (var x = 0; x < qrCode.Size + 2; ++x)
+ {
+ var foregroundBlack = qrCode.GetModule(x - 1, y - 1);
+ var backgroundBlack = qrCode.GetModule(x - 1, y) || y > qrCode.Size;
+
+ if (foregroundBlack && !backgroundBlack)
+ {
+ Console.Write(bottomHalfBlock);
+ }
+ else if (!foregroundBlack && backgroundBlack)
+ {
+ Console.Write(topHalfBlock);
+ }
+ else if (foregroundBlack && backgroundBlack)
+ {
+ Console.Write(emptyBlock);
+
+ }
+ else if (!foregroundBlack && !backgroundBlack)
+ {
+ Console.Write(fullBlock);
+ }
+ }
+ Console.Write("\n");
+ }
+
+ if (compatibilityMode)
+ {
+ Console.WriteLine("Please scan this QR code from a distance with your smart phone.\nScanning may fail if you are too close.");
+ }
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.Test/AssemblyInfo.cs b/Lagrange.Core.Test/AssemblyInfo.cs
new file mode 100644
index 00000000..4952ec12
--- /dev/null
+++ b/Lagrange.Core.Test/AssemblyInfo.cs
@@ -0,0 +1 @@
+[assembly: Parallelizable(ParallelScope.All)]
\ No newline at end of file
diff --git a/Lagrange.Core.Test/Binary/BinaryPacketTest.cs b/Lagrange.Core.Test/Binary/BinaryPacketTest.cs
index 455d1701..dfd090f6 100644
--- a/Lagrange.Core.Test/Binary/BinaryPacketTest.cs
+++ b/Lagrange.Core.Test/Binary/BinaryPacketTest.cs
@@ -67,12 +67,12 @@ public void TestStackBuffer()
{
var packet = new BinaryPacket(StackBuffer.AsSpan());
- uint length = packet.ReadUInt32();
- int value1 = packet.ReadInt32();
- long value2 = packet.ReadInt64();
- uint value3 = packet.ReadUInt32();
- long value4 = packet.ReadInt64();
- ulong value5 = packet.ReadUInt64();
+ uint length = packet.Read();
+ int value1 = packet.Read();
+ long value2 = packet.Read();
+ uint value3 = packet.Read();
+ long value4 = packet.Read();
+ ulong value5 = packet.Read();
string value6 = Encoding.UTF8.GetString(packet.ReadBytes(Prefix.Int16 | Prefix.WithPrefix));
string value7 = Encoding.UTF8.GetString(packet.ReadBytes(Prefix.Int32 | Prefix.WithPrefix));
@@ -96,9 +96,9 @@ public void TestArrayPoolBuffer()
{
var packet = new BinaryPacket(ArrayPoolBuffer.AsSpan());
- short value1 = packet.ReadInt16();
- long value2 = packet.ReadInt64();
- ushort value3 = packet.ReadUInt16();
+ short value1 = packet.Read();
+ long value2 = packet.Read();
+ ushort value3 = packet.Read();
string value4 = Encoding.UTF8.GetString(packet.ReadBytes(Prefix.Int8 | Prefix.WithPrefix));
string value5 = Encoding.UTF8.GetString(packet.ReadBytes(Prefix.Int32 | Prefix.WithPrefix));
var value6 = packet.ReadBytes(Prefix.Int32 | Prefix.WithPrefix).ToArray();
@@ -120,15 +120,15 @@ public void TestArrayPoolBuffer()
public void TestPeekBuffer()
{
var reader = new BinaryPacket(PeekBuffer.AsSpan());
+
+ byte value1 = reader.Peek();
+ short value2 = reader.Peek();
+ int value3 = reader.Peek();
+ long value4 = reader.Peek();
- byte value1 = reader.PeekByte();
- short value2 = reader.PeekInt16();
- int value3 = reader.PeekInt32();
- long value4 = reader.PeekInt64();
-
- ushort value5 = reader.PeekUInt16();
- uint value6 = reader.PeekUInt32();
- ulong value7 = reader.PeekUInt64();
+ ushort value5 = reader.Peek();
+ uint value6 = reader.Peek();
+ ulong value7 = reader.Peek();
reader.Skip(8);
var span = reader.CreateReadOnlySpan();
@@ -154,8 +154,8 @@ public void TestReadOnlyMemory()
{
var reader = new BinaryPacket(ReadOnlyMemoryBuffer);
- long value1 = reader.ReadInt64();
- long value2 = reader.ReadInt64();
+ long value1 = reader.Read();
+ long value2 = reader.Read();
int length = reader.ToArray().Length;
Assert.Multiple(() =>
@@ -171,7 +171,7 @@ public void TestExitLengthBarrier()
{
var packet = new BinaryPacket(ExitLengthBarrierBuffer.AsSpan());
- int value = packet.ReadInt32();
+ int value = packet.Read();
Assert.Multiple(() =>
{
diff --git a/Lagrange.Core.Test/Codec/VideoTest.cs b/Lagrange.Core.Test/Codec/VideoTest.cs
deleted file mode 100644
index 0ad7825e..00000000
--- a/Lagrange.Core.Test/Codec/VideoTest.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using Lagrange.Codec;
-using Lagrange.Core.Utility;
-
-namespace Lagrange.Core.Test.Codec;
-
-[TestFixture]
-public class VideoTest
-{
- private byte[] _video;
-
- [SetUp]
- public void Setup()
- {
- _video = File.ReadAllBytes("/Users/wenxuanlin/Downloads/28426634695-1-192.mp4");
- }
-
- [Test]
- public void Test()
- {
- var size = VideoCodec.GetSize(_video);
- var firstFrame = VideoCodec.FirstFrame(_video);
- File.WriteAllBytes("/Users/wenxuanlin/Downloads/firstFrame.jpg", firstFrame);
-
- var format = ImageHelper.Resolve(firstFrame, out var frameSize);
-
- Assert.Multiple(() =>
- {
- Assert.That(size, Is.Not.Default);
- Assert.That(firstFrame, Is.Not.Null);
- Assert.That(format, Is.EqualTo(ImageFormat.Jpeg2000));
- Assert.That(size.Height, Is.EqualTo(frameSize.X));
- Assert.That(size.Width, Is.EqualTo(frameSize.Y));
- });
- Assert.Pass();
- }
-}
\ No newline at end of file
diff --git a/Lagrange.Core.Test/Cryptography/AesGcmTest.cs b/Lagrange.Core.Test/Cryptography/AesGcmTest.cs
new file mode 100644
index 00000000..c33cf180
--- /dev/null
+++ b/Lagrange.Core.Test/Cryptography/AesGcmTest.cs
@@ -0,0 +1,157 @@
+using System.Security.Cryptography;
+using Lagrange.Core.Utility.Cryptography;
+
+namespace Lagrange.Core.Test.Cryptography;
+
+[TestFixture]
+public class AesGcmTests
+{
+ private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
+ private static readonly int[] PlaintextSizes = [0, 1, 15, 16, 33, 64];
+
+ [TestCase(128, false)]
+ [TestCase(192, false)]
+ [TestCase(256, false)]
+ [TestCase(128, true)]
+ [TestCase(192, true)]
+ [TestCase(256, true)]
+ public void Encrypt_Decrypt_Matches_SystemAesGcm(int keyBits, bool useHwAes)
+ {
+ int keySize = keyBits / 8;
+ byte[] key = new byte[keySize];
+ byte[] nonce = new byte[12]; // Standard 12-byte nonce for GCM
+ byte[] associatedData = new byte[17];
+
+ Rng.GetBytes(key);
+ Rng.GetBytes(nonce);
+ Rng.GetBytes(associatedData);
+
+ foreach (int ptSize in PlaintextSizes)
+ {
+ byte[] plaintext = new byte[ptSize];
+ Rng.GetBytes(plaintext);
+
+ byte[] expectedCiphertext = new byte[ptSize];
+ byte[] expectedTag = new byte[AesGcmImpl.TagSize];
+ using (var net = new AesGcm(key, AesGcmImpl.TagSize))
+ {
+ net.Encrypt(nonce, plaintext, expectedCiphertext, expectedTag, associatedData);
+ }
+
+ byte[] actualCiphertext = new byte[ptSize];
+ byte[] actualTag = new byte[AesGcmImpl.TagSize];
+ var impl = new AesGcmImpl(key, useHwAes);
+ impl.Encrypt(nonce, plaintext, associatedData, actualCiphertext, actualTag);
+
+ Assert.That(actualCiphertext, Is.EqualTo(expectedCiphertext), $"Ciphertext mismatch for {keyBits}-bit key, plaintext length {ptSize}");
+ Assert.That(actualTag, Is.EqualTo(expectedTag), $"Tag mismatch for {keyBits}-bit key, plaintext length {ptSize}");
+
+ byte[] decrypted = new byte[ptSize];
+ impl.Decrypt(nonce, actualCiphertext, associatedData, actualTag, decrypted);
+ Assert.That(decrypted, Is.EqualTo(plaintext), $"Decrypted plaintext mismatch for {keyBits}-bit key");
+ }
+ }
+
+ [TestCase(128, false)]
+ [TestCase(192, false)]
+ [TestCase(256, false)]
+ [TestCase(128, true)]
+ [TestCase(192, true)]
+ [TestCase(256, true)]
+ public void CrossDecrypt_CustomDecryptsSystemCipher(int keySizeBits, bool useHwAes)
+ {
+ byte[] key = new byte[keySizeBits / 8];
+ byte[] nonce = new byte[12];
+ RandomNumberGenerator.Fill(key);
+ RandomNumberGenerator.Fill(nonce);
+
+ foreach (int ptLen in (int[])[0, 1, 16, 100, 1024])
+ {
+ byte[] plaintext = new byte[ptLen];
+ byte[] aad = new byte[16];
+ RandomNumberGenerator.Fill(plaintext);
+ RandomNumberGenerator.Fill(aad);
+
+ byte[] ciphertext = new byte[ptLen];
+ byte[] tag = new byte[16];
+
+ using (var sysAes = new AesGcm(key, AesGcmImpl.TagSize))
+ {
+ sysAes.Encrypt(nonce, plaintext, ciphertext, tag, aad);
+ }
+
+ var impl = new AesGcmImpl(key, useHwAes);
+ byte[] decrypted = new byte[ptLen];
+ impl.Decrypt(nonce, ciphertext, aad, tag, decrypted);
+
+ Assert.That(decrypted, Is.EqualTo(plaintext), $"System→Custom cross-decrypt failed for keySize={keySizeBits}, ptLen={ptLen}");
+ }
+ }
+
+ [TestCase(128, false)]
+ [TestCase(192, false)]
+ [TestCase(256, false)]
+ [TestCase(128, true)]
+ [TestCase(192, true)]
+ [TestCase(256, true)]
+ public void CrossDecrypt_SystemDecryptsCustomCipher(int keySizeBits, bool useHwAes)
+ {
+ byte[] key = new byte[keySizeBits / 8];
+ byte[] nonce = new byte[12];
+ RandomNumberGenerator.Fill(key);
+ RandomNumberGenerator.Fill(nonce);
+
+ foreach (int ptLen in new[] { 0, 1, 16, 100, 1024 })
+ {
+ byte[] plaintext = new byte[ptLen];
+ byte[] aad = new byte[16];
+ RandomNumberGenerator.Fill(plaintext);
+ RandomNumberGenerator.Fill(aad);
+
+ byte[] ciphertext = new byte[ptLen];
+ byte[] tag = new byte[16];
+
+ var impl = new AesGcmImpl(key, useHwAes);
+ impl.Encrypt(nonce, plaintext, aad, ciphertext, tag);
+
+ byte[] decrypted = new byte[ptLen];
+ using (var sysAes = new AesGcm(key, AesGcmImpl.TagSize))
+ {
+ sysAes.Decrypt(nonce, ciphertext, tag, decrypted, aad);
+ }
+
+ Assert.That(decrypted, Is.EqualTo(plaintext), $"Custom→System cross-decrypt failed for keySize={keySizeBits}, ptLen={ptLen}");
+ }
+ }
+
+ [TestCase(12), TestCase(13), TestCase(14), TestCase(15), TestCase(16)]
+ public void Encrypt_Decrypt_Multiple_Nonce(int nonceSize)
+ {
+ byte[] key = new byte[16];
+ byte[] nonce = new byte[nonceSize]; // 128-bit nonce
+ byte[] plaintext = new byte[32];
+ byte[] associatedData = new byte[16];
+
+ Rng.GetBytes(key);
+ Rng.GetBytes(nonce);
+ Rng.GetBytes(plaintext);
+ Rng.GetBytes(associatedData);
+
+ var impl = new AesGcmImpl(key, false);
+ var ciphertext = new byte[plaintext.Length];
+ var tag = new byte[AesGcmImpl.TagSize];
+
+ impl.Encrypt(nonce, plaintext, associatedData, ciphertext, tag);
+
+ var decrypted = new byte[plaintext.Length];
+ impl.Decrypt(nonce, ciphertext, associatedData, tag, decrypted);
+
+ Assert.That(decrypted, Is.EqualTo(plaintext), "Decrypted plaintext mismatch for 128-bit nonce");
+ }
+
+ [OneTimeTearDown]
+ public void Cleanup()
+ {
+ Rng.Dispose();
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core.Test/Cryptography/EcdhTest.cs b/Lagrange.Core.Test/Cryptography/EcdhTest.cs
index dcc817e8..7d01868d 100644
--- a/Lagrange.Core.Test/Cryptography/EcdhTest.cs
+++ b/Lagrange.Core.Test/Cryptography/EcdhTest.cs
@@ -1,3 +1,4 @@
+using System.Security.Cryptography;
using Lagrange.Core.Utility.Cryptography;
namespace Lagrange.Core.Test.Cryptography;
@@ -8,9 +9,8 @@ public class EcdhTest
{
private EcdhProvider _alice;
private EcdhProvider _bob;
-
private EcdhProvider _customSecret;
-
+
[SetUp]
public void Setup()
{
@@ -20,42 +20,498 @@ public void Setup()
var secret = _alice.PackSecret();
_customSecret = new EcdhProvider(EllipticCurve.Prime256V1, secret); // same secret should generate same public key
}
-
+
+ #region Basic ECDH Tests
+
[Test]
- public void Test()
+ public void Test_BasicKeyExchange_CompressedKeys()
{
var alicePubCompressed = _alice.PackPublic(true);
var bobPubCompressed = _bob.PackPublic(true);
-
+
var aliceSharedPacked = _alice.KeyExchange(bobPubCompressed, true);
var bobSharedPacked = _bob.KeyExchange(alicePubCompressed, true);
-
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceSharedPacked, Is.EqualTo(bobSharedPacked), "Shared secrets should match");
+ Assert.That(aliceSharedPacked, Has.Length.EqualTo(16), "MD5 hash should be 16 bytes");
+ });
+ }
+
+ [Test]
+ public void Test_BasicKeyExchange_UncompressedKeys()
+ {
var alicePub = _alice.PackPublic(false);
var bobPub = _bob.PackPublic(false);
-
+
var aliceShared = _alice.KeyExchange(bobPub, true);
var bobShared = _bob.KeyExchange(alicePub, true);
-
- var aliceSecret = _alice.PackSecret();
- var bobSecret = _bob.PackSecret();
-
+
Assert.Multiple(() =>
{
- Assert.That(aliceShared, Is.EqualTo(bobShared)); // Equality check
- Assert.That(aliceSharedPacked, Is.EqualTo(bobSharedPacked)); // Equality check
- Assert.That(aliceSecret, Is.Not.EqualTo(bobSecret)); // Uniqueness check
- Assert.That(aliceSecret, Has.Length.EqualTo(aliceSecret[3] + 4)); // Length check
- Assert.That(bobSecret, Has.Length.EqualTo(bobSecret[3] + 4)); // Length check
+ Assert.That(aliceShared, Is.EqualTo(bobShared), "Shared secrets should match");
+ Assert.That(aliceShared, Has.Length.EqualTo(16), "MD5 hash should be 16 bytes");
});
- Assert.Pass();
}
-
+
[Test]
public void TestCustomSecret()
{
var customPub = _customSecret.PackPublic(false);
var alicePub = _alice.PackPublic(false);
-
- Assert.That(customPub, Is.EqualTo(alicePub));
+
+ Assert.That(customPub, Is.EqualTo(alicePub), "Same secret should generate same public key");
+ }
+
+ [Test]
+ public void Test_SecretUniqueness()
+ {
+ var aliceSecret = _alice.PackSecret();
+ var bobSecret = _bob.PackSecret();
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceSecret, Is.Not.EqualTo(bobSecret), "Secrets should be unique");
+ Assert.That(aliceSecret, Has.Length.EqualTo(aliceSecret[3] + 4), "Secret length should match metadata");
+ Assert.That(bobSecret, Has.Length.EqualTo(bobSecret[3] + 4), "Secret length should match metadata");
+ });
+ }
+
+ #endregion
+
+ #region Fixed-Size Output Tests (Critical for the bug fix)
+
+ [Test]
+ public void Test_SharedSecret_FixedSize_Prime256V1_NoHash()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPub = bob.PackPublic(false);
+ var sharedSecret = alice.KeyExchange(bobPub, false);
+
+ Assert.That(sharedSecret, Has.Length.EqualTo(32),
+ "Prime256V1 shared secret without hash should be exactly 32 bytes");
+ }
+
+ [Test]
+ public void Test_SharedSecret_FixedSize_Prime256V1_WithHash()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPub = bob.PackPublic(false);
+ var sharedSecret = alice.KeyExchange(bobPub, true);
+
+ Assert.That(sharedSecret, Has.Length.EqualTo(16),
+ "Prime256V1 shared secret with MD5 hash should be exactly 16 bytes");
+ }
+
+ [Test]
+ public void Test_SharedSecret_FixedSize_Secp192K1_NoHash()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Secp192K1);
+ var bob = new EcdhProvider(EllipticCurve.Secp192K1);
+
+ var bobPub = bob.PackPublic(false);
+ var sharedSecret = alice.KeyExchange(bobPub, false);
+
+ Assert.That(sharedSecret, Has.Length.EqualTo(24),
+ "Secp192K1 shared secret without hash should be exactly 24 bytes");
+ }
+
+ [Test]
+ public void Test_SharedSecret_FixedSize_Secp192K1_WithHash()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Secp192K1);
+ var bob = new EcdhProvider(EllipticCurve.Secp192K1);
+
+ var bobPub = bob.PackPublic(false);
+ var sharedSecret = alice.KeyExchange(bobPub, true);
+
+ Assert.That(sharedSecret, Has.Length.EqualTo(16),
+ "Secp192K1 shared secret with MD5 hash should be exactly 16 bytes");
+ }
+
+ [Test]
+ public void Test_SharedSecret_ConsistentSize_MultipleExchanges()
+ {
+ // Test that the shared secret size is consistent across multiple key exchanges
+ var sizes = new HashSet();
+
+ for (int i = 0; i < 10; i++)
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPub = bob.PackPublic(false);
+ var sharedSecret = alice.KeyExchange(bobPub, false);
+ sizes.Add(sharedSecret.Length);
+ }
+
+ Assert.That(sizes, Has.Count.EqualTo(1), "All shared secrets should have the same length");
+ Assert.That(sizes.First(), Is.EqualTo(32), "All Prime256V1 shared secrets should be 32 bytes");
+ }
+
+ #endregion
+
+ #region Public Key Format Tests
+
+ [Test]
+ public void Test_CompressedPublicKey_Prime256V1_Format()
+ {
+ var provider = new EcdhProvider(EllipticCurve.Prime256V1);
+ var compressed = provider.PackPublic(true);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(compressed, Has.Length.EqualTo(33), "Compressed Prime256V1 key should be 33 bytes");
+ Assert.That(compressed[0], Is.EqualTo(0x02).Or.EqualTo(0x03), "First byte should be 0x02 or 0x03");
+ });
+ }
+
+ [Test]
+ public void Test_UncompressedPublicKey_Prime256V1_Format()
+ {
+ var provider = new EcdhProvider(EllipticCurve.Prime256V1);
+ var uncompressed = provider.PackPublic(false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(uncompressed, Has.Length.EqualTo(65), "Uncompressed Prime256V1 key should be 65 bytes");
+ Assert.That(uncompressed[0], Is.EqualTo(0x04), "First byte should be 0x04");
+ });
+ }
+
+ [Test]
+ public void Test_CompressedPublicKey_Secp192K1_Format()
+ {
+ var provider = new EcdhProvider(EllipticCurve.Secp192K1);
+ var compressed = provider.PackPublic(true);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(compressed, Has.Length.EqualTo(25), "Compressed Secp192K1 key should be 25 bytes");
+ Assert.That(compressed[0], Is.EqualTo(0x02).Or.EqualTo(0x03), "First byte should be 0x02 or 0x03");
+ });
+ }
+
+ [Test]
+ public void Test_UncompressedPublicKey_Secp192K1_Format()
+ {
+ var provider = new EcdhProvider(EllipticCurve.Secp192K1);
+ var uncompressed = provider.PackPublic(false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(uncompressed, Has.Length.EqualTo(49), "Uncompressed Secp192K1 key should be 49 bytes");
+ Assert.That(uncompressed[0], Is.EqualTo(0x04), "First byte should be 0x04");
+ });
+ }
+
+ [Test]
+ public void Test_PublicKey_Padding_NoLeadingZerosStripped()
+ {
+ // This test ensures that even when X or Y coordinates have leading zeros,
+ // they are properly padded to the full size
+ var provider = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ // Generate multiple keys and check they all have consistent size
+ for (int i = 0; i < 20; i++)
+ {
+ var newProvider = new EcdhProvider(EllipticCurve.Prime256V1);
+ var compressed = newProvider.PackPublic(true);
+ var uncompressed = newProvider.PackPublic(false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(compressed, Has.Length.EqualTo(33),
+ $"Iteration {i}: Compressed key should always be 33 bytes");
+ Assert.That(uncompressed, Has.Length.EqualTo(65),
+ $"Iteration {i}: Uncompressed key should always be 65 bytes");
+ });
+ }
+ }
+
+ #endregion
+
+ #region Interoperability Tests
+
+ [Test]
+ public void Test_CompressedAndUncompressed_ProduceSameSharedSecret()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPubCompressed = bob.PackPublic(true);
+ var bobPubUncompressed = bob.PackPublic(false);
+
+ var sharedFromCompressed = alice.KeyExchange(bobPubCompressed, false);
+ var sharedFromUncompressed = alice.KeyExchange(bobPubUncompressed, false);
+
+ Assert.That(sharedFromCompressed, Is.EqualTo(sharedFromUncompressed),
+ "Shared secret should be the same regardless of public key compression");
+ }
+
+ [Test]
+ public void Test_SymmetricKeyExchange_Compressed()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var alicePub = alice.PackPublic(true);
+ var bobPub = bob.PackPublic(true);
+
+ var aliceShared = alice.KeyExchange(bobPub, false);
+ var bobShared = bob.KeyExchange(alicePub, false);
+
+ Assert.That(aliceShared, Is.EqualTo(bobShared),
+ "Alice and Bob should derive the same shared secret");
+ }
+
+ [Test]
+ public void Test_SymmetricKeyExchange_Uncompressed()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var alicePub = alice.PackPublic(false);
+ var bobPub = bob.PackPublic(false);
+
+ var aliceShared = alice.KeyExchange(bobPub, false);
+ var bobShared = bob.KeyExchange(alicePub, false);
+
+ Assert.That(aliceShared, Is.EqualTo(bobShared),
+ "Alice and Bob should derive the same shared secret");
+ }
+
+ #endregion
+
+ #region Error Handling Tests
+
+ [Test]
+ public void Test_InvalidPublicKey_Length()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var invalidKey = new byte[20]; // Invalid length
+
+ Assert.Throws(() => alice.KeyExchange(invalidKey, false),
+ "Should throw exception for invalid public key length");
+ }
+
+ [Test]
+ public void Test_InvalidPublicKey_NotOnCurve()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ // Create an invalid public key (random bytes that won't be on the curve)
+ var invalidKey = new byte[65];
+ invalidKey[0] = 0x04;
+ RandomNumberGenerator.Fill(invalidKey.AsSpan(1));
+
+ Assert.Throws(() => alice.KeyExchange(invalidKey, false),
+ "Should throw exception when public key is not on the curve");
+ }
+
+ [Test]
+ public void Test_InvalidSecret_Length()
+ {
+ var invalidSecret = new byte[10];
+ invalidSecret[3] = 20; // Claim length is 20 but actual is 6
+ RandomNumberGenerator.Fill(invalidSecret.AsSpan(4));
+
+ Assert.Throws(() => new EcdhProvider(EllipticCurve.Prime256V1, invalidSecret),
+ "Should throw exception when secret length doesn't match metadata");
+ }
+
+ #endregion
+
+ #region Secret Packing/Unpacking Tests
+
+ [Test]
+ public void Test_SecretPacking_RoundTrip()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var packedSecret = alice.PackSecret();
+
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1, packedSecret);
+
+ var alicePub = alice.PackPublic(false);
+ var bobPub = bob.PackPublic(false);
+
+ Assert.That(bobPub, Is.EqualTo(alicePub),
+ "Same secret should produce same public key after unpacking");
+ }
+
+ [Test]
+ public void Test_SecretPacking_Format()
+ {
+ var provider = new EcdhProvider(EllipticCurve.Prime256V1);
+ var packed = provider.PackSecret();
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(packed, Has.Length.GreaterThanOrEqualTo(4), "Packed secret should have at least 4 bytes");
+ Assert.That(packed[3], Is.EqualTo(packed.Length - 4), "Length metadata should match actual data length");
+ });
+ }
+
+ #endregion
+
+ #region Both Curves Tests
+
+ [Test]
+ public void Test_Prime256V1_FullKeyExchange()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var alicePub = alice.PackPublic(false);
+ var bobPub = bob.PackPublic(false);
+
+ var aliceShared = alice.KeyExchange(bobPub, false);
+ var bobShared = bob.KeyExchange(alicePub, false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceShared, Is.EqualTo(bobShared), "Shared secrets should match");
+ Assert.That(aliceShared, Has.Length.EqualTo(32), "Prime256V1 shared secret should be 32 bytes");
+ });
+ }
+
+ [Test]
+ public void Test_Secp192K1_FullKeyExchange()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Secp192K1);
+ var bob = new EcdhProvider(EllipticCurve.Secp192K1);
+
+ var alicePub = alice.PackPublic(false);
+ var bobPub = bob.PackPublic(false);
+
+ var aliceShared = alice.KeyExchange(bobPub, false);
+ var bobShared = bob.KeyExchange(alicePub, false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceShared, Is.EqualTo(bobShared), "Shared secrets should match");
+ Assert.That(aliceShared, Has.Length.EqualTo(24), "Secp192K1 shared secret should be 24 bytes");
+ });
+ }
+
+ [Test]
+ public void Test_DifferentCurves_ProduceDifferentResults()
+ {
+ var provider1 = new EcdhProvider(EllipticCurve.Prime256V1);
+ var provider2 = new EcdhProvider(EllipticCurve.Secp192K1);
+
+ var pub1 = provider1.PackPublic(false);
+ var pub2 = provider2.PackPublic(false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(pub1, Has.Length.Not.EqualTo(pub2.Length),
+ "Different curves should produce different length public keys");
+ Assert.That(pub1, Is.Not.EqualTo(pub2),
+ "Different curves should produce different public keys");
+ });
}
-}
\ No newline at end of file
+
+ #endregion
+
+ #region Hash vs Non-Hash Tests
+
+ [Test]
+ public void Test_HashVsNonHash_DifferentLengths()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPub = bob.PackPublic(false);
+
+ var sharedNoHash = alice.KeyExchange(bobPub, false);
+ var sharedWithHash = alice.KeyExchange(bobPub, true);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(sharedNoHash, Has.Length.EqualTo(32), "Non-hashed should be 32 bytes");
+ Assert.That(sharedWithHash, Has.Length.EqualTo(16), "MD5 hashed should be 16 bytes");
+ Assert.That(sharedNoHash, Is.Not.EqualTo(sharedWithHash), "Hashed and non-hashed should be different");
+ });
+ }
+
+ [Test]
+ public void Test_HashedSharedSecret_IsDeterministic()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var bobPub = bob.PackPublic(false);
+
+ var shared1 = alice.KeyExchange(bobPub, true);
+ var shared2 = alice.KeyExchange(bobPub, true);
+
+ Assert.That(shared1, Is.EqualTo(shared2),
+ "Multiple calls with same keys should produce same hashed result");
+ }
+
+ #endregion
+
+ #region Multiple Exchange Tests
+
+ [Test]
+ public void Test_MultipleParties_KeyExchange()
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+ var charlie = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var alicePub = alice.PackPublic(false);
+ var bobPub = bob.PackPublic(false);
+ var charliePub = charlie.PackPublic(false);
+
+ var aliceBobShared = alice.KeyExchange(bobPub, false);
+ var bobAliceShared = bob.KeyExchange(alicePub, false);
+
+ var aliceCharlieShared = alice.KeyExchange(charliePub, false);
+ var charlieAliceShared = charlie.KeyExchange(alicePub, false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceBobShared, Is.EqualTo(bobAliceShared),
+ "Alice-Bob shared secret should match");
+ Assert.That(aliceCharlieShared, Is.EqualTo(charlieAliceShared),
+ "Alice-Charlie shared secret should match");
+ Assert.That(aliceBobShared, Is.Not.EqualTo(aliceCharlieShared),
+ "Different pairs should have different shared secrets");
+ });
+ }
+
+ #endregion
+
+ #region Stress Tests
+
+ [Test]
+ public void Test_StressTest_100KeyExchanges()
+ {
+ for (int i = 0; i < 100; i++)
+ {
+ var alice = new EcdhProvider(EllipticCurve.Prime256V1);
+ var bob = new EcdhProvider(EllipticCurve.Prime256V1);
+
+ var alicePub = alice.PackPublic(true);
+ var bobPub = bob.PackPublic(true);
+
+ var aliceShared = alice.KeyExchange(bobPub, false);
+ var bobShared = bob.KeyExchange(alicePub, false);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(aliceShared, Is.EqualTo(bobShared), $"Iteration {i}: Shared secrets should match");
+ Assert.That(aliceShared, Has.Length.EqualTo(32), $"Iteration {i}: Should be 32 bytes");
+ });
+ }
+ }
+
+ #endregion
+}
diff --git a/Lagrange.Core.Test/Lagrange.Core.Test.csproj b/Lagrange.Core.Test/Lagrange.Core.Test.csproj
index 3fbc5003..b4dcc69c 100644
--- a/Lagrange.Core.Test/Lagrange.Core.Test.csproj
+++ b/Lagrange.Core.Test/Lagrange.Core.Test.csproj
@@ -1,7 +1,7 @@
- net9.0
+ net10.0
latest
enable
enable
diff --git a/Lagrange.Core.sln b/Lagrange.Core.sln
deleted file mode 100644
index c490f6c0..00000000
--- a/Lagrange.Core.sln
+++ /dev/null
@@ -1,34 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lagrange.Core", "Lagrange.Core\Lagrange.Core.csproj", "{DEC7490B-BAF9-43D7-99D2-195804C2CB70}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lagrange.Core.Test", "Lagrange.Core.Test\Lagrange.Core.Test.csproj", "{11E31EFF-0EB8-40B3-AED7-3B262A004F8A}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lagrange.Codec", "Lagrange.Codec\Lagrange.Codec.csproj", "{3AB8C869-44DC-4F71-BA1F-50C19F124A1A}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lagrange.Core.Runner", "Lagrange.Core.Runner\Lagrange.Core.Runner.csproj", "{CEB9D300-9337-420E-B2BD-772399D84051}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {DEC7490B-BAF9-43D7-99D2-195804C2CB70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {DEC7490B-BAF9-43D7-99D2-195804C2CB70}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {DEC7490B-BAF9-43D7-99D2-195804C2CB70}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {DEC7490B-BAF9-43D7-99D2-195804C2CB70}.Release|Any CPU.Build.0 = Release|Any CPU
- {11E31EFF-0EB8-40B3-AED7-3B262A004F8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {11E31EFF-0EB8-40B3-AED7-3B262A004F8A}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {11E31EFF-0EB8-40B3-AED7-3B262A004F8A}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {11E31EFF-0EB8-40B3-AED7-3B262A004F8A}.Release|Any CPU.Build.0 = Release|Any CPU
- {3AB8C869-44DC-4F71-BA1F-50C19F124A1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3AB8C869-44DC-4F71-BA1F-50C19F124A1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3AB8C869-44DC-4F71-BA1F-50C19F124A1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3AB8C869-44DC-4F71-BA1F-50C19F124A1A}.Release|Any CPU.Build.0 = Release|Any CPU
- {CEB9D300-9337-420E-B2BD-772399D84051}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CEB9D300-9337-420E-B2BD-772399D84051}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CEB9D300-9337-420E-B2BD-772399D84051}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CEB9D300-9337-420E-B2BD-772399D84051}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
-EndGlobal
diff --git a/Lagrange.Core.slnx b/Lagrange.Core.slnx
new file mode 100644
index 00000000..53b6a938
--- /dev/null
+++ b/Lagrange.Core.slnx
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Lagrange.Core/AssemblyInfo.cs b/Lagrange.Core/AssemblyInfo.cs
index 7676179e..05abceda 100644
--- a/Lagrange.Core/AssemblyInfo.cs
+++ b/Lagrange.Core/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lagrange.Core.Test")]
-[assembly: InternalsVisibleTo("Lagrange.Core.Runner")]
-[assembly: InternalsVisibleTo("Lagrange.OneBot")]
\ No newline at end of file
+[assembly: InternalsVisibleTo("Lagrange.Core.Runner")]
\ No newline at end of file
diff --git a/Lagrange.Core/BotContext.cs b/Lagrange.Core/BotContext.cs
index 3a68a803..aceb89e0 100644
--- a/Lagrange.Core/BotContext.cs
+++ b/Lagrange.Core/BotContext.cs
@@ -1,11 +1,12 @@
-using Lagrange.Core.Common;
+using System.Diagnostics.CodeAnalysis;
+using Lagrange.Core.Common;
using Lagrange.Core.Events;
using Lagrange.Core.Events.EventArgs;
using Lagrange.Core.Internal.Context;
namespace Lagrange.Core;
-public class BotContext
+public class BotContext : IDisposable
{
internal BotContext(BotConfig config, BotKeystore keystore, BotAppInfo appInfo)
{
@@ -20,13 +21,15 @@ internal BotContext(BotConfig config, BotKeystore keystore, BotAppInfo appInfo)
ServiceContext = new ServiceContext(this);
SocketContext = new SocketContext(this);
EventContext = new EventContext(this);
+ HighwayContext = new HighwayContext(this);
+ FlashTransferContext = new FlashTransferContext(this);
}
public BotConfig Config { get; }
public BotAppInfo AppInfo { get; }
public BotKeystore Keystore { get; }
- public BotInfo? BotInfo { get; internal set; }
-
+ public long BotUin => Keystore.Uin;
+ public BotInfo? BotInfo => Keystore.BotInfo;
public bool IsOnline { get; internal set; }
public EventInvoker EventInvoker { get; }
@@ -36,20 +39,58 @@ internal BotContext(BotConfig config, BotKeystore keystore, BotAppInfo appInfo)
internal ServiceContext ServiceContext { get; }
internal SocketContext SocketContext { get; }
internal EventContext EventContext { get; }
+
+ internal HighwayContext HighwayContext { get; }
+ internal FlashTransferContext FlashTransferContext { get; }
#region Shortcut Methods
-
- public void LogCritical(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Critical, message));
-
- public void LogError(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Error, message));
- public void LogWarning(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Warning, message));
-
- public void LogInfo(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Information, message));
-
- public void LogDebug(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Debug, message));
-
- public void LogTrace(string tag, string message) => EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Trace, message));
+ public void LogCritical(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, Exception? exception = null, params object?[] args)
+ {
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Critical, string.Format(text, args), exception));
+ }
+
+ public void LogError(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, Exception? exception = null, params object?[] args)
+ {
+ if (Config.LogLevel > LogLevel.Error) return;
+
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Error, string.Format(text, args), exception));
+ }
+
+ public void LogWarning(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, Exception? exception = null, params object?[] args)
+ {
+ if (Config.LogLevel > LogLevel.Warning) return;
+
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Warning, string.Format(text, args), exception));
+ }
+
+ public void LogInfo(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, params object?[] args)
+ {
+ if (Config.LogLevel > LogLevel.Information) return;
+
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Information, string.Format(text, args), null));
+ }
+
+ public void LogDebug(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, params object?[] args)
+ {
+ if (Config.LogLevel > LogLevel.Debug) return;
+
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Debug, string.Format(text, args), null));
+ }
+
+ public void LogTrace(string tag, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string text, params object?[] args)
+ {
+ if (Config.LogLevel > LogLevel.Trace) return;
+
+ EventInvoker.PostEvent(new BotLogEvent(tag, LogLevel.Trace, string.Format(text, args), null));
+ }
#endregion
+
+ public void Dispose()
+ {
+ EventInvoker.Dispose();
+ SocketContext.Dispose();
+ EventContext.Dispose();
+ }
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/AndroidBotSignProvider.cs b/Lagrange.Core/Common/AndroidBotSignProvider.cs
new file mode 100644
index 00000000..054dec53
--- /dev/null
+++ b/Lagrange.Core/Common/AndroidBotSignProvider.cs
@@ -0,0 +1,247 @@
+using System.Text;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Lagrange.Core.Utility;
+
+namespace Lagrange.Core.Common;
+
+public abstract class AndroidBotSignProvider : BotSignProvider
+{
+ public abstract Task GetEnergy(long uin, string data);
+
+ public abstract Task GetDebugXwid(long uin, string data);
+}
+
+internal class DefaultAndroidBotSignProvider : AndroidBotSignProvider, IDisposable
+{
+ private const string Tag = nameof(DefaultAndroidBotSignProvider);
+
+ private readonly HttpClient _client = new();
+
+ private readonly string _url = "http://127.0.0.1:8081";
+
+ private static readonly HashSet WhiteListCommand =
+ [
+ "OidbSvcTrpcTcp.0xf88_1", "OidbSvcTrpcTcp.0x1105_1", "oidb_0xf7e_1",
+ "trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg", "OidbSvcTrpcTcp.0x92eb_0", "qzoneh5.h5.wnshtml",
+ "OidbSvc.0x580_1", "trpc.commercial.dataworks.UserActionReport_sso.SsoReport", "OidbSvcTrpcTcp.0xe37_1200",
+ "OidbSvcTrpcTcp.0xf67_5", "OidbSvcTrpcTcp.0x55f_0",
+ "MQUpdateSvc_com_qq_qzone_act.web.OidbSvcTrpcJsapiTcp.0x9377_0",
+ "trpc.down.intercept.Intercept.SsoGetInterceptFile", "wtlogin.device_lock", "qidianservice.207",
+ "SQQzoneSvc.addReply", "ResourceConfig.GetResourceReq", "wtlogin.name2uin",
+ "trpc.passwd.manager.PasswdManager.SetPasswd", "trpc.qqva.vipdata.Vipdata.SsoGetUserData",
+ "OidbSvc.0x8a1_0", "OidbSvcTrpcTcp.0x101e_2", "OidbSvcTrpcTcp.0xf67_1", "trpc.qpay.sso.web.Do",
+ "OidbSvcTrpcTcp.0xf6e_1", "OidbSvcTcp.0x102a", "trpc.o3.ecdh_access.EcdhAccess.SsoSecureA2Access",
+ "OidbSvcTrpcTcp.0x88d_0", "OidbSvcTrpcTcp.0x1258_1", "OidbSvcTrpcTcp.0x11ec_1", "OidbSvcTrpcTcp.0x899_9",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoComment", "SQQzoneSvc.like",
+ "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess", "OidbSvc.0x787_11", "OidbSvcTrpcTcp.0x1100_1",
+ "SQQzoneSvc.Custom.getFacade", "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
+ "ProfileService.Pb.ReqSystemMsgAction.Group", "OidbSvcTrpcTcp.0xf57_1", "OidbSvcTrpcTcp.0x12a9_200",
+ "wtlogin.exchange_emp", "OidbSvc.0x56c_6", "QChannelSvr.trpc.qchannel.commwriter.ComWriter.PublishFeed",
+ "OidbSvcTrpcTcp.0x6d9_4", "trpc.lplan.feed_svr.StatusWrite.SsoPostStatus",
+ "QChannelSvr.trpc.qchannel.commwriter.ComWriter.DoComment", "OidbSvc.0x592_15", "OidbSvc.0x592_8",
+ "OidbSvc.0x5eb_42261", "SummaryCard.ReqSummaryCard", "QQStranger.InteractiveMsgSvr.SsoSendInterMsg",
+ "ProfileService.GroupMngReq", "OidbSvcTrpcTcp.0xf89_1", "OidbSvc.0xe27", "ConnAuthSvr.get_app_info",
+ "qidianservice.135", "OidbSvc.0x5eb_96", "OidbSvc.0x592_5", "trpc.group_pro.msgproxy.sendmsg",
+ "oidb_0x43c_4", "OidbSvc.0x787_0", "ConnAuthSvr.get_app_info_emp", "OidbSvc.0xb3c_1",
+ "QQStranger.login_svr.SsoLoginInfoReport", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoBarrage",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetMainPageCommData", "QQConnectLogin.get_promote_page",
+ "trpc.springfestival.redpacket.LuckyBag.SsoSubmitGrade", "OidbSvc.0xb3c_6", "OidbSvc.0x89b_1",
+ "wtlogin.login", "OidbSvcTrpcTcp.0x7c2_5", "oidb_0xcf3_0", "gcbindgroupsso.get_appid",
+ "SQQzoneSvc.getVisitorNotify", "qidianservice.290", "trpc.qlive.word_svr.WordSvr.NewPublicChat",
+ "wtlogin.register", "OidbSvcTrpcTcp.0xf57_9", "friendlist.GetMultiTroopInfoReq", "StatSvc.GetOnlineStatus",
+ "OidbSvcTrpcTcp.0x10db_1", "OidbSvc.0x9fa", "OidbSvcTrpcTcp.0xe37_800", "qidianservice.269",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetCommentList", "OidbSvcTrpcTcp.0xf65_1",
+ "OidbSvcTrpcTcp.0x9127_1", "QQStranger.FeedPlazaSvr.SsoFeedPublish", "OidbSvc.0xb3c_get_by_id",
+ "OidbSvcTrpcTcp.0x11c5_100", "SQQzoneSvc.mobileqboss.get", "GDCTrpcProxy.down",
+ "trpc.login.ecdh.EcdhService.SsoQRLoginGenQr", "OidbSvcTrpcTcp.0xf59_2", "OidbSvc.0x592_10",
+ "OidbSvcTrpcTcp.0xfe7_3", "OidbSvc.0x592_18", "OidbSvc.0x88d_0", "trpc.qpay.red_pack_skin.Skin.SsoAddSkin",
+ "MsgProxy.SendMsg", "OidbSvcTrpcTcp.0x899_1", "trpc.lplan.user_manager_svr.User.SsoSetProfile",
+ "trpc.login.ecdh.EcdhService.SsoKeyExchange", "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLogin", "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginNewDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLoginUnusualDevice", "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
+ "QChannelSvr.trpc.qchannel.commwriter.ComWriter.DoReply", "OidbSvc.0x5eb_43",
+ "trpc.passwd.manager.PasswdManager.VerifyPasswd", "OidbSvc.0xb3c_update_5", "OidbSvc.0x592_17",
+ "trpc.login.ecdh.EcdhService.SsoQRLoginScanQr", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoLike",
+ "SQQzoneSvc.getProfileFeeds", "OidbSvc.0x6d6_0", "WalletGestureSvc.GetSignV2", "OidbSvcTrpcTcp.0x88d_14",
+ "friendlist.ModifyGroupInfoReq", "OidbSvc.oidb_0x758", "OidbSvcTrpcTcp.0xf57_106",
+ "QQConnectLogin.submit_promote_page_emp", "OidbSvcTrpcTcp.0x1107_1", "ProfileService.getGroupInfoReq",
+ "OidbSvcTrpcTcp.0x8a1_7", "OidbSvc.0x42d_4", "QQConnectLogin.auth", "OidbSvcTrpcTcp.0x8fc_3",
+ "ConnAuthSvr.get_auth_api_list_emp", "QQConnectLogin.auth_emp", "trpc.o3.report.Report.SsoReport",
+ "ConnAuthSvr.get_auth_api_list", "PushService.settoken", "trpc.lplan.feed_svr.StatusWrite.SsoComment",
+ "trpc.lplan.feed_svr.StatusWrite.SsoReply", "trpc.lplan.like_svr.Like.SsoDoLike", "OidbSvcTrpcTcp.0xf5d_11",
+ "miniapp.trpc.minigame.sdk_qgroup_svr.sdk_qgroup_svr.JoinGroup", "QQStranger.FeedSvr.SsoFeedPublish",
+ "OidbSvcTrpcTcp.0x9176_1", "OidbSvc.0x592_6", "LightAppSvc.mini_app_userapp.GetDropdownAppList",
+ "OidbSvc.0xb3c_add", "OidbSvc.0xb3c_get_undone", "OidbSvc.0x758_0", "OidbSvcTrpcTcp.0x10ed_1",
+ "OidbSvc.0xb3c_get_done", "OidbSvc.0xb3c_update", "OidbSvc.0xc26_0", "SQQzoneSvc.GetCate",
+ "OidbSvc.0xb3c_delete", "OidbSvc.0xb3c_share",
+ "FeedCloudSvr.trpc.videocircle.circleprofile.CircleProfile.SetProfile", "OidbSvc.0xb3c_get_done_count",
+ "OidbSvc.0x592_19", "OidbSvc.0xb3c", "OidbSvcTcp.0x88d_0", "OidbSvc.0xb3c_2",
+ "trpc.qlive.relationchain_svr.RelationchainSvr.Follow", "OidbSvc.0xe72", "OidbSvc.0xb3c_5",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoReply", "OidbSvc.0xb3c_4",
+ "trpc.qqstranger.common_proxy.CommonProxy.SsoHandle", "QQStranger.UserInfo.SsoSetMiniUserInfo",
+ "OidbSvcTrpcTcp.0xfe7_4", "oidb_0xd9c_11", "wtlogin_device.login", "OidbSvc.0x4ff_9", "OidbSvc.0xef0_1",
+ "OidbSvc.0xb3c_7", "OidbSvc.0x4ff_9_IMCore", "OidbSvcTrpcTcp.0x1250_0", "OidbSvcTrpcTcp.0xa80_1",
+ "OidbSvc.0x89a_0", "OidbSvc.0xb3c_8", "OidbSvcTrpcTcp.0x930e_0", "SQQzoneSvc.get", "OidbSvc.0x592",
+ "ConnAuthSvr.sdk_auth_api", "OidbSvc.0xcd5", "oidb_0xcf4_0", "OidbSvcTrpcTcp.0x5cf_11", "OidbSvc.0x899_0",
+ "OidbSvc.0x592_2", "OidbSvcTrpcTcp.0xf65_10", "OidbSvcTrpcTcp.0x92e4_0", "OidbSvc.0x592_7",
+ "ConnAuthSvr.fast_qq_login", "OidbSvc.0x758", "trpc.QQService.CommonLogic.StatusService.SsoGetLikeList",
+ "OidbSvc.0x592_11", "OidbSvc.0x592_12", "wtlogin_device.tran_sim_emp", "MessageSvc.PbGetGroupMsg",
+ "OidbSvc.0x8ba", "account.RequestQueryQQMobileContactsV3", "OidbSvcTrpcTcp.0x758_1",
+ "FeedCloudSvr.trpc.circlesearch.exhibition.ExhibitionSvr.ExhibitionSuggestion",
+ "trpc.msg.msg_svc.MsgService.SsoGetPeerSeq", "SQQzoneSvc.addComment", "WalletGestureSvc.GetPassword",
+ "OidbSvc.0x592_3", "OidbSvcTrpcTcp.0xf55_1", "WalletGestureSvc.SetPassword",
+ "friendlist.GetTroopMemberList", "OidbSvcTrpcTcp.0xfd4_1", "OidbSvcTrpcTcp.0xfa5_1",
+ "OidbSvcTrpcTcp.0x787_1", "trpc.qpay.encryptedtransfer.Encryption.SsoUINEncrypt", "oidb_0xeb1_1",
+ "gcbindgroupsso.unbind_group", "oidb_0xdc2_34", "trpc.qlive.qlive_proxy_svr.TrpcProxy.*", "OidbSvc.0x592_4",
+ "OidbSvcTrpcTcp.0xfe1_2", "SQQzoneSvc.publishmood", "trpc.down.intercept.Intercept.SsoGetDownloadTips",
+ "LightAppSvc.mini_app_cloudstorage.GetUserCloudStorage",
+ "trpc.down.joint_operation_game_intercept.JointOperationGameIntercept.SsoQueryConfig",
+ "GDCTrpcProxy.service", "SQQzoneSvc.forward", "OidbSvc.0x5eb_cn_switch", "OidbSvcTrpcTcp.0x930d_0",
+ "OidbSvc.0x6d7_0", "OidbSvcTrpcTcp.0xcd5", "trpc.o3.ecdh_access.EcdhAccess.SsoSecureA2Establish",
+ "OidbSvcTrpcTcp.0x102a_1", "OidbSvcTrpcTcp.0x89a_0", "trpc.msg.register_proxy.RegisterProxy.PushParams",
+ "QQConnectLogin.get_promote_page_emp", "QQStranger.UserInfo.SsoGetMiniUserInfo", "oidb_0xfd4_1",
+ "QQConnectLogin.submit_promote_page", "oidb_0xe37_800", "OidbSvcTrpcTcp.0x1102_1", "oidb_0x9045_1",
+ "oidb_0x7c4_0", "OidbSvcTrpcTcp.0xfe5_2", "oidb_0x7a2_0", "oidb_0x42e_3",
+ "friendlist.GetTroopAppointRemarkReq", "trpc.lplan.map_svr.Map.SsoReportLocation",
+ "OidbSvcTrpcTcp.0x125b_500", "friendlist.GetLastLoginInfoReq", "friendlist.GetFriendListReq",
+ "oidb_0xe37_1200", "OidbSvcTrpcTcp.0x9124_0", "VisitorSvc.ReqFavorite", "SQQzoneSvc.get_all_feedsphoto_ex",
+ "StatSvc.register", "SQQzoneSvc.getPhotoComment", "oidb_0x7df_3", "SQQzoneSvc.getActiveFeeds",
+ "SQQzoneSvc.preGetPassiveFeeds", "SQQzoneSvc.getAIONewestFeeds", "ResourceConfig.ClientReq",
+ "friendlist.getFriendGroupList", "SQQzoneSvc.photo", "OidbSvc.0xc33_42220",
+ "trpc.qmeta.mob_proxy_svr.MobProxy.SsoHandle", "OidbSvcTrpcTcp.0x102a_0",
+ "QQStranger.UserInfo.SsoBatchGetMiniUserInfo", "ProfileService.SimpleInfo", "PbMessageSvc.PbUnReadMsgSeq",
+ "OidbSvc_device.0x9f5", "OidbSvcTrpcTcp.0xf5d_1", "OidbSvcTcp.0xef0_1", "OidbSvcTrpcTcp.0xf5b_1",
+ "OidbSvcTrpcTcp.0xe37_1700", "OidbSvcTrpcTcp.0x972_6", "OidbSvc.0x758_1",
+ "trpc.g_qqrtc.qq_mav_room_state_read.GetRoomState.SsoGetInfoByUin", "OidbSvcTrpcTcp.0x901f_1",
+ "OidbSvc.0x5eb_99", "OidbSvcTrpcTcp.0x899_0", "OidbSvc.0x6d9_4", "OidbSvc.0x787_1",
+ "OidbSvcTrpcTcp.0x88d_111", "friendlist.addFriend", "OidbSvcTrpcTcp.0x6d9_2", "OidbSvcTrpcTcp.0x6d6_3",
+ "OidbSvcTrpcTcp.0x127a_0", "oidb_0xe61_1", "OidbSvc.0x88d_1_2", "OidbSvc.0x592_1",
+ "OidbSvcTrpcTcp.0x126e_200", "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetFeedList",
+ "OidbSvc.0xe61", "OidbSvcTrpcTcp.0x6d6_2", "OidbSvc.0x53c_2", "SQQzoneSvc.shuoshuo",
+ "OidbSvcTrpcTcp.0x126d_200", "OidbSvcTrpcTcp.0x1225_0", "OidbSvcTrpcTcp.0x11e9_200", "OidbSvc.0x852_48",
+ "OidbSvc.0xbcb", "OidbSvc.0x42d", "OidbSvc.0x515_2", "OidbSvcTrpcTcp.0x11c5_200",
+ "OidbSvcTrpcTcp.0x11c4_200", "trpc.qqhb.qqhb_proxy.Handler.sso_handle", "OidbSvcTrpcTcp.0x11c4_100",
+ "OidbSvc.0x852_35", "OidbSvcTrpcTcp.0x1194_1", "OidbSvcTrpcTcp.0x10c0_1", "OidbSvc.0x88d_7",
+ "OidbSvcTrpcTcp.0x110d_1", "OidbSvcTrpcTcp.0x10f4_1", "friendlist.AddFriendReq", "OidbSvcTrpcTcp.0xfe1",
+ "OidbSvcTrpcTcp.0x902e_1", "OidbSvcTrpcTcp.0x10c0_2", "QSec.AVEng", "SecuritySvc.GetConfig",
+ "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoFollow", "group_member_card.get_group_member_card_info",
+ "OidbSvc.0x570_8", "OidbSvc.0xe63_1", "OidbSvcTrpcTcp.0x8f9_14", "OidbSvc.0x7df_3",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetReplyList", "OidbSvc.0x58b", "OidbSvcTrpcTcp.0x9a2_12",
+ "OidbSvcTrpcTcp.0xfe7_2", "OidbSvc.0xe3e", "OidbSvc.0x592_16",
+ "CertifiedAccountSvc.certified_account_read.GetFollowList",
+ "QChannelSvr.trpc.qchannel.commreader.ComReader.BatchGetFeedDetail", "oidb_0x5d0_1", "OidbSvc.0xf7e_1",
+ "OidbSvcTrpcTcp.0x644_1", "oidb_0x43c_5", "OidbSvc.0xbe8", "OidbSvcTrpcTcp.0xfe1_8",
+ "OidbSvcTrpcTcp.0x101e_1", "OidbSvc.0x5d0_1", "OidbSvc.0x8a1_7", "MessageSvc.PbGetRoamMsg", "oidb_0xe8c_0",
+ "OidbSvcTrpcTcp.0x10d8_1", "OidbSvc.0x8a0_0", "OidbSvcTrpcTcp.0xe37_700", "OidbSvc.0x587_normalNightSet",
+ "OidbSvc.0x899_9", "OidbSvc.0x587_123", "QQRTCSvc.RoomManager-GetRoomInfo", "friendlist.GetTroopListReqV2",
+ "OidbSvc.0x592_13", "MessageSvc.PbSendMsg", "wtlogin.qrlogin", "oidb_0x9072_0", "OidbSvc.0x592_9",
+ "OidbSvcTrpcTcp.0x11ea_200", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.PublishFeed",
+ "OidbSvc.0x7a2_0", "OidbSvc.0x8a4", "OidbSvc.0x88d_1", "oidb_0x5d6_21", "oidb_0x5d6_19", "OidbSvc.0x8f1",
+ "OidbSvcTrpcTcp.0x11e9_100", "OidbSvcTrpcTcp.0x1017_1", "OidbSvc.0xb3c_3",
+ "trpc.qpay.midas_order.Order.SsoMakeOrder", "OidbSvcTrpcTcp.0x116c_1", "OidbSvc.0x5eb_ForTheme",
+ "SQQzoneSvc.getPhotoWall", "OidbSvc.0x5eb_22", "OidbSvc.0x5eb_42073", "ConnAuthSvr.sdk_auth_api_emp",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetRelationGroupList", "NowSummaryCard.NearbyMiniCardReq",
+ "OidbSvc.0x5eb_15", "OidbSvcTrpcTcp.0x116d_1", "FeedCloudSvr.trpc.feedcloud.commwriter.ComWriter.DoPush",
+ "group_member_statistic.get_group_member_statistic", "SQQzoneSvc.getMainPage", "OidbSvc.0x6d6_3",
+ "OidbSvcTrpcTcp.0x1224_0", "QQConnectLogin.pre_auth", "GameCenterMsg.GetUserInfo", "MessageSvc.PbGetMsg",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetBusiInfo", "OidbSvc.0xc6b",
+ "friendlist.GetTroopMemberListReq", "OidbSvc.0x6d6_2", "friendlist.getTroopMemberList",
+ "trpc.down.joint_operation_game_intercept.JointOperationGameIntercept.SsoCheck",
+ "SsoSnsSession.Cmd0x3_SubCmd0x1_FuncGetBlockList", "OidbSvcTrpcTcp.0x1262_19", "OidbSvcTrpcTcp.0x105b_1",
+ "friendlist.GetSimpleOnlineFriendInfoReq", "OidbSvc.0xbbb", "OidbSvcTrpcTcp.0x1130_1",
+ "OidbSvc_device.0x633", "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetRerankedFeedList",
+ "SQQzoneSvc.getProfile", "QQConnectLogin.pre_auth_emp", "OidbSvc.0xcdd", "MessageSvc.PbBindUinGetMsg",
+ "OidbSvc.0x480_9", "AvatarInfoSvr.QQHeadUrlReq", "OidbSvc.0x480_9_IMCore", "OidbSvcTrpcTcp.0x10c8_1",
+ "OidbSvcTcp.0x88d_1", "OidbSvcTrpcTcp.0x1289_1", "LightAppSvc.mini_app_privacy.GetPrivacyInfo",
+ "FeedCloudSvr.trpc.feedcloud.commreader.ComReader.GetMainPageBasicData", "OidbSvc.0x5eb_common",
+ "OidbSvcTrpcTcp.0xaf6_0", "IncreaseURLSvr.QQHeadUrlReq"
+ ];
+
+ public override bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
+
+ public override async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["cmd"] = cmd,
+ ["seq"] = seq,
+ ["buffer"] = Convert.ToHexString(body.Span),
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["version"] = Context.AppInfo.PtVersion,
+ ["qua"] = "V1_AND_SQ_9.2.20_11650_YYB_D"
+ };
+
+ var response = await _client.PostAsync($"{_url}/sign", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return null;
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ if (content == null) return null;
+
+ return new SsoSecureInfo
+ {
+ SecSign = Convert.FromHexString(content.Value.Sign),
+ SecToken = Convert.FromHexString(content.Value.Token),
+ SecExtra = Convert.FromHexString(content.Value.Extra)
+ };
+ }
+
+ public override async Task GetEnergy(long uin, string data)
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["data"] = data,
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["ver"] = Context.AppInfo.SdkInfo.SdkVersion,
+ ["version"] = Context.AppInfo.PtVersion,
+ ["qua"] = "V1_AND_SQ_9.2.20_11650_YYB_D"
+ };
+
+ var response = await _client.PostAsync($"{_url}/energy", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return [];
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ return content == null ? [] : Convert.FromHexString(content.Value);
+ }
+
+ public override async Task GetDebugXwid(long uin, string data)
+ {
+ var payload = new JsonObject
+ {
+ ["uin"] = uin,
+ ["data"] = data,
+ ["guid"] = Convert.ToHexString(Context.Keystore.Guid),
+ ["version"] = Context.AppInfo.PtVersion,
+ ["qua"] = "V1_AND_SQ_9.2.20_11650_YYB_D"
+ };
+
+ var response = await _client.PostAsync($"{_url}/get_tlv553", new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return [];
+
+ var content = JsonHelper.Deserialize>(await response.Content.ReadAsStringAsync());
+ return content == null ? [] : Convert.FromHexString(content.Value);
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+
+ [Serializable]
+ internal class ResponseRoot
+ {
+ [JsonPropertyName("data")] public T Value { get; set; } = default!;
+ }
+
+ [Serializable]
+ internal class SignResponse
+ {
+ [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
+
+ [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
+
+ [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotAppInfo.cs b/Lagrange.Core/Common/BotAppInfo.cs
index 22d48eab..16293620 100644
--- a/Lagrange.Core/Common/BotAppInfo.cs
+++ b/Lagrange.Core/Common/BotAppInfo.cs
@@ -1,63 +1,59 @@
-#pragma warning disable CS8618
+#pragma warning disable CS8618
namespace Lagrange.Core.Common;
public class BotAppInfo
{
- public string Os { get; set; }
-
- public string VendorOs { get; set; }
-
- public string Kernel { get; set; }
-
- public string CurrentVersion { get; set; }
-
- public int MiscBitmap { get; set; }
-
- public string PtVersion { get; set; }
-
- public int SsoVersion { get; set; }
-
- public string PackageName { get; set; }
-
- public string WtLoginSdk { get; set; }
-
- public int AppId { get; set; }
-
- /// Or known as pubId in tencent log
- public int SubAppId { get; set; }
-
- public int AppIdQrCode { get; set; }
-
- public ushort AppClientVersion { get; set; }
-
- public uint MainSigMap { get; set; }
-
- public ushort SubSigMap { get; set; }
-
- public ushort NTLoginType { get; set; }
+ public string Os { get; init; }
+
+ public string VendorOs { get; init; }
+
+ public string Kernel { get; init; } = "";
+
+ public string Qua { get; init; }
+
+ public string CurrentVersion { get; init; }
+
+ public string PtVersion { get; init; }
+
+ public int SsoVersion { get; init; }
+
+ public string PackageName { get; init; }
+
+ public byte[] ApkSignatureMd5 { get; init; }
+
+ public WtLoginSdkInfo SdkInfo { get; init; }
+
+ public int AppId { get; init; }
+
+ public int SubAppId { get; init; }
+
+ public ushort AppClientVersion { get; init; }
private static readonly BotAppInfo Linux = new()
{
Os = "Linux",
Kernel = "Linux",
VendorOs = "linux",
- CurrentVersion = "3.2.15-30366",
- MiscBitmap = 32764,
+ Qua = "V1_LNX_NQ_3.2.26_46494_GW_B",
+ CurrentVersion = "3.2.26-46494",
PtVersion = "2.0.0",
SsoVersion = 19,
PackageName = "com.tencent.qq",
- WtLoginSdk = "nt.wtlogin.0.0.1",
+ ApkSignatureMd5 = "com.tencent.qq"u8.ToArray(),
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 0,
+ SdkVersion = "nt.wtlogin.0.0.1",
+ MiscBitMap = 32764,
+ SubSigMap = 0,
+ MainSigMap = (Sig)169742560
+ },
AppId = 1600001615,
- SubAppId = 537258424,
- AppIdQrCode = 13697054,
- AppClientVersion = 30366,
-
- MainSigMap = 169742560,
- SubSigMap = 0,
- NTLoginType = 1
+ SubAppId = 537345891,
+ AppClientVersion = 46494
};
-
+
private static readonly BotAppInfo MacOs = new()
{
Os = "Mac",
@@ -65,45 +61,155 @@ public class BotAppInfo
VendorOs = "mac",
CurrentVersion = "6.9.23-20139",
PtVersion = "2.0.0",
- MiscBitmap = 32764,
SsoVersion = 23,
PackageName = "com.tencent.qq",
- WtLoginSdk = "nt.wtlogin.0.0.1",
+ ApkSignatureMd5 = "com.tencent.qq"u8.ToArray(),
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 0,
+ SdkVersion = "nt.wtlogin.0.0.1",
+ MiscBitMap = 12058620,
+ SubSigMap = 0,
+ MainSigMap = Sig.WLOGIN_STWEB | Sig.WLOGIN_A2 | Sig.WLOGIN_ST | Sig.WLOGIN_SKEY | Sig.WLOGIN_VKEY | Sig.WLOGIN_D2 | Sig.WLOGIN_SID | Sig.WLOGIN_PSKEY | Sig.WLOGIN_DA2 | Sig.WLOGIN_PT4Token
+ },
AppId = 1600001602,
SubAppId = 537200848,
- AppIdQrCode = 537200848,
- AppClientVersion = 13172,
-
- MainSigMap = 169742560,
- SubSigMap = 0,
- NTLoginType = 5
+ AppClientVersion = 13172
};
-
+
private static readonly BotAppInfo Windows = new()
{
Os = "Windows",
Kernel = "Windows_NT",
VendorOs = "win32",
- CurrentVersion = "9.9.2-15962",
+ CurrentVersion = "9.9.19-35184",
PtVersion = "2.0.0",
- MiscBitmap = 32764,
SsoVersion = 23,
PackageName = "com.tencent.qq",
- WtLoginSdk = "nt.wtlogin.0.0.1",
+ ApkSignatureMd5 = "com.tencent.qq"u8.ToArray(),
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 0,
+ SdkVersion = "nt.wtlogin.0.0.1",
+ MiscBitMap = 12058620,
+ SubSigMap = 0,
+ MainSigMap = Sig.WLOGIN_STWEB | Sig.WLOGIN_A2 | Sig.WLOGIN_ST | Sig.WLOGIN_SKEY | Sig.WLOGIN_VKEY | Sig.WLOGIN_D2 | Sig.WLOGIN_SID | Sig.WLOGIN_PSKEY | Sig.WLOGIN_DA2 | Sig.WLOGIN_PT4Token
+ },
AppId = 1600001604,
- SubAppId = 537138217,
- AppIdQrCode = 537138217,
- AppClientVersion = 13172,
-
- MainSigMap = 169742560,
- SubSigMap = 0,
- NTLoginType = 5
+ SubAppId = 537291048,
+ AppClientVersion = 35184
+ };
+
+ private static readonly BotAppInfo AndroidPhone = new()
+ {
+ Os = "Android",
+ CurrentVersion = "9.1.60.045f5d19",
+ PtVersion = "9.1.60",
+ SsoVersion = 22,
+ AppId = 16,
+ SubAppId = 537275636,
+ PackageName = "com.tencent.mobileqq",
+ ApkSignatureMd5 = [0xA6, 0xB7, 0x45, 0xBF, 0x24, 0xA2, 0xC2, 0x77, 0x52, 0x77, 0x16, 0xF6, 0xF3, 0x6E, 0xB6, 0x8D],
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 1740483688,
+ SdkVersion = "6.0.0.2568",
+ MiscBitMap = 150470524,
+ SubSigMap = 66560,
+ MainSigMap = Sig.WLOGIN_A5 | Sig.WLOGIN_RESERVED | Sig.WLOGIN_STWEB | Sig.WLOGIN_A2 | Sig.WLOGIN_ST | Sig.WLOGIN_LSKEY | Sig.WLOGIN_SKEY | Sig.WLOGIN_SIG64 | Sig.WLOGIN_VKEY | Sig.WLOGIN_D2 | Sig.WLOGIN_SID | Sig.WLOGIN_PSKEY | Sig.WLOGIN_AQSIG | Sig.WLOGIN_LHSIG | Sig.WLOGIN_PAYTOKEN | (Sig)65536
+ },
+ AppClientVersion = 0
+ };
+
+ private static readonly BotAppInfo AndroidPad = new()
+ {
+ Os = "ANDROID",
+ CurrentVersion = "9.2.20.777b5929",
+ PtVersion = "9.2.20",
+ Qua = "V1_AND_SQ_9.2.20_11650_YYB_D",
+ AppId = 16,
+ SubAppId = 537315825,
+ SsoVersion = 22,
+ PackageName = "com.tencent.mobileqq",
+ ApkSignatureMd5 = [0xA6, 0xB7, 0x45, 0xBF, 0x24, 0xA2, 0xC2, 0x77, 0x52, 0x77, 0x16, 0xF6, 0xF3, 0x6E, 0xB6, 0x8D],
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 1757058014,
+ SdkVersion = "6.0.0.2589",
+ MiscBitMap = 150470524,
+ SubSigMap = 66560,
+ MainSigMap = Sig.WLOGIN_A5 | Sig.WLOGIN_RESERVED | Sig.WLOGIN_STWEB | Sig.WLOGIN_A2 | Sig.WLOGIN_ST | Sig.WLOGIN_LSKEY | Sig.WLOGIN_SKEY | Sig.WLOGIN_SIG64 | Sig.WLOGIN_VKEY | Sig.WLOGIN_D2 | Sig.WLOGIN_SID | Sig.WLOGIN_PSKEY | Sig.WLOGIN_AQSIG | Sig.WLOGIN_LHSIG | Sig.WLOGIN_PAYTOKEN | (Sig)65536
+ },
+ AppClientVersion = 0
};
-
+
+ private static readonly BotAppInfo AndroidWatch = new()
+ {
+ Os = "Android",
+ CurrentVersion = "testrevision",
+ PtVersion = "9.0.5",
+ AppId = 16,
+ SubAppId = 537258298,
+ SsoVersion = 22,
+ PackageName = "com.tencent.qqlite",
+ ApkSignatureMd5 = [0xA6, 0xB7, 0x45, 0xBF, 0x24, 0xA2, 0xC2, 0x77, 0x52, 0x77, 0x16, 0xF6, 0xF3, 0x6E, 0xB6, 0x8D],
+ SdkInfo = new WtLoginSdkInfo
+ {
+ SdkBuildTime = 1724730201,
+ SdkVersion = "6.0.0.2564",
+ MiscBitMap = 150470524,
+ SubSigMap = 66560,
+ MainSigMap = Sig.WLOGIN_A5 | Sig.WLOGIN_RESERVED | Sig.WLOGIN_STWEB | Sig.WLOGIN_A2 | Sig.WLOGIN_ST | Sig.WLOGIN_LSKEY | Sig.WLOGIN_SKEY | Sig.WLOGIN_SIG64 | Sig.WLOGIN_VKEY | Sig.WLOGIN_D2 | Sig.WLOGIN_SID | Sig.WLOGIN_PSKEY | Sig.WLOGIN_AQSIG | Sig.WLOGIN_LHSIG | Sig.WLOGIN_PAYTOKEN | (Sig)65536
+ },
+ AppClientVersion = 0
+ };
+
public static readonly Dictionary ProtocolToAppInfo = new()
{
{ Protocols.Windows, Windows },
{ Protocols.Linux, Linux },
{ Protocols.MacOs, MacOs },
+ { Protocols.AndroidPhone, AndroidPhone },
+ { Protocols.AndroidPad, AndroidPad },
+ { Protocols.AndroidWatch, AndroidWatch }
};
+}
+
+public class WtLoginSdkInfo
+{
+ public uint SdkBuildTime { get; init; }
+
+ public string SdkVersion { get; init; }
+
+ public uint MiscBitMap { get; init; }
+
+ public uint SubSigMap { get; init; }
+
+ public Sig MainSigMap { get; init; }
+}
+
+[Flags]
+public enum Sig
+{
+ WLOGIN_A5 = 1 << 1,
+ WLOGIN_RESERVED = 1 << 4,
+ WLOGIN_STWEB = 1 << 5,
+ WLOGIN_A2 = 1 << 6,
+ WLOGIN_ST = 1 << 7,
+ WLOGIN_LSKEY = 1 << 9,
+ WLOGIN_SKEY = 1 << 12,
+ WLOGIN_SIG64 = 1 << 13,
+ WLOGIN_OPENKEY = 1 << 14,
+ WLOGIN_TOKEN = 1 << 15,
+ WLOGIN_VKEY = 1 << 17,
+ WLOGIN_D2 = 1 << 18,
+ WLOGIN_SID = 1 << 19,
+ WLOGIN_PSKEY = 1 << 20,
+ WLOGIN_AQSIG = 1 << 21,
+ WLOGIN_LHSIG = 1 << 22,
+ WLOGIN_PAYTOKEN = 1 << 23,
+ WLOGIN_PF = 1 << 24,
+ WLOGIN_DA2 = 1 << 25,
+ WLOGIN_QRPUSH = 1 << 26,
+ WLOGIN_PT4Token = 1 << 27
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotConfig.cs b/Lagrange.Core/Common/BotConfig.cs
index 25d681e6..5c6da4b6 100644
--- a/Lagrange.Core/Common/BotConfig.cs
+++ b/Lagrange.Core/Common/BotConfig.cs
@@ -1,3 +1,5 @@
+using Lagrange.Core.Events.EventArgs;
+
namespace Lagrange.Core.Common;
///
@@ -10,6 +12,8 @@ public class BotConfig
/// The protocol for the client, default is Linux
///
public Protocols Protocol { get; set; } = Protocols.Linux;
+
+ public LogLevel LogLevel { get; set; } = LogLevel.Information;
///
/// Auto reconnect to server when disconnected
@@ -35,24 +39,35 @@ public class BotConfig
/// Highway Uploading Concurrency, if the image failed to send, set this to 1
///
public uint HighwayConcurrent { get; set; } = 4;
+
///
/// Refresh the session when the session is about to expire
///
public bool AutoReLogin { get; set; } = true;
-
+
///
/// The Sign Provider for the bot, if null, the bot will use the default sign provider
///
- public IBotSignProvider? SignProvider { get; set; }
+ public BotSignProvider? SignProvider { get; set; }
}
///
/// The Protocol for the client
///
-public enum Protocols
+[Flags]
+public enum Protocols : byte
{
- Windows = 0,
- MacOs = 1,
- Linux = 2
+ None = 0b00000000,
+
+ Windows = 0b00000001,
+ MacOs = 0b00000010,
+ Linux = 0b00000100,
+ AndroidPhone = 0b00001000,
+ AndroidPad = 0b00010000,
+ AndroidWatch = 0b00100000,
+
+ PC = Windows | MacOs | Linux,
+ Android = AndroidPhone | AndroidPad | AndroidWatch,
+ All = Windows | MacOs | Linux | AndroidPhone | AndroidPad | AndroidWatch,
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotGender.cs b/Lagrange.Core/Common/BotGender.cs
new file mode 100644
index 00000000..94d7fdd7
--- /dev/null
+++ b/Lagrange.Core/Common/BotGender.cs
@@ -0,0 +1,9 @@
+namespace Lagrange.Core.Common;
+
+public enum BotGender
+{
+ Unset = 0,
+ Male = 1,
+ Female = 2,
+ Unknown = 255
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotInfo.cs b/Lagrange.Core/Common/BotInfo.cs
index 1ccd715e..59ec3004 100644
--- a/Lagrange.Core/Common/BotInfo.cs
+++ b/Lagrange.Core/Common/BotInfo.cs
@@ -1,20 +1,13 @@
namespace Lagrange.Core.Common;
[Serializable]
-public class BotInfo
+public class BotInfo(byte age, byte gender, string name)
{
- internal BotInfo(byte age, byte gender, string name)
- {
- Age = age;
- Gender = gender;
- Name = name;
- }
-
- public byte Age { get; set; }
-
- public byte Gender { get; set; }
-
- public string Name { get; set; }
+ public byte Age { get; set; } = age;
+
+ public byte Gender { get; set; } = gender;
+
+ public string Name { get; set; } = name;
public override string ToString() => $"Bot name: {Name} | Gender: {Gender} | Age: {Age}";
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotKeystore.cs b/Lagrange.Core/Common/BotKeystore.cs
index a3986e84..5e6c4d87 100644
--- a/Lagrange.Core/Common/BotKeystore.cs
+++ b/Lagrange.Core/Common/BotKeystore.cs
@@ -1,13 +1,13 @@
+using System.Security.Cryptography;
+using System.Text.Json.Serialization;
using Lagrange.Core.Utility.Cryptography;
namespace Lagrange.Core.Common;
public class BotKeystore
{
- private BotKeystore()
- {
-
- }
+ [JsonConstructor]
+ public BotKeystore() { }
public long Uin { get; set; }
@@ -15,10 +15,14 @@ private BotKeystore()
internal EcdhProvider Prime256V1 { get; } = new(EllipticCurve.Prime256V1);
internal EcdhProvider Secp192K1 { get; } = new(EllipticCurve.Secp192K1);
-
+ internal State State { get; } = new();
+
+ public BotInfo? BotInfo { get; set; }
public WLoginSigs WLoginSigs { get; set; } = new();
public byte[] Guid { get; set; } = [];
+ public string AndroidId { get; set; } = string.Empty;
+ public string Qimei { get; set; } = string.Empty;
public string DeviceName { get; set; } = string.Empty;
public static BotKeystore CreateEmpty()
@@ -26,35 +30,79 @@ public static BotKeystore CreateEmpty()
var guid = new byte[16];
Random.Shared.NextBytes(guid);
+ var androidId = new byte[8];
+ Random.Shared.NextBytes(androidId);
+
return new BotKeystore
{
Guid = guid,
- DeviceName = "Lagrange"
+ AndroidId = Convert.ToHexString(androidId),
+ DeviceName = $"Lagrange-{Random.Shared.Next(0, 16777215):X6}",
};
}
}
public class WLoginSigs
{
- public byte[] A2 { get; set; } = [];
+ public byte[] A2 { get; set; } = []; // Tlv10A
- public byte[] D2 { get; set; } = [];
+ public byte[] A2Key { get; set; } = new byte[16]; // Tlv10D
- public byte[] D2Key { get; set; } = [];
+ public byte[] D2 { get; set; } = []; // Tlv143
- public byte[] EncryptedA1 { get; set; } = [];
+ public byte[] D2Key { get; set; } = new byte[16]; // Tlv305
- public byte[]? NoPicSig { get; set; }
+ public byte[] A1 { get; set; } = []; // Tlv106
+
+ public byte[] A1Key { get; set; } = new byte[16]; // Tlv10C
+
+ public byte[] NoPicSig { get; set; } = [];// Tlv16A
public byte[] TgtgtKey { get; set; } = [];
+ public byte[] Ksid { get; set; } = [];
+
+ public byte[] SuperKey { get; set; } = [];
+
+ public byte[] StKey { get; set; } = [];
+
+ public byte[] StWeb { get; set; } = [];
+
+ public byte[] St { get; set; } = [];
+
+ public byte[] WtSessionTicket { get; set; } = [];
+
+ public byte[] WtSessionTicketKey { get; set; } = [];
+
+ public byte[] RandomKey { get; set; } = new byte[16];
+
+ public byte[] SKey { get; set; } = [];
+
+ public Dictionary PsKey { get; set; } = new();
+
public void Clear()
{
A2 = [];
D2 = [];
- D2Key = [];
- EncryptedA1 = [];
- NoPicSig = null;
+ D2Key = new byte[16];
+ A1 = [];
TgtgtKey = [];
+ RandomKey = new byte[16];
+ RandomNumberGenerator.Fill(RandomKey);
}
+}
+
+internal class State
+{
+ public byte[]? Tlv104 { get; set; }
+
+ public byte[]? Tlv547 { get; set; }
+
+ public byte[]? Tlv174 { get; set; }
+
+ public (byte[] SessionTicket, byte[] SessionKey)? KeyExchangeSession { get; set; }
+
+ public string? Cookie { get; set; }
+
+ public byte[]? QrSig { get; set; }
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/BotSignProvider.cs b/Lagrange.Core/Common/BotSignProvider.cs
new file mode 100644
index 00000000..a3babc4a
--- /dev/null
+++ b/Lagrange.Core/Common/BotSignProvider.cs
@@ -0,0 +1,141 @@
+using System.Text;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Lagrange.Core.Utility;
+using Lagrange.Proto;
+
+namespace Lagrange.Core.Common;
+
+public abstract class BotSignProvider
+{
+ private BotContext? _context;
+
+ public BotContext Context
+ {
+ get => _context ?? throw new InvalidOperationException("Context is not initialized.");
+ internal set => _context = value;
+ }
+
+ public abstract bool IsWhiteListCommand(string cmd);
+
+ public abstract Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body);
+}
+
+internal class DefaultBotSignProvider : BotSignProvider, IDisposable
+{
+ private const string Tag = nameof(DefaultBotSignProvider);
+
+ private readonly HttpClient _client = new();
+
+ private string Url => Context.Config.Protocol switch
+ {
+ Protocols.Windows => throw new NotSupportedException("Windows is not supported"),
+ Protocols.MacOs => throw new NotSupportedException("MacOs is not supported"),
+ Protocols.Linux => $"https://sign.lagrangecore.org/api/sign/{Context.AppInfo.AppClientVersion}",
+ Protocols.AndroidPhone => throw new NotSupportedException("AndroidPhone is not supported"),
+ Protocols.AndroidPad => throw new NotSupportedException("AndroidPad is not supported"),
+ _ => throw new ArgumentOutOfRangeException()
+ };
+
+ private static readonly HashSet WhiteListCommand =
+ [
+ "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
+ "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess",
+ "trpc.o3.report.Report.SsoReport",
+ "MessageSvc.PbSendMsg",
+ "wtlogin.trans_emp",
+ "wtlogin.login",
+ "wtlogin.exchange_emp",
+ "trpc.login.ecdh.EcdhService.SsoKeyExchange",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLogin",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginNewDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshTicket",
+ "trpc.login.ecdh.EcdhService.SsoNTLoginRefreshA2",
+ "OidbSvcTrpcTcp.0x11ec_1",
+ "OidbSvcTrpcTcp.0x758_1", // create group
+ "OidbSvcTrpcTcp.0x7c1_1",
+ "OidbSvcTrpcTcp.0x7c2_5", // request friend
+ "OidbSvcTrpcTcp.0x10db_1",
+ "OidbSvcTrpcTcp.0x8a1_7", // request group
+ "OidbSvcTrpcTcp.0x89a_0",
+ "OidbSvcTrpcTcp.0x89a_15",
+ "OidbSvcTrpcTcp.0x88d_0", // fetch group detail
+ "OidbSvcTrpcTcp.0x88d_14",
+ "OidbSvcTrpcTcp.0x112a_1",
+ "OidbSvcTrpcTcp.0x587_74",
+ "OidbSvcTrpcTcp.0x1100_1",
+ "OidbSvcTrpcTcp.0x1102_1",
+ "OidbSvcTrpcTcp.0x1103_1",
+ "OidbSvcTrpcTcp.0x1107_1",
+ "OidbSvcTrpcTcp.0x1105_1",
+ "OidbSvcTrpcTcp.0xf88_1",
+ "OidbSvcTrpcTcp.0xf89_1",
+ "OidbSvcTrpcTcp.0xf57_1",
+ "OidbSvcTrpcTcp.0xf57_106",
+ "OidbSvcTrpcTcp.0xf57_9",
+ "OidbSvcTrpcTcp.0xf55_1",
+ "OidbSvcTrpcTcp.0xf67_1",
+ "OidbSvcTrpcTcp.0xf67_5",
+ "OidbSvcTrpcTcp.0x6d9_4"
+ ];
+
+ public override bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
+
+ public override async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
+ {
+ var payload = new JsonObject
+ {
+ ["cmd"] = cmd,
+ ["seq"] = seq,
+ ["src"] = Convert.ToHexString(body.Span),
+ };
+
+ var response = await _client.PostAsync(Url, new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
+ if (!response.IsSuccessStatusCode) return null;
+
+ var content = JsonHelper.Deserialize(await response.Content.ReadAsStringAsync());
+ if (content == null) return null;
+
+ return new SsoSecureInfo
+ {
+ SecSign = Convert.FromHexString(content.Value.Sign),
+ SecToken = Convert.FromHexString(content.Value.Token),
+ SecExtra = Convert.FromHexString(content.Value.Extra)
+ };
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+
+ [Serializable]
+ internal class Root
+ {
+ [JsonPropertyName("value")] public Response Value { get; set; } = new();
+ }
+
+ [Serializable]
+ internal class Response
+ {
+ [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
+
+ [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
+
+ [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
+ }
+}
+
+[Serializable]
+[ProtoPackable]
+public partial class SsoSecureInfo
+{
+ [ProtoMember(1)] public byte[]? SecSign { get; set; }
+
+ [ProtoMember(2)] public byte[]? SecToken { get; set; }
+
+ [ProtoMember(3)] public byte[]? SecExtra { get; set; }
+}
diff --git a/Lagrange.Core/Common/Entity/BotFriend.cs b/Lagrange.Core/Common/Entity/BotFriend.cs
index 0d2b4cbf..5056c178 100644
--- a/Lagrange.Core/Common/Entity/BotFriend.cs
+++ b/Lagrange.Core/Common/Entity/BotFriend.cs
@@ -1,16 +1,22 @@
namespace Lagrange.Core.Common.Entity;
-public class BotFriend(long uin, string nickname, string uid, string remarks, string personalSign, string qid) : BotContact
+public class BotFriend(long uin, string nickname, string uid, string remarks, string personalSign, string qid, BotFriendCategory category) : BotContact
{
public override long Uin { get; } = uin;
- public override string Nickname { get; } = nickname;
+ public override string Nickname { get; } = nickname ?? string.Empty;
- public override string Uid { get; } = uid;
+ public override string Uid { get; } = uid ?? string.Empty;
+
+ public int Age { get; init; }
+
+ public BotGender Gender { get; init; }
- public string Remarks { get; } = remarks;
+ public string Remarks { get; } = remarks ?? string.Empty;
- public string PersonalSign { get; } = personalSign;
+ public string PersonalSign { get; } = personalSign ?? string.Empty;
- public string Qid { get; } = qid;
+ public string Qid { get; } = qid ?? string.Empty;
+
+ public BotFriendCategory Category { get; } = category;
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotFriendCategory.cs b/Lagrange.Core/Common/Entity/BotFriendCategory.cs
new file mode 100644
index 00000000..f01e56be
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotFriendCategory.cs
@@ -0,0 +1,12 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotFriendCategory(int id, string name, int count, int sortId)
+{
+ public int Id { get; } = id;
+
+ public string Name { get; } = name ?? string.Empty;
+
+ public int Count { get; } = count;
+
+ public int SortId { get; } = sortId;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroup.cs b/Lagrange.Core/Common/Entity/BotGroup.cs
index d8b1d914..20ad0c3d 100644
--- a/Lagrange.Core/Common/Entity/BotGroup.cs
+++ b/Lagrange.Core/Common/Entity/BotGroup.cs
@@ -8,11 +8,11 @@ public class BotGroup(
long createTime,
string? description,
string? question,
- string? announcement)
+ string? announcement) : BotContact
{
public long GroupUin { get; } = groupUin;
- public string GroupName { get; } = groupName;
+ public string GroupName { get; } = groupName ?? string.Empty;
public int MemberCount { get; } = memberCount;
@@ -25,4 +25,10 @@ public class BotGroup(
public string? Question { get; } = question;
public string? Announcement { get; } = announcement;
+
+ public override long Uin => GroupUin;
+
+ public override string Nickname => GroupName;
+
+ public override string Uid => GroupUin.ToString();
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupExitNotification.cs b/Lagrange.Core/Common/Entity/BotGroupExitNotification.cs
new file mode 100644
index 00000000..f08fd528
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupExitNotification.cs
@@ -0,0 +1,3 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupExitNotification(long groupUin, ulong sequence, long targetUin, string targetUid) : BotGroupNotificationBase(groupUin, sequence, BotGroupNotificationType.Exit, targetUin, targetUid);
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupExtra.cs b/Lagrange.Core/Common/Entity/BotGroupExtra.cs
new file mode 100644
index 00000000..c31b95a8
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupExtra.cs
@@ -0,0 +1,6 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupExtra
+{
+ public required long LatestMessageSequence { get; set; }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupInviteNotification.cs b/Lagrange.Core/Common/Entity/BotGroupInviteNotification.cs
new file mode 100644
index 00000000..7af8f14b
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupInviteNotification.cs
@@ -0,0 +1,16 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupInviteNotification(long group, ulong sequence, long targetUin, string targetUid, BotGroupNotificationState state, long? operatorUin, string? operatorUid, long inviterUin, string inviterUid, bool isFiltered) : BotGroupNotificationBase(group, sequence, BotGroupNotificationType.Invite, targetUin, targetUid)
+{
+ public BotGroupNotificationState State { get; } = state;
+
+ public long? OperatorUin { get; } = operatorUin;
+
+ public string? OperatorUid { get; } = operatorUid;
+
+ public long InviterUin { get; } = inviterUin;
+
+ public string InviterUid { get; } = inviterUid;
+
+ public bool IsFiltered { get; } = isFiltered;
+}
diff --git a/Lagrange.Core/Common/Entity/BotGroupJoinNotification.cs b/Lagrange.Core/Common/Entity/BotGroupJoinNotification.cs
new file mode 100644
index 00000000..5f780613
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupJoinNotification.cs
@@ -0,0 +1,14 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupJoinNotification(long group, ulong sequence, long targetUin, string targetUid, BotGroupNotificationState state, long? operatorUin, string? operatorUid, string comment, bool isFiltered) : BotGroupNotificationBase(group, sequence, BotGroupNotificationType.Join, targetUin, targetUid)
+{
+ public BotGroupNotificationState State { get; } = state;
+
+ public long? OperatorUin { get; } = operatorUin;
+
+ public string? OperatorUid { get; } = operatorUid;
+
+ public string Comment { get; } = comment;
+
+ public bool IsFiltered { get; } = isFiltered;
+}
diff --git a/Lagrange.Core/Common/Entity/BotGroupKickNotification.cs b/Lagrange.Core/Common/Entity/BotGroupKickNotification.cs
new file mode 100644
index 00000000..c2293c88
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupKickNotification.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupKickNotification(long group, ulong sequence, long targetUin, string targetUid, long operatorUin, string operatorUid) : BotGroupNotificationBase(group, sequence, BotGroupNotificationType.Exit, targetUin, targetUid)
+{
+ public long OperatorUin { get; } = operatorUin;
+
+ public string OperatorUid { get; } = operatorUid;
+}
diff --git a/Lagrange.Core/Common/Entity/BotGroupMember.cs b/Lagrange.Core/Common/Entity/BotGroupMember.cs
index a45f9f3b..dcad0360 100644
--- a/Lagrange.Core/Common/Entity/BotGroupMember.cs
+++ b/Lagrange.Core/Common/Entity/BotGroupMember.cs
@@ -1,6 +1,7 @@
namespace Lagrange.Core.Common.Entity;
public class BotGroupMember(
+ BotGroup group,
long uin,
string uid,
string nickname,
@@ -12,11 +13,17 @@ public class BotGroupMember(
DateTime lastMsgTime,
DateTime shutUpTimestamp) : BotContact
{
+ public BotGroup Group { get; } = group;
+
public override long Uin { get; } = uin;
- public override string Uid { get; } = uid;
+ public override string Uid { get; } = uid ?? string.Empty;
- public override string Nickname { get; } = nickname;
+ public override string Nickname { get; } = nickname ?? string.Empty;
+
+ public int Age { get; init; }
+
+ public BotGender Gender { get; init; }
public GroupMemberPermission Permission { get; } = permission;
@@ -36,6 +43,6 @@ public class BotGroupMember(
public enum GroupMemberPermission
{
Member,
+ Owner,
Admin,
- Owner
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupNotificationBase.cs b/Lagrange.Core/Common/Entity/BotGroupNotificationBase.cs
new file mode 100644
index 00000000..968d1ff3
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupNotificationBase.cs
@@ -0,0 +1,14 @@
+namespace Lagrange.Core.Common.Entity;
+
+public abstract class BotGroupNotificationBase(long groupUin, ulong sequence, BotGroupNotificationType type, long targetUin, string targetUid)
+{
+ public long GroupUin { get; } = groupUin;
+
+ public ulong Sequence { get; } = sequence;
+
+ public BotGroupNotificationType Type { get; } = type;
+
+ public long TargetUin { get; } = targetUin;
+
+ public string TargetUid { get; } = targetUid;
+}
diff --git a/Lagrange.Core/Common/Entity/BotGroupNotificationState.cs b/Lagrange.Core/Common/Entity/BotGroupNotificationState.cs
new file mode 100644
index 00000000..e75cd978
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupNotificationState.cs
@@ -0,0 +1,9 @@
+namespace Lagrange.Core.Common.Entity;
+
+public enum BotGroupNotificationState
+{
+ Wait = 1,
+ Accept,
+ Reject,
+ Ignore
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupNotificationType.cs b/Lagrange.Core/Common/Entity/BotGroupNotificationType.cs
new file mode 100644
index 00000000..7e063de4
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupNotificationType.cs
@@ -0,0 +1,12 @@
+namespace Lagrange.Core.Common.Entity;
+
+public enum BotGroupNotificationType
+{
+ Join = 1,
+ SetAdmin = 3,
+ KickOther = 6,
+ KickSelf = 7,
+ Exit = 13,
+ UnsetAdmin = 16,
+ Invite = 22
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotGroupRejectNotification.cs b/Lagrange.Core/Common/Entity/BotGroupRejectNotification.cs
new file mode 100644
index 00000000..69f94a40
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupRejectNotification.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupUnsetAdminNotification(long groupUin, ulong sequence, long targetUin, string targetUid, long operatorUin, string operatorUid) : BotGroupNotificationBase(groupUin, sequence, BotGroupNotificationType.UnsetAdmin, targetUin, targetUid)
+{
+ public long OperatorUin { get; } = operatorUin;
+
+ public string OperatorUid { get; } = operatorUid;
+}
diff --git a/Lagrange.Core/Common/Entity/BotGroupSetAdminNotification.cs b/Lagrange.Core/Common/Entity/BotGroupSetAdminNotification.cs
new file mode 100644
index 00000000..0c1f15e1
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotGroupSetAdminNotification.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotGroupSetAdminNotification(long group, ulong sequence, long targetUin, string targetUid, long operatorUin, string operatorUid) : BotGroupNotificationBase(group, sequence, BotGroupNotificationType.SetAdmin, targetUin, targetUid)
+{
+ public long OperatorUin { get; } = operatorUin;
+
+ public string OperatorUid { get; } = operatorUid;
+}
diff --git a/Lagrange.Core/Common/Entity/BotSsoPacket.cs b/Lagrange.Core/Common/Entity/BotSsoPacket.cs
new file mode 100644
index 00000000..eed543bc
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/BotSsoPacket.cs
@@ -0,0 +1,42 @@
+namespace Lagrange.Core.Common.Entity;
+
+public class BotSsoPacket
+{
+ public ReadOnlyMemory Data { get; }
+
+ public string Command { get; }
+
+ public string Extra { get; }
+
+ public int RetCode { get; }
+
+ public int Sequence { get; internal set; }
+
+ ///
+ /// Constructs a new SSO packet with the specified command and data.
+ ///
+ public BotSsoPacket(string command, ReadOnlyMemory data) : this(command, 0, 0, string.Empty) => Data = data;
+
+ internal BotSsoPacket(string command, ReadOnlyMemory data, int sequence) : this(command, sequence, 0, string.Empty) => Data = data;
+
+ internal BotSsoPacket(string command, int sequence, int retCode, string extra)
+ {
+ Command = command;
+ Extra = extra;
+ RetCode = retCode;
+ Sequence = sequence;
+ }
+}
+
+public enum EncryptType : byte
+{
+ NoEncrypt = 0x00,
+ EncryptD2Key = 0x01,
+ EncryptEmpty = 0x02,
+}
+
+public enum RequestType
+{
+ D2Auth = 0x0C,
+ Simple = 0x0D,
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/BotStranger.cs b/Lagrange.Core/Common/Entity/BotStranger.cs
index 7329974c..a1cfad71 100644
--- a/Lagrange.Core/Common/Entity/BotStranger.cs
+++ b/Lagrange.Core/Common/Entity/BotStranger.cs
@@ -1,10 +1,52 @@
namespace Lagrange.Core.Common.Entity;
-public class BotStranger(long uin, string nickname, string uid) : BotContact
+public class BotStranger(long uin, string nickname, string uid, string personalSign, string remark, ulong level, BotGender gender, DateTime registrationTime, DateTime? birthday, ulong age, string qID, string country, string city, string? school) : BotContact
{
public override long Uin { get; } = uin;
-
- public override string Nickname { get; } = nickname;
-
- public override string Uid { get; } = uid;
+
+ public override string Nickname { get; } = nickname ?? string.Empty;
+
+ public override string Uid { get; } = uid ?? string.Empty;
+
+ public string PersonalSign { get; } = personalSign;
+
+ public string Remark { get; } = remark;
+
+ public ulong Level { get; } = level;
+
+ public BotGender Gender { get; } = gender;
+
+ public DateTime RegistrationTime { get; } = registrationTime;
+
+ public DateTime? Birthday { get; } = birthday;
+
+ public ulong Age { get; } = age;
+
+ public string QID { get; } = qID;
+
+ public long Source { get; init; }
+
+ public string Country { get; init; } = country;
+
+ public string City { get; init; } = city;
+
+ public string? School { get; init; } = school;
+
+ internal BotStranger CloneWithSource(long source) => new(
+ Uin,
+ Nickname,
+ Uid,
+ PersonalSign,
+ Remark,
+ Level,
+ Gender,
+ RegistrationTime,
+ Birthday,
+ Age,
+ QID,
+ Country,
+ City,
+ School
+ )
+ { Source = source };
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Entity/GroupNotificationOperate.cs b/Lagrange.Core/Common/Entity/GroupNotificationOperate.cs
new file mode 100644
index 00000000..a2e65760
--- /dev/null
+++ b/Lagrange.Core/Common/Entity/GroupNotificationOperate.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Common.Entity;
+
+public enum GroupNotificationOperate
+{
+ Allow = 1,
+ Deny = 2,
+ Ignore = 3,
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/IBotSignProvider.cs b/Lagrange.Core/Common/IBotSignProvider.cs
deleted file mode 100644
index 1c1452a5..00000000
--- a/Lagrange.Core/Common/IBotSignProvider.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System.Net.Http.Json;
-using System.Text.Json.Nodes;
-using System.Text.Json.Serialization;
-
-namespace Lagrange.Core.Common;
-
-public interface IBotSignProvider
-{
- protected static readonly string[] WhiteListCommand =
- [
- "trpc.o3.ecdh_access.EcdhAccess.SsoEstablishShareKey",
- "trpc.o3.ecdh_access.EcdhAccess.SsoSecureAccess",
- "trpc.o3.report.Report.SsoReport",
- "MessageSvc.PbSendMsg",
- "wtlogin.trans_emp",
- "wtlogin.login",
- "trpc.login.ecdh.EcdhService.SsoKeyExchange",
- "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLogin",
- "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLogin",
- "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginNewDevice",
- "trpc.login.ecdh.EcdhService.SsoNTLoginEasyLoginUnusualDevice",
- "trpc.login.ecdh.EcdhService.SsoNTLoginPasswordLoginUnusualDevice",
- "OidbSvcTrpcTcp.0x11ec_1",
- "OidbSvcTrpcTcp.0x758_1", // create group
- "OidbSvcTrpcTcp.0x7c1_1",
- "OidbSvcTrpcTcp.0x7c2_5", // request friend
- "OidbSvcTrpcTcp.0x10db_1",
- "OidbSvcTrpcTcp.0x8a1_7", // request group
- "OidbSvcTrpcTcp.0x89a_0",
- "OidbSvcTrpcTcp.0x89a_15",
- "OidbSvcTrpcTcp.0x88d_0", // fetch group detail
- "OidbSvcTrpcTcp.0x88d_14",
- "OidbSvcTrpcTcp.0x112a_1",
- "OidbSvcTrpcTcp.0x587_74",
- "OidbSvcTrpcTcp.0x1100_1",
- "OidbSvcTrpcTcp.0x1102_1",
- "OidbSvcTrpcTcp.0x1103_1",
- "OidbSvcTrpcTcp.0x1107_1",
- "OidbSvcTrpcTcp.0x1105_1",
- "OidbSvcTrpcTcp.0xf88_1",
- "OidbSvcTrpcTcp.0xf89_1",
- "OidbSvcTrpcTcp.0xf57_1",
- "OidbSvcTrpcTcp.0xf57_106",
- "OidbSvcTrpcTcp.0xf57_9",
- "OidbSvcTrpcTcp.0xf55_1",
- "OidbSvcTrpcTcp.0xf67_1",
- "OidbSvcTrpcTcp.0xf67_5",
- "OidbSvcTrpcTcp.0x6d9_4"
- ];
-
- internal static bool IsWhiteListCommand(string cmd) => WhiteListCommand.Contains(cmd);
-
- Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body);
-}
-
-internal class DefaultBotSignProvider(Protocols protocol, BotAppInfo appInfo) : IBotSignProvider, IDisposable
-{
- private readonly HttpClient _client;
-
- private string _url = protocol switch
- {
- Protocols.Windows => throw new NotSupportedException("Windows is not supported"),
- Protocols.MacOs => throw new NotSupportedException("MacOs is not supported"),
- Protocols.Linux => $"https://sign.lagrangecore.org/api/sign/{appInfo.AppClientVersion}",
- _ => throw new ArgumentOutOfRangeException(nameof(protocol))
- };
-
- public async Task GetSecSign(long uin, string cmd, int seq, ReadOnlyMemory body)
- {
- try
- {
- var payload = new JsonObject
- {
- ["cmd"] = cmd,
- ["seq"] = seq,
- ["src"] = Convert.ToHexString(body.Span),
- };
-
- var response = await _client.PostAsJsonAsync(_url, payload);
- if (!response.IsSuccessStatusCode) return null;
-
- var content = await response.Content.ReadFromJsonAsync();
- if (content == null) return null;
-
- return new SsoSecureInfo(Convert.FromHexString(content.Sign),
- Convert.FromHexString(content.Token),
- Convert.FromHexString(content.Extra));
- }
- catch (Exception e)
- {
- // TODO: Log the exception
- return null;
- }
- }
-
- public void Dispose()
- {
- _client.Dispose();
- }
-
- [Serializable]
- private class Response
- {
- [JsonPropertyName("sign")] public string Sign { get; set; } = string.Empty;
-
- [JsonPropertyName("token")] public string Token { get; set; } = string.Empty;
-
- [JsonPropertyName("extra")] public string Extra { get; set; } = string.Empty;
- }
-}
-
-[Serializable]
-public record SsoSecureInfo(
- byte[] SecSign,
- byte[] SecToken,
- byte[] SecExtra);
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Interface/BotExt.cs b/Lagrange.Core/Common/Interface/BotExt.cs
new file mode 100644
index 00000000..fe933a02
--- /dev/null
+++ b/Lagrange.Core/Common/Interface/BotExt.cs
@@ -0,0 +1,28 @@
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Internal.Logic;
+
+namespace Lagrange.Core.Common.Interface;
+
+public static class BotExt
+{
+ public static Task Login(this BotContext context, long uin, string password, CancellationToken token = default) =>
+ context.EventContext.GetLogic().Login(uin, password, token);
+
+ public static Task Login(this BotContext context, CancellationToken token = default) =>
+ context.EventContext.GetLogic().Login(0, null, token);
+
+ public static Task Logout(this BotContext context) =>
+ context.EventContext.GetLogic().Logout();
+
+ public static Task ResolveUinByQid(this BotContext context, string qid) =>
+ context.EventContext.GetLogic().ResolveUinByQid(qid);
+
+ public static bool SubmitCaptcha(this BotContext context, string ticket, string randStr) =>
+ context.EventContext.GetLogic().SubmitCaptcha(ticket, randStr);
+
+ public static bool SubmitSMSCode(this BotContext context, string code) =>
+ context.EventContext.GetLogic().SubmitSMSCode(code);
+
+ public static ValueTask SendPacket(this BotContext context, BotSsoPacket packet, RequestType requestType = RequestType.D2Auth, EncryptType encryptType = EncryptType.EncryptD2Key)
+ => context.EventContext.GetLogic().SendPacket(packet, requestType, encryptType);
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Interface/BotFactory.cs b/Lagrange.Core/Common/Interface/BotFactory.cs
index 8f35c365..2c32c66f 100644
--- a/Lagrange.Core/Common/Interface/BotFactory.cs
+++ b/Lagrange.Core/Common/Interface/BotFactory.cs
@@ -7,15 +7,17 @@ public static class BotFactory
///
/// The config for Bot
/// Existing Keystore from deserialization
+ /// The app info for Bot, if null, will use default app info from
/// Created BotContext Instance
- public static BotContext Create(BotConfig config, BotKeystore keystore) =>
- new(config, keystore, BotAppInfo.ProtocolToAppInfo[config.Protocol]);
+ public static BotContext Create(BotConfig config, BotKeystore keystore, BotAppInfo? appInfo = null) =>
+ new(config, keystore, appInfo ?? BotAppInfo.ProtocolToAppInfo[config.Protocol]);
///
/// Create new Bot from Empty
///
/// The config for Bot
+ /// The app info for Bot, if null, will use default app info from
/// Created BotContext Instance
- public static BotContext Create(BotConfig config) =>
- new(config, BotKeystore.CreateEmpty(), BotAppInfo.ProtocolToAppInfo[config.Protocol]);
+ public static BotContext Create(BotConfig config, BotAppInfo? appInfo = null) =>
+ new(config, BotKeystore.CreateEmpty(), appInfo ?? BotAppInfo.ProtocolToAppInfo[config.Protocol]);
}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Interface/MessageExt.cs b/Lagrange.Core/Common/Interface/MessageExt.cs
new file mode 100644
index 00000000..db689634
--- /dev/null
+++ b/Lagrange.Core/Common/Interface/MessageExt.cs
@@ -0,0 +1,68 @@
+using Lagrange.Core.Internal.Logic;
+using Lagrange.Core.Message;
+using Lagrange.Core.Common.Response;
+
+namespace Lagrange.Core.Common.Interface;
+
+public static class MessageExt
+{
+ public static Task SendFriendMessage(this BotContext context, long friendUin, MessageChain chain)
+ => context.EventContext.GetLogic().SendFriendMessage(friendUin, chain);
+
+ public static Task SendGroupMessage(this BotContext context, long groupUin, MessageChain chain)
+ => context.EventContext.GetLogic().SendGroupMessage(groupUin, chain);
+
+ public static Task> GetGroupMessage(this BotContext context, long groupUin, ulong startSequence, ulong endSequence)
+ => context.EventContext.GetLogic().GetGroupMessage(groupUin, startSequence, endSequence);
+
+ public static Task> GetRoamMessage(this BotContext context, long friendUin, uint timestamp, uint count)
+ => context.EventContext.GetLogic().GetRoamMessage(friendUin, timestamp, count);
+
+ public static Task> GetRoamMessage(this BotContext context, BotMessage target, uint count)
+ {
+ uint timestamp = (uint)new DateTimeOffset(target.Time).ToUnixTimeSeconds();
+ return context.EventContext.GetLogic().GetRoamMessage(target.Contact.Uin, timestamp, count);
+ }
+
+ public static Task> GetC2CMessage(this BotContext context, long peerUin, ulong startSequence, ulong endSequence)
+ => context.EventContext.GetLogic().GetC2CMessage(peerUin, startSequence, endSequence);
+
+ public static Task<(ulong Sequence, DateTime Time)> SendFriendFile(this BotContext context, long targetUin, Stream fileStream, string? fileName = null)
+ => context.EventContext.GetLogic().SendFriendFile(targetUin, fileStream, fileName);
+
+ public static Task SendGroupFile(this BotContext context, long groupUin, Stream fileStream, string? fileName = null, string parentDirectory = "/")
+ => context.EventContext.GetLogic().SendGroupFile(groupUin, fileStream, fileName, parentDirectory);
+
+ public static Task UploadFlashTransfer(this BotContext context, IReadOnlyList<(Stream Stream, string? FileName)> files, string? title = null)
+ => context.EventContext.GetLogic().UploadFlashTransfer(files, title);
+
+ public static Task RecallMessage(this BotContext context, BotMessage message)
+ => context.EventContext.GetLogic().RecallMessage(message);
+
+ public static Task GroupFSDownload(this BotContext context, long groupUin, string fileId)
+ => context.EventContext.GetLogic().GroupFSDownload(groupUin, fileId);
+
+ public static Task GroupFSDelete(this BotContext context, long groupUin, string fileId)
+ => context.EventContext.GetLogic().GroupFSDelete(groupUin, fileId);
+
+ public static Task GroupFSMove(this BotContext context, long groupUin, string fileId, string targetDirectory, string parentDirectory)
+ => context.EventContext.GetLogic().GroupFSMove(groupUin, fileId, targetDirectory, parentDirectory);
+
+ public static Task SendFriendNudge(this BotContext context, long peerUin, long? targetUin = null)
+ => context.EventContext.GetLogic().SendNudge(false, peerUin, targetUin ?? context.BotUin);
+
+ public static Task SendGroupNudge(this BotContext context, long peerUin, long targetUin)
+ => context.EventContext.GetLogic().SendNudge(true, peerUin, targetUin);
+
+ public static Task GroupSetSpecialTitle(this BotContext context, long groupUin, long targetUin, string title)
+ => context.EventContext.GetLogic().GroupSetSpecialTitle(groupUin, targetUin, title);
+
+ public static Task GroupMemberRename(this BotContext context, long groupUin, long targetUin, string name)
+ => context.EventContext.GetLogic().GroupMemberRename(groupUin, targetUin, name);
+
+ public static Task GroupRename(this BotContext context, long groupUin, string name)
+ => context.EventContext.GetLogic().GroupRename(groupUin, name);
+
+ public static Task GroupQuit(this BotContext context, long groupUin)
+ => context.EventContext.GetLogic().GroupQuit(groupUin);
+}
diff --git a/Lagrange.Core/Common/Interface/OperationExt.cs b/Lagrange.Core/Common/Interface/OperationExt.cs
new file mode 100644
index 00000000..f38ba2a4
--- /dev/null
+++ b/Lagrange.Core/Common/Interface/OperationExt.cs
@@ -0,0 +1,53 @@
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Common.Response;
+using Lagrange.Core.Internal.Logic;
+
+namespace Lagrange.Core.Common.Interface;
+
+public static class OperationExt
+{
+ public static Task FetchQrCodeInfo(this BotContext context, byte[] k) =>
+ context.EventContext.GetLogic().FetchQrCodeInfo(k);
+
+ public static Task<(bool Success, string Message)> CloseQrCode(this BotContext context, byte[] k, bool confirm) =>
+ context.EventContext.GetLogic().CloseQrCode(k, confirm);
+
+ public static Task> FetchCookies(this BotContext context, params List domains) =>
+ context.EventContext.GetLogic().FetchCookies(domains);
+
+ public static Task<(string Key, uint Expiration)> FetchClientKey(this BotContext context) =>
+ context.EventContext.GetLogic().FetchClientKey();
+
+ public static Task> FetchFriends(this BotContext context, bool refresh = false) =>
+ context.CacheContext.GetFriendList(refresh);
+
+ public static Task> FetchGroups(this BotContext context, bool refresh = false) =>
+ context.CacheContext.GetGroupList(refresh);
+
+ public static Task FetchGroupExtra(this BotContext context, long groupUin) =>
+ context.EventContext.GetLogic().FetchGroupExtra(groupUin);
+
+ public static Task> FetchMembers(this BotContext context, long groupUin, bool refresh = false) =>
+ context.CacheContext.GetMemberList(groupUin, refresh);
+
+ public static Task> FetchGroupNotifications(this BotContext context, ulong count, ulong start = 0) =>
+ context.EventContext.GetLogic().FetchGroupNotifications(count, start);
+
+ public static Task> FetchFilteredGroupNotifications(this BotContext context, ulong count, ulong start = 0) =>
+ context.EventContext.GetLogic().FetchFilteredGroupNotifications(count, start);
+
+ public static Task FetchStranger(this BotContext context, long uin) =>
+ context.EventContext.GetLogic().FetchStranger(uin);
+
+ public static Task SetGroupNotification(this BotContext context, long groupUin, ulong sequence, BotGroupNotificationType type, bool isFiltered, GroupNotificationOperate operate, string message = "") =>
+ context.EventContext.GetLogic().SetGroupNotification(groupUin, sequence, type, isFiltered, operate, message);
+
+ public static Task SetGroupReaction(this BotContext context, long groupUin, ulong sequence, string code, bool isAdd) =>
+ context.EventContext.GetLogic().SetGroupReaction(groupUin, sequence, code, isAdd);
+
+ public static Task GetNTV2RichMediaUrl(this BotContext context, string fileUuid) =>
+ context.EventContext.GetLogic().GetNTV2RichMediaUrl(fileUuid);
+
+ public static Task SetBotAvatar(this BotContext context, Stream stream) =>
+ context.HighwayContext.UploadFile(stream, 90, Array.Empty());
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Common/Response/BotFlashTransferUpload.cs b/Lagrange.Core/Common/Response/BotFlashTransferUpload.cs
new file mode 100644
index 00000000..c67abf3f
--- /dev/null
+++ b/Lagrange.Core/Common/Response/BotFlashTransferUpload.cs
@@ -0,0 +1,10 @@
+namespace Lagrange.Core.Common.Response;
+
+public class BotFlashTransferUpload(string fileSetId, List fileIds, string shareLink)
+{
+ public string FileSetId { get; } = fileSetId;
+
+ public List FileIds { get; } = fileIds;
+
+ public string ShareLink { get; } = shareLink;
+}
diff --git a/Lagrange.Core/Common/Response/BotQrCodeInfo.cs b/Lagrange.Core/Common/Response/BotQrCodeInfo.cs
new file mode 100644
index 00000000..0f58ff21
--- /dev/null
+++ b/Lagrange.Core/Common/Response/BotQrCodeInfo.cs
@@ -0,0 +1,15 @@
+using System.Text.Json.Serialization;
+
+namespace Lagrange.Core.Common.Response;
+
+[Serializable]
+public class BotQrCodeInfo(string message, string platform, string location, string? device)
+{
+ [JsonPropertyName("message")] public string Message { get; } = message;
+
+ [JsonPropertyName("platform")] public string Platform { get; } = platform;
+
+ [JsonPropertyName("location")] public string Location { get; } = location;
+
+ [JsonPropertyName("device")] public string? Device { get; } = device;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotCaptchaEvent.cs b/Lagrange.Core/Events/EventArgs/BotCaptchaEvent.cs
new file mode 100644
index 00000000..1320e2e9
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotCaptchaEvent.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotCaptchaEvent(string captchaUrl) : EventBase
+{
+ public string CaptchaUrl { get; } = captchaUrl;
+
+ public override string ToEventMessage() => $"{nameof(BotCaptchaEvent)}: Captcha required, URL: {CaptchaUrl}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotFriendRecallEvent.cs b/Lagrange.Core/Events/EventArgs/BotFriendRecallEvent.cs
new file mode 100644
index 00000000..346a2708
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotFriendRecallEvent.cs
@@ -0,0 +1,17 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotFriendRecallEvent(long peerUin, long authorUin, ulong sequence, string tip) : EventBase
+{
+ public long PeerUin { get; } = peerUin;
+
+ public long AuthorUin { get; } = authorUin;
+
+ public ulong Sequence { get; } = sequence;
+
+ public string Tip { get; } = tip;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupRecallEvent)}: ${AuthorUin} recalled {Sequence} in {PeerUin}";
+ }
+}
diff --git a/Lagrange.Core/Events/EventArgs/BotFriendRequestEvent.cs b/Lagrange.Core/Events/EventArgs/BotFriendRequestEvent.cs
new file mode 100644
index 00000000..59ed1297
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotFriendRequestEvent.cs
@@ -0,0 +1,17 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotFriendRequestEvent(string initiatorUid, long initiatorUin, string message, string source) : EventBase
+{
+ public string InitiatorUid { get; } = initiatorUid;
+
+ public long InitiatorUin { get; } = initiatorUin;
+
+ public string Message { get; } = message;
+
+ public string Source { get; } = source;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotFriendRequestEvent)}: InitiatorUid: {InitiatorUid}, InitiatorUin: {InitiatorUin}, Message: {Message}, Source: {Source}";
+ }
+}
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupInviteNotificationEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupInviteNotificationEvent.cs
new file mode 100644
index 00000000..292e069a
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupInviteNotificationEvent.cs
@@ -0,0 +1,10 @@
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupInviteNotificationEvent(BotGroupInviteNotification notification) : EventBase
+{
+ public BotGroupInviteNotification Notification { get; } = notification;
+
+ public override string ToEventMessage() => $"{nameof(BotGroupInviteNotificationEvent)} Group {Notification.GroupUin} Inviter {Notification.InviterUin} Target {Notification.TargetUin}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupJoinNotificationEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupJoinNotificationEvent.cs
new file mode 100644
index 00000000..74945d58
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupJoinNotificationEvent.cs
@@ -0,0 +1,10 @@
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupJoinNotificationEvent(BotGroupJoinNotification notification) : EventBase
+{
+ public BotGroupJoinNotification Notification { get; } = notification;
+
+ public override string ToEventMessage() => $"{nameof(BotGroupJoinNotificationEvent)} Group {Notification.GroupUin} Target {Notification.TargetUin}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupMemberDecreaseEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupMemberDecreaseEvent.cs
new file mode 100644
index 00000000..f922c73b
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupMemberDecreaseEvent.cs
@@ -0,0 +1,15 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupMemberDecreaseEvent(long groupUin, long userUin, long? operatorUin) : EventBase
+{
+ public long GroupUin { get; } = groupUin;
+
+ public long UserUin { get; } = userUin;
+
+ public long? OperatorUin { get; } = operatorUin;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupMemberDecreaseEvent)}: GroupUin={GroupUin}, UserUin={UserUin}, OperatorUin={OperatorUin}";
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupMemberIncreaseEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupMemberIncreaseEvent.cs
new file mode 100644
index 00000000..9f94fb1a
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupMemberIncreaseEvent.cs
@@ -0,0 +1,15 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupMemberIncreaseEvent(long groupUin, long memberUin, long invitorUin, uint type, long operatorUin) : EventBase
+{
+ public long GroupUin { get; } = groupUin;
+ public long MemberUin { get; } = memberUin;
+ public long InvitorUin { get; } = invitorUin;
+ public uint Type { get; } = type;
+ public long OperatorUin { get; } = operatorUin;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupMemberIncreaseEvent)}: GroupUin={GroupUin}, MemberUin={MemberUin}, InvitorUin={InvitorUin}, Type={Type}, OperatorUin={OperatorUin}";
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupNudgeEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupNudgeEvent.cs
new file mode 100644
index 00000000..a45e9d40
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupNudgeEvent.cs
@@ -0,0 +1,21 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupNudgeEvent(long groupUin, long operatorUin, string action, string actionImgUrl, long targetUin, string suffix) : EventBase
+{
+ public long GroupUin { get; } = groupUin;
+
+ public long OperatorUin { get; } = operatorUin;
+
+ public string Action { get; } = action;
+
+ public string ActionImageUrl { get; } = actionImgUrl;
+
+ public long TargetUin { get; } = targetUin;
+
+ public string Suffix { get; } = suffix;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupNudgeEvent)}: In Group {GroupUin}, {OperatorUin} {Action}({ActionImageUrl}) {TargetUin} {Suffix}";
+ }
+}
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupReactionEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupReactionEvent.cs
new file mode 100644
index 00000000..371e3b79
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupReactionEvent.cs
@@ -0,0 +1,21 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupReactionEvent(long targetGroupUin, ulong targetSequence, long operatorUin, bool isAdd, string code, ulong currentCount) : EventBase
+{
+ public long TargetGroupUin { get; } = targetGroupUin;
+
+ public ulong TargetSequence { get; } = targetSequence;
+
+ public long OperatorUin { get; } = operatorUin;
+
+ public bool IsAdd { get; } = isAdd;
+
+ public string Code { get; } = code;
+
+ public ulong CurrentCount { get; } = currentCount;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupReactionEvent)}: Target {TargetGroupUin} > {TargetSequence} Operator {OperatorUin} {(IsAdd ? "Add" : "Reduce")} {Code} Current {CurrentCount}";
+ }
+}
diff --git a/Lagrange.Core/Events/EventArgs/BotGroupRecallEvent.cs b/Lagrange.Core/Events/EventArgs/BotGroupRecallEvent.cs
new file mode 100644
index 00000000..56ef1204
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotGroupRecallEvent.cs
@@ -0,0 +1,19 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotGroupRecallEvent(long groupUin, ulong sequence, long authorUin, long operatorUin, string tip) : EventBase
+{
+ public long GroupUin { get; } = groupUin;
+
+ public ulong Sequence { get; } = sequence;
+
+ public long AuthorUin { get; } = authorUin;
+
+ public long OperatorUin { get; } = operatorUin;
+
+ public string Tip { get; } = tip;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotGroupRecallEvent)}: ${OperatorUin} recalled {GroupUin}-{Sequence} of {AuthorUin}";
+ }
+}
diff --git a/Lagrange.Core/Events/EventArgs/BotLogEvent.cs b/Lagrange.Core/Events/EventArgs/BotLogEvent.cs
index 9d2afadd..99ae7215 100644
--- a/Lagrange.Core/Events/EventArgs/BotLogEvent.cs
+++ b/Lagrange.Core/Events/EventArgs/BotLogEvent.cs
@@ -10,13 +10,15 @@ public enum LogLevel
Critical = 5
}
-public class BotLogEvent(string tag, LogLevel level, string message) : EventBase
+public class BotLogEvent(string tag, LogLevel level, string message, Exception? exception) : EventBase
{
public string Tag { get; } = tag;
public LogLevel Level { get; } = level;
public string Message { get; } = message;
+
+ public Exception? Exception { get; } = exception;
public override string ToEventMessage() => $"[{Tag}] [{Level.ToString().ToUpper()}]: {Message}";
}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotLoginEvent.cs b/Lagrange.Core/Events/EventArgs/BotLoginEvent.cs
new file mode 100644
index 00000000..dc2c96da
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotLoginEvent.cs
@@ -0,0 +1,14 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotLoginEvent(int state, (string, string)? error) : EventBase
+{
+ public bool Success => State == 0;
+
+ public int State { get; } = state;
+
+ public (string Tag, string Message)? Error { get; } = error;
+
+ public override string ToEventMessage() => Error == null
+ ? $"[{nameof(BotLoginEvent)}] State: {State}"
+ : $"[{nameof(BotLoginEvent)}] State: {State} | Error: {Error?.Tag} | Message: {Error?.Message}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotMessageEvent.cs b/Lagrange.Core/Events/EventArgs/BotMessageEvent.cs
new file mode 100644
index 00000000..e4e19807
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotMessageEvent.cs
@@ -0,0 +1,12 @@
+using Lagrange.Core.Message;
+
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotMessageEvent(BotMessage message, ReadOnlyMemory rawMessage) : EventBase
+{
+ public BotMessage Message { get; } = message;
+
+ internal ReadOnlyMemory RawMessage { get; } = rawMessage;
+
+ public override string ToEventMessage() => $"{nameof(EventBase)} {Message}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotNewDeviceVerifyEvent.cs b/Lagrange.Core/Events/EventArgs/BotNewDeviceVerifyEvent.cs
new file mode 100644
index 00000000..5d77d0f9
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotNewDeviceVerifyEvent.cs
@@ -0,0 +1,8 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotNewDeviceVerifyEvent(string url) : EventBase
+{
+ public string Url { get; } = url;
+
+ public override string ToEventMessage() => $"[{nameof(BotNewDeviceVerifyEvent)}] URL: {Url}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotOfflineEvent.cs b/Lagrange.Core/Events/EventArgs/BotOfflineEvent.cs
new file mode 100644
index 00000000..e2ffc5e1
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotOfflineEvent.cs
@@ -0,0 +1,17 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotOfflineEvent(BotOfflineEvent.Reasons reason, (string, string)? tips) : EventBase
+{
+ public Reasons Reason { get; } = reason;
+
+ public (string Tag, string Message)? Tips { get; } = tips;
+
+ public override string ToEventMessage() => $"{nameof(BotOfflineEvent)}: {Reason} ({Tips?.Tag}, {Tips?.Message})";
+
+ public enum Reasons
+ {
+ Logout,
+ Kicked,
+ Disconnected,
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotOnlineEvent.cs b/Lagrange.Core/Events/EventArgs/BotOnlineEvent.cs
new file mode 100644
index 00000000..16464bc5
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotOnlineEvent.cs
@@ -0,0 +1,14 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotOnlineEvent(BotOnlineEvent.Reasons reason) : EventBase
+{
+ public enum Reasons
+ {
+ Login,
+ Reconnect,
+ }
+
+ public Reasons Reason { get; } = reason;
+
+ public override string ToEventMessage() => $"{nameof(BotOnlineEvent)}: {Reason}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotQrCodeEvent.cs b/Lagrange.Core/Events/EventArgs/BotQrCodeEvent.cs
new file mode 100644
index 00000000..fb26f3da
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotQrCodeEvent.cs
@@ -0,0 +1,10 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotQrCodeEvent(string url, byte[] image) : EventBase
+{
+ public string Url { get; } = url;
+
+ public byte[] Image { get; } = image;
+
+ public override string ToEventMessage() => $"[{nameof(BotQrCodeEvent)}] URL: {Url}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotQrCodeQueryEvent.cs b/Lagrange.Core/Events/EventArgs/BotQrCodeQueryEvent.cs
new file mode 100644
index 00000000..8f88bf26
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotQrCodeQueryEvent.cs
@@ -0,0 +1,18 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotQrCodeQueryEvent(BotQrCodeQueryEvent.TransEmpState state) : EventBase
+{
+ public TransEmpState State { get; } = state;
+
+ public override string ToEventMessage() => $"[{nameof(BotQrCodeQueryEvent)}] State: {State}";
+
+ public enum TransEmpState : byte
+ {
+ Confirmed = 0,
+ CodeExpired = 17,
+ WaitingForScan = 48,
+ WaitingForConfirm = 53,
+ Canceled = 54,
+ Invalid = 144
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotRefreshKeystoreEvent.cs b/Lagrange.Core/Events/EventArgs/BotRefreshKeystoreEvent.cs
new file mode 100644
index 00000000..3aa51154
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotRefreshKeystoreEvent.cs
@@ -0,0 +1,13 @@
+using Lagrange.Core.Common;
+
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotRefreshKeystoreEvent(BotKeystore keystore) : EventBase
+{
+ public BotKeystore Keystore { get; } = keystore;
+
+ public override string ToEventMessage()
+ {
+ return $"{nameof(BotRefreshKeystoreEvent)}";
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventArgs/BotSMSEvent.cs b/Lagrange.Core/Events/EventArgs/BotSMSEvent.cs
new file mode 100644
index 00000000..876efb8b
--- /dev/null
+++ b/Lagrange.Core/Events/EventArgs/BotSMSEvent.cs
@@ -0,0 +1,10 @@
+namespace Lagrange.Core.Events.EventArgs;
+
+public class BotSMSEvent(string? url, string phone) : EventBase
+{
+ public string? Url { get; } = url;
+
+ public string Phone { get; } = phone;
+
+ public override string ToEventMessage() => $"{nameof(BotSMSEvent)} {Phone} | URL: {Url}";
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Events/EventBase.cs b/Lagrange.Core/Events/EventBase.cs
index ea28c51d..673ee248 100644
--- a/Lagrange.Core/Events/EventBase.cs
+++ b/Lagrange.Core/Events/EventBase.cs
@@ -2,9 +2,12 @@ namespace Lagrange.Core.Events;
public abstract class EventBase : System.EventArgs
{
+ ///
+ /// Local receipt time, not server arrival time.
+ ///
public DateTime EventTime { get; }
- internal EventBase() => EventTime = DateTime.Now;
+ internal EventBase() => EventTime = DateTime.UtcNow;
public abstract string ToEventMessage();
diff --git a/Lagrange.Core/Events/EventInvoker.cs b/Lagrange.Core/Events/EventInvoker.cs
index faee5606..3bbe6e99 100644
--- a/Lagrange.Core/Events/EventInvoker.cs
+++ b/Lagrange.Core/Events/EventInvoker.cs
@@ -1,98 +1,152 @@
+using System.Collections.Concurrent;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Lagrange.Core.Events.EventArgs;
namespace Lagrange.Core.Events;
-public class EventInvoker(BotContext context)
+public sealed class EventInvoker(BotContext context) : IDisposable
{
private const string Tag = nameof(EventInvoker);
-
- private readonly Dictionary> _actions = new();
-
- private readonly Dictionary> _asyncActions = new();
- public delegate void LagrangeEventHandler(BotContext context, TEvent e) where TEvent : EventBase;
-
- public delegate Task LagrangeAsyncEventHandler(BotContext context, TEvent e) where TEvent : EventBase;
-
+ private static readonly ConcurrentDictionary SyncHandlerCache = new();
+ private static readonly ConcurrentDictionary AsyncHandlerCache = new();
+
+ private readonly ConcurrentDictionary _syncHandlers = new();
+ private readonly ConcurrentDictionary _asyncHandlers = new();
+
+ public delegate void LagrangeEventHandler (BotContext ctx, TEvent e) where TEvent : EventBase;
+ public delegate Task LagrangeAsyncEventHandler(BotContext ctx, TEvent e) where TEvent : EventBase;
+
public void RegisterEvent(LagrangeEventHandler handler) where TEvent : EventBase
{
- Debug.Assert(!handler.Method.IsStatic);
- ArgumentNullException.ThrowIfNull(handler.Target);
+ Debug.Assert(handler.Method.IsStatic is false);
- if (RuntimeFeature.IsDynamicCodeSupported)
- {
- Type[] args = [handler.Target.GetType(), typeof(BotContext), typeof(EventBase)];
- var method = new DynamicMethod($"EventInvoker_{typeof(TEvent)}", typeof(void), args, typeof(EventInvoker), true);
- var il = method.GetILGenerator();
-
- il.Emit(OpCodes.Ldarg_0); // [Target]
- il.Emit(OpCodes.Ldarg_1); // [Target, BotContext]
- il.Emit(OpCodes.Ldarg_2); // [Target, BotContext, EventBase]
- il.Emit(OpCodes.Castclass, typeof(TEvent)); // [Target, BotContext, TEvent]
- il.Emit(OpCodes.Callvirt, handler.Method); // []
- il.Emit(OpCodes.Ret); // []
-
- _actions[typeof(TEvent)] = method.CreateDelegate>(handler.Target);
- }
- else
- {
- _actions[typeof(TEvent)] = (ctx, e) => handler(ctx, (TEvent)e);
- }
+ var wrappedHandler = BuildSyncDelegate(handler);
+ AddHandler(_syncHandlers, typeof(TEvent), wrappedHandler);
}
-
+
public void RegisterEvent(LagrangeAsyncEventHandler handler) where TEvent : EventBase
{
- Debug.Assert(!handler.Method.IsStatic);
- ArgumentNullException.ThrowIfNull(handler.Target);
+ Debug.Assert(handler.Method.IsStatic is false);
- if (RuntimeFeature.IsDynamicCodeSupported)
- {
- Type[] args = [handler.Target.GetType(), typeof(BotContext), typeof(EventBase)];
- var method = new DynamicMethod($"EventInvoker_{typeof(TEvent)}", typeof(Task), args, typeof(EventInvoker), true);
- var il = method.GetILGenerator();
-
- il.Emit(OpCodes.Ldarg_0); // [Target]
- il.Emit(OpCodes.Ldarg_1); // [Target, BotContext]
- il.Emit(OpCodes.Ldarg_2); // [Target, BotContext, EventBase]
- il.Emit(OpCodes.Castclass, typeof(TEvent)); // [Target, BotContext, TEvent]
- il.Emit(OpCodes.Callvirt, handler.Method); // [Task]
- il.Emit(OpCodes.Ret); // []
-
- _asyncActions[typeof(TEvent)] = method.CreateDelegate>(handler.Target);
- }
- else
- {
- _asyncActions[typeof(TEvent)] = (ctx, e) => handler(ctx, (TEvent)e);
- }
+ var wrappedHandler = BuildAsyncDelegate(handler);
+ AddHandler(_asyncHandlers, typeof(TEvent), wrappedHandler);
}
- internal void PostEvent(T @event) where T : EventBase => Task.Run(async () =>
+ public void UnregisterEvent(LagrangeEventHandler handler) where TEvent : EventBase
{
- await context.EventContext.HandleOutgoingEvent(@event);
-
+ var wrappedHandler = BuildSyncDelegate(handler);
+ RemoveHandler(_syncHandlers, typeof(TEvent), wrappedHandler);
+ }
+
+ public void UnregisterEvent(LagrangeAsyncEventHandler handler) where TEvent : EventBase
+ {
+ var wrappedHandler = BuildAsyncDelegate(handler);
+ RemoveHandler(_asyncHandlers, typeof(TEvent), wrappedHandler);
+ }
+
+ public void UnregisterEvent() where TEvent : EventBase
+ {
+ _syncHandlers.TryRemove(typeof(TEvent), out _);
+ _asyncHandlers.TryRemove(typeof(TEvent), out _);
+ }
+
+ internal void PostEvent(T ev) where T : EventBase => Task.Run(async () =>
+ {
+ await context.EventContext.HandleOutgoingEvent(ev);
+
try
{
- if (_actions.TryGetValue(typeof(T), out var @delegate))
+ if (_syncHandlers.TryGetValue(typeof(T), out var @delegate) && @delegate is not null)
{
- @delegate(context, @event);
+ ((Action)@delegate).Invoke(context, ev);
}
- else if (_asyncActions.TryGetValue(typeof(T), out var asyncDelegate))
+
+ if (_asyncHandlers.TryGetValue(typeof(T), out var asyncDelegate) && asyncDelegate is not null)
{
- await asyncDelegate(context, @event);
+ await ((Func)asyncDelegate)(context, ev);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
- if (typeof(T) == typeof(BotLogEvent))
+ if (typeof(T) == typeof(BotLogEvent))
{
- Console.WriteLine($"Failed to post event: {@event}");
+ Console.WriteLine($"Failed to post event: {ev}");
return;
}
-
- PostEvent(new BotLogEvent(Tag, LogLevel.Error, $"{ex}"));
+ PostEvent(new BotLogEvent(Tag, LogLevel.Error, ex.ToString(), ex));
}
});
+
+ public void Dispose()
+ {
+ _syncHandlers.Clear();
+ _asyncHandlers.Clear();
+ }
+
+ private static void AddHandler(ConcurrentDictionary dict, Type key, Delegate handler)
+ {
+ dict.AddOrUpdate(key, handler, (_, old) => Delegate.Combine(old, handler));
+ }
+
+ private static void RemoveHandler(ConcurrentDictionary dict, Type key, Delegate handler)
+ {
+ dict.AddOrUpdate(key, _ => null, (_, old) => Delegate.Remove(old, handler)!);
+
+ if (dict.TryGetValue(key, out var currentDelegate) && currentDelegate == null)
+ {
+ dict.TryRemove(key, out _);
+ }
+ }
+
+ [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "DynamicMethod is not supported in AOT, but this branch is skipped there")]
+ private static Delegate BuildSyncDelegate(LagrangeEventHandler h) where TEvent : EventBase
+ {
+ return SyncHandlerCache.GetOrAdd(h, handler =>
+ {
+ if (!RuntimeFeature.IsDynamicCodeSupported)
+ {
+ return (Action)((ctx, ev) => ((LagrangeEventHandler)handler)(ctx, (TEvent)ev));
+ }
+
+ var dm = new DynamicMethod($"EventInvoker_{typeof(TEvent).Name}_{Guid.NewGuid()}", typeof(void), [handler.Target!.GetType(), typeof(BotContext), typeof(EventBase)], typeof(EventInvoker), true);
+ var il = dm.GetILGenerator();
+
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Ldarg_1);
+ il.Emit(OpCodes.Ldarg_2);
+ il.Emit(OpCodes.Castclass, typeof(TEvent));
+ il.Emit(OpCodes.Callvirt, handler.Method);
+ il.Emit(OpCodes.Ret);
+
+ return dm.CreateDelegate>(handler.Target);
+ });
+ }
+
+ [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "DynamicMethod is not supported in AOT, but this branch is skipped there")]
+ private static Delegate BuildAsyncDelegate(LagrangeAsyncEventHandler h) where TEvent : EventBase
+ {
+ return AsyncHandlerCache.GetOrAdd(h, handler =>
+ {
+ if (!RuntimeFeature.IsDynamicCodeSupported)
+ {
+ return (Func)((ctx, ev) => ((LagrangeAsyncEventHandler)handler)(ctx, (TEvent)ev));
+ }
+
+ var dm = new DynamicMethod($"EventInvoker_{typeof(TEvent).Name}_Async_{Guid.NewGuid()}", typeof(Task), [handler.Target!.GetType(), typeof(BotContext), typeof(EventBase)], typeof(EventInvoker), true);
+ var il = dm.GetILGenerator();
+
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Ldarg_1);
+ il.Emit(OpCodes.Ldarg_2);
+ il.Emit(OpCodes.Castclass, typeof(TEvent));
+ il.Emit(OpCodes.Callvirt, handler.Method);
+ il.Emit(OpCodes.Ret);
+
+ return dm.CreateDelegate>(handler.Target);
+ });
+ }
}
\ No newline at end of file
diff --git a/Lagrange.Core/Exceptions/InvalidTargetException.cs b/Lagrange.Core/Exceptions/InvalidTargetException.cs
new file mode 100644
index 00000000..581adad6
--- /dev/null
+++ b/Lagrange.Core/Exceptions/InvalidTargetException.cs
@@ -0,0 +1,26 @@
+using Lagrange.Core.Common.Entity;
+
+namespace Lagrange.Core.Exceptions;
+
+///
+/// When specified target is not found or invalid, this exception will be thrown.
+///
+public class InvalidTargetException : LagrangeException
+{
+ public long? TargetUin { get; }
+
+ public long? GroupUin { get; }
+
+ public InvalidTargetException(long targetUin) :
+ base($"Target {targetUin} is invalid or not found.")
+ {
+ TargetUin = targetUin;
+ }
+
+ public InvalidTargetException(long? targetUin, long groupUin) :
+ base($"Target {targetUin} is invalid in group {groupUin} or not found.")
+ {
+ TargetUin = targetUin;
+ GroupUin = groupUin;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Exceptions/LagrangeException.cs b/Lagrange.Core/Exceptions/LagrangeException.cs
new file mode 100644
index 00000000..480c167f
--- /dev/null
+++ b/Lagrange.Core/Exceptions/LagrangeException.cs
@@ -0,0 +1,25 @@
+namespace Lagrange.Core.Exceptions;
+
+///
+/// The Exception class for Lagrange.Core, All exceptions should be derived from this class.
+///
+public class LagrangeException : Exception
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public LagrangeException() { }
+
+ ///
+ /// Initializes a new instance of the class with a specified error message.
+ ///
+ /// The error message that explains the reason for the exception.
+ public LagrangeException(string message) : base(message) { }
+
+ ///
+ /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.
+ ///
+ /// The error message that explains the reason for the exception.
+ /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.
+ public LagrangeException(string? message, Exception innerException) : base(message, innerException) { }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Exceptions/LoginException.cs b/Lagrange.Core/Exceptions/LoginException.cs
deleted file mode 100644
index d6ed2d7c..00000000
--- a/Lagrange.Core/Exceptions/LoginException.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace Lagrange.Core.Exceptions;
-
-public class LoginException(short retCode, string tag, string message) : Exception($"{tag}({retCode}) | {message}")
-{
- public short RetCode { get; } = retCode;
-
- public string Tag { get; } = tag;
-
- public string ErrorMsg { get; } = message;
-}
\ No newline at end of file
diff --git a/Lagrange.Core/Exceptions/OperationException.cs b/Lagrange.Core/Exceptions/OperationException.cs
new file mode 100644
index 00000000..7b98ffcd
--- /dev/null
+++ b/Lagrange.Core/Exceptions/OperationException.cs
@@ -0,0 +1,11 @@
+namespace Lagrange.Core.Exceptions;
+
+///
+/// Exception thrown when an operation fails.
+///
+public class OperationException(int result, string? errMsg = null) : LagrangeException($"Operation failed with code {result}: {errMsg}")
+{
+ public int Result { get; } = result;
+
+ public string? ErrMsg { get; } = errMsg;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Exceptions/ServiceNotFoundException.cs b/Lagrange.Core/Exceptions/ServiceNotFoundException.cs
new file mode 100644
index 00000000..7f444907
--- /dev/null
+++ b/Lagrange.Core/Exceptions/ServiceNotFoundException.cs
@@ -0,0 +1,6 @@
+namespace Lagrange.Core.Exceptions;
+
+internal class ServiceNotFoundException(string command) : LagrangeException($"Service not found for command: {command}")
+{
+ public string Command { get; } = command;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Context/CacheContext.cs b/Lagrange.Core/Internal/Context/CacheContext.cs
index 5b2a4e34..c07d28dd 100644
--- a/Lagrange.Core/Internal/Context/CacheContext.cs
+++ b/Lagrange.Core/Internal/Context/CacheContext.cs
@@ -1,6 +1,195 @@
+using System.Collections.Concurrent;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Internal.Events.System;
+
namespace Lagrange.Core.Internal.Context;
-public class CacheContext(BotContext context)
+internal class CacheContext(BotContext context)
{
-
+ private List? _friends;
+
+ private List? _groups;
+
+ private readonly ConcurrentDictionary _uinToUid = new();
+ private readonly ConcurrentDictionary _uidToUin = new();
+
+ private readonly ConcurrentDictionary> _members = new();
+
+ private readonly Dictionary _categories = [];
+
+ private readonly Dictionary _strangersWithUid = [];
+ private readonly Dictionary _strangersWithUin = [];
+ private readonly SemaphoreSlim _strangersLock = new(1);
+
+ public async Task> GetFriendList(bool refresh = false)
+ {
+ if (refresh || _friends == null) Interlocked.Exchange(ref _friends, await FetchFriends());
+
+ return _friends;
+ }
+
+ public async Task> GetGroupList(bool refresh = false)
+ {
+ if (refresh) Interlocked.Exchange(ref _groups, await FetchGroups());
+ Interlocked.CompareExchange(ref _groups, await FetchGroups(), null);
+
+ return _groups;
+ }
+
+ public async Task> GetMemberList(long groupUin, bool refresh = false)
+ {
+ if (refresh || !_members.TryGetValue(groupUin, out var members))
+ {
+ members = _members[groupUin] = await FetchGroupMembers(groupUin);
+ }
+
+ return members;
+ }
+
+ public async Task> GetCategories(bool refresh = false)
+ {
+ if (refresh || _categories.Count == 0) Interlocked.Exchange(ref _friends, await FetchFriends());
+
+ return _categories.Values.ToList();
+ }
+
+ public async Task ResolveFriend(long uin)
+ {
+ if (_friends == null) Interlocked.Exchange(ref _friends, await FetchFriends());
+ var friend = _friends?.FirstOrDefault(f => f.Uin == uin);
+
+ if (friend == null)
+ {
+ _friends = Interlocked.Exchange(ref _friends, await FetchFriends());
+ friend = _friends?.FirstOrDefault(f => f.Uin == uin);
+ }
+
+ return friend;
+ }
+
+ public async Task<(BotGroup, BotGroupMember)?> ResolveMember(long groupUin, long memberUin)
+ {
+ var group = await ResolveGroup(groupUin);
+ if (group == null) return null;
+
+ if (!_members.TryGetValue(groupUin, out var members))
+ {
+ members = _members[groupUin] = await FetchGroupMembers(groupUin);
+ }
+ var member = members.FirstOrDefault(m => m.Uin == memberUin);
+ return member == null ? null : (group, member);
+ }
+
+ public async Task ResolveGroup(long groupUin)
+ {
+ if (_groups == null) Interlocked.Exchange(ref _groups, await FetchGroups());
+ var group = _groups?.FirstOrDefault(f => f.GroupUin == groupUin);
+
+ if (group == null)
+ {
+ _groups = Interlocked.Exchange(ref _groups, await FetchGroups());
+ group = _groups?.FirstOrDefault(f => f.GroupUin == groupUin);
+ }
+
+ return group;
+ }
+
+ public async Task ResolveStranger(long uin)
+ {
+ await _strangersLock.WaitAsync();
+ try
+ {
+ if (_strangersWithUin.TryGetValue(uin, out BotStranger? stranger)) return stranger;
+
+ stranger = await FetchStranger(uin);
+ _strangersWithUin.Add(uin, stranger);
+
+ return stranger;
+ }
+ finally { _strangersLock.Release(); }
+ }
+
+ public async Task ResolveStranger(string uid)
+ {
+ await _strangersLock.WaitAsync();
+ try
+ {
+ if (_strangersWithUid.TryGetValue(uid, out BotStranger? stranger)) return stranger;
+
+ stranger = await FetchStranger(uid);
+ _strangersWithUin.TryAdd(stranger.Uin, stranger);
+ _strangersWithUid.Add(uid, stranger);
+
+ return stranger;
+ }
+ finally { _strangersLock.Release(); }
+ }
+
+ public string? ResolveCachedUid(long uin) => _uinToUid.GetValueOrDefault(uin);
+
+ public long ResolveUin(string uid)
+ {
+ if (_uidToUin.TryGetValue(uid, out long value)) return value;
+
+ long uin = _uinToUid.FirstOrDefault(kvp => kvp.Value == uid).Key;
+ if (uin != 0) return uin;
+
+ return ResolveStranger(uid).GetAwaiter().GetResult().Uin;
+ }
+
+ ///
+ /// Fetches the friends list from the server.
+ ///
+ private async Task> FetchFriends()
+ {
+ var friends = new List();
+
+ byte[]? cookie = null;
+ do
+ {
+ var result = await context.EventContext.SendEvent(new FetchFriendsEventReq(cookie));
+ cookie = result.Cookie;
+
+ friends.AddRange(result.Friends);
+ foreach (var category in result.Category) _categories[category.Id] = category;
+ foreach (var friend in friends) _uinToUid[friend.Uin] = friend.Uid;
+ } while (cookie != null);
+
+ return friends;
+ }
+
+ private async Task> FetchGroups()
+ {
+ var result = await context.EventContext.SendEvent(new FetchGroupsEventReq());
+ return result.Groups;
+ }
+
+ private async Task> FetchGroupMembers(long groupUin)
+ {
+ var members = new List();
+
+ byte[]? cookie = null;
+ do
+ {
+ var result = await context.EventContext.SendEvent(new FetchGroupMembersEventReq(groupUin, cookie));
+ cookie = result.Cookie;
+
+ members.AddRange(result.GroupMembers);
+ foreach (var member in result.GroupMembers) _uinToUid[member.Uin] = member.Uid;
+ } while (cookie != null);
+
+ return members;
+ }
+
+ private async Task FetchStranger(long uin)
+ {
+ var result = await context.EventContext.SendEvent(new FetchStrangerByUinEventReq(uin));
+ return result.Stranger;
+ }
+
+ private async Task FetchStranger(string uid)
+ {
+ var result = await context.EventContext.SendEvent(new FetchStrangerByUidEventReq(uid));
+ return result.Stranger;
+ }
}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Context/EventContext.cs b/Lagrange.Core/Internal/Context/EventContext.cs
index a0232c8a..bdb74291 100644
--- a/Lagrange.Core/Internal/Context/EventContext.cs
+++ b/Lagrange.Core/Internal/Context/EventContext.cs
@@ -1,28 +1,36 @@
-using System.Collections.Frozen;
+using System.Collections.Frozen;
+using System.Diagnostics.CodeAnalysis;
using System.Reflection;
+using Lagrange.Core.Common.Entity;
using Lagrange.Core.Events;
+using Lagrange.Core.Exceptions;
using Lagrange.Core.Internal.Events;
using Lagrange.Core.Internal.Logic;
-using Lagrange.Core.Internal.Packets.Struct;
+using Lagrange.Core.Utility.Extension;
namespace Lagrange.Core.Internal.Context;
-internal class EventContext
+internal class EventContext : IDisposable
{
+ private const string Tag = nameof(EventContext);
+
private readonly BotContext _context;
-
+
private readonly FrozenDictionary> _events;
private readonly FrozenDictionary _logics;
+ [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
+ [UnconditionalSuppressMessage("Trimming", "IL2062", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
+ [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
public EventContext(BotContext context)
{
var events = new Dictionary>();
var logics = new Dictionary();
-
+
foreach (var type in typeof(ILogic).Assembly.GetTypes())
{
- if (type.GetInterfaces().Contains(typeof(ILogic)) && Activator.CreateInstance(type, context) is ILogic instance)
+ if (type.HasImplemented() && Activator.CreateInstance(type, context) is ILogic instance)
{
foreach (var @event in type.GetCustomAttributes())
{
@@ -31,48 +39,45 @@ public EventContext(BotContext context)
list = [];
events.Add(@event.EventType, list);
}
-
+
list.Add(instance);
}
-
+
logics[type] = instance;
}
}
-
+
_context = context;
_events = events.ToFrozenDictionary();
_logics = logics.ToFrozenDictionary();
}
-
- public async ValueTask SendEvent(T @event) where T : ProtocolEvent
+
+ public async ValueTask SendEvent(ProtocolEvent @event) where T : ProtocolEvent
{
try
{
await HandleOutgoingEvent(@event);
- var (frame, attribute) = await _context.ServiceContext.Resolve(@event);
- if (frame.Sequence == 0)
- {
- // TODO: Log
- return null;
- }
-
+ var (frame, attribute) = await _context.ServiceContext.Resolve(@event);
+ if (frame.Sequence == 0) throw new LagrangeException("The sequence number is 0 for the SSOFrame");
+
+
var @return = await _context.PacketContext.SendPacket(frame, attribute);
var resolved = await _context.ServiceContext.Resolve(@return);
-
+
if (resolved is T result)
{
await HandleIncomingEvent(result);
return result;
}
+
+ throw new LagrangeException($"The event type is not the same as the expected type. Expected: {typeof(T)}, Actual: {resolved.GetType()}");
}
- catch (Exception e)
+ catch (Exception e) when (e is not LagrangeException)
{
- // TODO: Log
+ throw new LagrangeException("An error occurred while sending the event", e);
}
-
- return null;
}
-
+
private async ValueTask HandleIncomingEvent(ProtocolEvent @event)
{
if (_events.TryGetValue(@event.GetType(), out var logics))
@@ -83,9 +88,9 @@ private async ValueTask HandleIncomingEvent(ProtocolEvent @event)
{
await logic.Incoming(@event);
}
- catch (Exception e)
+ catch (Exception e) when (e is not LagrangeException)
{
- // TODO: Log
+ throw new LagrangeException("An error occurred while processing the incoming event", e);
}
}
}
@@ -101,14 +106,14 @@ private async ValueTask HandleOutgoingEvent(ProtocolEvent @event)
{
await logic.Outgoing(@event);
}
- catch (Exception e)
+ catch (Exception e) when (e is not LagrangeException)
{
- // TODO: Log
+ throw new LagrangeException("An error occurred while processing the outgoing event", e);
}
}
}
}
-
+
public async ValueTask HandleOutgoingEvent(EventBase @event)
{
if (_events.TryGetValue(@event.GetType(), out var logics))
@@ -119,19 +124,38 @@ public async ValueTask HandleOutgoingEvent(EventBase @event)
{
await logic.Outgoing(@event);
}
- catch (Exception e)
+ catch (Exception e) when (e is not LagrangeException)
{
- // TODO: Log
+ throw new LagrangeException("An error occurred while processing the outgoing event", e);
}
}
}
}
- public async Task HandleServerPacket(SsoPacket packet)
+ public async Task HandleServerPacket(BotSsoPacket packet)
{
- var @event = await _context.ServiceContext.Resolve(packet);
- if (@event is not null) await HandleIncomingEvent(@event);
+ try
+ {
+ var @event = await _context.ServiceContext.Resolve(packet);
+ await HandleIncomingEvent(@event);
+ }
+ catch (ServiceNotFoundException e)
+ {
+ _context.LogDebug(Tag, "Service not found for command: {0}", e, e.Command);
+ }
+ catch (Exception e)
+ {
+ _context.LogError(Tag, "Handle {0} server packet failed", e, packet.Command);
+ }
}
-
+
public T GetLogic() where T : ILogic => (T)_logics[typeof(T)];
+
+ public void Dispose()
+ {
+ foreach (var logic in _logics.Values)
+ {
+ if (logic is IDisposable disposable) disposable.Dispose();
+ }
+ }
}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Context/FlashTransferContext.cs b/Lagrange.Core/Internal/Context/FlashTransferContext.cs
new file mode 100644
index 00000000..7fd7b07d
--- /dev/null
+++ b/Lagrange.Core/Internal/Context/FlashTransferContext.cs
@@ -0,0 +1,137 @@
+using System.Security.Cryptography;
+using Lagrange.Core.Internal.Packets.Service;
+using Lagrange.Core.Utility;
+using Lagrange.Core.Utility.Cryptography;
+using Lagrange.Core.Utility.Extension;
+
+namespace Lagrange.Core.Internal.Context;
+
+public class FlashTransferContext
+{
+ private const string Tag = nameof(FlashTransferContext);
+ private readonly BotContext _botContext;
+ private readonly HttpClient _client;
+ private readonly string? _url;
+ private const uint ChunkSize = 1024 * 1024;
+
+ internal FlashTransferContext(BotContext botContext)
+ {
+ _botContext = botContext;
+ _client = new HttpClient();
+ _client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
+ _url = "https://multimedia.qfile.qq.com/sliceupload";
+ }
+
+ public async Task UploadFile(string uKey, uint appId, Stream bodyStream)
+ {
+ return await UploadFile(uKey, appId, 2, bodyStream, null, _url);
+ }
+
+ public async Task UploadFile(string uploadToken, string uploadHost, uint appId, uint uploadIndex, string fileSetId, string fileId, uint bindingStage, uint fileType, uint bindingField5, uint bindingField6, Stream bodyStream)
+ {
+ var binding = new FlashTransferUploadFileBinding
+ {
+ FileSetId = fileSetId,
+ FileSetIdDup = fileSetId,
+ FileId = fileId,
+ Stage = bindingStage,
+ Field5 = bindingField5,
+ Field6 = bindingField6,
+ FileType = fileType,
+ FileIdDup = fileId,
+ };
+
+ return await UploadFile(uploadToken, appId, uploadIndex, bodyStream, binding, $"https://{uploadHost}/sliceupload");
+ }
+
+ private async Task UploadFile(string uKey, uint appId, uint uploadIndex, Stream bodyStream, FlashTransferUploadFileBinding? binding, string? url)
+ {
+ var sha1StateVs = new FlashTransferSha1StateV { State = [] };
+ var chunkCount = (uint)((bodyStream.Length + ChunkSize - 1) / ChunkSize);
+
+ var sha1Stream = new Sha1Stream();
+ for (uint i = 0; i < chunkCount; i++)
+ {
+ if (i != chunkCount - 1)
+ {
+ var accLength = (int)((i + 1) * ChunkSize);
+ var accBuffer = new byte[accLength];
+
+ bodyStream.Position = 0;
+ await bodyStream.ReadExactlyAsync(accBuffer, 0, accLength);
+
+ var accSpan = accBuffer.AsSpan();
+ var digest = new byte[20];
+ sha1Stream.Update(accSpan);
+ sha1Stream.Hash(digest, false);
+ sha1Stream.Reset();
+ sha1StateVs.State.Add(digest.ToArray());
+ }
+ else
+ {
+ bodyStream.Position = 0;
+ sha1StateVs.State.Add(bodyStream.Sha1());
+ }
+ }
+
+ for (uint i = 0; i < chunkCount; i++)
+ {
+ var chunkStart = (long)(i * ChunkSize);
+ var chunkLength = (int)Math.Min(ChunkSize, bodyStream.Length - chunkStart);
+
+ bodyStream.Position = chunkStart;
+ var uploadBuffer = new byte[chunkLength];
+ await bodyStream.ReadExactlyAsync(uploadBuffer, 0, chunkLength);
+
+ var success = await UploadChunk(uKey, appId, uploadIndex, (uint)chunkStart, sha1StateVs, uploadBuffer, binding, url);
+ if (!success) return false;
+ }
+
+ return true;
+ }
+
+ private async Task UploadChunk(string uKey, uint appId, uint uploadIndex, uint start, FlashTransferSha1StateV chunkSha1S, byte[] body, FlashTransferUploadFileBinding? binding, string? url)
+ {
+ byte[] chunkSha1 = SHA1.HashData(body);
+ var req = new FlashTransferUploadReq
+ {
+ FileId = 0,
+ AppId = appId,
+ UploadIndex = uploadIndex,
+ Body = new FlashTransferUploadBody
+ {
+ FileId = [],
+ UKey = uKey,
+ Start = start,
+ End = (uint)(start + body.Length - 1),
+ Sha1 = chunkSha1,
+ Sha1StateV = binding == null ? chunkSha1S : new FlashTransferSha1StateV { State = [chunkSha1] },
+ Body = body,
+ FileBinding = binding
+ }
+ };
+ var payload = ProtoHelper.Serialize(req).ToArray();
+ var request = new HttpRequestMessage(HttpMethod.Post, url)
+ {
+ Headers =
+ {
+ { "Accept", "*/*" },
+ { "Expect", "100-continue" },
+ { "Connection", "Keep-Alive" }
+ },
+ Content = new ByteArrayContent(payload)
+ };
+ var response = await _client.SendAsync(request);
+ var responseBytes = await response.Content.ReadAsByteArrayAsync();
+ var resp = ProtoHelper.Deserialize(responseBytes);
+
+ if (resp.Status != "success")
+ {
+ _botContext.LogError(Tag,
+ $"FlashTransfer Upload chunk {start} failed: {resp.Status} appId: {appId}, uploadIndex: {uploadIndex}, keyLength: {uKey?.Length ?? 0}");
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/Lagrange.Core/Internal/Context/HighwayContext.cs b/Lagrange.Core/Internal/Context/HighwayContext.cs
new file mode 100644
index 00000000..a1c8240d
--- /dev/null
+++ b/Lagrange.Core/Internal/Context/HighwayContext.cs
@@ -0,0 +1,182 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Security.Cryptography;
+using Lagrange.Core.Internal.Events.System;
+using Lagrange.Core.Internal.Packets.Service;
+using Lagrange.Core.Utility;
+using Lagrange.Core.Utility.Binary;
+using Lagrange.Core.Utility.Extension;
+
+namespace Lagrange.Core.Internal.Context;
+
+internal class HighwayContext
+{
+ private const string Tag = nameof(HighwayContext);
+
+ private readonly BotContext _context;
+
+ private readonly HttpClient _client;
+
+ private readonly ulong _chunkSize;
+
+ private readonly int _concurrent;
+
+ private int _sequence;
+
+ private (byte[], DateTime)? _ticket;
+
+ private string? _url;
+
+ public HighwayContext(BotContext context)
+ {
+ _context = context;
+
+ _client = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, _, _, _) => true });
+ _client.DefaultRequestHeaders.Add("Accept-Encoding", "identity");
+ _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)");
+
+ _sequence = 0;
+ _chunkSize = context.Config.HighwayChunkSize;
+ _concurrent = (int)context.Config.HighwayConcurrent;
+ }
+
+ public async Task UploadFile(Stream stream, int commandId, ReadOnlyMemory extendInfo)
+ {
+ if (_ticket == null || _url == null || DateTime.Now - _ticket.Value.Item2 > TimeSpan.FromDays(0.5))
+ {
+ var resp = await _context.EventContext.SendEvent(new HighwaySessionEventReq());
+ _ticket = (resp.SigSession, DateTime.Now);
+ _url = resp.HighwayUrls[1][0];
+ }
+
+ var tasks = new List>();
+ bool result = true;
+
+ ulong fileSize = (ulong)stream.Length;
+ ulong offset = 0;
+ var fileMd5 = stream.Md5();
+ while (offset < fileSize)
+ {
+ var buffer = ArrayPool.Shared.Rent((int)_chunkSize);
+ ulong payload = (ulong)await stream.ReadAsync(buffer.AsMemory(0, (int)_chunkSize));
+
+ ulong currentBlockOffset = offset;
+ var task = Task.Run(async () => // closure
+ {
+ var bufferSpan = buffer.AsSpan(0, (int)payload);
+ int sequence = GetNewSequence();
+
+ var head = new DataHighwayHead
+ {
+ Version = 1,
+ Uin = _context.Keystore.Uin.ToString(),
+ Command = "PicUp.DataUp",
+ Seq = (uint)sequence,
+ AppId = (uint)_context.AppInfo.AppId,
+ DataFlag = 16,
+ CommandId = (uint)commandId,
+ };
+ var segHead = new SegHead
+ {
+ Filesize = fileSize,
+ DataOffset = currentBlockOffset,
+ DataLength = (uint)payload,
+ ServiceTicket = _ticket.Value.Item1,
+ Md5 = MD5.HashData(bufferSpan),
+ FileMd5 = fileMd5,
+ };
+ var loginHead = new LoginSigHead
+ {
+ Uint32LoginSigType = 8,
+ BytesLoginSig = _context.Keystore.WLoginSigs.A2,
+ AppId = (uint)_context.AppInfo.AppId
+ };
+ var highwayHead = new ReqDataHighwayHead
+ {
+ MsgBaseHead = head,
+ MsgSegHead = segHead,
+ BytesReqExtendInfo = extendInfo,
+ Timestamp = 0,
+ MsgLoginSigHead = loginHead
+ };
+ var headProto = ProtoHelper.Serialize(highwayHead);
+
+ bool end = currentBlockOffset + payload >= fileSize;
+ var upload = ArrayPool.Shared.Rent(1 + 1 + 4 + 4 + headProto.Length + (int)payload);
+ var memory = upload.AsMemory(0, 1 + 1 + 4 + 4 + headProto.Length + (int)payload);
+
+ memory.Span[0] = 0x28;
+ BinaryPrimitives.WriteUInt32BigEndian(memory.Span[1..], (uint)headProto.Length);
+ BinaryPrimitives.WriteUInt32BigEndian(memory.Span[5..], (uint)payload);
+ headProto.Span.CopyTo(memory.Span[9..]);
+ bufferSpan.CopyTo(memory.Span[(9 + headProto.Length)..]);
+ memory.Span[^1] = 0x29;
+
+ var request = new HttpRequestMessage(HttpMethod.Post, $"http://{_url}")
+ {
+ Content = new ReadOnlyMemoryContent(memory), Headers = { { "Connection", end ? "close" : "keep-alive" } }
+ };
+
+ try
+ {
+ var response = await _client.SendAsync(request);
+ var reader = new BinaryPacket((await response.Content.ReadAsByteArrayAsync()).AsSpan());
+
+ if (reader.Read() == 0x28)
+ {
+ int headLen = reader.Read();
+ int bodyLen = reader.Read();
+ var respHead = reader.CreateSpan(headLen);
+ var body = GC.AllocateUninitializedArray(bodyLen);
+ reader.ReadBytes(body.AsSpan());
+
+ if (reader.Read() == 0x29)
+ {
+ var obj = ProtoHelper.Deserialize(respHead);
+ _context.LogDebug(Tag, "Highway Block Result: {0} | {1} | {2}", obj.ErrorCode, obj.MsgSegHead?.RetCode, Convert.ToHexString(body));
+ return obj.ErrorCode == 0;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ _context.LogError(Tag, "Highway HTTP error: {0}", e, e.Message);
+ if (e.StackTrace is { } stack) _context.LogDebug(Tag, stack);
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(buffer);
+ ArrayPool.Shared.Return(upload);
+ request.Dispose();
+ new ReadOnlyMemoryContent(memory).Dispose();
+ }
+
+ return false;
+ });
+ offset += payload;
+
+ tasks.Add(task);
+ if (tasks.Count == (_concurrent))
+ {
+ var successBlocks = await Task.WhenAll(tasks);
+ foreach (bool t in successBlocks) result &= t;
+ tasks.Clear();
+ }
+
+ if (tasks.Count != 0)
+ {
+ var finalBlocks = await Task.WhenAll(tasks);
+ foreach (bool t in finalBlocks) result &= t;
+ tasks.Clear();
+ }
+ }
+
+ return result;
+ }
+
+ private int GetNewSequence()
+ {
+ Interlocked.CompareExchange(ref _sequence, 0, 100000);
+ return Interlocked.Increment(ref _sequence);
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Context/PacketContext.cs b/Lagrange.Core/Internal/Context/PacketContext.cs
index 1b172ce9..c07c2b35 100644
--- a/Lagrange.Core/Internal/Context/PacketContext.cs
+++ b/Lagrange.Core/Internal/Context/PacketContext.cs
@@ -1,69 +1,109 @@
-using System.Collections.Concurrent;
+using System.Collections.Concurrent;
using Lagrange.Core.Common;
+using Lagrange.Core.Common.Entity;
using Lagrange.Core.Internal.Packets.Struct;
using Lagrange.Core.Internal.Services;
namespace Lagrange.Core.Internal.Context;
-internal class PacketContext(BotContext context)
+internal class PacketContext
{
private readonly ConcurrentDictionary _pendingTasks = new();
-
- private readonly BotKeystore _keystore = context.Keystore;
- private readonly SsoPacker _ssoPacker = new(context);
- private readonly ServicePacker _servicePacker = new(context);
- private readonly IBotSignProvider _signProvider = context.Config.SignProvider ?? new DefaultBotSignProvider(context.Config.Protocol, context.AppInfo);
- public ValueTask SendPacket(SsoPacket packet, ServiceAttribute options)
+ private readonly BotKeystore _keystore;
+ private readonly SsoPacker _ssoPacker;
+ private readonly ServicePacker _servicePacker;
+
+ internal readonly BotSignProvider SignProvider;
+
+ private readonly BotContext _context;
+
+ public PacketContext(BotContext context)
+ {
+ _context = context;
+ _keystore = context.Keystore;
+ _ssoPacker = new SsoPacker(context);
+ _servicePacker = new ServicePacker(context);
+
+ SignProvider = context.Config.SignProvider ?? context.Config.Protocol switch
+ {
+ Protocols.Linux or Protocols.Windows or Protocols.MacOs => new DefaultBotSignProvider(),
+ Protocols.AndroidPhone or Protocols.AndroidPad => new DefaultAndroidBotSignProvider(),
+ _ => throw new ArgumentOutOfRangeException(nameof(context.Config.Protocol))
+ };
+
+ SignProvider.Context = context; // Initialize the sign provider with the context
+ }
+
+ public ValueTask SendPacket(BotSsoPacket packet, ServiceAttribute options)
{
var tcs = new SsoPacketValueTaskSource();
_pendingTasks.TryAdd(packet.Sequence, tcs);
Task.Run(async () => // Schedule the task to the ThreadPool
{
- ReadOnlyMemory frame;
-
- switch (options.RequestType)
+ try
{
- case RequestType.D2Auth:
+ ReadOnlyMemory frame;
+
+ switch (options.RequestType)
{
- if (IBotSignProvider.IsWhiteListCommand(packet.Command))
+ case RequestType.D2Auth:
{
- var secInfo = await _signProvider.GetSecSign(_keystore.Uin, packet.Command, packet.Sequence, packet.Data);
- var sso = _ssoPacker.BuildProtocol12(packet, secInfo);
- frame = _servicePacker.BuildProtocol12(sso, options);
+ if (SignProvider.IsWhiteListCommand(packet.Command))
+ {
+ var secInfo = await SignProvider.GetSecSign(_keystore.Uin, packet.Command, packet.Sequence, packet.Data);
+ var sso = _ssoPacker.BuildProtocol12(packet, secInfo);
+ frame = _servicePacker.BuildProtocol12(sso, options);
+ }
+ else
+ {
+ var sso = _ssoPacker.BuildProtocol12(packet, null);
+ frame = _servicePacker.BuildProtocol12(sso, options);
+ }
+
+ break;
}
- else
+ case RequestType.Simple:
{
- var sso = _ssoPacker.BuildProtocol12(packet, null);
- frame = _servicePacker.BuildProtocol12(sso, options);
+ if (SignProvider.IsWhiteListCommand(packet.Command))
+ {
+ var secInfo = await SignProvider.GetSecSign(_keystore.Uin, packet.Command, packet.Sequence, packet.Data);
+ var sso = _ssoPacker.BuildProtocol13(packet, secInfo);
+ frame = _servicePacker.BuildProtocol13(packet, sso, options);
+ }
+ else
+ {
+ var sso = _ssoPacker.BuildProtocol13(packet, null);
+ frame = _servicePacker.BuildProtocol13(packet, sso, options);
+ }
+ break;
+ }
+ default:
+ {
+ throw new InvalidOperationException($"Unknown RequestType: {options.RequestType}");
}
-
- break;
- }
- case RequestType.Simple:
- {
- var sso = _ssoPacker.BuildProtocol13(packet);
- frame = _servicePacker.BuildProtocol13(packet, sso, options);
- break;
}
- default:
+
+ await _context.SocketContext.Send(frame);
+ }
+ catch (Exception e)
+ {
+ if (_pendingTasks.TryRemove(packet.Sequence, out var tcs))
{
- throw new InvalidOperationException($"Unknown RequestType: {options.RequestType}");
+ tcs.SetException(e);
}
}
-
- await context.SocketContext.Send(frame);
});
-
- return new ValueTask(tcs, 0);
+
+ return new ValueTask(tcs, 0);
}
public void DispatchPacket(ReadOnlySpan buffer)
{
var service = _servicePacker.Parse(buffer);
var sso = _ssoPacker.Parse(service);
-
+
if (_pendingTasks.TryRemove(sso.Sequence, out var tcs))
{
if (sso is { RetCode: not 0, Extra: var extra })
@@ -78,7 +118,7 @@ public void DispatchPacket(ReadOnlySpan buffer)
}
else
{
- _ = context.EventContext.HandleServerPacket(sso);
+ Task.Run(() => _context.EventContext.HandleServerPacket(sso));
}
}
-}
\ No newline at end of file
+}
diff --git a/Lagrange.Core/Internal/Context/ServiceContext.cs b/Lagrange.Core/Internal/Context/ServiceContext.cs
index 3a772ac5..465b2352 100644
--- a/Lagrange.Core/Internal/Context/ServiceContext.cs
+++ b/Lagrange.Core/Internal/Context/ServiceContext.cs
@@ -1,73 +1,82 @@
using System.Collections.Frozen;
+using System.Diagnostics.CodeAnalysis;
using System.Reflection;
+using Lagrange.Core.Common;
+using Lagrange.Core.Common.Entity;
+using Lagrange.Core.Exceptions;
using Lagrange.Core.Internal.Events;
-using Lagrange.Core.Internal.Packets.Struct;
using Lagrange.Core.Internal.Services;
+using Lagrange.Core.Utility.Extension;
namespace Lagrange.Core.Internal.Context;
internal class ServiceContext
{
private const string Tag = nameof(ServiceContext);
-
+
private int _sequence = Random.Shared.Next(5000000, 9900000);
-
+
+ private readonly HashSet _disabledLog = [];
private readonly FrozenDictionary _services;
private readonly FrozenDictionary _servicesEventType;
private readonly BotContext _context;
-
+
+ [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
+ [UnconditionalSuppressMessage("Trimming", "IL2062", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
+ [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "All the types are preserved in the csproj by using the TrimmerRootAssembly attribute")]
public ServiceContext(BotContext context)
{
_context = context;
+
var services = new Dictionary();
var servicesEventType = new Dictionary();
- foreach (var type in typeof(IService).Assembly.GetTypes())
+ foreach (var type in typeof(IService).Assembly.GetTypes())
{
- if (type.GetCustomAttribute() is { } attr && type.GetInterfaces().Contains(typeof(IService)) && !type.IsAbstract)
+ foreach (var attribute in type.GetCustomAttributes())
{
- var service = (IService?)Activator.CreateInstance(type) ?? throw new InvalidOperationException("Failed to create service instance");
- services[attr.Command] = service;
-
- foreach (var attribute in type.GetCustomAttributes())
+ if ((~attribute.Protocol & context.Config.Protocol) != Protocols.None) continue; // skip if not supported
+
+ if (type.GetCustomAttribute() is { } attr && type.HasImplemented())
{
- if (!servicesEventType.TryGetValue(attribute.EventType, out var list))
- {
- servicesEventType[attribute.EventType] = (attr, service);
- }
- else
+ if (!services.TryGetValue(attr.Command, out var service))
{
- throw new InvalidOperationException($"Multiple services for event type: {attribute.EventType}");
+ service = (IService?)Activator.CreateInstance(type) ?? throw new InvalidOperationException("Failed to create service instance");
+ services[attr.Command] = service;
+ if (attr.DisableLog) _disabledLog.Add(attr.Command);
}
+
+ servicesEventType[attribute.EventType] = !servicesEventType.ContainsKey(attribute.EventType)
+ ? (attr, service)
+ : throw new InvalidOperationException($"Multiple services for event type: {attribute.EventType}");
}
}
}
-
+
_services = services.ToFrozenDictionary();
_servicesEventType = servicesEventType.ToFrozenDictionary();
}
- public ValueTask Resolve(SsoPacket ssoPacket)
+ public ValueTask Resolve(BotSsoPacket ssoPacket)
{
- if (!_services.TryGetValue(ssoPacket.Command, out var service))
- {
- _context.LogWarning(Tag, $"Service not found for command: {ssoPacket.Command}");
- return new ValueTask(default(ProtocolEvent));
- }
-
+ if (!_services.TryGetValue(ssoPacket.Command, out var service)) throw new ServiceNotFoundException(ssoPacket.Command);
+
+ if (!_disabledLog.Contains(ssoPacket.Command)) _context.LogTrace(Tag, "Incoming SSOFrame: {0}", ssoPacket.Command);
return service.Parse(ssoPacket.Data, _context);
}
- public async ValueTask<(SsoPacket, ServiceAttribute)> Resolve(ProtocolEvent @event)
+ public async ValueTask<(BotSsoPacket, ServiceAttribute)> Resolve(ProtocolEvent @event)
{
if (!_servicesEventType.TryGetValue(@event.GetType(), out var handler)) return default;
-
+
var (attr, service) = handler;
- return (new SsoPacket(attr.Command, await service.Build(@event, _context), GetNewSequence()), attr);
+ if (!handler.Attribute.DisableLog) _context.LogTrace(Tag, "Outgoing SSOFrame: {0}", handler.Attribute.Command);
+
+ return (new BotSsoPacket(attr.Command, await service.Build(@event, _context), GetNewSequence()), attr);
}
- private int GetNewSequence()
+ public int GetNewSequence()
{
Interlocked.CompareExchange(ref _sequence, 5000000, 9900000);
return Interlocked.Increment(ref _sequence);
diff --git a/Lagrange.Core/Internal/Context/SocketContext.cs b/Lagrange.Core/Internal/Context/SocketContext.cs
index 194ba36d..c0062e32 100644
--- a/Lagrange.Core/Internal/Context/SocketContext.cs
+++ b/Lagrange.Core/Internal/Context/SocketContext.cs
@@ -50,8 +50,8 @@ public async Task Connect()
if (_config.GetOptimumServer) await SortServers(servers);
bool connected = await _client.Connect(servers[0]);
- if (connected) _context.LogInfo(Tag, $"Connected to the server {servers[0]}");
- else _context.LogError(Tag, $"Failed to connect to the server {servers[0]}");
+ if (connected) _context.LogInfo(Tag, "Connected to the server {0}", servers[0]);
+ else _context.LogError(Tag, "Failed to connect to the server {0}", null,servers[0]);
return connected;
}
@@ -60,18 +60,18 @@ public async Task Connect()
public ValueTask Send(ReadOnlyMemory packet) => _client.Send(packet);
- private async Task SortServers(Uri[] servers)
+ private async Task SortServers(string[] servers)
{
using var ping = new Ping();
- var sorted = new List<(long, Uri)>(servers.Length);
+ var sorted = new List<(long, string)>(servers.Length);
foreach (var server in servers)
{
- var latency = await ping.SendPingAsync(server.Host, 1000);
+ var latency = await ping.SendPingAsync(server, 1000);
if (latency.Status == IPStatus.Success)
{
sorted.Add((latency.RoundtripTime, server));
- _context.LogDebug(Tag, $"Server: {server} Latency: {latency.RoundtripTime}ms");
+ _context.LogDebug(Tag, "Server: {0} Latency: {1}ms", server, latency.RoundtripTime);
}
}
@@ -79,13 +79,13 @@ private async Task SortServers(Uri[] servers)
for (int i = 0; i < sorted.Count; i++) servers[i] = sorted[i].Item2;
}
- private static async Task ResolveDns(bool useIPv6Network = false)
+ private async Task ResolveDns()
{
- string host = useIPv6Network ? "msfwifiv6.3g.qq.com" : "msfwifi.3g.qq.com";
- var entry = await Dns.GetHostEntryAsync(host, useIPv6Network ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork);
- var result = new Uri[entry.AddressList.Length];
-
- for (int i = 0; i < entry.AddressList.Length; i++) result[i] = new Uri($"http://{entry.AddressList[i]}:8080");
+ string host = _config.UseIPv6Network ? "msfwifiv6.3g.qq.com" : "msfwifi.3g.qq.com";
+ var entry = await Dns.GetHostEntryAsync(host, _config.UseIPv6Network ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork);
+ var result = new string[entry.AddressList.Length];
+
+ for (int i = 0; i < entry.AddressList.Length; i++) result[i] = entry.AddressList[i].ToString();
return result;
}
diff --git a/Lagrange.Core/Internal/Events/EventSubscribeAttribute.cs b/Lagrange.Core/Internal/Events/EventSubscribeAttribute.cs
index 0623ecbc..6d6426b3 100644
--- a/Lagrange.Core/Internal/Events/EventSubscribeAttribute.cs
+++ b/Lagrange.Core/Internal/Events/EventSubscribeAttribute.cs
@@ -1,10 +1,14 @@
+using Lagrange.Core.Common;
+
namespace Lagrange.Core.Internal.Events;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
-internal class EventSubscribeAttribute() : EventSubscribeAttribute(typeof(T)) where T : ProtocolEvent;
+internal class EventSubscribeAttribute(Protocols protocol) : EventSubscribeAttribute(typeof(T), protocol) where T : ProtocolEvent;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
-internal class EventSubscribeAttribute(Type type) : Attribute
+internal class EventSubscribeAttribute(Type type, Protocols protocol) : Attribute
{
public Type EventType { get; } = type;
+
+ public Protocols Protocol { get; set; } = protocol;
}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/CloseCodeEvent.cs b/Lagrange.Core/Internal/Events/Login/CloseCodeEvent.cs
new file mode 100644
index 00000000..d63503db
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/CloseCodeEvent.cs
@@ -0,0 +1,15 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class CloseCodeEventReq(byte[] k, bool isApproved) : ProtocolEvent
+{
+ public byte[] K { get; } = k;
+
+ public bool IsApproved { get; } = isApproved;
+}
+
+internal class CloseCodeEventResp(byte state, string message) : ProtocolEvent
+{
+ public byte State { get; } = state;
+
+ public string Message { get; } = message;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/ExchangeEmpEvent.cs b/Lagrange.Core/Internal/Events/Login/ExchangeEmpEvent.cs
new file mode 100644
index 00000000..fc40029f
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/ExchangeEmpEvent.cs
@@ -0,0 +1,18 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class ExchangeEmpEventReq(ExchangeEmpEventReq.Command cmd) : ProtocolEvent
+{
+ public enum Command
+ {
+ RefreshByA1 = 0xF
+ }
+
+ public Command Cmd { get; } = cmd;
+}
+
+internal class ExchangeEmpEventResp(byte retCode, Dictionary tlvs) : ProtocolEvent
+{
+ public byte RetCode { get; } = retCode;
+
+ public Dictionary Tlvs { get; set; } = tlvs;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/KeyExchangeEvent.cs b/Lagrange.Core/Internal/Events/Login/KeyExchangeEvent.cs
new file mode 100644
index 00000000..f7d2a415
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/KeyExchangeEvent.cs
@@ -0,0 +1,10 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class KeyExchangeEventReq : ProtocolEvent;
+
+internal class KeyExchangeEventResp(byte[] sessionTicket, byte[] sessionKey) : ProtocolEvent
+{
+ public byte[] SessionTicket { get; } = sessionTicket;
+
+ public byte[] SessionKey { get; } = sessionKey;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/LoginEvent.cs b/Lagrange.Core/Internal/Events/Login/LoginEvent.cs
new file mode 100644
index 00000000..7dbac354
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/LoginEvent.cs
@@ -0,0 +1,65 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class LoginEventReq(LoginEventReq.Command cmd, string password = "") : ProtocolEvent
+{
+ public enum Command
+ {
+ Tgtgt = 0x09,
+ Captcha = 0x02,
+ FetchSMSCode = 0x08,
+ SubmitSMSCode = 0x07
+ }
+
+ public Command Cmd { get; } = cmd;
+
+ public string Password { get; } = password;
+
+ public string Ticket { get; init; } = string.Empty;
+
+ public string Code { get; init; } = string.Empty;
+}
+
+internal class LoginEventResp : ProtocolEvent
+{
+ public byte RetCode { get; }
+
+ public States State => (States)RetCode;
+
+ public (string, string)? Error { get; }
+
+ public Dictionary Tlvs { get; set; }
+
+ public LoginEventResp(byte retCode, (string, string) error)
+ {
+ RetCode = retCode;
+ Error = error;
+ Tlvs = new Dictionary();
+ }
+
+ public LoginEventResp(byte retCode, Dictionary tlvs)
+ {
+ RetCode = retCode;
+ Tlvs = tlvs;
+ }
+
+ public enum States
+ {
+ Success = 0,
+ CaptchaVerify = 2,
+ SmsRequired = 160,
+ DeviceLock = 204,
+ DeviceLockViaSmsNewArea = 239,
+
+ PreventByIncorrectPassword = 1,
+ PreventByReceiveIssue = 3,
+ PreventByTokenExpired = 15,
+ PreventByAccountBanned = 40,
+ PreventByOperationTimeout = 155,
+ PreventBySmsSentFailed = 162,
+ PreventByIncorrectSmsCode = 163,
+ PreventByLoginDenied = 167,
+ PreventByOutdatedVersion = 235,
+ PreventByHighRiskOfEnvironment = 237,
+ Unknown = 240,
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/NTLoginEvent.cs b/Lagrange.Core/Internal/Events/Login/NTLoginEvent.cs
new file mode 100644
index 00000000..33800428
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/NTLoginEvent.cs
@@ -0,0 +1,76 @@
+using Lagrange.Core.Internal.Packets.Login;
+
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal interface INTLoginEventResp
+{
+ public NTLoginRetCode State { get; }
+
+ public (string, string) Tips { get; }
+}
+
+internal class EasyLoginEventReq : ProtocolEvent;
+
+internal class UnusualEasyLoginEventReq : ProtocolEvent;
+
+internal class NewDeviceLoginEventReq(byte[] sig) : ProtocolEvent
+{
+ public byte[] Sig { get; } = sig;
+};
+
+internal class RefreshTicketEventReq : ProtocolEvent;
+
+internal class RefreshA2EventReq : ProtocolEvent;
+
+internal class PasswordLoginEventReq(string password, (string, string, string)? captcha) : ProtocolEvent
+{
+ public string Password { get; } = password;
+
+ public (string, string, string)? Captcha { get; } = captcha;
+}
+
+internal class PasswordLoginEventResp(NTLoginRetCode state, (string, string)? tips, string? jumpingUrl) : ProtocolEvent, INTLoginEventResp
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+
+ public string JumpingUrl { get; } = jumpingUrl ?? string.Empty;
+}
+
+internal class EasyLoginEventResp(NTLoginRetCode state, (string, string)? tips, byte[]? unusualSigs) : ProtocolEvent, INTLoginEventResp
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+
+ public byte[]? UnusualSigs { get; } = unusualSigs;
+}
+
+internal class UnusualEasyLoginEventResp(NTLoginRetCode state, (string, string)? tips) : ProtocolEvent
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+}
+
+internal class NewDeviceLoginEventResp(NTLoginRetCode state, (string, string)? tips) : ProtocolEvent
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+}
+
+internal class RefreshTicketEventResp(NTLoginRetCode state, (string, string)? tips) : ProtocolEvent
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+}
+
+internal class RefreshA2EventResp(NTLoginRetCode state, (string, string)? tips) : ProtocolEvent
+{
+ public NTLoginRetCode State { get; } = state;
+
+ public (string, string) Tips { get; } = tips ?? (string.Empty, string.Empty);
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/TransEmpEvent.cs b/Lagrange.Core/Internal/Events/Login/TransEmpEvent.cs
new file mode 100644
index 00000000..464d83ec
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/TransEmpEvent.cs
@@ -0,0 +1,36 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class TransEmp31EventReq(byte[]? unusualSig) : ProtocolEvent
+{
+ public byte[]? UnusualSig { get; } = unusualSig;
+}
+
+internal class TransEmp31EventResp(string url, byte[] image, byte[] qrSig) : ProtocolEvent
+{
+ public string Url { get; } = url;
+
+ public byte[] Image { get; } = image;
+
+ public byte[] QrSig { get; } = qrSig;
+}
+
+internal class TransEmp12EventReq : ProtocolEvent;
+
+internal class TransEmp12EventResp(byte state, long uin, (byte[], byte[], byte[])? data) : ProtocolEvent
+{
+ public TransEmpState State { get; } = (TransEmpState)state;
+
+ public long Uin { get; } = uin;
+
+ public (byte[] TgtgtKey, byte[] NoPicSig, byte[] TempPassword)? Data { get; } = data;
+
+ internal enum TransEmpState : byte
+ {
+ Confirmed = 0,
+ CodeExpired = 17,
+ WaitingForScan = 48,
+ WaitingForConfirm = 53,
+ Canceled = 54,
+ Invalid = 144
+ }
+}
diff --git a/Lagrange.Core/Internal/Events/Login/UinResolveEvent.cs b/Lagrange.Core/Internal/Events/Login/UinResolveEvent.cs
new file mode 100644
index 00000000..db15428f
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/UinResolveEvent.cs
@@ -0,0 +1,30 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class UinResolveEventReq(string qid) : ProtocolEvent
+{
+ public string Qid { get; } = qid;
+}
+
+internal class UinResolveEventResp : ProtocolEvent
+{
+ public byte State { get; }
+
+ public (string, string)? Error { get; }
+
+ public (long, string)? Info { get; }
+
+ public byte[] Tlv104 { get; } = [];
+
+ public UinResolveEventResp(byte retCode, (string, string)? error)
+ {
+ State = retCode;
+ Error = error;
+ }
+
+ public UinResolveEventResp(byte retCode, (long, string) info, byte[] tlv104)
+ {
+ State = retCode;
+ Info = info;
+ Tlv104 = tlv104;
+ }
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Login/VerifyCodeEvent.cs b/Lagrange.Core/Internal/Events/Login/VerifyCodeEvent.cs
new file mode 100644
index 00000000..0cf3aa0b
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Login/VerifyCodeEvent.cs
@@ -0,0 +1,19 @@
+namespace Lagrange.Core.Internal.Events.Login;
+
+internal class VerifyCodeEventReq(byte[] k) : ProtocolEvent
+{
+ public byte[] K { get; } = k;
+}
+
+internal class VerifyCodeEventResp(byte state, string message, string platform, string location, string? device) : ProtocolEvent
+{
+ public byte State { get; } = state;
+
+ public string Message { get; } = message;
+
+ public string Platform { get; } = platform;
+
+ public string Location { get; } = location;
+
+ public string? Device { get; } = device;
+}
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Message/C2CRecallMsgEvent.cs b/Lagrange.Core/Internal/Events/Message/C2CRecallMsgEvent.cs
new file mode 100644
index 00000000..b18eca61
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Message/C2CRecallMsgEvent.cs
@@ -0,0 +1,16 @@
+namespace Lagrange.Core.Internal.Events.Message;
+
+internal class C2CRecallMsgEventReq(string targetUid, ulong sequence, ulong clientSequence, uint random, uint timestamp) : ProtocolEvent
+{
+ public string TargetUid { get; } = targetUid;
+
+ public ulong Sequence { get; } = sequence;
+
+ public ulong ClientSequence { get; } = clientSequence;
+
+ public uint Random { get; } = random;
+
+ public uint Timestamp { get; } = timestamp;
+}
+
+internal class C2CRecallMsgEventResp : ProtocolEvent;
\ No newline at end of file
diff --git a/Lagrange.Core/Internal/Events/Message/GetC2CMessageEvent.cs b/Lagrange.Core/Internal/Events/Message/GetC2CMessageEvent.cs
new file mode 100644
index 00000000..59960e67
--- /dev/null
+++ b/Lagrange.Core/Internal/Events/Message/GetC2CMessageEvent.cs
@@ -0,0 +1,17 @@
+using Lagrange.Core.Internal.Packets.Message;
+
+namespace Lagrange.Core.Internal.Events.Message;
+
+internal class GetC2CMessageEventReq(string peerUid, ulong startSequence, ulong endSequence) : ProtocolEvent
+{
+ public string PeerUid { get; } = peerUid;
+
+ public ulong StartSequence { get; } = startSequence;
+
+ public ulong EndSequence { get; } = endSequence;
+}
+
+internal class GetC2CMessageEventResp(List