First Version of Tuyoo SDK Package

This commit is contained in:
wsycarlos 2025-12-06 10:50:57 +08:00
commit 1feb0fbd3d
284 changed files with 17607 additions and 0 deletions

106
.gitignore vendored Normal file
View File

@ -0,0 +1,106 @@
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore
#
.utmp/
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/
*.log
# By default unity supports Blender asset imports, *.blend1 blender files do not need to be commited to version control.
*.blend1
*.blend1.meta
# MemoryCaptures can get excessive in size.
# They also could contain extremely sensitive data
/[Mm]emoryCaptures/
# Recordings can get excessive in size
/[Rr]ecordings/
# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*
# Autogenerated Jetbrains Rider plugin
/[Aa]ssets/Plugins/Editor/JetBrains*
# Jetbrains Rider personal-layer settings
*.DotSettings.user
# Visual Studio cache directory
.vs/
# Gradle cache directory
.gradle/
# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db
# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta
# Unity3D generated file on crash reports
sysinfo.txt
# Mono auto generated files
mono_crash.*
# Builds
*.apk
*.aab
*.unitypackage
*.unitypackage.meta
# Crashlytics generated file
crashlytics-build.properties
# TestRunner generated files
InitTestScene*.unity*
# Addressables default ignores, before user customizations
/ServerData
/[Aa]ssets/StreamingAssets/aa*
/[Aa]ssets/AddressableAssetsData/link.xml*
/[Aa]ssets/Addressables_Temp*
# By default, Addressables content builds will generate addressables_content_state.bin
# files in platform-specific subfolders, for example:
# /Assets/AddressableAssetsData/OSX/addressables_content_state.bin
/[Aa]ssets/AddressableAssetsData/*/*.bin*
# Visual Scripting auto-generated files
/[Aa]ssets/Unity.VisualScripting.Generated/VisualScripting.Flow/UnitOptions.db
/[Aa]ssets/Unity.VisualScripting.Generated/VisualScripting.Flow/UnitOptions.db.meta
/[Aa]ssets/Unity.VisualScripting.Generated/VisualScripting.Core/Property Providers
/[Aa]ssets/Unity.VisualScripting.Generated/VisualScripting.Core/Property Providers.meta
# Auto-generated scenes by play mode tests
/[Aa]ssets/[Ii]nit[Tt]est[Ss]cene*.unity*
.vsconfig
Logs/
[Aa]ssets/
[Pp]ublish/
.vscode/settings.json
*.dat

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3c8e031ae3a7e0e4d8856244a1c6a5e4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1d566609b714d40508c148b67774735c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- This module was also published with a richer model, Gradle metadata, -->
<!-- which should be used instead. Do not delete the following line which -->
<!-- is to indicate to Gradle or any Gradle module metadata file consumer -->
<!-- that they should prefer consuming it instead. -->
<!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component</groupId>
<artifactId>growsdk-gasdk</artifactId>
<version>2.4.24_0711-RELEASE</version>
<packaging>aar</packaging>
</project>

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-common</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>1.15.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.12.13</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.3.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.2.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>2.1.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxandroid</artifactId>
<version>1.2.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>1.1.9</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>growsdk-gasdk</artifactId>
<version>2.4.24_0711-RELEASE</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-oversea</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-common</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login.third</groupId>
<artifactId>appsflyer</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.appsflyer</groupId>
<artifactId>af-android-sdk</artifactId>
<version>6.12.5</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.android.installreferrer</groupId>
<artifactId>installreferrer</artifactId>
<version>2.2</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.miui.referrer</groupId>
<artifactId>homereferrer</artifactId>
<version>1.0.0.6</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>androidx.core</groupId>
<artifactId>core</artifactId>
<version>1.3.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login.third</groupId>
<artifactId>hwFacebook</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-oversea</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.facebook.android</groupId>
<artifactId>facebook-android-sdk</artifactId>
<version>16.2.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login.third</groupId>
<artifactId>hwGoogle</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-oversea</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>androidx.credentials</groupId>
<artifactId>credentials</artifactId>
<version>1.5.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>androidx.credentials</groupId>
<artifactId>credentials-play-services-auth</artifactId>
<version>1.5.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.google.android.libraries.identity.googleid</groupId>
<artifactId>googleid</artifactId>
<version>1.1.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.google.android.gms</groupId>
<artifactId>play-services-auth</artifactId>
<version>21.4.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login.third</groupId>
<artifactId>hwGooglePlay</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-oversea</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-common</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.android.billingclient</groupId>
<artifactId>billing</artifactId>
<version>7.1.1</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component.login.third</groupId>
<artifactId>hwGuest</artifactId>
<version>0.2.0</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-oversea</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer</artifactId>
<version>0.6.1</version>
<packaging>aar</packaging>
<dependencies/>
</project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer_ga</artifactId>
<version>0.6.1</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer</artifactId>
<version>0.6.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>growsdk-gasdk</artifactId>
<version>2.4.23_0618-RELEASE</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer_login</artifactId>
<version>0.6.1</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer</artifactId>
<version>0.6.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.tuyoo.component.login</groupId>
<artifactId>framework-common</artifactId>
<version>0.2.0</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer_unity</artifactId>
<version>0.4.7</version>
<packaging>aar</packaging>
<dependencies>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer</artifactId>
<version>0.6.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.tuyoo.component</groupId>
<artifactId>sdk_inter_layer_ga</artifactId>
<version>0.6.1</version>
<scope>implementation</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<scope>implementation</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,69 @@
{
"formatVersion": "1.1",
"component": {
"group": "com.tuyoo.sdk_plugin",
"module": "com.tuyoo.sdk_plugin.gradle.plugin",
"version": "1.7.5.2",
"attributes": {
"org.gradle.status": "release"
}
},
"createdBy": {
"gradle": {
"version": "8.5"
}
},
"variants": [
{
"name": "apiElements",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.jvm.version": 8,
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-api"
},
"files": [
{
"name": "com.tuyoo.sdk_plugin.gradle.plugin-1.7.5.2.jar",
"url": "com.tuyoo.sdk_plugin.gradle.plugin-1.7.5.2.jar",
"size": 359887,
"sha512": "b116df2f58b39cc7716238591bd0f7cd1cdfe2687b295917ae3332fbc8e5803b4252b7208bcbd65ec18fde2a1eff0f030f7265461c2c71cd7458ea82e081ca3e",
"sha256": "915293c3374fde81aecc6d63a88c986e0cc72e2263e38142f872dd69920f4504",
"sha1": "699288cce58dc3b79981eab728163af63ae73448",
"md5": "4683dece9f7fcbe1fd4ac02c984708d5"
}
]
},
{
"name": "runtimeElements",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.jvm.version": 8,
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-runtime"
},
"dependencies": [
{
"group": "com.google.code.gson",
"module": "gson",
"version": {
"requires": "2.8.9"
}
}
],
"files": [
{
"name": "com.tuyoo.sdk_plugin.gradle.plugin-1.7.5.2.jar",
"url": "com.tuyoo.sdk_plugin.gradle.plugin-1.7.5.2.jar",
"size": 359887,
"sha512": "b116df2f58b39cc7716238591bd0f7cd1cdfe2687b295917ae3332fbc8e5803b4252b7208bcbd65ec18fde2a1eff0f030f7265461c2c71cd7458ea82e081ca3e",
"sha256": "915293c3374fde81aecc6d63a88c986e0cc72e2263e38142f872dd69920f4504",
"sha1": "699288cce58dc3b79981eab728163af63ae73448",
"md5": "4683dece9f7fcbe1fd4ac02c984708d5"
}
]
}
]
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- This module was also published with a richer model, Gradle metadata, -->
<!-- which should be used instead. Do not delete the following line which -->
<!-- is to indicate to Gradle or any Gradle module metadata file consumer -->
<!-- that they should prefer consuming it instead. -->
<!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuyoo.sdk_plugin</groupId>
<artifactId>com.tuyoo.sdk_plugin.gradle.plugin</artifactId>
<version>1.7.5.2</version>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,77 @@
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
class BuildGradleProcessor
{
private string launcherBuildGradle;
private string unityLibraryBuildGradle;
private string rootBuildGradle;
private string rootProjectPath;
private string settings;
public BuildGradleProcessor(string rootProjectPath)
{
this.rootProjectPath = rootProjectPath;
this.launcherBuildGradle = Path.Combine(rootProjectPath, "launcher/build.gradle");
this.unityLibraryBuildGradle = Path.Combine(rootProjectPath, "unityLibrary/build.gradle");
this.rootBuildGradle = Path.Combine(rootProjectPath, "build.gradle");
this.settings = Path.Combine(rootProjectPath, "settings.gradle");
Debug.Log("BuildGradleProcessor, rootProjectPath:" + rootProjectPath + "\n,launcherBuildGradle:"
+ launcherBuildGradle + "\n,unityLibraryBuildGradle:" + unityLibraryBuildGradle + "\n,settings:" + settings);
}
public static string GetAGPVersion(string rootBuildGradle)
{
if (!File.Exists(rootBuildGradle))
{
Debug.LogError("build.gradle 文件不存在: " + rootBuildGradle);
return null;
}
string buildGradleContent = File.ReadAllText(rootBuildGradle);
string agpVersion = null;
// 尝试匹配 id 'com.android.application' version 'x.y.z'
Match idVersionMatch = Regex.Match(buildGradleContent, @"id\s+['""]com\.android\.application['""]\s+version\s+['""](\d+\.\d+\.\d+)['""]");
if (idVersionMatch.Success)
{
agpVersion = idVersionMatch.Groups[1].Value;
Debug.Log("AGP Version from id version: " + agpVersion);
}
else
{
// 如果 id version 未匹配,尝试匹配 classpath 'com.android.tools.build:gradle:x.y.z'
Match classpathMatch = Regex.Match(buildGradleContent, @"classpath\s+['""]com\.android\.tools\.build:gradle:(\d+\.\d+\.\d+)['""]");
if (classpathMatch.Success)
{
agpVersion = classpathMatch.Groups[1].Value;
Debug.Log("AGP Version from classpath: " + agpVersion);
}
}
if (agpVersion == null)
{
Debug.LogError("AGP Version not found in build.gradle");
}
return agpVersion;
}
public void process()
{
string agpVersion = GetAGPVersion(rootBuildGradle);
Debug.Log("process, agpVersion:" + agpVersion);
if (agpVersion.StartsWith("7.") || agpVersion.StartsWith("8."))
{
(new BuildGradleProcessor7x(rootProjectPath)).process();
}
else
{
(new BuildGradleProcessor4x(rootProjectPath)).process();
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: feb747b7ceeb74a1393d78b94baccd48
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,155 @@
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
class BuildGradleProcessor4x
{
private string launcherBuildGradle;
private string unityLibraryBuildGradle;
private string rootBuildGradle;
public BuildGradleProcessor4x(string rootProjectPath)
{
this.launcherBuildGradle = Path.Combine(rootProjectPath, "launcher/build.gradle");
this.unityLibraryBuildGradle = Path.Combine(rootProjectPath, "unityLibrary/build.gradle");
this.rootBuildGradle = Path.Combine(rootProjectPath, "build.gradle");
Debug.Log("BuildGradleProcessor, rootProjectPath:" + rootProjectPath + "\n,launcherBuildGradle:"
+ launcherBuildGradle + "\n,unityLibraryBuildGradle:" + unityLibraryBuildGradle);
}
public void process()
{
Debug.Log("BuildGradleProcessor4x, process start....");
//1. 添加maven仓库
processMaven();
//3. 添加插件 apply + classpath + json文件 + 打包设置
processPlugin();
Debug.Log("BuildGradleProcessor4x, process end....");
}
private void processMaven()
{
string buildGradleContent = File.ReadAllText(rootBuildGradle);
List<string> pluginMaven = new List<string>();
buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component/");
pluginMaven.Add("https://jcenter.bintray.com/");
// pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component-test/");
pluginMaven.Add("https://developer.huawei.com/repo/");
buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
// 保存修改后的内容回文件
File.WriteAllText(rootBuildGradle, buildGradleContent);
}
private string insertMaven(List<string> maven, string buildGradleContent)
{
if (maven == null)
{
return buildGradleContent;
}
// 添加自定义的 Maven 仓库
foreach (string url in maven)
{
if (!buildGradleContent.Contains(url))
{
string mavenRepository = buildMavenString(url);
Debug.Log("mavenRepository: " + mavenRepository);
// 在 repositories 块中添加自定义仓库
buildGradleContent = buildGradleContent.Replace("repositories {", $"repositories {{\n{mavenRepository}");
}
}
return buildGradleContent;
}
string buildMavenString(string url)
{
string mavenString = "";
mavenString += $@"
maven {{
allowInsecureProtocol = true
url '{url}'
}}";
return mavenString;
}
private void processPlugin()
{
//root build gradle 处理
string rootBuildGradleContent = File.ReadAllText(rootBuildGradle);
if (!rootBuildGradleContent.Contains("com.tuyoo.sdk_plugin"))
{
rootBuildGradleContent = rootBuildGradleContent.Replace("dependencies {", @"dependencies {
classpath 'com.tuyoo.sdk_plugin:com.tuyoo.sdk_plugin.gradle.plugin:1.7.5.2'");
File.WriteAllText(rootBuildGradle, rootBuildGradleContent);
}
//launcher build gradle 处理
string launcherBuildGradleContent = File.ReadAllText(launcherBuildGradle);
// 正则表达式:匹配 #START1 到 #END1 之间的所有内容(包括换行)
string pattern = @"//START1[\s\S]*?//END1";
// string replaceMent = @"import groovy.json.JsonSlurper
// // File tyConfigFileDir = project.rootProject.file('config')
// // File tyConfigFile = new File(tyConfigFileDir,'build.json')
// // // 使用 JsonSlurper 解析 JSON
// // def jsonSlurper = new JsonSlurper()
// // def jsonObject = jsonSlurper.parseText(tyConfigFile.text)
// buildscript {
// repositories {
// google {
// content {
// includeGroupByRegex(""com\\.android.*"")
// includeGroupByRegex(""com\\.google.*"")
// includeGroupByRegex(""androidx.*"")
// }
// }
// mavenCentral()
// gradlePluginPortal()
// // 配置HMS Core SDK的Maven仓地址。
// maven { url 'https://developer.huawei.com/repo/' }
// }
// dependencies {
// // 增加Android Gradle插件版本号配置{version}为实际的Gradle插件版本号例如7.1.1。
// // 增加AGC插件配置请您参见AGC插件依赖关系选择合适的AGC插件版本。
// classpath 'com.huawei.agconnect:agcp:1.9.0.300'
// // 增加Android Gradle插件版本号配置{version}为实际的Gradle插件版本号例如7.1.1。
// classpath 'com.android.tools.build:gradle:7.4.2'
// }
// }
// apply plugin: 'com.tuyoo.sdk_plugin'";
string replaceMent = @"
apply plugin: 'com.tuyoo.sdk_plugin'";
string insertContent = $"//START1\n{replaceMent}\n//END1";
// 执行替换
string tmp = Regex.Replace(launcherBuildGradleContent, pattern, insertContent);
if (tmp.Equals(launcherBuildGradleContent))
{
if (!tmp.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
{
launcherBuildGradleContent = launcherBuildGradleContent + "\n" + insertContent;
}
}
else
{
launcherBuildGradleContent = tmp;
}
File.WriteAllText(launcherBuildGradle, launcherBuildGradleContent);
//unity build gradle 处理
string unityBuildGradleContent = File.ReadAllText(unityLibraryBuildGradle);
if (!unityBuildGradleContent.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
{
unityBuildGradleContent = unityBuildGradleContent + "\n" + "apply plugin: 'com.tuyoo.sdk_plugin'";
File.WriteAllText(unityLibraryBuildGradle, unityBuildGradleContent);
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9e0134cd3b6c846b1b6f23f3a516680f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,133 @@
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
class BuildGradleProcessor7x
{
private string launcherBuildGradle;
private string unityLibraryBuildGradle;
private string rootBuildGradle;
private string settings;
public BuildGradleProcessor7x(string rootProjectPath)
{
this.launcherBuildGradle = Path.Combine(rootProjectPath, "launcher/build.gradle");
this.unityLibraryBuildGradle = Path.Combine(rootProjectPath, "unityLibrary/build.gradle");
this.rootBuildGradle = Path.Combine(rootProjectPath, "build.gradle");
this.settings = Path.Combine(rootProjectPath, "settings.gradle");
Debug.Log("BuildGradleProcessor, rootProjectPath:" + rootProjectPath + "\n,launcherBuildGradle:"
+ launcherBuildGradle + "\n,unityLibraryBuildGradle:" + unityLibraryBuildGradle + "\n,settings:" + settings);
}
public void process()
{
//1. 添加maven仓库
processMaven();
//3. 添加插件 apply + classpath + json文件 + 打包设置
processPlugin();
}
private void processMaven()
{
string buildGradleContent = File.ReadAllText(settings);
List<string> pluginMaven = new List<string>();
buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
//pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component/");
pluginMaven.Add("file:///" + FileUtil.GetPhysicalPath("Packages/com.bywaystudios.tuyoosdk/Editor/Android") + "/.m2/repository");
pluginMaven.Add("https://jcenter.bintray.com/");
// pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component-test/");
pluginMaven.Add("https://developer.huawei.com/repo/");
buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
// 保存修改后的内容回文件
File.WriteAllText(settings, buildGradleContent);
}
private string insertMaven(List<string> maven, string buildGradleContent)
{
if (maven == null)
{
return buildGradleContent;
}
// 添加自定义的 Maven 仓库
foreach (string url in maven)
{
if (!buildGradleContent.Contains(url))
{
string mavenRepository = buildMavenString(url);
Debug.Log("mavenRepository: " + mavenRepository);
// 在 repositories 块中添加自定义仓库
buildGradleContent = buildGradleContent.Replace("repositories {", $"repositories {{\n{mavenRepository}");
}
}
return buildGradleContent;
}
string buildMavenString(string url)
{
string mavenString = "";
mavenString += $@"
maven {{
allowInsecureProtocol = true
url '{url}'
}}";
return mavenString;
}
private void processPlugin()
{
string projectPluginVersion = "1.7.5.2";
string firebasePluginVersion = "4.3.15"; // AGP 7.x 适合用4.3.15版本, AGP 8.x 适合用4.4.x版本
string crashPluginVersion = "2.9.5"; //支持AGP8以下
// string crashPluginVersion = "3.0.2"; //支持AGP8
//root build gradle 处理
string rootBuildGradleContent = File.ReadAllText(rootBuildGradle);
if (!rootBuildGradleContent.Contains("com.tuyoo.sdk_plugin"))
{
rootBuildGradleContent = rootBuildGradleContent.Replace("plugins {", @"plugins {
id 'com.tuyoo.sdk_plugin' version '" + projectPluginVersion + @"' apply false
id 'com.google.gms.google-services' version '" + firebasePluginVersion + @"' apply false;
id 'com.google.firebase.crashlytics' version '" + crashPluginVersion + @"' apply false");
File.WriteAllText(rootBuildGradle, rootBuildGradleContent);
}
//launcher build gradle 处理
string launcherBuildGradleContent = File.ReadAllText(launcherBuildGradle);
// 正则表达式:匹配 #START1 到 #END1 之间的所有内容(包括换行)
string pattern = @"//START1[\s\S]*?//END1";
string replaceMent = @"
apply plugin: 'com.tuyoo.sdk_plugin'";
string insertContent = $"//START1\n{replaceMent}\n//END1";
// 执行替换
string tmp = Regex.Replace(launcherBuildGradleContent, pattern, insertContent);
if (tmp.Equals(launcherBuildGradleContent))
{
if (!tmp.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
{
launcherBuildGradleContent = launcherBuildGradleContent + "\n" + insertContent;
}
}
else
{
launcherBuildGradleContent = tmp;
}
File.WriteAllText(launcherBuildGradle, launcherBuildGradleContent);
//unity build gradle 处理
string unityBuildGradleContent = File.ReadAllText(unityLibraryBuildGradle);
if (!unityBuildGradleContent.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
{
unityBuildGradleContent = unityBuildGradleContent + "\n" + "apply plugin: 'com.tuyoo.sdk_plugin'";
File.WriteAllText(unityLibraryBuildGradle, unityBuildGradleContent);
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e72cb856786c2404f988cc074d9f1734
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,257 @@
using System.IO;
using System.Xml;
using System.Collections.Generic;
using UnityEditor;
using System.Text.RegularExpressions;
using System;
#if UNITY_EDITOR && UNITY_ANDROID
using UnityEngine;
using UnityEditor.Android;
class TySdkProjectGenerator : IPostGenerateGradleAndroidProject
{
public int callbackOrder { get { return 0; } }
public static string sdkInUnityRootPath;
public static string rootProjectPath;
public static string assetsRootPath;
/**
*
* 1. AndroidManifest修改
1. activity \ applciatoin
2.
3. json配置文件
*
**/
public void OnPostGenerateGradleAndroidProject(string path)
{
Debug.Log("TySdkProjectGenerator.OnPostGenerateGradleAndroidProject at path " + path);
rootProjectPath = Directory.GetParent(path).FullName;
//获取Assets根目录
assetsRootPath = Application.dataPath;
//获取sdk在unity中的路径
//var stackTrace = new System.Diagnostics.StackTrace(true);
//var frame = stackTrace.GetFrame(0);
//string filePath = frame.GetFileName();
//sdkInUnityRootPath = Path.GetDirectoryName(filePath);
sdkInUnityRootPath = FileUtil.GetPhysicalPath("Packages/com.bywaystudios.tuyoosdk/Editor/Android");
Debug.Log("TySdkProjectGenerator.OnPostGenerateGradleAndroidProject sdkInUnityRootPath " + sdkInUnityRootPath);
//处理androidMnifest
ManifestProcessor manifestProcessor = new ManifestProcessor(Path.Combine(path, "src/main/AndroidManifest.xml"));
manifestProcessor.process();
//处理build.gradle
BuildGradleProcessor buildGradleProcessor = new BuildGradleProcessor(rootProjectPath);
buildGradleProcessor.process();
//拷贝json文件
copyJsonFile();
}
private void copyJsonFile()
{
Debug.Log("TySdkProjectGenerator.copyJsonFile start");
//package gameConfig -> root/config/..
CopyFile(Path.Combine(FileUtil.GetPhysicalPath("ProjectSettings/Packages/com.bywaystudios.tuyoosdk"), "gameconfig.json"), Path.Combine(rootProjectPath, "config", "gameconfig.json"));
CopyFile(Path.Combine(FileUtil.GetPhysicalPath("ProjectSettings/Packages/com.bywaystudios.tuyoosdk"), "gameconfig.json"), Path.Combine(rootProjectPath, "launcher", "gameconfig.json"));
//gameConfigs/.. -> root/config/..
CopyFiles(Path.Combine(sdkInUnityRootPath, "gameConfigs"), Path.Combine(rootProjectPath, "config"));
CopyFiles(Path.Combine(sdkInUnityRootPath, "gameConfigs"), Path.Combine(rootProjectPath, "launcher"));
//兼容firebase crashlytics
CopyFile(Path.Combine(FileUtil.GetPhysicalPath("ProjectSettings/Packages/com.bywaystudios.firebase"), "google-services.json"), Path.Combine(rootProjectPath, "launcher","google-services.json"));
Debug.Log("TySdkProjectGenerator.copyJsonFile end");
}
public static void CopyFile(string sourceFile, string destinationFile)
{
// 检查源文件是否存在
if (!File.Exists(sourceFile))
{
Console.WriteLine("源文件不存在: " + sourceFile);
return;
}
// 创建目标文件夹(如果不存在)
string destinationFolder = Path.GetDirectoryName(destinationFile);
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
Console.WriteLine("目标文件夹已创建: " + destinationFolder);
}
// 复制文件到目标路径
File.Copy(sourceFile, destinationFile, true); // 允许覆盖
Console.WriteLine("已复制文件: " + sourceFile + " 到 " + destinationFile);
}
public static void CopyFiles(string sourceFolder, string destinationFolder)
{
// 检查源文件夹是否存在
if (!Directory.Exists(sourceFolder))
{
Console.WriteLine("源文件夹不存在: " + sourceFolder);
return;
}
// 创建目标文件夹(如果不存在)
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
Console.WriteLine("目标文件夹已创建: " + destinationFolder);
}
// 获取源文件夹中的所有文件
string[] files = Directory.GetFiles(sourceFolder);
// 复制每个文件到目标文件夹
foreach (string file in files)
{
if (!file.EndsWith("json"))
{
continue;
}
string fileName = Path.GetFileName(file); // 获取文件名
string destFile = Path.Combine(destinationFolder, fileName); // 组合目标文件路径
File.Copy(file, destFile, true); // 复制文件,允许覆盖
Console.WriteLine("已复制文件: " + file + " 到 " + destFile);
}
}
internal class ManifestProcessor
{
private string manifestPath;
public ManifestProcessor(string manifestPath)
{
Debug.Log("ManifestProcessor, manifestPath:" + manifestPath);
this.manifestPath = manifestPath;
}
// 1. 处理Applicatioin
// 2. 处理Activity
public void process()
{
Debug.Log("ManifestProcessor, process start.");
if (!File.Exists(manifestPath))
{
Debug.LogError("manifestPath not exit!! manifestPath:" + manifestPath);
return;
}
// 加载AndroidManifest.xml文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(manifestPath);
// 定义 Android 命名空间
string androidNamespaceURI = "http://schemas.android.com/apk/res/android";
// 获取<manifest>节点
XmlNode manifestNode = xmlDoc.SelectSingleNode("/manifest");
if (manifestNode == null)
{
Debug.LogError("manifestNode is NULL!!");
return;
}
// 获取<application>节点
XmlNode applicationNode = manifestNode.SelectSingleNode("application");
if (applicationNode == null)
{
Debug.LogError("applicationNode is NULL!!");
return;
}
// 设置name属性
XmlAttribute nameAttribute = applicationNode.Attributes["android:name"];
var applicationName = "android.app.Application";
if (nameAttribute == null || nameAttribute.Value.Equals(applicationName))
{
//默认application修改成sdk的application
Debug.Log("修改成SDK的application");
// 修改已有的name属性
if(nameAttribute == null){
nameAttribute = xmlDoc.CreateAttribute("android:name", androidNamespaceURI);
nameAttribute.Value = "com.tuyoo.sdk.Application";
applicationNode.Attributes.Append(nameAttribute);
}else{
nameAttribute.Value = "com.tuyoo.sdk.Application";
}
}
else
{
//游戏自定义了application,不做处理了
Debug.Log("游戏自定义了application,不做处理了,需要游戏自行处理sdk接口调用");
}
// 复制sdk的application到游戏中。
var tuyooJavaDir = Path.Combine(rootProjectPath, "unityLibrary/src/main/java/com/tuyoo/sdk");
if (!Directory.Exists(tuyooJavaDir))
{
Directory.CreateDirectory(tuyooJavaDir);
Console.WriteLine("文件夹创建成功: " + tuyooJavaDir);
}
//设置sdk的application继承游戏的applicaiton
var sdkApplicationContent = File.ReadAllText(Path.Combine(sdkInUnityRootPath, "sdkConfigs", "Application.txt"));
sdkApplicationContent = sdkApplicationContent.Replace(@"${0}", applicationName);
File.WriteAllText(Path.Combine(tuyooJavaDir, "Application.java"), sdkApplicationContent);
// 创建命名空间管理器,并添加命名空间
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("android", androidNamespaceURI);
// 查找主Activity包含<meta-data android:name="unityplayer.UnityActivity" android:value="true" /> 的<activity>节点
XmlNode mainActivity = xmlDoc.SelectSingleNode("/manifest/application/activity[meta-data[@android:name='unityplayer.UnityActivity' and @android:value='true']]", nsManager);
Debug.Log("mainActivity :" + mainActivity.Attributes["android:name"]);
// 找到主Activity修改android:name属性
XmlAttribute nameAttribute1 = mainActivity.Attributes["android:name"];
var activityName = "com.unity3d.player.UnityPlayerActivity";
if (nameAttribute1 == null || nameAttribute1.Value.Equals(activityName))
{
Debug.Log("游戏使用的默认Activity插件替换成SDK的Activity");
if(nameAttribute1 == null){
nameAttribute1 = xmlDoc.CreateAttribute("android", "name", androidNamespaceURI);
nameAttribute1.Value = "com.tuyoo.sdk.Activity";
mainActivity.Attributes.Append(nameAttribute1);
}else{
nameAttribute1.Value = "com.tuyoo.sdk.Activity";
}
}
else
{
Debug.Log("游戏自定义了MainActivity因此插件不做处理,由游戏自行调用SDK声明周期接口");
}
//将SDK的activity引入的游戏
if (!Directory.Exists(tuyooJavaDir))
{
Directory.CreateDirectory(tuyooJavaDir);
Console.WriteLine("文件夹创建成功: " + tuyooJavaDir);
}
//设置sdk的application继承游戏的applicaiton
var sdkActivityContent = File.ReadAllText(Path.Combine(sdkInUnityRootPath, "sdkConfigs", "Activity.txt"));
sdkActivityContent = sdkActivityContent.Replace(@"${0}", activityName);
File.WriteAllText(Path.Combine(tuyooJavaDir, "Activity.java"), sdkActivityContent);
// 保存修改后的AndroidManifest.xml文件
xmlDoc.Save(manifestPath);
UnityEngine.Debug.Log("AndroidManifest.xml 已修改,设置 application name 为 com.tuyoo.sdk.Application.");
UnityEngine.Debug.Log("AndroidManifest.xml 已修改设置主Activity为 com.tuyoo.sdk.Activity.");
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6237c5592c4b446e3ab1ed8570bf7920
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 69cd8b9b58430450f859954bc7dd1082
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
{
"engine_sdk": "com.tuyoo.component:sdk_inter_layer_unity:0.4.7",
"com.tuyoo.component:sdk_inter_layer_login": "com.tuyoo.component:sdk_inter_layer_login:0.6.1",
"com.tuyoo.component:sdk_inter_layer_survey": "com.tuyoo.component:sdk_inter_layer_survey:0.6.1",
"com.tuyoo.component:sdk_inter_layer_push": "com.tuyoo.component:sdk_inter_layer_survey:0.6.1",
"com.tuyoo.component.login.third:alipayweb": "com.tuyoo.component.login.third:alipayweb:0.2.0",
"com.tuyoo.component.login.third:quickLogin": "com.tuyoo.component.login.third:quickLogin:0.2.0"
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: bda52be9838704740ab7e2dc94aa3c87
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4cd2e24681bc744368dcd5a6979a3e7a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,57 @@
package com.tuyoo.sdk;
import android.content.Intent;
import android.os.Bundle;
import com.tuyoo.sdk.sdk_inter_layer_unity.UnityInterface;
public class Activity extends ${0} {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UnityInterface.onActivityCreate(this);
}
@Override
protected void onResume() {
super.onResume();
UnityInterface.onActivityResume(this);
}
@Override
protected void onStart() {
super.onStart();
UnityInterface.onActivityStart(this);
}
@Override
protected void onStop() {
super.onStop();
UnityInterface.onActivityStop(this);
}
@Override
protected void onPause() {
super.onPause();
UnityInterface.onActivityPause(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UnityInterface.onResult(this, requestCode, resultCode, data);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
UnityInterface.onNewIntent(this, intent);
}
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a471b5ba113ff40d89068a6751b8f789
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,20 @@
package com.tuyoo.sdk;
import android.content.Context;
import com.tuyoo.sdk.sdk_inter_layer_unity.UnityInterface;
public class Application extends ${0} {
@Override
public void onCreate() {
super.onCreate();
UnityInterface.onApplicationCreate(this);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
UnityInterface.onAttachBaseContext(this, base);
}
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: eba7b7f816a5c4b90bc1ce1019b97ec2
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7082721ea27c14ebab76f86ef86f8b3b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,105 @@
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using System.IO;
using UnityEngine;
public class TYPostProcessWeb : IPostprocessBuildWithReport
{
public int callbackOrder => int.MaxValue;
private string buildPath;
// 导出完成后调用的方法
public void OnPostprocessBuild(BuildReport report)
{
string platform = report.summary.platform.ToString();
if (platform == "WebGL" || platform == "MiniGame")
{
buildPath = report.summary.outputPath;
Debug.Log("channel compile buildPath: " + buildPath);
CopyTyResouceFile();
}
}
private void CopyTyResouceFile()
{
string destinationDir = string.Empty;
string sourceDir = string.Empty;
string channelType = TYPreProcessWeb.GetBuildChannelType();
Debug.Log("TYPostProcessWeb channelType: " + channelType);
if (channelType == TYWebBuildConfig.MiniGameChannelType.ALI)
{
// 阿里小游戏
destinationDir = ProcessDestinationDir("alipay");
if (!Directory.Exists(destinationDir))
{
destinationDir = ProcessDestinationDir("alipaygame");
}
sourceDir = ProcessSourceDir("aliminigame");
}
if (!string.IsNullOrEmpty(destinationDir) && !string.IsNullOrEmpty(sourceDir))
{
Debug.Log("TYPostProcessWeb CopyTyResouceFile, sourceDir: " + sourceDir);
Debug.Log("TYPostProcessWeb CopyTyResouceFile, destinationDir: " + destinationDir);
CopyFilesToDirectory(sourceDir, destinationDir);
} else {
Debug.Log("TYPostProcessWeb CopyTyResouceFile, current channel dont need copy resource file.");
}
}
private string ProcessDestinationDir(string finnalOutputPath)
{
return Path.Combine(Directory.GetParent(buildPath).FullName, finnalOutputPath);
}
private string ProcessSourceDir(string ChannelResPath)
{
return Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, ChannelResPath);
}
public static void CopyFilesToDirectory(string sourceDir, string destinationDir)
{
if (!Directory.Exists(destinationDir))
{
Debug.LogError("目标文件目录不存在");
return;
}
// 获取源目录下的所有文件
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
// 获取文件的文件名(不包含路径)
string fileName = Path.GetFileName(file);
// 跳过以 .meta 结尾的文件
if (fileName.EndsWith(".meta"))
{
continue;
}
if (fileName == "TyJsBridge.js")
{
continue;
}
// 目标文件的完整路径
string destFile = Path.Combine(destinationDir, fileName);
try
{
// 复制文件到目标目录(如果目标文件已经存在,覆盖它)
File.Copy(file, destFile, true);
Debug.Log($"File copied: {fileName}");
}
catch (System.Exception e)
{
Debug.Log($"Failed to copy file {fileName}: {e.Message}");
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2c83ce3ffa42443eda040950dacbd36f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,432 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EngineSdkConverter.Unity.Plugins.WebGL;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
public class TYPreProcessWeb : IPreprocessBuildWithReport
{
// 定义回调的顺序
public int callbackOrder => 0;
private string configFilePath;
private string configJsonString;
private ConfigData configData;
private static string channelType;
// 构建前的回调方法
public void OnPreprocessBuild(BuildReport report)
{
string platform = report.summary.platform.ToString();
if (platform == "WebGL" || platform == "MiniGame")
{
configFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_GAMECONFIG_DIR);
configJsonString = File.ReadAllText(configFilePath);
configData = JsonUtility.FromJson<ConfigData>(configJsonString);
channelType = configData.tuyooParam.channelType;
CopyTyConfigFile();
CopyTyBridgeFile();
if (channelType == TYWebBuildConfig.MiniGameChannelType.WeiXin)
{
CopyTywxToWXTemplate();
if (configData.login.tywx.txAdSetId != 0 && !string.IsNullOrEmpty(configData.login.tywx.txAdSetKey))
{
// copy 广点通归因上报sdk的资源
CopyDnSdkResouce();
}
InsertTywx();
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.BYTEDANCE)
{
// copy js sdk 资源到 StreamingAssets下只有StreamingAssets的资源会被渠道打包zip包里
CopyBytedanceResource();
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.JINGDONG)
{
string jdDirectoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "jingdongminigame");
string[] files = Directory.GetFiles(jdDirectoryPath, "tuyoosdk_jingdong*.js");
string sourceFile = files[0];
CopyTuyooSdkJdRes(sourceFile);
InsertJDTuyooSdk(sourceFile);
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.OPPO)
{
string oppoDirectoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "oppominigame");
string[] files = Directory.GetFiles(oppoDirectoryPath, "tuyoosdk_oppo*.js");
string sourceFile = files[0];
CopyTuyooSdkOppoRes(sourceFile);
InsertOppoTuyooSdk(sourceFile);
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.MEITUAN)
{
string mtDirectoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "meituanminigame");
string[] files = Directory.GetFiles(mtDirectoryPath, "tuyoosdk_meituan*.js");
string sourceFile = files[0];
CopyTuyooSdkMtRes(sourceFile);
InsertMtTuyooSdk(sourceFile);
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.KUAISHOU)
{
string mtDirectoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "kuaishouminigame");
string[] files = Directory.GetFiles(mtDirectoryPath, "tuyoosdk_kuaishou*.js");
string sourceFile = files[0];
CopyTuyooSdkKSRes(sourceFile);
InsertKSTuyooSdk(sourceFile);
}
if (channelType == TYWebBuildConfig.MiniGameChannelType.XIAOMI)
{
string mtDirectoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "xiaomiminigame");
string[] files = Directory.GetFiles(mtDirectoryPath, "tuyoosdk_xiaomi*.js");
string sourceFile = files[0];
CopyTuyooSdkMIRes(sourceFile);
InsertMITuyooSdk(sourceFile);
}
}
}
public static string GetBuildChannelType()
{
return channelType;
}
private void CopyTyConfigFile()
{
string destinationPath = Path.Combine(Application.dataPath, "Resources/tygameconfig.json");
CopyFileContent(configFilePath, destinationPath);
}
private void CopyTyBridgeFile()
{
if (channelType == TYWebBuildConfig.MiniGameChannelType.ALI)
{
// 阿里小游戏
CopyBridgeContent("aliminigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.WeiXin)
{
// 微信小游戏
CopyBridgeContent("tywx");
InsertTywx();
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.BYTEDANCE)
{
// 字节小游戏
CopyBridgeContent("zijieminigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.JINGDONG)
{
// 京东小游戏
CopyBridgeContent("jingdongminigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.OPPO)
{
// oppo小游戏
CopyBridgeContent("oppominigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.MEITUAN)
{
CopyBridgeContent("meituanminigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.KUAISHOU)
{
CopyBridgeContent("kuaishouminigame");
}
else if (channelType == TYWebBuildConfig.MiniGameChannelType.XIAOMI)
{
CopyBridgeContent("xiaomiminigame");
}
else
{
// 打一个的默认jslib,可以直接导出WebGL
CopyBridgeContent("tywx");
}
}
public void CopyBridgeContent(string filePath)
{
string sourceFile = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, filePath, "TyJsBridge.js");
string targetFile = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_JSBRIDGE_DIR);
CopyFileContent(sourceFile, targetFile);
}
// https://wechat-miniprogram.github.io/minigame-unity-webgl-transform/Design/BuildTemplate.html
private void CopyTywxToWXTemplate()
{
string sourceFile = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "tywx/tywx.js");
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_WX_DEFULT_DIR, "tysdk");
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
}
private void CopyDnSdkResouce()
{
string sourcePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "tywx/dn-sdk-minigame-1.5.4");
string targetPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_WX_DEFULT_DIR, "tysdk/dn-sdk-minigame-1.5.4");
CopyDirectoryAllFiles(sourcePath, targetPath);
}
private void InsertTywx()
{
string wxGameJSFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_WX_DEFULT_DIR, "game.js");
string content = "import { tywx } from \"./tysdk/tywx.js\";\nGameGlobal.tywx = tywx;";
string[] keyword = new string[] { "GameGlobal.tywx = tywx;", "GameGlobal.TuyooSdk = TuyooSdk;" };
InsertContentToFile(wxGameJSFilePath, 2, content, keyword);
}
private void CopyBytedanceResource()
{
string directoryPath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "zijieminigame");
string[] files = Directory.GetFiles(directoryPath, "tuyoosdk_zijiegame*.js");
string sourceFile = files[0];
string targetFilePath = Path.Combine(Application.streamingAssetsPath, "__cp_js_files/tysdk.js");
CopyFileContent(sourceFile, targetFilePath);
}
private void CopyTuyooSdkJdRes(string sourceFile)
{
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_JD_DEFULT_DIR, "tysdk");
// 如果已经存在了删除里面的tysdk避免重复copy不同版本
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
if (configData.login.jingdongminigame.packageType == "wasmsplit")
{
string tywxSourceFile = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "tywx/tywx.js");
string tywxTargetFilePath = Path.Combine(targetFilePath, "tywx.js");
CopyFileContent(tywxSourceFile, tywxTargetFilePath);
}
}
private void InsertJDTuyooSdk(string sourceFile)
{
string jdGameJSDefaultFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_JD_DEFULT_DIR, "game.js");
string tyfileName = "./tysdk/" + Path.GetFileName(sourceFile);
string content = $"var TuyooSdk = require(\"{tyfileName}\");\nGameGlobal.TuyooSdk = TuyooSdk;";
string[] keyword = new string[] { "GameGlobal.tywx = tywx;", "GameGlobal.TuyooSdk = TuyooSdk;" };
InsertContentToFile(jdGameJSDefaultFilePath, 2, content, keyword);
if (configData.login.jingdongminigame.packageType == "wasmsplit")
{
string tywxContent = "import { tywx } from \"./tysdk/tywx.js\";\nGameGlobal.tywx = tywx;";
InsertContentToFile(jdGameJSDefaultFilePath, 2, tywxContent, new string[] { });
}
}
private void CopyTuyooSdkOppoRes(string sourceFile)
{
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_WX_DEFULT_DIR, "tysdk");
// 如果已经存在了删除里面的tysdk避免重复copy不同版本
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
if (configData.login.oppominigame.packageType == "wasmsplit")
// 因为oppo小游戏需要用微信小游戏的开发者工具跑分包所以需要把微信的资源脚本也打到包里
{
string tywxSourceFile = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, "tywx/tywx.js");
string tywxTargetFilePath = Path.Combine(targetFilePath, "tywx.js");
CopyFileContent(tywxSourceFile, tywxTargetFilePath);
}
}
private void InsertOppoTuyooSdk(string sourceFile)
{
string gameJSDefaultFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_WX_DEFULT_DIR, "game.js");
string tyfileName = "./tysdk/" + Path.GetFileName(sourceFile);
string content = $"var TuyooSdk = require(\"{tyfileName}\");\nGameGlobal.TuyooSdk = TuyooSdk;";
string[] keyword = new string[] { "GameGlobal.tywx = tywx;", "GameGlobal.TuyooSdk = TuyooSdk;" };
InsertContentToFile(gameJSDefaultFilePath, 2, content, keyword);
if (configData.login.oppominigame.packageType == "wasmsplit")
{
string tywxContent = "import { tywx } from \"./tysdk/tywx.js\";\nGameGlobal.tywx = tywx;";
InsertContentToFile(gameJSDefaultFilePath, 2, tywxContent, new string[] { });
}
}
private void CopyTuyooSdkMtRes(string sourceFile)
{
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_MT_DEFULT_DIR, "tysdk");
// 如果已经存在了删除里面的tysdk避免重复copy不同版本
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
}
private void InsertMtTuyooSdk(string sourceFile)
{
string tyfileName = "./tysdk/" + Path.GetFileName(sourceFile);
string mtGameJSFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_MT_DEFULT_DIR, "game.js");
string content = $"var TuyooSdk = require(\"{tyfileName}\");\nGameGlobal.TuyooSdk = TuyooSdk;";
string[] keyword = new string[] { "GameGlobal.TuyooSdk = TuyooSdk;" };
InsertContentToFile(mtGameJSFilePath, 2, content, keyword);
}
private void CopyTuyooSdkKSRes(string sourceFile)
{
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_KS_DEFULT_DIR, "tysdk");
// 如果已经存在了删除里面的tysdk避免重复copy不同版本
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
}
private void InsertKSTuyooSdk(string sourceFile)
{
string tyfileName = "./tysdk/" + Path.GetFileName(sourceFile);
string ksGameJSFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_KS_DEFULT_DIR, "game.js");
string content = $"var TuyooSdk = require(\"{tyfileName}\");\nGameGlobal.TuyooSdk = TuyooSdk;";
string[] keyword = new string[] { "GameGlobal.TuyooSdk = TuyooSdk;" };
InsertContentToFile(ksGameJSFilePath, 2, content, keyword);
}
private void CopyTuyooSdkMIRes(string sourceFile)
{
string targetFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_MI_DEFULT_DIR, "tysdk");
// 如果已经存在了删除里面的tysdk避免重复copy不同版本
CheckAndDeletePath(targetFilePath);
string targetFile = Path.Combine(targetFilePath, Path.GetFileName(sourceFile));
CopyFileContent(sourceFile, targetFile);
}
private void InsertMITuyooSdk(string sourceFile)
{
string tyfileName = "./tysdk/" + Path.GetFileName(sourceFile);
string miGameJSFilePath = Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_MI_DEFULT_DIR, "game.js");
string content = $"var TuyooSdk = require(\"{tyfileName}\");\nwindow.TuyooSdk = TuyooSdk;";
string[] keyword = new string[] { "window.TuyooSdk = TuyooSdk;" };
InsertContentToFile(miGameJSFilePath, 1, content, keyword);
}
public void CheckAndDeletePath(string targetPath)
{
if (Directory.Exists(targetPath))
{
string[] files = Directory.GetFiles(targetPath, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
}
}
public void CopyDirectoryAllFiles(string sourcePath, string targetPath)
{
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
string[] files = Directory.GetFiles(sourcePath);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
if (fileName.EndsWith(".meta"))
{
continue;
}
string destFile = Path.Combine(targetPath, fileName);
try
{
File.Copy(file, destFile, true);
}
catch (System.Exception e)
{
Debug.Log($"Failed to copy file {fileName}: {e.Message}");
}
}
}
public void CopyFileContent(string sourceFile, string targetFile)
{
if (!File.Exists(sourceFile))
{
Debug.LogError($"源文件不存在: {sourceFile}");
return;
}
// 确保目标目录存在
string targetDirectory = Path.GetDirectoryName(targetFile);
if (!Directory.Exists(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}
// 读取源文件内容并写入目标文件(覆盖方式)
File.Copy(sourceFile, targetFile, true);
Debug.Log($"已复制 {sourceFile} 的内容到 {targetFile}");
}
public void InsertContentToFile(string filePath, int targetLine, string insertContent, string[] checkKeyword)
{
try
{
if (!File.Exists(filePath))
{
Debug.LogError("文件不存在: " + filePath);
return;
}
var fileLines = new List<string>(File.ReadAllLines(filePath));
foreach (string keyword in checkKeyword)
{
int matchIndex = fileLines.FindIndex(line => line.Trim() == keyword);
if (matchIndex >= 1)
{
// 删除该行和它上面一行,如: "import { tywx } from \"./tysdk/tywx.js\";\nGameGlobal.tywx = tywx;";
fileLines.RemoveAt(matchIndex);
fileLines.RemoveAt(matchIndex - 1);
}
}
string[] lines = fileLines.ToArray();
// 插入内容
if (targetLine > lines.Length)
{
// 如果目标行号超过文件行数,则追加
File.AppendAllText(filePath, Environment.NewLine + insertContent + Environment.NewLine);
}
else
{
// 在指定行插入
fileLines.Insert(targetLine - 1, insertContent);
File.WriteAllLines(filePath, fileLines);
}
Debug.Log($"已修改文件: {filePath}");
}
catch (System.Exception e)
{
Debug.LogError($"修改文件失败: {e.Message}");
}
}
public void RemoveTargetContent(string filePath, string target)
{
try
{
if (!File.Exists(filePath))
{
Debug.LogError("文件不存在: " + filePath);
return;
}
// 读取文件内容
string text = File.ReadAllText(filePath);
// 删除目标内容
string newText = text.Replace(target, "");
// 写回文件
File.WriteAllText(filePath, newText);
}
catch (System.Exception e)
{
Debug.LogError($"删除指定内容失败: {e.Message}");
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bf40edd3df60c492981a79cb33398b5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,39 @@
public class TYWebBuildConfig
{
// gameconfig dir
public const string TY_WEB_GAMECONFIG_DIR = "EngineSdkConverter/Unity/Plugins/WebGL/gameconfig.json";
public const string TY_WEB_CHANNEL_RESOURCE_DIR = "EngineSdkConverter/Unity/Plugins/WebGL/ChannelResource";
public const string TY_WEB_JSBRIDGE_DIR = "EngineSdkConverter/Unity/Plugins/WebGL/TyJsBridge.jslib";
public const string TY_WEB_WX_TEMPLATE_DIR = "WX-WASM-SDK-V2/Editor/template/minigame";
public const string TY_WEB_WX_DEFULT_DIR = "WX-WASM-SDK-V2/Runtime/wechat-default";
public const string TY_WEB_JD_TEMPLATE_DIR = "WX-WASM-SDK-V2/Editor/template/minigame";
public const string TY_WEB_JD_DEFULT_DIR = "WX-WASM-SDK-V2/Runtime/wechat-default";
public const string TY_WEB_MT_TEMPLATE_DIR = "MGC-WASM-SDK/Editor/template/minigame";
public const string TY_WEB_MT_DEFULT_DIR = "MGC-WASM-SDK/Runtime/wechat-default";
public const string TY_WEB_KS_DEFULT_DIR = "KS-WASM-SDK-V2/Runtime/minigame-default";
public const string TY_WEB_MI_DEFULT_DIR = "XIAOMI-minigame/MiQGame";
public class MiniGameChannelType
{
public const string ALI = "ali.cn.minigame";
public const string WeiXin = "wx.cn.minigame";
public const string BYTEDANCE = "bytedance.cn.minigame";
public const string JINGDONG = "jingdong.cn.minigame";
public const string OPPO = "oppo.cn.minigame";
public const string MEITUAN = "mt.cn.minigame";
public const string KUAISHOU = "kuaishou.cn.minigame";
public const string XIAOMI = "xiaomi.cn.minigame";
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 894b657888acb4a1d9a61ed5a1efd7db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,18 @@
{
"name": "com.tuyoo.unitysdk.editor",
"rootNamespace": "",
"references": [
"GUID:2104153dbb22d46e89c9a1195f478f01"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f232f093b6a904b4a84b64f3bac882ca
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5779445bed0ed4206a40991b635b0b0c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,160 @@
using System;
using System.IO;
using UnityEditor;
using System.Diagnostics;
namespace EngineSdkConverter.Unity.Editor
{
public class Result
{
/// <summary>
/// Standard output stream from command line.
/// </summary>
public string StandardOutput;
/// <summary>
/// Standard error stream from command line.
/// </summary>
public string StandardError;
/// <summary>
/// Exit code returned from command line.
/// </summary>
public int ExitCode;
/// <summary>
/// The description of the result that can be used for error logging.
/// </summary>
public string Message;
}
public class EngineSdkConverterUtils
{
const string TAG = "EnginSdkConverterUtils ";
static public string GetFilePathByAssetName(string assetName)
{
var assetGuids = AssetDatabase.FindAssets(assetName);
string retPath = "";
foreach (var guid in assetGuids)
{
retPath = AssetDatabase.GUIDToAssetPath(guid);
if (File.Exists(retPath))
{
retPath = Path.Combine(retPath);
break;
}
else
{
retPath = "";
}
}
return retPath;
}
public static Result RunShell(string toolPath, string arguments, string workingDirectory)
{
var stdoutFileName = Path.GetTempFileName();
var stderrFileName = Path.GetTempFileName();
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardInput = false;
process.StartInfo.RedirectStandardOutput = false;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.EnvironmentVariables["LANG"] = "en_US.UTF-8";
process.StartInfo.EnvironmentVariables["PATH"] = $"{Environment.GetEnvironmentVariable("PATH")}:/usr/local/bin";
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.FileName = "bash";
string argumentsFormat = string.Format("-l -c '\"{0}\" {1} 1> {2} 2> {3}'", toolPath, arguments, stdoutFileName, stderrFileName);
process.StartInfo.Arguments = argumentsFormat;
process.Start();
process.WaitForExit();
var stdout = File.ReadAllText(stdoutFileName);
var stderr = File.ReadAllText(stderrFileName);
File.Delete(stdoutFileName);
File.Delete(stderrFileName);
var result = new Result();
result.StandardOutput = stdout;
result.StandardError = stderr;
result.ExitCode = process.ExitCode;
var messagePrefix = result.ExitCode == 0 ? "Command executed successfully" : "Failed to run command";
result.Message = string.Format("{0}: '{1} {2}'\nstdout: {3}\nstderr: {4}\nExit code: {5}", messagePrefix, toolPath, arguments, stdout, stderr, process.ExitCode);
return result;
}
public static Result RunPython(string scriptPath, string arguments, string workingDirectory)
{
var stdoutFileName = Path.GetTempFileName();
var stderrFileName = Path.GetTempFileName();
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardInput = false;
process.StartInfo.RedirectStandardOutput = false;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.EnvironmentVariables["LANG"] = "en_US.UTF-8";
process.StartInfo.EnvironmentVariables["PATH"] = $"{Environment.GetEnvironmentVariable("PATH")}:/usr/local/bin";
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.FileName = "bash";
// 直接调用 Python3 并保证参数安全
string argumentsFormat = $"-l -c 'python3 \"{scriptPath}\" {arguments} 1> \"{stdoutFileName}\" 2> \"{stderrFileName}\"'";
process.StartInfo.Arguments = argumentsFormat;
process.Start();
process.WaitForExit();
var stdout = File.ReadAllText(stdoutFileName);
var stderr = File.ReadAllText(stderrFileName);
File.Delete(stdoutFileName);
File.Delete(stderrFileName);
var result = new Result
{
StandardOutput = stdout,
StandardError = stderr,
ExitCode = process.ExitCode,
Message = $"{(process.ExitCode == 0 ? "Command executed successfully" : "Failed to run command")}: 'python3 {scriptPath} {arguments}'\nstdout: {stdout}\nstderr: {stderr}\nExit code: {process.ExitCode}"
};
return result;
}
public static void CopyDirectory(string sourceDir, string destDir, bool replace)
{
// 确保目标文件夹存在
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
// 复制所有文件
foreach (var file in Directory.GetFiles(sourceDir))
{
string destFilePath = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFilePath, replace); // true 表示覆盖已有文件
}
// 递归复制子文件夹
foreach (var subDir in Directory.GetDirectories(sourceDir))
{
string newDestDir = Path.Combine(destDir, Path.GetFileName(subDir));
CopyDirectory(subDir, newDestDir, replace);
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d7ebf1247305d4ac3bd13cf3cc628e1c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,948 @@
import os
import re
import json
import argparse
from pbxproj import XcodeProject
from pbxproj.pbxsections import PBXShellScriptBuildPhase
import subprocess
import plistlib
#TODO:待修改字段
IOSMINIVERSION = '12.0'
LOCAL_SOURCE_LINE = 'http://tygit.tuyoo.com/dev_platform/ios/frameworks/pods/private-pod-repo.git'
SOURCE_LINE = 'ssh://git@tygit.tuyoo.com:2222/dev_platform/ios/frameworks/pods/private-pod-repo.git'
CUSTOM_OSS_HTTP_PATH = 'https://sa201-ptsdk-res.oss-cn-beijing.aliyuncs.com'
build_config = {}
build_package_config = {}
build_sdk_names_list = []
dependencies = []
CHANNEL_AND_NAME_LIST = ["wechat",
"wangyiyidun",
"yidunloginv2",
"douyin",
"rongheguiyin",
"yidunzhiwen",
"yiduncaptcha",
"yidunlivedetect",
"appsflyer",
"firebaseanalytics",
"firebasecrashlytics",
"firebaseodm",
"yuenanlogin",
"facebook",
"google",
"line",
"twitter",
"idfa",
"haiwailogin",
"aihelp",
"bugly",
"push",
"fcm"]
BUNDLE_SOURCE = {
"yidunloginv2":["NTESResource.bundle","TDKYiDunLoginV2Bundle.bundle"],
"yidunzhiwen":["FPSupport.bundle"],
"yiduncaptcha":["NTESVerifyCodeResources.bundle","TDKYidunCaptchaBundle.bundle"],
"yidunlivedetect":["NTESLiveDetectBundle.bundle","TDKYidunLiveDetectBundle.bundle"],
"haiwailogin":["TDKHaiWaiLoginSource.bundle"],
"aihelp":["AIHelpSupportSDK.bundle"]
}
EMBEM_FRAMEWORK_SOURCE = {
"douyin":["UnionOpenPlatformCore.framework","UnionOpenPlatformCPS.framework"],
"yidunlivedetect":["NEYDnn.framework"]
}
def parse_build_config_json(build_config_json_path, coustom_plist_path):
print(f"1⃣ parse_build_config_json, path = {build_config_json_path} begin")
abs_build_config_json_path = os.path.abspath(build_config_json_path)
if os.path.isfile(abs_build_config_json_path):
with open(abs_build_config_json_path, 'r', encoding='utf-8') as json_file:
data = json.loads(json_file.read())
# print(f"1⃣ parse_build_config_json, json = {data} ing")
# 将数据写入 plist 文件
with open(coustom_plist_path, 'wb') as plist_file:
plistlib.dump(data, plist_file)
global coustom_plist_file_path
coustom_plist_file_path = coustom_plist_path
global build_config
build_config = data
global build_package_config
build_package_config = data.get('buildConfig')
global build_sdk_names_list
names = data.get('login').get('sdks')
build_sdk_names_list = list(set([name for name in names if name]))
fcm = data.get('fcm')
push = data.get('push')
if fcm:
build_sdk_names_list.append('fcm')
if push:
build_sdk_names_list.append('push')
if ('firebasecrashlytics' in build_sdk_names_list or 'firebaseodm' in build_sdk_names_list) and 'firebaseanalytics' not in build_sdk_names_list:
build_sdk_names_list.append('firebaseanalytics')
else:
print(f"❌ parse_build_config_json file error")
exit(1)
def get_add_project_capability_flag():
if build_package_config and "addCapability" in build_package_config:
return build_package_config.get("addCapability")
else:
return False
def get_git_access_method():
if build_package_config and "gitAccessMethod" in build_package_config:
return build_package_config.get("gitAccessMethod")
else:
return "ssh"
def get_sdk_source_method():
if build_package_config and "getSourceMethod" in build_package_config:
return build_package_config.get("getSourceMethod")
else:
return "git"
def add_file_to_project(project, file_path, skip_if_exsit=True, target_name = None):
print(f"💡 add_file_to_project {file_path}")
abs_file_path = os.path.abspath(file_path)
if os.path.exists(abs_file_path):
if not project.get_files_by_path(abs_file_path):
project.add_file(abs_file_path, target_name = target_name)
print(f"⚠️ add_file_to_project {abs_file_path} add")
elif not skip_if_exsit:
project.remove_files_by_path(abs_file_path)
print(f"🗑️ 已删除旧的 {abs_file_path}")
file_ref = project.add_file(abs_file_path, target_name = target_name)
print(f"✅ 已添加: {abs_file_path} -> {file_ref}")
else:
print(f"⚠️ add_file_to_project {abs_file_path} already exist")
else:
print(f"⚠️ add_file_to_project {abs_file_path} not exist")
def set_library_search_paths(project, search_paths, target_name=None):
print(f"💡 set_library_search_paths {search_paths}")
library_search_paths = None
for target in project.objects.get_targets():
build_configurations = project.objects.get_configurations_on_targets(target.name)
for config in build_configurations:
library_search_paths = config.buildSettings.get("LIBRARY_SEARCH_PATHS", [])
default_paths = ['$(inherited)']
if library_search_paths:
if not isinstance(library_search_paths, list):
library_search_paths = [library_search_paths]
print(f"💡 set_library_search_paths {library_search_paths}")
library_search_paths = default_paths + list(dict.fromkeys(search_paths + library_search_paths))
library_search_paths = default_paths + [item for item in library_search_paths if item not in default_paths]
else:
library_search_paths = default_paths
config.buildSettings["LIBRARY_SEARCH_PATHS"] = library_search_paths
print(f"💡 set_library_search_paths {target.name} - {library_search_paths}")
else:
print(f"💡 set_library_search_paths fail")
return None
# **处理 Info.plist Begin**
def add_bool_to_info_plist(plist_file_path, key, value, skip_existing_elements = True):
print(f"💡 add_bool_to_info_plist {plist_file_path} - {key} - {value}")
if not key and key == '':
print(f"⚠️ add_bool_to_info_plist {key} invalue")
return
if not isinstance(value, bool):
print(f"⚠️ add_bool_to_info_plist {value} invalue")
return
with open(plist_file_path, 'rb') as f:
plist_data = plistlib.load(f)
if not skip_existing_elements or key not in plist_data:
# 如果存在,但不跳过,则直接覆盖, 如果不存在,则创建一个新的列表并添加 schemes_to_add
plist_data[key] = value
# 将修改后的数据写回 info.plist 文件
with open(plist_file_path, 'wb') as f:
plistlib.dump(plist_data, f)
def add_string_to_info_plist(plist_file_path, key, value, skip_existing_elements = True):
print(f"💡 add_string_to_info_plist {plist_file_path} - {key} - {value}")
if not key and key == '':
print(f"⚠️ add_string_to_info_plist {key} invalue")
return
if not isinstance(value, str):
print(f"⚠️ add_array_to_info_plist {value} invalue")
return
with open(plist_file_path, 'rb') as f:
plist_data = plistlib.load(f)
if not skip_existing_elements or key not in plist_data:
# 如果存在,但不跳过,则直接覆盖, 如果不存在,则创建一个新的列表并添加 schemes_to_add
plist_data[key] = value
# 将修改后的数据写回 info.plist 文件
with open(plist_file_path, 'wb') as f:
plistlib.dump(plist_data, f)
def add_array_to_info_plist(plist_file_path, key, value, skip_existing_elements = True):
print(f"💡 add_array_to_info_plist {plist_file_path} - {key} - {value}")
if not os.path.exists(plist_file_path):
print(f"⚠️ add_array_to_info_plist {plist_file_path} invalue")
return
if not key or key == '':
print(f"⚠️ add_array_to_info_plist {key} invalue")
return
if not isinstance(value, list):
print(f"⚠️ add_array_to_info_plist {value} invalue")
return
with open(plist_file_path, 'rb') as f:
plist_data = plistlib.load(f)
# 检查 key 是否存在
if key not in plist_data:
plist_data[key] = []
current_array = plist_data[key]
for item in value:
if not skip_existing_elements or item not in current_array:
current_array.append(item)
with open(plist_file_path, 'wb') as f:
plistlib.dump(plist_data, f)
def is_json(variable):
try:
json.loads(variable)
return True
except (json.JSONDecodeError, TypeError):
return False
def add_dictionary_to_info_plist(plist_file_path, key, value, skip_existing_elements = True):
print(f"💡 add_dictionary_to_info_plist {plist_file_path} - {key} - {value}")
if not key and key == '':
print(f"⚠️ add_dictionary_to_info_plist {key} invalue")
return
if not is_json(value):
print(f"⚠️ add_dictionary_to_info_plist {value} invalue")
return
with open(plist_file_path, 'rb') as f:
plist_data = plistlib.load(f)
if not skip_existing_elements or key not in plist_data:
# 如果存在,但不跳过,则直接覆盖, 如果不存在,则创建一个新的列表并添加 schemes_to_add
plist_data[key] = value
# 将修改后的数据写回 info.plist 文件
with open(plist_file_path, 'wb') as f:
plistlib.dump(plist_data, f)
# **处理 Info.plist End**
# **处理 BuildSetting-ShellScript Begin**
def normalize_script(script: str):
if not script:
return ''
return script.strip().strip('"').strip("'")
def add_shell_script(project, run_script, input_files=None, output_files=None ,target_name=None, insert_before_compile=False, run_install_build=0):
# 检查是否已经存在该脚本,避免重复添加
for target in project.objects.get_targets(target_name):
print(f'target = {target}')
for build_phase_id in target.buildPhases:
build_phase = project.objects[build_phase_id]
print(f'build_phase = {build_phase_id} = {build_phase}')
if not isinstance(build_phase, PBXShellScriptBuildPhase):
continue
shellScript = build_phase.shellScript or ""
print(f'build_phase = start1 {shellScript}')
print(f'build_phase = start2 {run_script}')
if normalize_script(shellScript) == normalize_script(run_script):
print("⚠️ 已存在 先删除 ")
del project.objects[build_phase_id]
target.remove_build_phase(build_phase)
project.add_run_script(
script=run_script,
input_files=input_files,
output_files=output_files,
target_name=target_name,
insert_before_compile=insert_before_compile,
run_install_build=run_install_build
)
print("✅ 已添加 Run Script Phase。")
project.save()
# **处理 BuildSetting-ShellScript Begin**
# **处理 entitlements Begin**
def get_entitlements_file_path(project, skip_file_not_exist=True, app_target_name=None):
print(f"💡 get_entitlements_file_path ")
entitlements_path = None
for target in project.objects.get_targets():
build_configurations = project.objects.get_configurations_on_targets(target.name)
for config in build_configurations:
entitlements_path = config.buildSettings.get("CODE_SIGN_ENTITLEMENTS", "")
if entitlements_path:
print(f"💡 get_entitlements_file_path {entitlements_path}")
return os.path.abspath(entitlements_path)
if not skip_file_not_exist and app_target_name:
entitlements_file_path = f"{app_target_name}/{app_target_name}.entitlements"
with open(entitlements_file_path, "wb") as f:
plistlib.dump({}, f)
for target in project.objects.get_targets():
build_configurations = project.objects.get_configurations_on_targets(target.name)
for config in build_configurations:
config.buildSettings["CODE_SIGN_ENTITLEMENTS"] = entitlements_file_path
project.save()
return os.path.abspath(entitlements_file_path)
else:
return None
def add_sign_in_with_apple_capability(project, app_target_name):
print(f"💡 add_sign_in_with_apple_capability")
if not get_add_project_capability_flag():
print(f"💡 add_sign_in_with_apple_capability skip")
return
entitlements_file_path = get_entitlements_file_path(project, False, app_target_name)
SIGNIN_KEY = "com.apple.developer.applesignin"
if os.path.exists(entitlements_file_path):
with open(entitlements_file_path, "rb") as f:
entitlements = plistlib.load(f)
if SIGNIN_KEY in entitlements:
print(f"✅ add_sign_in_with_apple_capability 已启用")
else:
print(f" add_sign_in_with_apple_capability 新增 ")
entitlements[SIGNIN_KEY] = ["Default"]
with open(entitlements_file_path, "wb") as f:
plistlib.dump(entitlements, f)
print(f"✅ add_sign_in_with_apple_capability `.entitlements` 文件已更新")
else:
print(f"⚠️ add_sign_in_with_apple_capability `.entitlements` not exist")
def add_notification_capability(project, app_target_name):
print(f"💡 add_notification_capability")
if not get_add_project_capability_flag():
print(f"💡 add_notification_capability skip")
return
entitlements_file_path = get_entitlements_file_path(project, False, app_target_name)
APS_ENV_KEY = "aps-environment"
if os.path.exists(entitlements_file_path):
with open(entitlements_file_path, "rb") as f:
entitlements = plistlib.load(f)
if APS_ENV_KEY in entitlements:
print(f"✅ add_notification_capability 已启用")
else:
print(f" add_notification_capability 新增 ")
entitlements[APS_ENV_KEY] = "production"
with open(entitlements_file_path, "wb") as f:
plistlib.dump(entitlements, f)
print(f"✅ add_notification_capability `.entitlements` 文件已更新")
else:
print(f"⚠️ add_notification_capability `.entitlements` not exist")
def add_background_modes_capability(info_plist_path):
print(f"💡 add_background_modes_capability")
if not get_add_project_capability_flag():
print(f"💡 add_background_modes_capability skip")
return
print(f"✅ `info.plist` 文件已更新 UIBackgroundModes 和 remote-notification 权限")
add_array_to_info_plist(info_plist_path, 'UIBackgroundModes', ['remote-notification'])
def add_keychain_capability(project, app_target_name):
print(f"💡 add_keychain_capability")
if not get_add_project_capability_flag():
print(f"💡 add_keychain_capability skip")
return
entitlements_file_path = get_entitlements_file_path(project, False, app_target_name)
KEY_CHANIN_KEY = "keychain-access-groups"
if os.path.exists(entitlements_file_path):
with open(entitlements_file_path, "rb") as f:
entitlements = plistlib.load(f)
if KEY_CHANIN_KEY in entitlements:
print(f"✅ add_keychain_capability 已启用")
else:
print(f" add_keychain_capability 新增 ")
entitlements[KEY_CHANIN_KEY] = [""]
with open(entitlements_file_path, "wb") as f:
plistlib.dump(entitlements, f)
print(f"✅ add_keychain_capability `.entitlements` 文件已更新")
else:
print(f"⚠️ add_keychain_capability `.entitlements` not exist")
def process_applinks(applinks):
"""
处理 applinks 列表确保每个 URL 被转换为符合 Apple Universal Links 规范的格式
"""
processed_applinks = []
for url in applinks:
if url.startswith("http://"):
domain = url[len("http://"):]
elif url.startswith("https://"):
domain = url[len("https://"):]
else:
domain = url
domain = domain.split('/')[0]
processed_applinks.append(f"applinks:{domain}")
return processed_applinks
def add_associated_domains_capability(project, applinks, app_target_name):
print(f"💡 add_associated_domains_capability")
if not get_add_project_capability_flag():
print(f"💡 add_associated_domains_capability skip")
return
entitlements_file_path = get_entitlements_file_path(project, False, app_target_name)
DOMAINS_KEY = "com.apple.developer.associated-domains"
processed_applinks = process_applinks(applinks)
if os.path.exists(entitlements_file_path):
with open(entitlements_file_path, "rb") as f:
entitlements = plistlib.load(f)
if DOMAINS_KEY in entitlements:
print(f"✅ 已启用 Associated Domains正在补充信息")
current_domains = entitlements[DOMAINS_KEY]
# 合并两个列表,去重
updated_domains = list(set(current_domains + processed_applinks))
entitlements[DOMAINS_KEY] = updated_domains
else:
print(f" add_associated_domains_capability 新增 ")
entitlements[DOMAINS_KEY] = processed_applinks
with open(entitlements_file_path, "wb") as f:
plistlib.dump(entitlements, f)
print(f"✅ add_associated_domains_capability `.entitlements` 文件已更新")
else:
print(f"⚠️ add_associated_domains_capability `.entitlements` not exist")
# **处理 entitlements End**
def add_dependencies_set(dependency):
if dependency and isinstance(dependency, list):
global dependencies
dependencies = list(set(dependencies+dependency))
def create_podfile(podfile_path, miniversion, app_target_name, target_name):
"""创建一个新的 Podfile 文件"""
print(f"💡 create_podfile {podfile_path} - {target_name}")
with open(podfile_path, 'w') as f:
f.write(f"platform :ios, '{miniversion}'\n")
# if app_target_name != target_name:
# f.write(f"target '{app_target_name}' do\n")
# f.write(f" use_frameworks!\n")
# f.write(f" target '{target_name}' do\n")
# f.write(f" use_frameworks!\n")
# f.write(" end\n")
# f.write("end\n")
# else:
f.write(f"target '{target_name}' do\n")
f.write(f" use_frameworks!\n")
f.write("end\n")
def read_podfile(podfile_path):
"""读取 Podfile 内容"""
with open(podfile_path, 'r') as f:
return f.readlines()
def write_podfile(podfile_path, lines):
"""写入更新后的 Podfile 内容"""
with open(podfile_path, 'w') as f:
f.writelines(lines)
def extract_pod_info(pod_line):
# 正则表达式模式,处理可能的多个空格
# 解释:
# \s* 匹配任意数量的空格包括0个
# '([^']+)' 匹配单引号内的内容(组件名和版本号)
pattern = r"pod\s+'([^']+)'\s*,\s*'([^']+)'"
# 执行匹配
match = re.match(pattern, pod_line.strip())
if match:
# 返回组件名和版本号
return match.group(1), match.group(2)
else:
return None, None
def update_dependencies(lines, app_target_name, target_name, dependencies):
"""更新 Podfile 中的依赖项 - 根据目标名称判断更新方式"""
# 检查 source 信息
source_found = False
# 检查 source 获取方式
if get_sdk_source_method() == 'http':
source_line = f"OSS_HTTP_PATH = '{CUSTOM_OSS_HTTP_PATH}'"
else:
if get_git_access_method() == 'ssh':
source_line = f"source '{SOURCE_LINE}'"
else:
source_line = f"source '{LOCAL_SOURCE_LINE}'"
for i, line in enumerate(lines):
if line.strip() == source_line.strip():
source_found = True
break
# 处理 target_name 和 app_target_name 是否相同的情况
# if app_target_name == target_name:
print(f"🔄 Updating dependencies for target '{target_name}'")
# 直接处理 target_name 闭包
target_found = False
target_index = -1
end_index = -1
# 查找target闭包
for i, line in enumerate(lines):
if f"target '{target_name}' do" in line:
target_found = True
target_index = i
# 在目标的 do 之前插入 source
if not source_found:
lines.insert(i, f'{source_line}\n')
target_index = target_index + 1
break
if not target_found:
print(f" Adding new target '{target_name}'")
lines.append(f"\ntarget '{target_name}' do\n")
lines.append(" use_frameworks!\n")
lines.append("end\n")
target_index = len(lines) - 3
end_index = len(lines) - 1
else:
for j in range(target_index + 1, len(lines)):
if 'end' in lines[j]:
end_index = j
break
# 查找依赖项并更新
existing_deps = [
dep.strip().split(',')[0].strip() for dep in lines[target_index + 1:end_index]
if dep.strip().lower().startswith("pod ")
]
dealDependencies = []
# 处理 http 资源
if get_sdk_source_method() == 'http':
# "pod 'TYWeChatHandle', '1.1.0'"
for dep in dependencies:
podName, podVersion = extract_pod_info(dep)
if podName != None and podVersion != None:
# TODO: 得把test改掉
dealDependencies.append(f"pod '{podName}', :podspec => \"#{{OSS_HTTP_PATH}}/{podName}/test/{podVersion}/{podName}.podspec\"")
else :
dealDependencies = dependencies
new_lines = lines.copy()
for dep in dealDependencies:
dep_name = dep.strip().split(',')[0].strip()
if dep_name and dep_name not in existing_deps:
new_lines.insert(target_index + 1, f" {dep}\n")
end_index += 1
else:
for i in range(len(new_lines)):
if i > target_index and i < end_index:
line = new_lines[i]
if line.strip().startswith('pod ') and line.strip().split(',')[0].strip() == dep_name:
new_lines[i] = f" {dep}\n"
lines[:] = new_lines
return True
# else:
# # 如果 target_name 和 app_target_name 不同,则嵌套 target_name 在 app_target_name 内部
# print(f"🔄 Updating dependencies for target '{target_name}' inside the '{app_target_name}' target.")
# # 处理 app_target_name 闭包
# target_found = False
# app_target_index = -1
# app_end_index = -1
# for i, line in enumerate(lines):
# if f"target '{app_target_name}' do" in line:
# target_found = True
# app_target_index = i
# # 在目标的 do 之前插入 source
# if not source_found:
# lines.insert(i, f'{source_line}\n')
# break
# if not target_found:
# print(f" Adding new target '{app_target_name}'")
# lines.append(f"\ntarget '{app_target_name}' do\n")
# lines.append(" use_frameworks!\n")
# lines.append("end\n")
# app_target_index = len(lines) - 3
# app_end_index = len(lines) - 1
# else:
# for j in range(app_target_index + 1, len(lines)):
# if 'end' in lines[j]:
# app_end_index = j
# break
# # 查找 app_target_name 下的子目标 target_name 的闭包
# child_target_found = False
# child_target_index = -1
# for i, line in enumerate(lines[app_target_index + 1: app_end_index]):
# if f"target '{target_name}' do" in line:
# child_target_found = True
# child_target_index = i + app_target_index + 1
# break
# if not child_target_found:
# print(f" Adding target '{target_name}' inside '{app_target_name}'")
# lines.insert(app_end_index, f"\ntarget '{target_name}' do\n")
# lines.insert(app_end_index + 1, " use_frameworks!\n")
# lines.insert(app_end_index + 2, "end\n")
# child_target_index = app_end_index + 1
# # 在 target_name 的闭包中添加依赖项
# for dep in dependencies:
# lines.insert(child_target_index + 1, f" {dep}\n")
# child_target_index += 1
# return True
def process_podfile(podfile_path, app_target_name, target_name, miniversion, dependencies):
"""处理 Podfile
1. podfile_pathpodfile文件的路径
2. target_name项目名称
3. dependenciespod依赖信息的列表示例 ["pod 'XYSDK'", "pod 'TDKWechatHandle'"]
"""
print(f"process_podfile {podfile_path} - {target_name} - {miniversion} - {dependencies}")
if not os.path.exists(podfile_path):
create_podfile(podfile_path, miniversion, app_target_name, target_name)
lines = read_podfile(podfile_path)
# 更新依赖项
if update_dependencies(lines, app_target_name, target_name, dependencies):
write_podfile(podfile_path, lines)
def install_podfile(project_dir):
# 执行 pod 命令
print("执行 pod deintegrate && pod install")
result = subprocess.run(["pod", "deintegrate"], cwd=project_dir)
if result.returncode != 0:
print("❌ pod deintegrate 失败")
exit(4)
result = subprocess.run(["pod", "install", "--repo-update"], cwd=project_dir)
if result.returncode != 0:
print("❌ pod install 失败")
exit(4)
print("✅ Podfile 处理完成!")
def find_app_target_names(project):
print(f"💡 find_app_targets ")
# 遍历所有的targets找到主工程target
app_targets = []
for target in project.objects.get_targets():
if target.productType == "com.apple.product-type.application":
app_targets.append(target.name)
return app_targets
def copy_bundle_to_main_projet(project, project_path):
print(f"💡 copy_bundle_to_main_projet {project_path}")
pod_source_path = os.path.join(project_path, "Pods")
if os.path.exists(pod_source_path):
bundle_paths = []
bundle_sources = [bundle for bundles in BUNDLE_SOURCE.values() for bundle in bundles]
for root, dirs, files in os.walk(pod_source_path):
folder_name = os.path.basename(root)
if "Pods" in root and root.endswith(".bundle") and folder_name in bundle_sources:
bundle_paths.append(os.path.abspath(root))
target_names = find_app_target_names(project)
print(f"💡 copy_bundle_to_main_projet target_names {target_names}")
for bundle in bundle_paths:
for target_name in target_names:
add_file_to_project(project, bundle, target_name=target_name, skip_if_exsit=False)
project.save()
def add_file_to_embed_frameworks(project, project_path):
print(f"💡 add_file_to_embed_frameworks {project_path}")
pod_source_path = os.path.join(project_path, "Pods")
if os.path.exists(pod_source_path):
embed_framework_paths = []
embed_framework_sources = [framework for frameworks in EMBEM_FRAMEWORK_SOURCE.values() for framework in frameworks]
for root, dirs, files in os.walk(pod_source_path):
folder_name = os.path.basename(root)
if "Pods" in root and (root.endswith(".framework") or root.endswith(".xcframework")) and folder_name in embed_framework_sources:
embed_framework_paths.append(os.path.abspath(root))
target_names = find_app_target_names(project)
print(f"💡 add_file_to_embed_frameworks target_names {embed_framework_paths}")
print(f"💡 add_file_to_embed_frameworks target_names {target_names}")
for framework in embed_framework_paths:
for target_name in target_names:
add_file_to_project(project, framework, target_name=target_name, skip_if_exsit=False)
project.save()
def process_wechat_setting(project,info_plist_path, app_target_name):
print(f"💡 process_wechat_setting ")
wechat_config = build_config.get('login').get('wechat')
if wechat_config.get('wxAppId') and wechat_config.get('wxUniversalLink'):
add_array_to_info_plist(info_plist_path, 'LSApplicationQueriesSchemes', ['weixin','weixinULAPI','weixinURLParamsAPI','wechat'])
url_scheme = {
'CFBundleURLName': 'wx',
'CFBundleURLSchemes': [wechat_config.get('wxAppId')]
}
add_array_to_info_plist(info_plist_path, 'CFBundleURLTypes', [url_scheme])
add_associated_domains_capability(project, wechat_config.get('wxUniversalLink'), app_target_name)
else:
print(f"❌ process_wechat_setting configs are incomplete ")
def process_yidunlivedetect_setting(project,info_plist_path):
print(f"💡 process_yidunlivedetect_setting ")
channel_config = build_config.get('login').get('yidunlivedetect')
if channel_config.get('businessId'):
add_string_to_info_plist(info_plist_path, 'kYiDunLiveDetectBusinessId', channel_config.get('businessId'), False)
if not channel_config.get('NSPhotoLibraryUsageDescription'):
add_string_to_info_plist(info_plist_path, 'NSPhotoLibraryUsageDescription', '相册权限文案')
else:
add_string_to_info_plist(info_plist_path, 'NSPhotoLibraryUsageDescription', channel_config.get('NSPhotoLibraryUsageDescription'))
if not channel_config.get('NSCameraUsageDescription'):
add_string_to_info_plist(info_plist_path, 'NSCameraUsageDescription', '相机权限文案')
else:
add_string_to_info_plist(info_plist_path, 'NSCameraUsageDescription', channel_config.get('NSCameraUsageDescription'))
else:
print(f"❌ process_yidunlivedetect_setting configs are incomplete ")
def process_facebook_setting(project,info_plist_path):
print(f"💡 process_facebook_setting ")
channel_config = build_config.get('login').get('facebook')
if channel_config.get('facebookAppId') and channel_config.get('facebookClientToken') and channel_config.get('facebookDisplayName'):
facebookAppId = channel_config.get('facebookAppId')
add_string_to_info_plist(info_plist_path, 'FacebookAppID', facebookAppId, False)
add_string_to_info_plist(info_plist_path, 'FacebookClientToken', channel_config.get('facebookClientToken'), False)
add_string_to_info_plist(info_plist_path, 'FacebookDisplayName', channel_config.get('facebookDisplayName'), False)
add_array_to_info_plist(info_plist_path, 'LSApplicationQueriesSchemes', ['fb-messenger-share-api','fbapi'])
url_scheme = {
'CFBundleURLName': 'fb',
'CFBundleURLSchemes': [f'fb{facebookAppId}']
}
add_array_to_info_plist(info_plist_path, 'CFBundleURLTypes', [url_scheme])
else:
print(f"❌ process_facebook_setting configs are incomplete ")
def process_google_setting(project,info_plist_path):
print(f"💡 process_google_setting ")
channel_config = build_config.get('login').get('google')
googleiOSClientId = channel_config.get('googleiOSClientId')
if googleiOSClientId:
add_string_to_info_plist(info_plist_path, 'GIDClientID', googleiOSClientId, False)
fanzhuan_google_client_id = ".".join(googleiOSClientId.split(".")[::-1])
url_scheme = {
'CFBundleURLName': 'google',
'CFBundleURLSchemes': [fanzhuan_google_client_id]
}
add_array_to_info_plist(info_plist_path, 'CFBundleURLTypes', [url_scheme])
else:
print(f"❌ process_google_setting configs are incomplete ")
def process_line_setting(project,info_plist_path):
print(f"💡 process_line_setting ")
channel_config = build_config.get('login').get('line')
if channel_config.get('TYLineChannelID') and channel_config.get('TYLineLinkURL'):
add_string_to_info_plist(info_plist_path, 'TYLineChannelID', channel_config.get('TYLineChannelID'), False)
add_string_to_info_plist(info_plist_path, 'TYLineLinkURL', channel_config.get('TYLineLinkURL'), False)
add_array_to_info_plist(info_plist_path, 'LSApplicationQueriesSchemes', ['lineauth2'])
package = build_config.get('package')
url_scheme = {
'CFBundleURLName': 'line',
'CFBundleURLSchemes': [f'line3rdp.{package}']
}
add_array_to_info_plist(info_plist_path, 'CFBundleURLTypes', [url_scheme])
try:
result = subprocess.run(["where", "carthage"], capture_output=True, text=True, check=True)
carthage_path = result.stdout.strip().split("\n")[0]
shell_scrip = f"{carthage_path} copy-frameworks"
target_names = find_app_target_names(project)
add_shell_script(project, shell_scrip, target_name=target_names)
except subprocess.CalledProcessError:
print(f"❌ process_line_setting Carthage not exist ")
exit(1)
else:
print(f"❌ process_line_setting configs are incomplete ")
def process_twitter_setting(project,info_plist_path):
print(f"💡 process_twitter_setting ")
channel_config = build_config.get('login').get('twitter')
if channel_config.get('twitterClientid') and channel_config.get('twitterSpoce'):
add_string_to_info_plist(info_plist_path, 'TYTwitterClientid', channel_config.get('twitterClientid'), False)
add_array_to_info_plist(info_plist_path, 'TYTwitterSpoce', list(channel_config.get('twitterSpoce')))
else:
print(f"❌ process_twitter_setting configs are incomplete ")
def process_rongheguiyin_setting(project, info_plist_path):
channel_config = build_config.get('login').get('rongheguiyin')
url_scheme = {
'CFBundleURLName': 'rongheguiyin',
'CFBundleURLSchemes': [build_config.get('package')]
}
add_array_to_info_plist(info_plist_path, 'CFBundleURLTypes', [url_scheme])
if channel_config and 'RongHeGuiYinStrategy' in channel_config:
add_bool_to_info_plist(info_plist_path, "RongHeGuiYinStrategy", channel_config.get('RongHeGuiYinStrategy'), False)
def process_aihelp_setting(project, info_plist_path):
channel_config = build_config.get('login').get('aihelp')
if channel_config.get('TYAIHelpAppID') and channel_config.get('TYAIHelpDomainName') and channel_config.get('TYAIHelpLanguage'):
add_string_to_info_plist(info_plist_path, 'TYAIHelpAppID', channel_config.get('TYAIHelpAppID'), False)
add_string_to_info_plist(info_plist_path, 'TYAIHelpDomainName', channel_config.get('TYAIHelpDomainName'), False)
add_string_to_info_plist(info_plist_path, 'TYAIHelpLanguage', channel_config.get('TYAIHelpLanguage'), False)
add_string_to_info_plist(info_plist_path, 'NSPhotoLibraryUsageDescription', channel_config.get('NSPhotoLibraryUsageDescription'), False)
add_bool_to_info_plist(info_plist_path, 'PHPhotoLibraryPreventAutomaticLimitedAccessAlert', channel_config.get('PHPhotoLibraryPreventAutomaticLimitedAccessAlert'), False)
else:
print(f"❌ process_aihelp_setting configs are incomplete ")
def process_bugly_setting(project, info_plist_path):
channel_config = build_config.get('login').get('bugly')
if channel_config.get('BuglyAppID'):
add_string_to_info_plist(info_plist_path, 'BuglyAppID', channel_config.get('BuglyAppID'), False)
else:
print(f"❌ process_bugly_setting configs are incomplete ")
def get_info_plist_path(project_path, target_name):
path = os.path.join(project_path, f'Info.plist')
if os.path.exists(path):
info_plist_path = path
else:
path = os.path.join(project_path, f'{target_name}/Info.plist')
if os.path.exists(path):
info_plist_path = path
print(f"💡 get_info_plist_path {info_plist_path}")
return info_plist_path
def process_project_setting(project_path, project_name, miniversion, target_name):
print("2⃣ process_project_setting")
project_pbxproj_path = os.path.join(project_path, f'{project_name}/project.pbxproj')
# 工程
project = XcodeProject.load(project_pbxproj_path)
# plist文件
info_plist_path = get_info_plist_path(project_path, target_name)
target_names = find_app_target_names(project)
if len(target_names) != 0:
app_target_name = target_names[0]
else:
app_target_name = None
# 基础设置: 钥匙串 apple登录 applink C++兼容 swift
add_file_to_project(project, coustom_plist_file_path, skip_if_exsit=False)
project.add_other_ldflags(['$(inherited)', '-ObjC', '-all_load'])
add_sign_in_with_apple_capability(project, app_target_name)
set_library_search_paths(project, [])
# add_keychain_capability(project, app_target_name)
# 遍历设置每一个渠道所需信息
print(f"2⃣ process_project_setting {build_sdk_names_list}")
for channel_name in build_sdk_names_list:
if channel_name in CHANNEL_AND_NAME_LIST:
if channel_name == "fcm" or channel_name == "push":
print(f"💡 process_{channel_name}_setting ")
channel_config = build_config.get(channel_name)
add_dependencies_set(channel_config.get('podDependencies'))
if channel_name == "push":
add_notification_capability(project, app_target_name)
add_background_modes_capability(info_plist_path)
else:
channel_config = build_config.get('login').get(channel_name)
add_dependencies_set(channel_config.get('podDependencies'))
if channel_name == "wechat":
process_wechat_setting(project, info_plist_path, app_target_name)
elif channel_name == "wangyiyidun" or channel_name == "yidunloginv2":
if channel_config.get('unionSpecialLogo'):
union_special_logo_path = os.path.join(project_path, 'union_special_logo.png')
add_file_to_project(project, union_special_logo_path, skip_if_exsit=False)
project.add_other_ldflags(['$(inherited)', '-fprofile-instr-generate'])
elif channel_name == "yidunzhiwen":
add_string_to_info_plist(info_plist_path, 'kYiDunDeviceBusinessId', channel_config.get('businessId'), False)
elif channel_name == "yiduncaptcha":
add_string_to_info_plist(info_plist_path, 'kYiDunCaptchaBusinessId', channel_config.get('businessId'), False)
if channel_config.get('kYiDunCaptchaCloseBtn'):
add_string_to_info_plist(info_plist_path, 'kYiDunCaptchaCloseBtn', "1", False)
elif channel_name == "yidunlivedetect":
process_yidunlivedetect_setting(project, info_plist_path)
elif channel_name == "appsflyer":
add_string_to_info_plist(info_plist_path, 'TYAppsFlyerAppleAppId', channel_config.get('appsFlyerAppleAppId'), False)
add_string_to_info_plist(info_plist_path, 'TYAppsFlyerDevkey', channel_config.get('appsFlyerDevkey'), False)
elif channel_name == "firebaseanalytics":
google_plist_path = os.path.join(project_path, 'GoogleService-Info.plist')
add_file_to_project(project, google_plist_path, skip_if_exsit=False)
elif channel_name == "facebook":
process_facebook_setting(project, info_plist_path)
elif channel_name == "google":
process_google_setting(project, info_plist_path)
elif channel_name == "line":
process_line_setting(project, info_plist_path)
elif channel_name == "twitter":
process_twitter_setting(project, info_plist_path)
elif channel_name == "rongheguiyin":
process_rongheguiyin_setting(project, info_plist_path)
elif channel_name == "douyin":
douyin_config_path = os.path.join(project_path, 'UOPSDKConfig.json')
add_file_to_project(project, douyin_config_path, skip_if_exsit=False)
elif channel_name == "aihelp":
process_aihelp_setting(project, info_plist_path)
elif channel_name == "bugly":
process_bugly_setting(project, info_plist_path)
elif channel_name == "firebasecrashlytics":
input_files = [
'${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}',
'$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)'
]
shell_scrip = '"$SRCROOT/Pods/FirebaseCrashlyticsSDK/run"'
target_names = find_app_target_names(project)
print(f'✅ target_namestarget_namestarget_names = {target_names}')
add_shell_script(project, shell_scrip, target_name=target_names, input_files=input_files)
project.set_flags('DEBUG_INFORMATION_FORMAT', 'dwarf-with-dsym')
elif channel_name == "firebaseodm":
add_bool_to_info_plist(info_plist_path, 'kFirebaseODM', True, False)
project.save()
# 处理pod文件并install
podfile_path = os.path.join(project_path, "Podfile")
add_dependencies_set(build_config.get('tuyooParam').get('podDependencies'))
process_podfile(podfile_path, app_target_name, target_name, miniversion, dependencies)
install_podfile(project_path)
if app_target_name and app_target_name != target_name:
copy_bundle_to_main_projet(project, project_path)
add_file_to_embed_frameworks(project, project_path)
install_podfile(project_path)
if __name__ == "__main__":
print(f'✅ input info {argparse}')
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument('--configFile', type=str, required=True, help='build config json path')
parser.add_argument('--workspace', type=str, required=True, help='export ipa project path')
parser.add_argument('--minos', type=str, required=True, help='miniversion')
parser.add_argument('--targetName', type=str, help='target_name')
args = parser.parse_args()
print(f"args: {args}")
if args.configFile:
build_config_json_path = args.configFile
else:
print('❌ config json path not set')
exit(1)
if args.workspace:
export_ipa_project_path = args.workspace
if not export_ipa_project_path or not os.path.isdir(export_ipa_project_path):
print('❌ project path not set')
exit(1)
xcodeproj_path = ''
project_name = ''
for file in os.listdir(export_ipa_project_path):
xcodeproj_path = os.path.join(export_ipa_project_path, file)
if os.path.exists(xcodeproj_path) and xcodeproj_path.endswith('.xcodeproj'):
project_name = os.path.basename(xcodeproj_path)
print(f"✅ project 文件存在: {project_name} - {xcodeproj_path}")
break
if args.minos:
miniversion = args.minos
if args.targetName:
target_name = args.targetName
if not miniversion:
miniversion = IOSMINIVERSION
if not target_name:
target_name = target_name = os.path.splitext(project_name)[0]
print(f"✅ 打包基础信息:\n build_config_json_path - {build_config_json_path} \n export_ipa_project_path - {export_ipa_project_path} \n project_name - {project_name} \n miniversion - {miniversion} \n target_name - {target_name}")
if os.path.exists(xcodeproj_path) and project_name != '':
# 解析配置信息
costom_plist_file_path = os.path.join(export_ipa_project_path, 'EngineSdkBaseInfo.plist')
parse_build_config_json(build_config_json_path, costom_plist_file_path)
# SDK+渠道配置
process_project_setting(export_ipa_project_path, project_name, miniversion, target_name)
else:
print('❌ xcodeproj file not exist')
exit(1)

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 687db4b74404e453abf9203b736952a3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,69 @@
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
namespace EngineSdkConverter.Unity.Editor
{
public class TYPostProcessiOS
{
const string TAG = "TYPostProcessiOS OnPostProcessBuild ";
const string ENGINE_SDK_CONVERTER_RESOURCE_FROM_UNITY_RELATIVE_PATH = "EngineSdkConverter/Unity/Editor/iOS";
const string ENGINE_SDK_CONVERTER_PLUGINS_FROM_UNITY_RELATIVE_PATH = "EngineSdkConverter/Unity/Plugins/iOS";
const string ENGINE_SDK_CONVERTER_PYTHON_PACKAGE_SITE_PATH = "EngineSdkConverter/Unity/Plugins/iOS/python_sites";
const string GAME_BUILD_CONFIG_FILE_PATH = "gameConfigs";
const string GAME_BUILD_CONFIG_FILE_NAME = "gameconfig.json";
const string UNION_SPECIAL_LOGO = "union_special_logo.png";
// iOSSDK资源-脚本文件名称
const string CUSTOMIZE_SCRIPT_FILE_NAME = "EngineSdkiOSBuildProcess.py";
// 项目Unity Traget Name
const string UNITY_TARGET_NAME = "Unity-iPhone";
const string UNITY_FRAMEWORK_TARGET_NAME = "UnityFramework";
[PostProcessBuild(49)]
public static void OnPostProcessBuild(BuildTarget buildTarget, string path)
{
Debug.Log(TAG + " start " + path);
if (buildTarget == BuildTarget.iOS)
{
Debug.Log(TAG + "start");
// 移动脚本/配置 - 运行脚本
string resourceOfUnityPluginsPath = Path.Combine(Application.dataPath, ENGINE_SDK_CONVERTER_RESOURCE_FROM_UNITY_RELATIVE_PATH);
string pythonPackageSitePath = Path.Combine(Application.dataPath, ENGINE_SDK_CONVERTER_PYTHON_PACKAGE_SITE_PATH);
string pluginsPath = Path.Combine(Application.dataPath, ENGINE_SDK_CONVERTER_PLUGINS_FROM_UNITY_RELATIVE_PATH);
string unionSpecialLogoPath = Path.Combine(pluginsPath, UNION_SPECIAL_LOGO);
string targetUnionSpecialLogoPath = Path.Combine(path, UNION_SPECIAL_LOGO);
File.Copy(unionSpecialLogoPath, targetUnionSpecialLogoPath, true);
string customScriptPath = Path.Combine(resourceOfUnityPluginsPath, CUSTOMIZE_SCRIPT_FILE_NAME);
string targetScriptPath = Path.Combine(path, CUSTOMIZE_SCRIPT_FILE_NAME);
File.Copy(customScriptPath, targetScriptPath, true);
// 资源
string customGameConfigPath = Path.Combine(resourceOfUnityPluginsPath, GAME_BUILD_CONFIG_FILE_PATH);
string targetGameConfigPath = path;
EngineSdkConverterUtils.CopyDirectory(customGameConfigPath, targetGameConfigPath, true);
EngineSdkConverterUtils.CopyDirectory(pythonPackageSitePath, targetGameConfigPath, true);
string targetConfigPath = Path.Combine(path, GAME_BUILD_CONFIG_FILE_NAME);
TryRunBuildScript(path, targetScriptPath, targetConfigPath);
}
}
static void TryRunBuildScript(string workspace, string scriptFilePath, string configFilePath)
{
Debug.Log(TAG + " TryRunBuildScript start " + workspace + " " + scriptFilePath);
string iosMinOSVersion = PlayerSettings.iOS.targetOSVersionString;
string arguments = $"--configFile \"{configFilePath}\" --workspace \"{workspace}\" --minos \"{iosMinOSVersion}\" --targetName \"{UNITY_FRAMEWORK_TARGET_NAME}\"";
Debug.Log(TAG + $"EngineSDKConverter RunPython arguments :{arguments} ");
Result buildResult = EngineSdkConverterUtils.RunPython(scriptFilePath, arguments, workspace);
Debug.Log(TAG + $"EngineSDKConverter buildResult error :{buildResult.ExitCode} ");
Debug.Log(TAG + $"EngineSDKConverter buildResult error :{buildResult.Message} ");
Debug.Log(TAG + "TryRunBuildScript finish");
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3c05b2395d8b1438e9a2340e07356dff
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df2ae868d776f465c971b79b02356948
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bc6ad16c05bd04a12a8726fed4ef7a5b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6d4cdd383393d49448f34dc594d8d244
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3cbd9f85438a64df39f96a750daa1685
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,228 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
var TuyooSdk;
if (channelTypeFromCS == "ali.cn.minigame") {
TuyooSdk = require("./tuyoosdk_aliminigame_1.0.4.250915_release.js");
}
window.TuyooSdk = TuyooSdk;
},
InitToBridge: function (initEventInfo) {
try {
var initCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "InitResult", callbackString);
}
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
var tyInitParams = {};
tyInitParams.appId = initInfo.tuyooParam.appId;
tyInitParams.gameId = initInfo.tuyooParam.gameId;
tyInitParams.pay_version = "hall37";
tyInitParams.baseurl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
tyInitParams.bi_base_url = "https://cbi.tuyoo.com/";
tyInitParams.cloudId = initInfo.tuyooParam.cloudId;
tyInitParams.packageName = initInfo.package;
tyInitParams.clientId = initInfo.tuyooParam.clientId;
tyInitParams.ali_appId = initInfo.login.aliminigame.ali_appId;
console.log("initInfo: " + JSON.stringify(initInfo));
window.TuyooSdk.OnInit(initInfo.tuyooParam.channelType, tyInitParams, initCallback, this);
} catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
window.TuyooSdk.baseuri = (serverUrlFromCS.substring(serverUrlFromCS.length - 1) === '/') ? serverUrlFromCS.substring(0, serverUrlFromCS.length - 1) : serverUrlFromCS;
console.log("update serverUrl to: " + window.TuyooSdk.baseuri);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackResult = {
code: code,
result: result && result.logindata ? result.logindata : result,
error: error
};
var callbackString = JSON.stringify(callbackResult);
SendMessage("NativeCallBack", "LoginResult", callbackString);
}
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var loginInfo = JSON.parse(loginInfoFromCS);
var tyLoginParams = {};
if (loginInfo.loginType) {
tyLoginParams.ChannelType = loginInfo.loginType;
}
if (loginInfo.extraParams) {
var extraParams = JSON.parse(loginInfo.extraParams);
tyLoginParams.extraParams = extraParams;
}
console.log("tyLoginParams: " + JSON.stringify(tyLoginParams));
window.TuyooSdk.Login(tyLoginParams, loginCallback, this);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.ChargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
tyPayParams.extraParams = extraParams;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
window.TuyooSdk.Pay(tyPayParams, payCallback, this);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
shareInfoToJs.callback = shareCallback;
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
window.TuyooSdk.SetDefaultShareInfo(shareInfoToJs);
} catch (e) {
console.error("SetShareInfoToBridge catch error: " + e);
}
},
ShareToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
window.TuyooSdk.Share(shareInfoToJs, shareCallback);
} catch (e) {
console.error("ShareToBridge catch error: " + e);
}
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
window.TuyooSdk.bi.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
window.TuyooSdk.bi.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function (shareEventInfo) {
console.error("current channel not support GetShareInfo function");
},
GetAdInfoBridge: function () {
console.error("current channel not support GetAdInfo function");
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
console.error("current channel not support TxAdSDKReport function");
},
CheckBindToBridge: function (bindEventInfo) {
console.error("current channel not support CheckBind function");
},
SendSmsCodeToBridge: function (loginEventInfo) {
console.error("current channel not support SendSmsCode function");
},
BindToBridge: function (bindEventInfo) {
console.error("current channel not support Bind function");
},
SetWxUserInfoToBridge: function (type, userInfo) {
console.error("current channel not support SetWxUserInfo function");
},
GetDeviceLevelToBridge: function() {
try {
var callback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "GetDeviceLevelResult", callbackString);
}
window.TuyooSdk.getDeviceBenchmarkLevel(callback, this);
} catch (error) {
console.error("GetDeviceLevelToBridge catch error: " + error);
}
},
CreatGridGamePanelToBridge: function(gridGameModule) {
console.error("current channel not support CreatGridGamePanel function");
},
ShowGridGamePanelToBridge: function(panelId) {
console.error("current channel not support ShowGridGamePanel function");
},
HideGridGamePanelToBridge: function(panelId) {
console.error("current channel not support HideGridGamePanel function");
},
DestroyGridGamePanelToBridge: function(panelId) {
console.error("current channel not support DestroyGridGamePanel function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9ba02a912db5c43fe8d5e99add46e7e0
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b5a72e3fac2214d22b1626dcba46ba35
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8778c3a0c2fd54bd79e6da7000b3f202
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,300 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
},
InitToBridge: function (initEventInfo) {
try {
var initCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "InitResult", callbackString);
}
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
var tyInitParams = {};
tyInitParams.appId = initInfo.tuyooParam.appId;
tyInitParams.gameId = initInfo.tuyooParam.gameId;
tyInitParams.pay_version = "hall37";
tyInitParams.baseurl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
tyInitParams.bi_base_url = "https://cbi.tuyoo.com/";
tyInitParams.cloudId = initInfo.tuyooParam.cloudId;
tyInitParams.packageName = initInfo.package;
tyInitParams.clientId = initInfo.tuyooParam.clientId;
tyInitParams.jingdongAppId = initInfo.login.jingdongminigame.jingdongAppId;
console.log("initInfo: " + JSON.stringify(initInfo));
if (initInfo.login.jingdongminigame.packageType === "wasmsplit" && GameGlobal.tywx) {
GameGlobal.tywx.StateInfo.debugMode = initInfo.debug.toLowerCase() === "true";
GameGlobal.tywx.SystemInfo.loginUrl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
GameGlobal.tywx.SystemInfo.clientId = initInfo.tuyooParam.clientId;
GameGlobal.tywx.SystemInfo.cloudId = initInfo.tuyooParam.cloudId;
GameGlobal.tywx.SystemInfo.appId = initInfo.tuyooParam.appId;
GameGlobal.tywx.SystemInfo.gameId = initInfo.tuyooParam.gameId;
GameGlobal.tywx.SystemInfo.wxAppId = initInfo.login.tywx.wx_appId;
GameGlobal.tywx.SystemInfo.packageName = initInfo.package;
}
GameGlobal.TuyooSdk.OnInit(initInfo.tuyooParam.channelType, tyInitParams, initCallback, this);
} catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
window.TuyooSdk.baseuri = (serverUrlFromCS.substring(serverUrlFromCS.length - 1) === '/') ? serverUrlFromCS.substring(0, serverUrlFromCS.length - 1) : serverUrlFromCS;
console.log("update serverUrl to: " + window.TuyooSdk.baseuri);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackResult = {
code: code,
result: result && result.logindata ? result.logindata : result,
error: error
};
var callbackString = JSON.stringify(callbackResult);
SendMessage("NativeCallBack", "LoginResult", callbackString);
}
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var loginInfo = JSON.parse(loginInfoFromCS);
if (loginInfo.loginType === "wx.cn.minigame" && GameGlobal.tywx) {
GameGlobal.tywx.TuyooSDK.login(loginCallback);
return;
}
var tyLoginParams = {};
if (loginInfo.loginType) {
tyLoginParams.ChannelType = loginInfo.loginType;
}
if (loginInfo.extraParams) {
var extraParams = JSON.parse(loginInfo.extraParams);
tyLoginParams.extraParams = extraParams;
}
console.log("tyLoginParams: " + JSON.stringify(tyLoginParams));
GameGlobal.TuyooSdk.Login(tyLoginParams, loginCallback, this);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.ChargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
if(extraParams.jingdongCurrency) {
tyPayParams.jingdongCurrency = extraParams.jingdongCurrency;
delete extraParams.jingdongCurrency;
}
tyPayParams.extraParams = extraParams;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
GameGlobal.TuyooSdk.Pay(tyPayParams, payCallback, this);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
var tyShareParams = {};
shareInfoToJs.title && (tyShareParams.title = shareInfoToJs.title);
shareInfoToJs.imageUrl && (tyShareParams.imageUrl = shareInfoToJs.imageUrl);
shareInfoToJs.desc && (tyShareParams.desc = shareInfoToJs.desc);
shareInfoToJs.type && (tyShareParams.type = shareInfoToJs.type);
if(shareInfoToJs.extraParams) {
var extraParams = JSON.parse(shareInfoToJs.extraParams);
if(extraParams.channel) {
tyShareParams.channel = extraParams.channel;
delete extraParams.channel;
}
if(extraParams.url) {
tyShareParams.url = extraParams.url;
delete extraParams.url;
}
if(extraParams.keyShareChannel) {
tyShareParams.keyShareChannel = extraParams.keyShareChannel;
delete extraParams.keyShareChannel;
}
if(extraParams.localImageUrl) {
tyShareParams.localImageUrl = extraParams.localImageUrl;
delete extraParams.localImageUrl;
}
if(extraParams.onlineImageUrl) {
tyShareParams.onlineImageUrl = extraParams.onlineImageUrl;
delete extraParams.onlineImageUrl;
}
tyShareParams.extraParams = extraParams;
}
tyShareParams.callback = shareCallback;
console.log("tyShareParams: " + JSON.stringify(tyShareParams));
GameGlobal.TuyooSdk.SetDefaultShareInfo(tyShareParams);
} catch (e) {
console.error("SetShareInfoToBridge catch error: " + e);
}
},
ShareToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
var tyShareParams = {};
shareInfoToJs.title && (tyShareParams.title = shareInfoToJs.title);
shareInfoToJs.imageUrl && (tyShareParams.imageUrl = shareInfoToJs.imageUrl);
shareInfoToJs.desc && (tyShareParams.desc = shareInfoToJs.desc);
shareInfoToJs.type && (tyShareParams.type = shareInfoToJs.type);
if(shareInfoToJs.extraParams) {
var extraParams = JSON.parse(shareInfoToJs.extraParams);
if(extraParams.channel) {
tyShareParams.channel = extraParams.channel;
delete extraParams.channel;
}
if(extraParams.url) {
tyShareParams.url = extraParams.url;
delete extraParams.url;
}
if(extraParams.keyShareChannel) {
tyShareParams.keyShareChannel = extraParams.keyShareChannel;
delete extraParams.keyShareChannel;
}
if(extraParams.localImageUrl) {
tyShareParams.localImageUrl = extraParams.localImageUrl;
delete extraParams.localImageUrl;
}
if(extraParams.onlineImageUrl) {
tyShareParams.onlineImageUrl = extraParams.onlineImageUrl;
delete extraParams.onlineImageUrl;
}
tyShareParams.extraParams = extraParams;
}
console.log("tyShareParams: " + JSON.stringify(tyShareParams));
GameGlobal.TuyooSdk.Share(tyShareParams, shareCallback);
} catch (e) {
console.error("ShareToBridge catch error: " + e);
}
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
GameGlobal.TuyooSdk.bi.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
GameGlobal.TuyooSdk.bi.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function (shareEventInfo) {
console.error("current channel not support GetShareInfo function");
},
GetAdInfoBridge: function () {
console.error("current channel not support GetAdInfo function");
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
console.error("current channel not support TxAdSDKReport function");
},
CheckBindToBridge: function (bindEventInfo) {
console.error("current channel not support CheckBind function");
},
SendSmsCodeToBridge: function (loginEventInfo) {
console.error("current channel not support SendSmsCode function");
},
BindToBridge: function (bindEventInfo) {
console.error("current channel not support Bind function");
},
SetWxUserInfoToBridge: function (type, userInfo) {
console.error("current channel not support SetWxUserInfo function");
},
GetDeviceLevelToBridge: function() {
// try {
// var callback = function (code, result, error) {
// var callbackString = JSON.stringify({ code, result, error });
// SendMessage("NativeCallBack", "GetDeviceLevelResult", callbackString);
// }
// GameGlobal.TuyooSdk.getDeviceBenchmarkLevel(callback, this);
// } catch (error) {
// console.error("GetDeviceLevelToBridge catch error: " + error);
// }
console.error("current channel not support GetDeviceLevelToBridge function");
},
CreatGridGamePanelToBridge: function(gridGameModule) {
console.error("current channel not support CreatGridGamePanel function");
},
ShowGridGamePanelToBridge: function(panelId) {
console.error("current channel not support ShowGridGamePanel function");
},
HideGridGamePanelToBridge: function(panelId) {
console.error("current channel not support HideGridGamePanel function");
},
DestroyGridGamePanelToBridge: function(panelId) {
console.error("current channel not support DestroyGridGamePanel function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5c3c4c83df2cf42639069d6e1e3bf76f
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 68b516af9e39e473891535f4e764041a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 786cf4d95c48b4dbfacc52cdd9831796
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,170 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
},
InitToBridge: function (initEventInfo) {
try {
var initCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "InitResult", callbackString);
}
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
var tyInitParams = {};
tyInitParams.appId = initInfo.tuyooParam.appId;
tyInitParams.gameId = initInfo.tuyooParam.gameId;
tyInitParams.pay_version = "hall37";
tyInitParams.baseurl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
tyInitParams.bi_base_url = "https://cbi.tuyoo.com/";
tyInitParams.cloudId = initInfo.tuyooParam.cloudId;
tyInitParams.packageName = initInfo.package;
tyInitParams.clientId = initInfo.tuyooParam.clientId;
tyInitParams.kuaishou_appId = initInfo.login.kuaishouminigame.kuaishouAppId;
console.log("initInfo: " + JSON.stringify(initInfo));
GameGlobal.TuyooSdk.OnInit(initInfo.tuyooParam.channelType, tyInitParams, initCallback, this);
} catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
GameGlobal.TuyooSdk.baseuri = (serverUrlFromCS.substring(serverUrlFromCS.length - 1) === '/') ? serverUrlFromCS.substring(0, serverUrlFromCS.length - 1) : serverUrlFromCS;
console.log("update serverUrl to: " + window.TuyooSdk.baseuri);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackResult = {
code: code,
result: result && result.logindata ? result.logindata : result,
error: error
};
var callbackString = JSON.stringify(callbackResult);
SendMessage("NativeCallBack", "LoginResult", callbackString);
}
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var loginInfo = JSON.parse(loginInfoFromCS);
var tyLoginParams = {};
if (loginInfo.loginType) {
tyLoginParams.ChannelType = loginInfo.loginType;
}
if (loginInfo.extraParams) {
var extraParams = JSON.parse(loginInfo.extraParams);
tyLoginParams.extraParams = extraParams;
}
console.log("tyLoginParams: " + JSON.stringify(tyLoginParams));
GameGlobal.TuyooSdk.Login(tyLoginParams, loginCallback, this);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.ChargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
tyPayParams.extraParams = extraParams;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
GameGlobal.TuyooSdk.Pay(tyPayParams, payCallback, this);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
console.error("current channel not support SetShareInfo function");
},
ShareToBridge: function (shareEventInfo) {
console.error("current channel not support Share function");
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
GameGlobal.TuyooSdk.bi.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
GameGlobal.TuyooSdk.bi.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function () {
console.error("current channel not support GetShareInfo function");
},
GetAdInfoBridge: function () {
console.error("current channel not support GetAdInfo function");
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
console.error("current channel not support TxAdSDKReport function");
},
CheckBindToBridge: function (bindEventInfo) {
console.error("current channel not support CheckBind function");
},
SendSmsCodeToBridge: function (loginEventInfo) {
console.error("current channel not support SendSmsCode function");
},
BindToBridge: function (bindEventInfo) {
console.error("current channel not support Bind function");
},
SetWxUserInfoToBridge: function (type, userInfo) {
console.error("current channel not support SetWxUserInfo function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1bdda16891c2c4b19a48cb96f19c4a6f
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
<linker>
<assembly fullname="com.tuyoo.unitysdk.plugin">
<type fullname="EngineSdkConverter.Unity.Plugins.WebGL.ConfigData" preserve="all"/>
<type fullname="EngineSdkConverter.Unity.Plugins.WebGL.TuyooParam" preserve="all"/>
<type fullname="EngineSdkConverter.Unity.Plugins.WebGL.Login" preserve="all"/>
<type fullname="EngineSdkConverter.Unity.Plugins.WebGL.KuaishouMinigame" preserve="all"/>
</assembly>
</linker>

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 3c56e51a2563d47bb9e7e1fb87018692
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e0a150155a395461ca774ce51de60925
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 558202106df2546b6ae11a5ae152cef2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,224 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
},
InitToBridge: function (initEventInfo) {
try {
var initCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "InitResult", callbackString);
}
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
var tyInitParams = {};
tyInitParams.appId = initInfo.tuyooParam.appId;
tyInitParams.gameId = initInfo.tuyooParam.gameId;
tyInitParams.pay_version = "hall37";
tyInitParams.baseurl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
tyInitParams.bi_base_url = "https://cbi.tuyoo.com/";
tyInitParams.cloudId = initInfo.tuyooParam.cloudId;
tyInitParams.packageName = initInfo.package;
tyInitParams.clientId = initInfo.tuyooParam.clientId;
tyInitParams.meituan_appId = initInfo.login.meituanminigame.meituanAppId;
console.log("initInfo: " + JSON.stringify(initInfo));
window.TuyooSdk.OnInit(initInfo.tuyooParam.channelType, tyInitParams, initCallback, this);
} catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
window.TuyooSdk.baseuri = (serverUrlFromCS.substring(serverUrlFromCS.length - 1) === '/') ? serverUrlFromCS.substring(0, serverUrlFromCS.length - 1) : serverUrlFromCS;
console.log("update serverUrl to: " + window.TuyooSdk.baseuri);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackResult = {
code: code,
result: result && result.logindata ? result.logindata : result,
error: error
};
var callbackString = JSON.stringify(callbackResult);
SendMessage("NativeCallBack", "LoginResult", callbackString);
}
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var loginInfo = JSON.parse(loginInfoFromCS);
var tyLoginParams = {};
if (loginInfo.loginType) {
tyLoginParams.ChannelType = loginInfo.loginType;
}
if (loginInfo.extraParams) {
var extraParams = JSON.parse(loginInfo.extraParams);
tyLoginParams.extraParams = extraParams;
}
console.log("tyLoginParams: " + JSON.stringify(tyLoginParams));
window.TuyooSdk.Login(tyLoginParams, loginCallback, this);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.ChargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
tyPayParams.extraParams = extraParams;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
window.TuyooSdk.Pay(tyPayParams, payCallback, this);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
shareInfoToJs.callback = shareCallback;
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
window.TuyooSdk.SetDefaultShareInfo(shareInfoToJs);
} catch (e) {
console.error("SetShareInfoToBridge catch error: " + e);
}
},
ShareToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var shareInfoToJs = shareInfo.resource;
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
window.TuyooSdk.Share(shareInfoToJs, shareCallback);
} catch (e) {
console.error("ShareToBridge catch error: " + e);
}
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
window.TuyooSdk.bi.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
window.TuyooSdk.bi.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function (shareEventInfo) {
console.error("current channel not support GetShareInfo function");
},
GetAdInfoBridge: function () {
console.error("current channel not support GetAdInfo function");
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
console.error("current channel not support TxAdSDKReport function");
},
CheckBindToBridge: function (bindEventInfo) {
console.error("current channel not support CheckBind function");
},
SendSmsCodeToBridge: function (loginEventInfo) {
console.error("current channel not support SendSmsCode function");
},
BindToBridge: function (bindEventInfo) {
console.error("current channel not support Bind function");
},
SetWxUserInfoToBridge: function (type, userInfo) {
console.error("current channel not support SetWxUserInfo function");
},
GetDeviceLevelToBridge: function() {
// try {
// var callback = function (code, result, error) {
// var callbackString = JSON.stringify({ code, result, error });
// SendMessage("NativeCallBack", "GetDeviceLevelResult", callbackString);
// }
// window.TuyooSdk.getDeviceBenchmarkLevel(callback, this);
// } catch (error) {
// console.error("GetDeviceLevelToBridge catch error: " + error);
// }
console.error("current channel not support GetDeviceLevelToBridge function");
},
CreatGridGamePanelToBridge: function(gridGameModule) {
console.error("current channel not support CreatGridGamePanel function");
},
ShowGridGamePanelToBridge: function(panelId) {
console.error("current channel not support ShowGridGamePanel function");
},
HideGridGamePanelToBridge: function(panelId) {
console.error("current channel not support HideGridGamePanel function");
},
DestroyGridGamePanelToBridge: function(panelId) {
console.error("current channel not support DestroyGridGamePanel function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 271e924d713444a5c870cb92ec5f7e4c
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c5ae2508677d34e3a8905d1f385f0ec3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a5423a6658141421e99e082908eb26d6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,213 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
},
InitToBridge: function (initEventInfo) {
try {
var initCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "InitResult", callbackString);
}
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
var tyInitParams = {};
tyInitParams.appId = initInfo.tuyooParam.appId;
tyInitParams.gameId = initInfo.tuyooParam.gameId;
tyInitParams.pay_version = "hall37";
tyInitParams.baseurl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
tyInitParams.bi_base_url = "https://cbi.tuyoo.com/";
tyInitParams.cloudId = initInfo.tuyooParam.cloudId;
tyInitParams.packageName = initInfo.package;
tyInitParams.clientId = initInfo.tuyooParam.clientId;
tyInitParams.oppo_appId = initInfo.login.oppominigame.oppoAppId;
console.log("initInfo: " + JSON.stringify(initInfo));
if (initInfo.login.oppominigame.packageType === "wasmsplit" && GameGlobal.tywx) {
GameGlobal.tywx.StateInfo.debugMode = initInfo.debug.toLowerCase() === "true";
GameGlobal.tywx.SystemInfo.loginUrl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
GameGlobal.tywx.SystemInfo.clientId = initInfo.tuyooParam.clientId;
GameGlobal.tywx.SystemInfo.cloudId = initInfo.tuyooParam.cloudId;
GameGlobal.tywx.SystemInfo.appId = initInfo.tuyooParam.appId;
GameGlobal.tywx.SystemInfo.gameId = initInfo.tuyooParam.gameId;
GameGlobal.tywx.SystemInfo.wxAppId = initInfo.login.tywx.wx_appId;
GameGlobal.tywx.SystemInfo.packageName = initInfo.package;
}
GameGlobal.TuyooSdk.OnInit(initInfo.tuyooParam.channelType, tyInitParams, initCallback, this);
} catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
window.TuyooSdk.baseuri = (serverUrlFromCS.substring(serverUrlFromCS.length - 1) === '/') ? serverUrlFromCS.substring(0, serverUrlFromCS.length - 1) : serverUrlFromCS;
console.log("update serverUrl to: " + window.TuyooSdk.baseuri);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackResult = {
code: code,
result: result && result.logindata ? result.logindata : result,
error: error
};
var callbackString = JSON.stringify(callbackResult);
SendMessage("NativeCallBack", "LoginResult", callbackString);
}
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var loginInfo = JSON.parse(loginInfoFromCS);
if (loginInfo.loginType === "wx.cn.minigame" && GameGlobal.tywx) {
GameGlobal.tywx.TuyooSDK.login(loginCallback);
return;
}
var tyLoginParams = {};
if (loginInfo.loginType) {
tyLoginParams.ChannelType = loginInfo.loginType;
}
if (loginInfo.extraParams) {
var extraParams = JSON.parse(loginInfo.extraParams);
tyLoginParams.extraParams = extraParams;
}
console.log("tyLoginParams: " + JSON.stringify(tyLoginParams));
GameGlobal.TuyooSdk.Login(tyLoginParams, loginCallback, this);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.ChargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
tyPayParams.extraParams = extraParams;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
GameGlobal.TuyooSdk.Pay(tyPayParams, payCallback, this);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
console.error("current channel not support SetShareInfo function");
},
ShareToBridge: function (shareEventInfo) {
console.error("current channel not support Share function");
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
GameGlobal.TuyooSdk.bi.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
GameGlobal.TuyooSdk.bi.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function (shareEventInfo) {
console.error("current channel not support GetShareInfo function");
},
GetAdInfoBridge: function () {
console.error("current channel not support GetAdInfo function");
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
console.error("current channel not support TxAdSDKReport function");
},
CheckBindToBridge: function (bindEventInfo) {
console.error("current channel not support CheckBind function");
},
SendSmsCodeToBridge: function (loginEventInfo) {
console.error("current channel not support SendSmsCode function");
},
BindToBridge: function (bindEventInfo) {
console.error("current channel not support Bind function");
},
SetWxUserInfoToBridge: function (type, userInfo) {
console.error("current channel not support SetWxUserInfo function");
},
GetDeviceLevelToBridge: function() {
// try {
// var callback = function (code, result, error) {
// var callbackString = JSON.stringify({ code, result, error });
// SendMessage("NativeCallBack", "GetDeviceLevelResult", callbackString);
// }
// GameGlobal.TuyooSdk.getDeviceBenchmarkLevel(callback, this);
// } catch (error) {
// console.error("GetDeviceLevelToBridge catch error: " + error);
// }
console.error("current channel not support GetDeviceLevelToBridge function");
},
CreatGridGamePanelToBridge: function(gridGameModule) {
console.error("current channel not support CreatGridGamePanel function");
},
ShowGridGamePanelToBridge: function(panelId) {
console.error("current channel not support ShowGridGamePanel function");
},
HideGridGamePanelToBridge: function(panelId) {
console.error("current channel not support HideGridGamePanel function");
},
DestroyGridGamePanelToBridge: function(panelId) {
console.error("current channel not support DestroyGridGamePanel function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 49f6a69fc2dc245aeacaeab1ac4a1d78
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 39fc15a1494854837b768d65550fb7ec
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: db431760cfd904f22b2a9edf0780c4de
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,435 @@
var TuyooSdkBridge = {
loadJsScriptToBridge: function (channelType) {
var channelTypeFromCS = UTF8ToString(channelType);
console.log("channelTypeFromCS:" + channelTypeFromCS);
},
InitToBridge: function (initEventInfo) {
try {
var initInfoFromCS = UTF8ToString(initEventInfo);
var initInfo = JSON.parse(initInfoFromCS);
GameGlobal.tywx.StateInfo.debugMode = initInfo.debug.toLowerCase() === "true";
GameGlobal.tywx.SystemInfo.loginUrl = initInfo.tuyooParam.serverUrl.endsWith("/") ? initInfo.tuyooParam.serverUrl : initInfo.tuyooParam.serverUrl + "/";
GameGlobal.tywx.SystemInfo.wxPayVersion = "2.0";
GameGlobal.tywx.SystemInfo.clientId = initInfo.tuyooParam.clientId;
GameGlobal.tywx.SystemInfo.cloudId = initInfo.tuyooParam.cloudId;
GameGlobal.tywx.SystemInfo.appId = initInfo.tuyooParam.appId;
GameGlobal.tywx.SystemInfo.gameId = initInfo.tuyooParam.gameId;
GameGlobal.tywx.SystemInfo.wxAppId = initInfo.login.tywx.wx_appId;
GameGlobal.tywx.SystemInfo.packageName = initInfo.package;
if (initInfo.login.tywx.wxShareEnable === false) {
GameGlobal.tywx.StateInfo.wxShareEnable = false;
wx.hideShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
});
}
// 默认关闭拉取营销系统分享配置开关
GameGlobal.tywx.StateInfo.pullShareConfig = false;
if (initInfo.login.tywx.pullShareConfig === true) {
GameGlobal.tywx.StateInfo.pullShareConfig = true;
}
// 默认关闭交叉导流功能
GameGlobal.tywx.StateInfo.adManagerMode = false;
if (initInfo.login.tywx.adManagerMode === true) {
GameGlobal.tywx.StateInfo.adManagerMode = true;
}
// 广点通上报,默认开启
if (initInfo.login.tywx.txAdEventReportMode === false) {
GameGlobal.tywx.StateInfo.txAdEventReportMode = false;
}
// 错误日志上报,默认关闭
if (initInfo.login.tywx.errorLogMode === true) {
GameGlobal.tywx.StateInfo.errorLogMode = false;
}
if (initInfo.login.tywx.shareManagerUrl) {
GameGlobal.tywx.SystemInfo.shareManagerUrl = initInfo.login.tywx.shareManagerUrl.endsWith("/") ? initInfo.login.tywx.shareManagerUrl : initInfo.login.tywx.shareManagerUrl + "/";
}
if (initInfo.login.tywx.txAdSetId) {
GameGlobal.tywx.SystemInfo.txAdSetId = initInfo.login.tywx.txAdSetId;
}
if (initInfo.login.tywx.txAdSetKey) {
GameGlobal.tywx.SystemInfo.txAdSetKey = initInfo.login.tywx.txAdSetKey;
}
if (initInfo.login.tywx.openFeatureFilter === true) {
GameGlobal.tywx.SystemInfo.openFeatureFilter = true;
}
var launchInfo = wx.getLaunchOptionsSync();
GameGlobal.tywx && GameGlobal.tywx.wxOnshowAction && GameGlobal.tywx.wxOnshowAction(launchInfo);
wx.onShow(function (result) {
GameGlobal.tywx && GameGlobal.tywx.wxOnshowAction && GameGlobal.tywx.wxOnshowAction(result);
})
var callbackResult = {
code: 0,
result: "wx init completed!",
error: ""
};
var callbackString = JSON.stringify(callbackResult);
GameGlobal.Module.SendMessage("NativeCallBack", "InitResult", callbackString);
}
catch (e) {
console.error("InitToBridge catch error: " + e);
}
},
// 切换SDK域名
UpdateServerUrlToBridge: function (serverUrl) {
try {
var serverUrlFromCS = UTF8ToString(serverUrl);
GameGlobal.tywx.SystemInfo.loginUrl = serverUrlFromCS.endsWith("/") ? serverUrlFromCS : serverUrlFromCS + "/";
console.log("update serverUrl to: " + GameGlobal.tywx.SystemInfo.loginUrl);
} catch (e) {
console.error("UpdateServerUrlToBridge catch error: " + e);
}
},
// 登录
LoginToBridge: function (loginEventInfo) {
try {
var loginCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
GameGlobal.Module.SendMessage("NativeCallBack", "LoginResult", callbackString);
}
GameGlobal.tywx.TuyooSDK.login(loginCallback);
} catch (e) {
console.error("LoginToBridge catch error: " + e);
}
},
// 支付
PayToBridge: function (payEventInfo) {
try {
var payCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
GameGlobal.Module.SendMessage("NativeCallBack", "PayResult", callbackString);
}
var payInfoFromCS = UTF8ToString(payEventInfo);
var payInfo = JSON.parse(payInfoFromCS);
var tyPayParams = {};
tyPayParams.prodCount = 1;
tyPayParams.appInfo = "";
if (payInfo.chargeService) {
tyPayParams.chargeType = payInfo.chargeService;
}
if (payInfo.productCount) {
tyPayParams.prodCount = payInfo.productCount;
}
if (payInfo.serverAppInfo) {
tyPayParams.appInfo = payInfo.serverAppInfo;
}
if (payInfo.gameOrderId) {
tyPayParams.prodOrderId = payInfo.gameOrderId;
}
tyPayParams.prodId = payInfo.productId;
tyPayParams.prodName = payInfo.productName;
tyPayParams.prodPrice = payInfo.productPrice;
tyPayParams.sdk_game_role_id = payInfo.gameRoleId;
tyPayParams.sdk_game_zone_id = payInfo.gameZoneId;
if (payInfo.extraParams) {
var extraParams = JSON.parse(payInfo.extraParams);
if (extraParams.actId) {
tyPayParams.actId = extraParams.actId;
delete extraParams.actId;
}
if (extraParams.levelList) {
tyPayParams.levelList = JSON.parse(extraParams.levelList);
delete extraParams.levelList;
}
if (extraParams.sendMessageTitle) {
tyPayParams.sendMessageTitle = extraParams.sendMessageTitle;
delete extraParams.sendMessageTitle;
}
if (extraParams.sendMessagePath) {
tyPayParams.sendMessagePath = extraParams.sendMessagePath;
delete extraParams.sendMessagePath;
}
if (extraParams.sendMessageImg) {
tyPayParams.sendMessageImg = extraParams.sendMessageImg;
delete extraParams.sendMessageImg;
}
tyPayParams.extraParams = extraParams;
}
console.log("tyPayParams: " + JSON.stringify(tyPayParams));
GameGlobal.tywx.TYPayInterface.pay(tyPayParams, payCallback);
} catch (e) {
console.error("PayToBridge catch error: " + e);
}
},
GAEventTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
if (!reportInfo.typeName) {
reportInfo.typeName = "track";
}
GameGlobal.tywx.GALog.trackWithType(reportInfo.typeName, reportInfo.eventName, reportInfo.reportEvent);
} catch (e) {
console.error("GAEventTrackToBridge catch error: " + e);
}
},
GAProfileTrackToBridge: function (reportEventInfo) {
try {
var reportInfoFromCS = UTF8ToString(reportEventInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
GameGlobal.tywx.GALog.profileTrack(reportInfo.profileType, reportInfo.profileSubjectType, reportInfo.profileSubjectPrimary, reportInfo.reportEvent);
} catch (e) {
console.error("GAProfileTrackToBridge catch error: " + e);
}
},
GetShareInfoBridge: function (shareEventInfo) {
try {
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var resource = shareInfo.resource;
var shareCallback = function (code, result, error) {
if(code == 0 && result){
result.sharePoint = resource.sharePointId;
}
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "GetShareInfoResult", callbackString);
}
GameGlobal.tywx.ShareInterface.GetServerShareConfig(resource.type || 'wx_normal', resource.sharePointId, shareCallback);
} catch (error) {
console.error("GetShareInfoBridge catch error: " + error);
}
},
SetShareInfoToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var resource = shareInfo.resource;
var extraData = shareInfo.extra;
var shareInfoToJs = {};
resource.title && (shareInfoToJs.shareContent = resource.title);
resource.imageUrl && (shareInfoToJs.sharePicUrl = resource.imageUrl);
resource.shareSchemeId && (shareInfoToJs.shareSchemeId = resource.shareSchemeId);
resource.extraParams && (shareInfoToJs.extraInfo = resource.extraParams);
resource.sharePointId && (shareInfoToJs.sharePoint = resource.sharePointId);
if(extraData){
Object.assign(shareInfoToJs, extraData);
}
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
GameGlobal.tywx.ShareInterface.setOnShareAppMessageInfo(shareInfoToJs.sharePoint, shareInfoToJs, shareCallback);
} catch (e) {
console.error("SetShareInfoToBridge catch error: " + e);
}
},
ShareToBridge: function (shareEventInfo) {
try {
var shareCallback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
GameGlobal.Module.SendMessage("NativeCallBack", "ShareResult", callbackString);
}
var shareInfoFromCS = UTF8ToString(shareEventInfo);
var shareInfo = JSON.parse(shareInfoFromCS);
var resource = shareInfo.resource;
var extraData = resource.extra;
var shareInfoToJs = {};
resource.title && (shareInfoToJs.shareContent = resource.title);
resource.imageUrl && (shareInfoToJs.sharePicUrl = resource.imageUrl);
resource.shareSchemeId && (shareInfoToJs.shareSchemeId = resource.shareSchemeId);
resource.extraParams && (shareInfoToJs.extraInfo = resource.extraParams);
resource.sharePointId && (shareInfoToJs.sharePoint = resource.sharePointId);
if(extraData){
Object.assign(shareInfoToJs, extraData);
}
console.log("shareInfoToJs: " + JSON.stringify(shareInfoToJs));
if(resource.type == 'wx_activity_not_chat'){
GameGlobal.tywx.ShareInterface.activityShare(shareInfoToJs.sharePoint, shareInfoToJs, shareCallback);
}else if(resource.type == 'wx_poster'){
GameGlobal.tywx.ShareInterface.posterShare(shareInfoToJs.sharePoint, shareInfoToJs, shareCallback);
}else{
GameGlobal.tywx.ShareInterface.share(shareInfoToJs.sharePoint, shareInfoToJs, shareCallback);
}
} catch (e) {
console.error("ShareToBridge catch error: " + e);
}
},
GetAdInfoBridge: function () {
try {
var iconCallback = function (result) {
var callbackResult = {
code: 0,
result: result,
};
var callbackString = JSON.stringify(callbackResult);
GameGlobal.Module.SendMessage("NativeCallBack", "GetIconInfoResult", callbackString);
}
var newIconCallback = function (result) {
var callbackResult = {
code: 0,
result: result,
};
var callbackString = JSON.stringify(callbackResult);
GameGlobal.Module.SendMessage("NativeCallBack", "GetNewIconInfoResult", callbackString);
}
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.GET_ADMANAGER_ICON_INFO_SUCCESS, iconCallback);
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.GET_ADMANAGER_NEWICON_INFO_SUCCESS, newIconCallback);
GameGlobal.tywx.AdManager.init();
} catch (error) {
console.error("ShareToBridge catch error: " + error);
}
},
TxAdSDKReportToBridge: function (txAdReportInfo) {
try {
var reportInfoFromCS = UTF8ToString(txAdReportInfo);
var reportInfo = JSON.parse(reportInfoFromCS);
console.log("reportInfoToJs: " + JSON.stringify(reportInfo.actionParams));
GameGlobal.tywx.TxAdSDKReportInterface.track(reportInfo.actionType, JSON.parse(reportInfo.actionParams));
} catch (error) {
console.error("TxAdSDKReportToBridge catch error: " + error);
}
},
CheckBindToBridge: function (bindEventInfo) {
try {
var bindInfoFromCS = UTF8ToString(bindEventInfo);
var bindInfo = JSON.parse(bindInfoFromCS);
var checkBindCallback = function (code, result) {
var finnalResult = {
code: code,
};
if (code == -1) {
finnalResult.error = result;
} else {
finnalResult.result = result;
}
var callbackString = JSON.stringify(finnalResult);
GameGlobal.Module.SendMessage("NativeCallBack", "CheckResult", callbackString);
}
GameGlobal.tywx.TuyooSDK.CheckBind(bindInfo.userId, checkBindCallback);
} catch (error) {
console.error("checkBindToBridge catch error: " + error);
}
},
SendSmsCodeToBridge: function (loginEventInfo) {
try {
var loginInfoFromCS = UTF8ToString(loginEventInfo);
var phoneInfo = JSON.parse(loginInfoFromCS);
var sendSmsCodeCallback = function (code, result) {
var finnalResult = {
code: code,
};
if (code == 0) {
finnalResult.result = result;
} else {
finnalResult.error = result;
}
var callbackString = JSON.stringify(finnalResult);
GameGlobal.Module.SendMessage("NativeCallBack", "SendCodeResult", callbackString);
}
GameGlobal.tywx.TuyooSDK.ThirdSmsSend(phoneInfo.phoneNumber, sendSmsCodeCallback);
} catch (error) {
console.error("SendSmsCodeToBridge catch error: " + error);
}
},
BindToBridge: function (bindEventInfo) {
try {
var bindInfoFromCS = UTF8ToString(bindEventInfo);
var bindInfo = JSON.parse(bindInfoFromCS);
var doBindCallback = function (code, result) {
var finnalResult = {
code: code,
};
if (code == 0) {
finnalResult.result = result;
} else {
finnalResult.error = result;
}
var callbackString = JSON.stringify(finnalResult);
GameGlobal.Module.SendMessage("NativeCallBack", "onBindSucc", callbackString);
}
GameGlobal.tywx.TuyooSDK.ThirdBindSns(bindInfo.phoneNumber, bindInfo.phoneCode, bindInfo.userId, bindInfo.password, doBindCallback);
} catch (error) {
console.error("BindToBridge catch error: " + error);
}
},
SetWxUserInfoToBridge: function (type, userInfo) {
try {
var userInfoFromCS = UTF8ToString(userInfo);
var currentUserInfo = JSON.parse(userInfoFromCS);
var reportInfo = currentUserInfo.wxUserInfo;
var currentType = UTF8ToString(type);
var succCb = function () {
var finnalResult = {
code: 0,
result: "success!"
};
var callbackString = JSON.stringify(finnalResult);
GameGlobal.Module.SendMessage("NativeCallBack", "SetWxInfoResult", callbackString);
}
var failCb = function () {
var finnalResult = {
code: -1,
error: "fail!"
};
var callbackString = JSON.stringify(finnalResult);
GameGlobal.Module.SendMessage("NativeCallBack", "SetWxInfoResult", callbackString);
}
if (currentType == "1") {
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_USER_INFO_SUCCESS, succCb);
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_USER_INFO_FAIL, failCb);
GameGlobal.tywx.TuyooSDK.setWxUserInfo(reportInfo);
} else if (currentType == "2") {
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_SENSITIVE_DATA_SUCCESS, succCb);
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_SENSITIVE_DATA_FAIL, failCb);
GameGlobal.tywx.TuyooSDK.setWxEncryptedData(reportInfo.encryptedData, reportInfo.iv);
} else if (currentType == "3") {
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_SENSITIVE_DATA_SUCCESS, succCb);
GameGlobal.tywx.NotificationCenter.listen(tywx.EventType.SET_WX_SENSITIVE_DATA_SUCCESS, failCb);
GameGlobal.tywx.TuyooSDK.setThreeWxEncryptedData(reportInfo.wxOpenId, reportInfo.unionId, reportInfo.session_key);
}
} catch (error) {
console.error("SetWxUserInfoToBridge catch error: " + error);
}
},
GetDeviceLevelToBridge: function() {
try {
var callback = function (code, result, error) {
var callbackString = JSON.stringify({ code, result, error });
GameGlobal.Module.SendMessage("NativeCallBack", "GetDeviceLevelResult", callbackString);
}
GameGlobal.tywx.TuyooSDK.getDeviceBenchmarkLevel(callback);
} catch (error) {
console.error("GetDeviceLevelToBridge catch error: " + error);
}
},
CreatGridGamePanelToBridge: function(gridGameModule) {
console.error("current channel not support CreatGridGamePanel function");
},
ShowGridGamePanelToBridge: function(panelId) {
console.error("current channel not support ShowGridGamePanel function");
},
HideGridGamePanelToBridge: function(panelId) {
console.error("current channel not support HideGridGamePanel function");
},
DestroyGridGamePanelToBridge: function(panelId) {
console.error("current channel not support DestroyGridGamePanel function");
}
}
mergeInto(LibraryManager.library, TuyooSdkBridge);

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2ca65f180cf9f414aa2630d83f81f306
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1e71e06e22de84bab9c7114861753f3d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,491 @@
/**
* SDK
*/
interface SdkConfig {
/**
* ID
*/
user_action_set_id: number;
/**
* key
*/
secret_key: string;
/**
* /APPIDwx开头
*/
appid: string;
/**
* openidopenid unionid , setOpenId
*/
openid?: string;
/**
* unionidopenid unionid , setUnionId
*/
unionid?: string;
/**
* ID
*/
user_unique_id?: string;
/**
*
*/
auto_track?: boolean;
/**
*
*/
auto_attr?: boolean;
}
/**
* /
*/
interface GameInfo {
/**
* 广idid
*/
ad_trace_id?: string;
/**
* ,
*/
page_url?: string;
/**
* ,
*/
page_title?: string;
/**
*
*/
component_name?: string;
/**
*
*/
source_scene?: number;
/**
*
*/
pkg_channel_id?: string;
/**
* ,
*/
framework?: string;
/**
*
*/
channel: string;
/**
*
*/
launch_options: string;
}
/**
*
*/
interface DeviceInfo {
/**
*
*/
device_brand: string;
/**
*
*/
device_model: string;
/**
* App版本
*/
wx_version: string;
/**
*
*/
wx_lib_version: string;
/**
*
*/
wx_platform: string;
/**
*
*/
os: string;
/**
*
*/
os_version: string;
/**
*
*/
benchmark_level: number;
/**
*
*/
screen_height: number;
/**
*
*/
screen_width: number;
}
interface TrackBaseInfo extends SdkConfig, DeviceInfo {
local_id: string;
sdk_name: string;
sdk_version: string;
inner_param: {
app_version: string;
app_env_version: string;
};
}
/**
*
*/
interface ActionInfo {
action_type: string;
action_param?: Record<string | number | symbol, unknown>;
is_sdk_auto_track: boolean;
session_id: string;
log_id: number;
action_id: string;
action_time: number;
revised_action_time: number;
is_retry: boolean;
retry_count: number;
ad_trace_id?: string;
page_url?: string;
page_title?: string;
component_name?: string;
source_scene?: number;
pkg_channel_id?: string;
/**
*
*/
network_type?: string;
inner_param?: Record<string | number | symbol, unknown>;
channel?: string;
}
interface LogParams {
log_type: string;
code?: number;
message?: string;
err_stack?: string;
user_action_set_id?: number;
appid?: string;
local_id?: string;
session_id?: string;
sdk_name?: string;
sdk_version?: string;
page_url?: string;
framework?: string;
device_brand?: string;
device_model?: string;
wx_version?: string;
wx_lib_version?: string;
wx_platform?: string;
os?: string;
os_version?: string;
}
interface QueueProps {
/**
* IDkey
*/
userActionSetId: number;
/**
*
*/
maxLength: number;
}
interface QueueManagerProps extends QueueProps {
/**
* OG事件列表
*/
ogEvents: string[];
}
interface IEvent extends ActionInfo {
inner_status?: string;
}
/**
*
*/
declare class Queue {
protected maxLength: any;
protected userActionSetId: any;
protected lostActionMaps: Record<string, number>;
private stack;
private localStorageKey;
private timeStamp;
constructor({ userActionSetId, maxLength }: QueueProps);
getItems(): IEvent[];
getStorage(): IEvent[];
/**
*
*/
reportLostNum(): void;
/**
* map
* @returns map
*/
getLostMaps(): Record<string, number>;
protected init(): void;
protected addItem(eventData: IEvent): void;
protected removeItems(actionIds: string[]): void;
protected updateForReportFail(actionIds: string[]): void;
protected updateForReporting(actionIds: string[]): void;
protected updateAllStack(stack: IEvent[]): void;
protected updateToStorage(): void;
/**
*
* @param sessionId id
*/
protected updateLostAction(sessionId: string): void;
/**
*
*/
protected setTimeStamp(): void;
}
declare class QueueManage extends Queue {
protected ogEvents: string[];
constructor({ userActionSetId, maxLength, ogEvents }: QueueManagerProps);
/**
*
* @param reportMaxLength
*/
getReportableActions(reportMaxLength?: number): IEvent[];
/**
*
* @param eventData
*/
addAction(eventData: IEvent): void;
/**
* acition_id删除行为
* @param actionIds id列表
*/
removeActions(actionIds: string[]): void;
/**
*
* @param actionIds
*/
updateActionsForReportFail(actionIds: string[]): void;
/**
* reporting
* @param actionIds id数组
*/
updateActionsForReporting(actionIds: string[]): void;
/**
*
* @returns
*/
getReportableActionsLength(): number;
/**
*
* @param currEvent
* @param stack
*/
sortQueue(currEvent: IEvent, stack: IEvent[]): IEvent[];
/**
*
* @param currTime
* @param event
* @returns
*/
private caculateWeight;
/**
*
* @param currTime
* @param actionTime
* @returns
*/
private formatWeight;
}
interface ConfigManager {
getRealTimeActionList: () => Array<string>;
getRequestTimeout: () => number;
}
interface ActionReporterProps {
getBaseInfo: () => TrackBaseInfo;
reportLog: (param: LogParams) => void;
queueManager: QueueManage;
configManager?: ConfigManager;
}
/**
*
*/
declare class ActionReporter {
private static currentRequestCount;
private static requestConcurrency;
static setRequestConcurrency(n: number): void;
private getBaseInfo;
private reportLog;
private queueManager;
private configManager;
private cgiBatchSize;
private reportThreshold;
private reportDelay;
private triggerExecuteSend;
private inspectDelay;
private inspectTimer;
private isNeedContinueSend;
constructor(props: ActionReporterProps);
/**
* track的时候触发
*/
batchSend(): void;
/**
* flush的时候触发
*/
flushSend(): void;
/**
* batch上限则并行发送请求
*/
private executeSend;
/**
*
*/
private generateActionReportParams;
/**
*
* @param resData
* @param actionIdList
*/
private dealSuccessData;
/**
*
* @param errData
* @param actionIdList
*/
private dealFailData;
/**
* wx.request文档https://developers.weixin.qq.com/minigame/dev/api/network/request/wx.request.html
* @param param.data:接口请求参数param.actionIdList:行为id列表
* @returns
*/
private report;
/**
*
*/
private startInspectTimer;
}
declare abstract class SdkExtCommon {
protected special_method_symbol: symbol;
/**
*
*/
onPurchase(value: number): void;
/**
*
*/
onEnterForeground(): void;
/**
*
*/
onEnterBackground(): void;
/**
*
*/
onAppStart(): void;
/**
* 退
*/
onAppQuit(): void;
/**
*
*/
onAddToWishlist(): void;
protected wrapTrack(action_type: ActionInfo["action_type"], action_param?: ActionInfo["action_param"]): void;
abstract track(action_type: ActionInfo["action_type"], action_param?: ActionInfo["action_param"]): void;
}
declare abstract class sdkExt extends SdkExtCommon {
/**
*
*/
onRegister(): void;
/**
*
*/
onCreateRole(name?: string): void;
/**
*
*/
onTutorialFinish(): void;
}
declare const initializedInstanceSymbol: unique symbol;
declare class SDK extends sdkExt {
private static [initializedInstanceSymbol];
static setRequestConcurrency(n: number): void;
static setDebug(debug: boolean): void;
protected env: string;
protected sdk_version: string;
protected sdk_name: string;
protected config?: SdkConfig;
protected deviceInfo: Partial<DeviceInfo>;
protected gameInfo: Partial<GameInfo>;
protected session_id: string;
protected log_id: number;
protected queueManage?: QueueManage;
protected actionReporter?: ActionReporter;
protected openid?: string;
protected unionid?: string;
protected user_unique_id?: string;
protected inited: boolean;
constructor(sdkConfig: SdkConfig);
/**
*
*/
track(action_type: ActionInfo['action_type'], action_param?: ActionInfo['action_param']): void;
/**
*
*/
flush(): void;
/**
* openId
*/
setOpenId(openid: string): void;
/**
* unionid
*/
setUnionId(unionid: string): void;
/**
* user_unique_id
* @param user_unique_id
*/
setUserUniqueId(user_unique_id: string): void;
protected doReportOnEnterBackground(): void;
/**
* info
*/
private getTrackBaseInfo;
/**
*
* @param actionParams
* @param is_sdk_auto_track
* @returns
*/
private createAction;
/**
* inner_param字段追加字段
* @param action
* @param key inner_param字段的key
* @param value key对应的value
*/
private addActionInnerParam;
/**
*
* @param actionType
* @returns
*/
private getChannelByActionType;
/**
*
* @param params
*/
private reportLog;
private useAutoTrack;
private getAutoProxyRemoteConfig;
/**
* openid时Storage
*/
private saveValidOpenidToStorage;
}
export { SDK };

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4281eb15fbaf94140ac04656d0b06e85
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 208b4345ee65d4f66968164f0c71bb91
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

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