update core

This commit is contained in:
2023-09-04 16:57:46 +08:00
parent 0ff31be7c4
commit 6567d59019
394 changed files with 5659 additions and 7144 deletions

View File

@@ -0,0 +1,148 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
using AnyThink.Scripts.IntegrationManager.Editor;
using Network = AnyThink.Scripts.IntegrationManager.Editor.Network;
using IntegrationManager = AnyThink.Scripts.IntegrationManager.Editor.ATIntegrationManager;
public class ATAssetDatabaseManager : ScriptableObject
{
public const string SettingsExportPath = "Assets/AnyThinkPlugin/Resources/Assets/ATAssetDatabaseManager.asset";
private static ATAssetDatabaseManager instance;
public Network importingNetwork = null;
public delegate void DownloadPluginProgressCallback(string pluginName, float progress, bool done);
public delegate void ImportPackageCompletedCallback(Network network);
public DownloadPluginProgressCallback downloadPluginProgressCallback;
public ImportPackageCompletedCallback importPackageCompletedCallback;
// public Network importingNetwork;
public static ATAssetDatabaseManager Instance
{
get
{
if (instance == null)
{
var settingsDir = Path.GetDirectoryName(SettingsExportPath);
if (!Directory.Exists(settingsDir))
{
Directory.CreateDirectory(settingsDir);
}
string settingsFilePath = SettingsExportPath;
instance = AssetDatabase.LoadAssetAtPath<ATAssetDatabaseManager>(settingsFilePath);
if (instance != null) return instance;
instance = CreateInstance<ATAssetDatabaseManager>();
AssetDatabase.CreateAsset(instance, settingsFilePath);
// init();
}
return instance;
}
}
private ATAssetDatabaseManager()
{
init();
}
private void init()
{
ATLog.log("ATAssetDatabaseManager inited");
AssetDatabase.importPackageCompleted += packageName =>
{
ATLog.logFormat("importPackageCompleted() >>> packageName: {0} importingNetwork: {1}", new object[] { packageName, importingNetwork });
if (!IsImportingNetwork(packageName)) return;
ATLog.log("importPackageCompleted() >>> import succeed.");
// ATConfig.saveInstalledNetworkVersion(packageName, )
// var pluginParentDir = PluginParentDirectory;
// var isPluginOutsideAssetsDir = IsPluginOutsideAssetsDirectory;
// MovePluginFilesIfNeeded(pluginParentDir, isPluginOutsideAssetsDir);
// AddLabelsToAssetsIfNeeded(pluginParentDir, isPluginOutsideAssetsDir);
AssetDatabase.Refresh();
CallImportPackageCompletedCallback(importingNetwork);
// importingNetwork = null;
setImportingNetworkNull();
};
AssetDatabase.importPackageCancelled += packageName =>
{
ATLog.logFormat("importPackageCancelled() >>> packageName: {0}", new object[] { packageName });
if (!IsImportingNetwork(packageName)) return;
// MaxSdkLogger.UserDebug("Package import cancelled.");
// importingNetwork = null;
setImportingNetworkNull();
};
AssetDatabase.importPackageFailed += (packageName, errorMessage) =>
{
ATLog.logFormat("importPackageFailed() >>> packageName: {0}, errorMsg: {1}", new object[] { packageName, errorMessage });
if (!IsImportingNetwork(packageName)) return;
// MaxSdkLogger.UserError(errorMessage);
// importingNetwork = null;
setImportingNetworkNull();
};
}
private void setImportingNetworkNull()
{
// ATPluginSetting.Instance.ImportingNetwork = null;
importingNetwork = null;
}
public void CallDownloadPluginProgressCallback(string pluginName, float progress, bool isDone)
{
if (downloadPluginProgressCallback == null) return;
downloadPluginProgressCallback(pluginName, progress, isDone);
}
public void CallImportPackageCompletedCallback(Network network)
{
ATLog.log("CallImportPackageCompletedCallback() >>> network: " + network + " importPackageCompletedCallback: " + importPackageCompletedCallback);
if (network != null)
{
ATConfig.saveInstalledNetworkVersion(network.Name, network.LatestVersions);
// ATIntegrationManager.Instance.UpdateCurrentVersions(network);
}
if (importPackageCompletedCallback == null) return;
importPackageCompletedCallback(network);
}
public string GetPluginFileName(Network network)
{
// return network.Name.ToLowerInvariant() + "_" + network.LatestVersions.Unity + ".unitypackage";
return network.PluginFileName;
}
private bool IsImportingNetwork(string packageName)
{
// Note: The pluginName doesn't have the '.unitypacakge' extension included in its name but the pluginFileName does. So using Contains instead of Equals.
//window系统packageName是项目路径/AnyThinkCoreMac系统是: AnyThinkCore
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if (packageName.Contains("\\"))
{
string[] packageNameArray = packageName.Split('\\');
if (packageNameArray != null && packageNameArray.Length > 0)
{
packageName = packageNameArray[packageNameArray.Length -1];
}
}
#endif
return importingNetwork != null && GetPluginFileName(importingNetwork).Contains(packageName);
}
}

View File

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

View File

@@ -0,0 +1,46 @@
using System;
using UnityEditor;
using UnityEngine;
using AnyThink.Scripts.IntegrationManager.Editor;
[InitializeOnLoad]
public class ATAssetPostprocessor : AssetPostprocessor
{
private static readonly string TAG = "ATAssetPostprocessor";
static ATAssetPostprocessor()
{
log("ATAssetPostprocessor is now initialized!");
}
void OnPostprocessAsset(string path)
{
log("OnPostprocessAsset() >>> path: " + path + " assetPath: " + assetPath);
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string str in importedAssets)
{
log("imported Asset: " + str);
}
foreach (string str in deletedAssets)
{
log("Deleted Asset: " + str);
}
for (int i = 0; i < movedAssets.Length; i++)
{
log("Moved Asset: " + movedAssets[i] + " from: " + movedFromAssetPaths[i]);
}
}
void OnPreprocessAsset()
{
log("OnPreprocessAsset() >>> called assetPath: " + assetPath);
}
private static void log(string msg)
{
ATLog.log(TAG, msg);
}
}

View File

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

View File

@@ -0,0 +1,249 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
// public class ATConfig : ScriptableObject
public class ATConfig
{
public static string PLUGIN_VERSION = "2.0.1";
public static bool isDebug = false;
private static string LAST_SELECT_COUNTRY_KEY = "country_key"; //国家
public static int CHINA_COUNTRY = 1;
public static int NONCHINA_COUNTRY = 2;
public static string ANYTHINK_SDK_FILES_PATH = "Assets/AnyThinkAds";
//国内core aar包的父目录
public static string CHINA_ANDROID_CORE_FILES_PATH = "Assets/AnyThinkAds/Plugins/Android/China/anythink_base/";
public static string NONCHINA_ANDROID_CORE_FILES_PATH = "Assets/AnyThinkAds/Plugins/Android/NonChina/anythink_base/";
//国内Android network aar包的父目录
public static string CHINA_ANDROID_NETWORK_FILES_PARENT_PATH = "Assets/AnyThinkAds/Plugins/Android/China/mediation/";
//海外Android network 依赖文件的目录
public static string NONCHINA_ANDROID_NETWORK_FILES_PARENT_PATH = "Assets/AnyThinkAds/Plugins/Android/NonChina/mediation/";
//iOS network依赖文件的目录不区分国家
public static string IOS_NETWORK_FILES_PARENT_PATH = "Assets/AnyThinkAds/Plugins/iOS/";
// 保存已安装的network到本地
public static void saveInstalledNetworkVersion(string networkName, Versions v)
{
Versions versions = v.clone();
int country = getLocalCountry();
ATLog.log("saveInstalledNetworkVersion() >>> networkName: " + networkName + " unity: " + versions.Unity);
versions = initUnityForVerions(versions, networkName, country);
// ATPluginSetting.Instance.saveInstalledNetwork(networkName, country, versions);
string jsonStr = JsonUtility.ToJson(versions);
PlayerPrefs.SetString(networkName + "_" + country, jsonStr);
PlayerPrefs.Save();
}
public static void saveLocalCountry(int country)
{
PlayerPrefs.SetInt(LAST_SELECT_COUNTRY_KEY, country);
PlayerPrefs.Save();
}
//获取已安装的network版本包括core network
public static Versions getInstalledNetworkVersion(string networkName, int country)
{
string key = networkName + "_" + country;
string sdkJson = PlayerPrefs.GetString(key);
ATLog.log("getInstalledNetworkVersion() >>> networkName: " + networkName + " sdkJson: " + sdkJson + " country: " + country);
if (sdkJson == null || sdkJson.Length == 0)
{
return null;
}
Versions versions = JsonUtility.FromJson<Versions>(sdkJson);
versions = initUnityForVerions(versions, networkName, country);
return versions;
}
private static Versions initUnityForVerions(Versions versions, string networkName, int country)
{
if (versions == null)
{
return null;
}
//查找本地的android、iOS是否都已安装
string androidPath = getAndroidNetworkPath(networkName, country);
bool androidInstalled = isInstalledByPath(androidPath);
string iosPath = getIosNetworkPath(networkName);
bool iosInstalled = isInstalledByPath(iosPath);
if (!androidInstalled && iosInstalled)
{
// versions.Android = "";
versions.Unity = string.Format("ios_{0}", versions.Ios);
}
else if (androidInstalled && !iosInstalled)
{
// versions.Ios = "";
versions.Unity = string.Format("android_{0}", versions.Android);
}
else if (!androidInstalled && !iosInstalled)
{
versions.Unity = "";
}
//core network的unity版本是插件版本
if (networkName.Equals(ATIntegrationManager.AnyThinkNetworkName))
{
versions.Unity = ATConfig.PLUGIN_VERSION;
}
ATLog.log("initUnityForVerions() >>> networkName: " + networkName + " androidInstalled: " + androidInstalled + " iosInstalled: " + iosInstalled + " unity: " + versions.Unity);
return versions;
}
public static bool isNetworkInstalled(string networkName, int country)
{
Versions versions = getInstalledNetworkVersion(networkName, country);
if (versions == null)
{
return false;
}
if (networkName.Equals(ATIntegrationManager.AnyThinkNetworkName)) //core network判断是否已安装
{
string androidPath = getAndroidNetworkPath(networkName, country);
bool androidInstalled = isInstalledByPath(androidPath);
string iosPath = getIosNetworkPath(networkName);
bool iosInstalled = isInstalledByPath(iosPath);
return androidInstalled && iosInstalled;
} else { //network判断是否已安装
return !string.IsNullOrEmpty(versions.Unity);
}
}
public static bool isAndroidNetworkInstalled(string networkName, int country)
{
Versions versions = getInstalledNetworkVersion(networkName, country);
if (versions == null)
{
return false;
}
string androidPath = getAndroidNetworkPath(networkName, country);
bool androidInstalled = isInstalledByPath(androidPath);
return androidInstalled;
}
public static bool isIOSNetworkInstalled(string networkName, int country)
{
Versions versions = getInstalledNetworkVersion(networkName, country);
if (versions == null)
{
return false;
}
string iosPath = getIosNetworkPath(networkName);
bool iosInstalled = isInstalledByPath(iosPath);
return iosInstalled;
}
private static string getAndroidNetworkPath(string networkName, int country)
{
if (networkName.Equals(ATIntegrationManager.AnyThinkNetworkName))
{
return country == CHINA_COUNTRY ? CHINA_ANDROID_CORE_FILES_PATH : NONCHINA_ANDROID_CORE_FILES_PATH;
}
else
{
return country == CHINA_COUNTRY ? CHINA_ANDROID_NETWORK_FILES_PARENT_PATH + networkName.ToLower() : NONCHINA_ANDROID_NETWORK_FILES_PARENT_PATH + networkName.ToLower();
}
}
private static string getIosNetworkPath(string networkName)
{
string defaultResult = IOS_NETWORK_FILES_PARENT_PATH + networkName.ToLower();
if (networkName.Equals(ATIntegrationManager.AnyThinkNetworkName))
{
return IOS_NETWORK_FILES_PARENT_PATH + networkName; //Core network在本地的目录名称首字母是大写
}
// else if (networkName.Equals("Pangle"))
// {
// //获取SDK版本
// // Network coreNework = ATPluginSetting.Instance.CoreNetwork;
// // if (coreNework != null && coreNework.CurrentVersions != null)
// // {
// // string iosSdkVersion = coreNework.CurrentVersions.Ios;
// // string compareVersion = "6.1.78";
// // ATLog.log("getIosNetworkPath() >>> iosSdkVersion: " + iosSdkVersion);
// // VersionComparisonResult comparisonResult = ATDataUtil.CompareVersions(iosSdkVersion, compareVersion);
// // if (comparisonResult == VersionComparisonResult.Lesser) //小于6.1.78
// // {
// // string pangleName = isSelectedChina() ? "pangle_China" : "pangle_nonChina";
// // ATLog.log("getIosNetworkPath() >>> pangleName: " + pangleName);
// // return IOS_NETWORK_FILES_PARENT_PATH + pangleName;
// // }
// // }
// string pangleName = isSelectedChina() ? "pangle_China" : "pangle_nonChina";
// // ATLog.log("getIosNetworkPath() >>> pangleName: " + pangleName);
// return IOS_NETWORK_FILES_PARENT_PATH + pangleName;
// }
else if (networkName.Equals("MyTarget"))
{
return IOS_NETWORK_FILES_PARENT_PATH + networkName;
}
return defaultResult;
}
public static int getLocalCountry()
{
return PlayerPrefs.GetInt(LAST_SELECT_COUNTRY_KEY, CHINA_COUNTRY); //默认是国内
// return CHINA_COUNTRY;
}
public static bool isSelectedChina()
{
return getLocalCountry() == CHINA_COUNTRY;
}
public static void removeInstalledNetworkVersion(string networkName, int country)
{
// int country = getLocalCountry();
PlayerPrefs.DeleteKey(networkName + "_" + country);
}
public static string[] getNetworkFilesPath(string networkName, int country)
{
// if (networkName.Equals(ATIntegrationManager.AnyThinkNetworkName)) {
// return new string[]{ANYTHINK_SDK_FILES_PATH};
// }
string[] filesPath = new string[2];
filesPath[0] = getAndroidNetworkPath(networkName, country);
filesPath[1] = getIosNetworkPath(networkName);
return filesPath;
}
private static bool isInstalledByPath(string path)
{
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
return files != null && files.Length > 0;
}
return false;
}
// private void OnEnable()
// {
// EditorApplication.quitting += Save;
// }
// private void OnDisable()
// {
// EditorApplication.quitting -= Save;
// }
// private void Save()
// {
// // EditorPrefs.SetInt("MySetting", 1); // 保存您的EditorPrefs数据
// PlayerPrefs.Save(); // 确保数据已被保存到磁盘上
// }
}
}

View File

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

View File

@@ -0,0 +1,397 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public class ATDataUtil
{
// private static string LAST_SELECT_COUNTRY_KEY = "country_key"; //当前选择的country
// public static Network[] chinaNetworks;
// public static Network[] nonChinaNetworks;
public static Network coreNetwork;
public static Network[] parseNetworksJson(PluginData pluginData, string netowrksJson)
{
try
{
int country = pluginData.country;
bool isChinaCountry = isChina(country);
ServerNetworks serverNetworks = JsonUtility.FromJson<ServerNetworks>(netowrksJson);
ServerNetworkInfo[] serverNetworkInfoList;
Network[] networks;
if (isChinaCountry)
{
serverNetworkInfoList = serverNetworks.ChinaSdk;
networks = formatServerNetworks(pluginData, country, serverNetworkInfoList);
// networks = chinaNetworks;
}
else
{
serverNetworkInfoList = serverNetworks.GlobalSdk;
networks = formatServerNetworks(pluginData, country, serverNetworkInfoList);
// networks = nonChinaNetworks;
}
return networks;
}
catch (Exception e)
{
// 错误处理代码
ATLog.log("parseNetworksJson() >>> failed: " + e);
}
return null;
}
public static PluginData parsePluginDataJson(string serverPluginVersionJson)
{
ATLog.log("plugin version data: " + serverPluginVersionJson);
try
{
var pluginData = new PluginData();
// var anythink = new Network();
ServerPluginVersion serverPluginVersion = JsonUtility.FromJson<ServerPluginVersion>(serverPluginVersionJson);
pluginData.networkUrlVersion = serverPluginVersion.networkUrlVersion;
pluginData.country = ATConfig.getLocalCountry();
pluginData.pluginVersion = serverPluginVersion.pluginVersion;
return pluginData;
}
catch (Exception e)
{
// 错误处理代码
ATLog.log("parse version data failed: " + e);
}
return null;
}
public static Network[] formatServerNetworks(PluginData pluginData, int country, ServerNetworkInfo[] networkInfoList)
{
if (networkInfoList == null || networkInfoList.Length == 0)
{
return null;
}
int length = networkInfoList.Length;
List<Network> networkList = new List<Network>();
for (int i = 0; i < length; i++)
{
Network network = new Network();
ServerNetworkInfo serverInfo = networkInfoList[i];
network.Name = serverInfo.name;
network.DisplayName = serverInfo.displayName;
network.DownloadUrl = serverInfo.downloadUrl;
network.PluginFileName = serverInfo.pluginFileName;
Versions latestVersion = new Versions();
ServerNetworkVersion serverVersion = serverInfo.versions;
if (serverVersion != null)
{
latestVersion.Android = serverVersion.android;
latestVersion.Ios = serverVersion.ios;
latestVersion.Unity = serverVersion.unity;
}
network.LatestVersions = latestVersion;
networkList.Add(network);
}
Network coreNetwork = networkList.First<Network>(n => n.Name.Equals(ATIntegrationManager.AnyThinkNetworkName));
//先初始化core network
if (coreNetwork != null)
{
// 获取当前已安装network的版本号
Versions curVerions = ATConfig.getInstalledNetworkVersion(coreNetwork.Name, country);
Versions latestVersion = coreNetwork.LatestVersions;
if (latestVersion == null)
{
latestVersion = new Versions();
}
latestVersion.Unity = pluginData.pluginVersion;
coreNetwork.LatestVersions = latestVersion;
ATLog.log("coreNetwork latestVersion: Android=" + latestVersion.Android);
if (curVerions != null)
{
coreNetwork.CurrentVersions = curVerions;
coreNetwork.CurrentToLatestVersionComparisonResult = getVersionComparisonResult(curVerions, latestVersion, false);
}
ATPluginSetting.Instance.CoreNetwork = coreNetwork;
}
networkList.Remove(coreNetwork);
//后初始化network
foreach (var network in networkList)
{
Versions curVerion = ATConfig.getInstalledNetworkVersion(network.Name, country);
network.CurrentVersions = curVerion;
VersionComparisonResult result = getVersionComparisonResult(curVerion, network.LatestVersions, true);
ATLog.log("formatServerNetworks() >>> compareResult: " + result);
network.CurrentToLatestVersionComparisonResult = result;
}
Network[] networks = (Network[])networkList.ToArray();
//排序
Array.Sort(networks);
return networks;
}
// public bool isChina()
// {
// int result = EditorPrefs.GetInt(LAST_SELECT_COUNTRY_KEY, 1);
// return result == 1;
// }
public static bool isChina(int country)
{
return country == ATConfig.CHINA_COUNTRY;
}
public static VersionComparisonResult getVersionComparisonResult(Versions curVersion, Versions latestVersion, bool isNetwork = false)
{
if (curVersion == null || latestVersion == null)
{
return VersionComparisonResult.Equal;
}
string curUnity = curVersion.Unity;
string latestUnity = latestVersion.Unity;
string curAndroid = curVersion.Android;
string latestAndroid = latestVersion.Android;
string curIos = curVersion.Ios;
string latestIos = latestVersion.Ios;
VersionComparisonResult compareVersionResult = VersionComparisonResult.Equal;
if (isNetwork)
{
if (string.IsNullOrEmpty(curUnity) || string.IsNullOrEmpty(latestUnity))
{
return VersionComparisonResult.Equal;
}
compareVersionResult = CompareUnityMediationVersions(curVersion.Unity, latestVersion.Unity);
}
else
{
var unityVersionComparison = CompareVersions(curUnity, latestUnity);
var androidVersionComparison = CompareVersions(curAndroid, latestAndroid);
var iosVersionComparison = CompareVersions(curIos, latestIos);
if (unityVersionComparison == VersionComparisonResult.Equal &&
androidVersionComparison == VersionComparisonResult.Equal &&
iosVersionComparison == VersionComparisonResult.Equal)
{
compareVersionResult = VersionComparisonResult.Equal;
}
else if (unityVersionComparison == VersionComparisonResult.Lesser ||
androidVersionComparison == VersionComparisonResult.Lesser ||
iosVersionComparison == VersionComparisonResult.Lesser)
{
compareVersionResult = VersionComparisonResult.Lesser;
}
else
{
compareVersionResult = VersionComparisonResult.Greater;
}
}
return compareVersionResult;
}
// public static long compareVersionToInt(string currentVersion, string currentNewVersion)
// {
// if (currentVersion == null || currentVersion.Length == 0
// || currentNewVersion == null || currentNewVersion.Length == 0)
// {
// return 0;
// }
// ATLog.log("compareVersionToInt() >>> before curVersion: " + currentVersion + " curNewVersion: " + currentNewVersion);
// string curVersion = currentVersion.Replace(".", "").Replace("_", "").Replace("android", "").Replace("ios", "").Replace(" ", "");
// string curNewVersion = currentNewVersion.Replace(".", "").Replace("_", "").Replace("android", "").Replace("ios", "").Replace(" ", "");
// ATLog.log("compareVersionToInt() >>> after curVersion: " + curVersion + " curNewVersion: " + curNewVersion);
// long intCurVersion = long.Parse(curVersion);
// long intNewVersion = long.Parse(curNewVersion);
// return intNewVersion - intCurVersion;
// }
//比较Unity集成的版本
public static VersionComparisonResult CompareUnityMediationVersions(string versionA, string versionB)
{
if (versionA.Equals(versionB)) return VersionComparisonResult.Equal;
// Unity version would be of format: android_w.x.y.z_ios_a.b.c.d
// For Android only versions it would be: android_w.x.y.z
// For iOS only version it would be: ios_a.b.c.d
// After splitting into their respective components, the versions would be at the odd indices.
var versionAComponents = versionA.Split('_').ToList();
var versionBComponents = versionB.Split('_').ToList();
var androidComparison = VersionComparisonResult.Equal;
if (versionA.Contains("android") && versionB.Contains("android"))
{
var androidVersionA = versionAComponents[1];
var androidVersionB = versionBComponents[1];
androidComparison = CompareVersions(androidVersionA, androidVersionB);
// Remove the Android version component so that iOS versions can be processed.
versionAComponents.RemoveRange(0, 2);
versionBComponents.RemoveRange(0, 2);
}
else if (versionA.Contains("android"))
{
androidComparison = VersionComparisonResult.Greater;
// Remove the Android version component so that iOS versions can be processed.
versionAComponents.RemoveRange(0, 2);
}
else if (versionB.Contains("android"))
{
androidComparison = VersionComparisonResult.Lesser;
// Remove the Android version component so that iOS version can be processed.
versionBComponents.RemoveRange(0, 2);
}
var iosComparison = VersionComparisonResult.Equal;
if (versionA.Contains("ios") && versionB.Contains("ios"))
{
var iosVersionA = versionAComponents[1];
var iosVersionB = versionBComponents[1];
iosComparison = CompareVersions(iosVersionA, iosVersionB);
}
else if (versionA.Contains("ios"))
{
iosComparison = VersionComparisonResult.Greater;
}
else if (versionB.Contains("ios"))
{
iosComparison = VersionComparisonResult.Lesser;
}
// If either one of the Android or iOS version is greater, the entire version should be greater.
return (androidComparison == VersionComparisonResult.Greater || iosComparison == VersionComparisonResult.Greater) ? VersionComparisonResult.Greater : VersionComparisonResult.Lesser;
}
//只比较Android、iOS
public static VersionComparisonResult CompareVersions(string versionA, string versionB)
{
if (string.IsNullOrEmpty(versionA) || string.IsNullOrEmpty(versionB) || versionA.Equals(versionB))
{
return VersionComparisonResult.Equal;
}
// var versionAComponents = versionA.Replace(".", "");
// var versionBComponents = versionB.Replace(".", "");
// var charArrayA = versionAComponents.ToCharArray();
// var charArrayB = versionBComponents.ToCharArray();
// for(var i = 0; i < charArrayA.Length; i++)
// {
// var aVersion = 0;
// int.TryParse(charArrayA[i].ToString(), out aVersion);
// var bVersion = 0;
// int.TryParse(charArrayB[i].ToString(), out bVersion);
// if (aVersion < bVersion) return VersionComparisonResult.Lesser;
// if (aVersion > bVersion) return VersionComparisonResult.Greater;
// }
try
{
var aVersionArrays = versionA.Split('.');
var bVersionArrays = versionB.Split('.');
var arrayLength = Mathf.Min(aVersionArrays.Length, bVersionArrays.Length);
for (var i = 0; i < arrayLength; i++)
{
var aVersionStr = aVersionArrays[i];
var bVersionStr = bVersionArrays[i];
var aVersionInt = int.Parse(aVersionStr);
var bVersionInt = int.Parse(bVersionStr);
if (i == arrayLength - 1) //末尾最后一个
{
if (aVersionStr.Length > bVersionStr.Length)
{
int gapLength = aVersionStr.Length - bVersionStr.Length;
bVersionInt = bVersionInt * (gapLength * 10);
}
else if (aVersionStr.Length < bVersionStr.Length)
{
int gapLength = bVersionStr.Length - aVersionStr.Length;
aVersionInt = aVersionInt * (gapLength * 10);
}
}
if (aVersionInt < bVersionInt) return VersionComparisonResult.Lesser;
if (aVersionInt > bVersionInt) return VersionComparisonResult.Greater;
}
}
catch (Exception e)
{
ATLog.logError("CompareVersions failed: " + e.Message);
}
// // Split the version string into beta component and the underlying version.
// int piece;
// // Compare the non beta component of the version string.
// var versionAComponents = versionA.Split('.').Select(version => int.TryParse(version, out piece) ? piece : 0).ToArray();
// var versionBComponents = versionB.Split('.').Select(version => int.TryParse(version, out piece) ? piece : 0).ToArray();
// var length = Mathf.Max(versionAComponents.Length, versionBComponents.Length);
// for (var i = 0; i < length; i++)
// {
// var aComponent = i < versionAComponents.Length ? versionAComponents[i] : 0;
// var bComponent = i < versionBComponents.Length ? versionBComponents[i] : 0;
// if (aComponent < bComponent) return VersionComparisonResult.Lesser;
// if (aComponent > bComponent) return VersionComparisonResult.Greater;
// }
return VersionComparisonResult.Equal;
}
}
//后端下发的Plugin、android、iOS版本号
[Serializable]
public class ServerPluginVersion
{
public string platformName;
public string networkUrlVersion;
public string pluginVersion;
public string androidVersion;
public string iosVersion;
public string[] versionList;
}
[Serializable]
public class ServerNetworks
{
public ServerNetworkInfo[] GlobalSdk;
public ServerNetworkInfo[] ChinaSdk;
public string platformName;
public string version;
}
[Serializable]
public class ServerNetworkInfo
{
public string name;
public string displayName;
public string downloadUrl;
public string pluginFileName;
public ServerNetworkVersion versions;
}
[Serializable]
public class ServerNetworkVersion
{
public string android;
public string ios;
public string unity;
}
}

View File

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

View File

@@ -0,0 +1,66 @@
#if !UNITY_2017_2_OR_NEWER
using System;
using System.IO;
using UnityEngine.Networking;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public class ATDownloadHandler : DownloadHandlerScript
{
// Required by DownloadHandler base class. Called when you address the 'bytes' property.
protected override byte[] GetData()
{
return null;
}
private FileStream fileStream;
public ATDownloadHandler(string path) : base(new byte[2048])
{
var downloadDirectory = Path.GetDirectoryName(path);
if (!Directory.Exists(downloadDirectory))
{
Directory.CreateDirectory(downloadDirectory);
}
try
{
//Open the current file to write to
fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
catch (Exception exception)
{
// MaxSdkLogger.UserError(string.Format("Failed to create file at {0}\n{1}", path, exception.Message));
ATLog.logError(string.Format("Failed to create file at {0}\n{1}", path, exception.Message));
}
}
protected override bool ReceiveData(byte[] byteFromServer, int dataLength)
{
if (byteFromServer == null || byteFromServer.Length < 1 || fileStream == null)
{
return false;
}
try
{
//Write the current data to the file
fileStream.Write(byteFromServer, 0, dataLength);
}
catch (Exception exception)
{
fileStream.Close();
fileStream = null;
ATLog.logError(string.Format("Failed to download file{0}", exception.Message));
}
return true;
}
protected override void CompleteContent()
{
fileStream.Close();
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,74 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public class ATEditorCoroutine
{
/// <summary>
/// Keeps track of the coroutine currently running.
/// </summary>
private IEnumerator enumerator;
/// <summary>
/// Keeps track of coroutines that have yielded to the current enumerator.
/// </summary>
private readonly List<IEnumerator> history = new List<IEnumerator>();
private ATEditorCoroutine(IEnumerator enumerator) {
this.enumerator = enumerator;
}
public static ATEditorCoroutine startCoroutine(IEnumerator enumerator) {
var coroutine = new ATEditorCoroutine(enumerator);
coroutine.Start();
return coroutine;
}
private void Start()
{
EditorApplication.update += OnEditorUpdate;
}
/// <summary>
/// Stops the coroutine.
/// </summary>
public void Stop()
{
if (EditorApplication.update == null) return;
EditorApplication.update -= OnEditorUpdate;
}
private void OnEditorUpdate()
{
if (enumerator.MoveNext())
{
// If there is a coroutine to yield for inside the coroutine, add the initial one to history and continue the second one
if (enumerator.Current is IEnumerator)
{
history.Add(enumerator);
enumerator = (IEnumerator) enumerator.Current;
}
}
else
{
// Current coroutine has ended, check if we have more coroutines in history to be run.
if (history.Count == 0)
{
// No more coroutines to run, stop updating.
Stop();
}
// Step out and finish the code in the coroutine that yielded to it
else
{
var index = history.Count - 1;
enumerator = history[index];
history.RemoveAt(index);
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,493 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using UnityEditor.PackageManager.Requests;
using UnityEditor.PackageManager;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public class ATIntegrationManager
{
public static ATIntegrationManager Instance = new ATIntegrationManager();
private UnityWebRequest downloadPluginRequest;
private const string AnyThinkAds = "AnyThinkAds";
//AnyThink的unity插件
public static string AnyThinkNetworkName = "Core";
private const string ATSdkAssetExportPath = "AnyThinkAds/Script/";
public static readonly string GradleTemplatePath = Path.Combine("Assets/Plugins/Android", "mainTemplate.gradle");
public static readonly string DefaultPluginExportPath = Path.Combine("Assets", AnyThinkAds);
private ATIntegrationManager()
{
}
public void CancelDownload()
{
if (downloadPluginRequest == null) return;
downloadPluginRequest.Abort();
}
public IEnumerator loadNetworksData(PluginData pluginData, Action<PluginData> callback)
{
if (pluginData == null)
{
callback(null);
}
else
{
var networksRequest = UnityWebRequest.Get(ATNetInfo.getNetworkListUrl(pluginData.networkUrlVersion));
var webRequest = networksRequest.SendWebRequest();
while (!webRequest.isDone)
{
yield return new WaitForSeconds(0.1f);
}
#if UNITY_2020_1_OR_NEWER
if (networksRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
if (networksRequest.isNetworkError || networksRequest.isHttpError)
#else
if (networksRequest.isError)
#endif
{
Debug.Log("loadNetworksData failed.");
callback(pluginData);
}
else
{
//解析network列表的版本数据
string netowrksJson = networksRequest.downloadHandler.text;
pluginData.mediatedNetworks = ATDataUtil.parseNetworksJson(pluginData, netowrksJson);
//初始化AnyThink的core network
Network coreNetwork = ATPluginSetting.Instance.CoreNetwork;
if (coreNetwork != null)
{
pluginData.anyThink = coreNetwork;
}
ATLog.log("loadNetworksData() >>> mediatedNetworks: " + pluginData.mediatedNetworks);
callback(pluginData);
}
}
}
public IEnumerator loadPluginData(Action<PluginData> callback)
{
var anythinkVersionRequest = UnityWebRequest.Get(ATNetInfo.getPluginConfigUrl());
var webRequest = anythinkVersionRequest.SendWebRequest();
while (!webRequest.isDone)
{
yield return new WaitForSeconds(0.1f);
}
#if UNITY_2020_1_OR_NEWER
if (anythinkVersionRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
if (anythinkVersionRequest.isNetworkError || anythinkVersionRequest.isHttpError)
#else
if (anythinkVersionRequest.isError)
#endif
{
Debug.Log("loadPluginData failed.");
callback(null);
}
else
{
//解析Anythink的版本数据
string anythinkVersionJson = anythinkVersionRequest.downloadHandler.text;
PluginData pluginData = ATDataUtil.parsePluginDataJson(anythinkVersionJson);
Debug.Log("loadPluginData succeed.");
callback(pluginData);
}
}
//默认下载core包在下载完network的数据时。
public void downloadCorePlugin(PluginData pluginData)
{
Network network = pluginData.anyThink;
int country = pluginData.country;
ATLog.log("downloadCorePlugin() >>> network: " + network);
if (network == null)
{
return;
}
bool isInstalled = ATConfig.isNetworkInstalled(network.Name, country);
ATLog.log("downloadCorePlugin() >>> isInstalled: " + isInstalled);
if (!isInstalled)
{
downloadPlugin(network, false);
// ATEditorCoroutine.startCoroutine(downloadPluginWithEnumerator(network, false));
} else {
handlerVersionAdapter(pluginData);
}
}
public void networkInstallOrUpdate(PluginData pluginData, Network network)
{
bool uninstall = true;
if (pluginData != null)
{
Network coreNetwork = pluginData.anyThink;
if (coreNetwork != null)
{
if (coreNetwork.isReqiureUpdate()) //network有更新并且core包也有更新则更新core包然后core包更新完会自动去更新全部network
{
uninstall = false;
network = coreNetwork;
}
}
}
int country = ATConfig.getLocalCountry();
if (ATConfig.isNetworkInstalled(network.Name, country))
{
if (uninstall)
{
uninstallNetwork(network, country);
}
downloadPlugin(network, false);
}
else
{
downloadPlugin(network, true);
}
}
/// <summary>
/// Downloads the plugin file for a given network.
/// </summary>
/// <param name="network">Network for which to download the current version.</param>
/// <param name="showImport">Whether or not to show the import window when downloading. Defaults to <c>true</c>.</param>
/// <returns></returns>
public void downloadPlugin(Network network, bool showImport = true)
{
ATEditorCoroutine.startCoroutine(downloadPluginWithEnumerator(network, showImport));
}
public IEnumerator downloadPluginWithEnumerator(Network network, bool showImport = true)
{
ATLog.log("downloadPluginWithEnumerator() >>> network: " + network);
if (downloadPluginRequest != null)
{
downloadPluginRequest.Dispose();
}
var path = Path.Combine(Application.temporaryCachePath, ATAssetDatabaseManager.Instance.GetPluginFileName(network));
ATLog.log("downloadPluginWithEnumerator() >>> path: " + path);
#if UNITY_2017_2_OR_NEWER
var downloadHandler = new DownloadHandlerFile(path);
#else
var downloadHandler = new ATDownloadHandler(path);
#endif
downloadPluginRequest = new UnityWebRequest(network.DownloadUrl)
{
method = UnityWebRequest.kHttpVerbGET,
downloadHandler = downloadHandler
};
#if UNITY_2017_2_OR_NEWER
var operation = downloadPluginRequest.SendWebRequest();
#else
var operation = downloadPluginRequest.Send();
#endif
while (!operation.isDone)
{
yield return new WaitForSeconds(0.1f); // Just wait till downloadPluginRequest is completed. Our coroutine is pretty rudimentary.
if (operation.progress != 1 && operation.isDone)
{
CallDownloadPluginProgressCallback(network.DisplayName, operation.progress, operation.isDone);
}
}
#if UNITY_2020_1_OR_NEWER
if (downloadPluginRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
if (downloadPluginRequest.isNetworkError || downloadPluginRequest.isHttpError)
#else
if (downloadPluginRequest.isError)
#endif
{
ATLog.logError(downloadPluginRequest.error);
}
else
{
CallDownloadPluginProgressCallback(network.DisplayName, 1, true);
// importingNetwork = network;
ATAssetDatabaseManager.Instance.importingNetwork = network;
AssetDatabase.Refresh();
AssetDatabase.ImportPackage(path, showImport);
}
downloadPluginRequest.Dispose();
downloadPluginRequest = null;
}
private static void CallDownloadPluginProgressCallback(string pluginName, float progress, bool isDone)
{
var callback = ATAssetDatabaseManager.Instance.downloadPluginProgressCallback;
if (callback == null) return;
callback(pluginName, progress, isDone);
}
// private static void CallImportPackageCompletedCallback(Network network)
// {
// ATLog.log("CallImportPackageCompletedCallback() >>> network: " + network);
// if (network != null)
// {
// ATConfig.saveInstalledNetworkVersion(network.Name, network.LatestVersions);
// }
// var callback = ATAssetDatabaseManager.Instance.importPackageCompletedCallback;
// if (callback == null) return;
// callback(network);
// }
//更新network已安装的版本
public void UpdateCurrentVersions(Network network)
{
if (network == null)
{
return;
}
bool isCoreNetwork = network.Name.Equals(AnyThinkNetworkName);
Versions curVerions = ATConfig.getInstalledNetworkVersion(network.Name, ATConfig.getLocalCountry());
network.CurrentVersions = curVerions;
network.CurrentToLatestVersionComparisonResult = ATDataUtil.getVersionComparisonResult(curVerions, network.LatestVersions, !isCoreNetwork);
// if (isCoreNetwork)
// {
// network.CurrentVersions.Unity = ATConfig.PLUGIN_VERSION;
// }
ATLog.log("UpdateCurrentVersions() >>> Name: " + network.Name + " latest Unity Version: " + network.LatestVersions.Unity);
}
public void uninstallNetwork(Network network, int country)
{
foreach (var filePath in ATConfig.getNetworkFilesPath(network.Name, country))
{
if (Directory.Exists(filePath))
{
FileUtil.DeleteFileOrDirectory(filePath);
}
if (File.Exists(filePath + ".meta"))
{
FileUtil.DeleteFileOrDirectory(filePath + ".meta");
}
}
ATConfig.removeInstalledNetworkVersion(network.Name, country);
UpdateCurrentVersions(network);
}
public void updateAnyThinkPlugin(PluginData pluginData)
{
Network coreNetwork = pluginData.anyThink;
bool unityUpdate = ATDataUtil.CompareVersions(coreNetwork.CurrentVersions.Unity, pluginData.pluginVersion) == VersionComparisonResult.Lesser;
if (unityUpdate)
{
Application.OpenURL(ATNetInfo.getPluginDownloadUrl(pluginData.pluginVersion));
// ATEditorCoroutine.startCoroutine(downloadAnyThinkPlugin(pluginData.pluginVersion));
}
else
{
downloadPlugin(coreNetwork);
}
}
public IEnumerator downloadAnyThinkPlugin(string pluginVersion)
{
Network network = new Network();
network.Name = "AnyThinkPlugin";
network.PluginFileName = ATNetInfo.getPluginFileName(pluginVersion);
network.DownloadUrl = ATNetInfo.getPluginDownloadUrl(pluginVersion);
//https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/Plugin/2.0.0/AnyThinkPlugin_2.0.0.unitypackage
var path = Path.Combine(Application.temporaryCachePath, network.PluginFileName);
ATLog.log("downloadPluginWithEnumerator() >>> path: " + path);
#if UNITY_2017_2_OR_NEWER
var downloadHandler = new DownloadHandlerFile(path);
#else
var downloadHandler = new ATDownloadHandler(path);
#endif
var downloadPluginRequest = new UnityWebRequest(network.DownloadUrl)
{
method = UnityWebRequest.kHttpVerbGET,
downloadHandler = downloadHandler
};
#if UNITY_2017_2_OR_NEWER
var operation = downloadPluginRequest.SendWebRequest();
#else
var operation = downloadPluginRequest.Send();
#endif
while (!operation.isDone)
{
yield return new WaitForSeconds(0.1f); // Just wait till downloadPluginRequest is completed. Our coroutine is pretty rudimentary.
if (operation.progress != 1 && operation.isDone)
{
CallDownloadPluginProgressCallback(network.Name, operation.progress, operation.isDone);
}
}
#if UNITY_2020_1_OR_NEWER
if (downloadPluginRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
if (downloadPluginRequest.isNetworkError || downloadPluginRequest.isHttpError)
#else
if (downloadPluginRequest.isError)
#endif
{
ATLog.logError(downloadPluginRequest.error);
}
else
{
CallDownloadPluginProgressCallback(network.Name, 1, true);
// importingNetwork = network;
ATAssetDatabaseManager.Instance.importingNetwork = network;
AssetDatabase.Refresh();
AssetDatabase.ImportPackage(path, false);
}
}
//处理插件版本,pangle、csj兼容问题
public void handlerVersionAdapter(PluginData pluginData) {
string comparePluginVersion = "2.0.1";
//插件版本>=2.0.1
VersionComparisonResult comparisonResult = ATDataUtil.CompareVersions(pluginData.pluginVersion, comparePluginVersion);
if (comparisonResult == VersionComparisonResult.Equal || comparisonResult == VersionComparisonResult.Greater) {
Network coreNetwork = pluginData.anyThink;
bool isChina = ATConfig.isSelectedChina();
if (isChina) {
//国内Android需要把原来已安装的pangle目录删除掉2.0.1插件后用csj作为目录
string androidPanglePath = ATConfig.CHINA_ANDROID_NETWORK_FILES_PARENT_PATH + "pangle";
deleteFilePath(androidPanglePath);
}
//海外iOS需要把原来已安装的pangle_nonChina目录删除掉2.0.1插件后用pangle作为目录
string iOSNonChinaPanglePath = ATConfig.IOS_NETWORK_FILES_PARENT_PATH + "pangle_nonChina";
//国内iOS需要把原来已安装的pangle_China目录删除掉2.0.1插件后用csj作为目录
string iOSPanglePath = ATConfig.IOS_NETWORK_FILES_PARENT_PATH + "pangle_China";
deleteFilePath(iOSNonChinaPanglePath);
deleteFilePath(iOSPanglePath);
}
}
private void deleteFilePath(string filePath) {
if (Directory.Exists(filePath))
{
FileUtil.DeleteFileOrDirectory(filePath);
}
if (File.Exists(filePath + ".meta"))
{
FileUtil.DeleteFileOrDirectory(filePath + ".meta");
}
}
}
[Serializable]
public class PluginData
{
public string networkUrlVersion;
public string pluginVersion; //插件版本
public int country = ATConfig.CHINA_COUNTRY; //默认是1=china
public Network anyThink;
public Network[] mediatedNetworks;
}
[Serializable]
public class Network : IComparable<Network>
{
//
// Sample network data:
//
// {
// "Name": "adcolony",
// "DisplayName": "AdColony",
// "DownloadUrl": "https://bintray.com/applovin/Unity-Mediation-Packages/download_file?file_path=AppLovin-AdColony-Adapters-Android-3.3.10.1-iOS-3.3.7.2.unitypackage",
// "PluginFileName": "AppLovin-AdColony-Adapters-Android-3.3.10.1-iOS-3.3.7.2.unitypackage",
// "DependenciesFilePath": "MaxSdk/Mediation/AdColony/Editor/Dependencies.xml",
// "LatestVersions" : {
// "Unity": "android_3.3.10.1_ios_3.3.7.2",
// "Android": "3.3.10.1",
// "Ios": "3.3.7.2"
// }
// }
//
public string Name;
public string DisplayName;
public string DownloadUrl;
public string DependenciesFilePath;
public string PluginFileName;
public string[] PluginFilePaths;
public Versions LatestVersions; //最新版本
public Versions CurrentVersions; //当前版本
[NonSerialized] public VersionComparisonResult CurrentToLatestVersionComparisonResult = VersionComparisonResult.Equal;
// [NonSerialized] public bool RequiresUpdate = CurrentToLatestVersionComparisonResult == VersionComparisonResult.Lesser;
public bool isReqiureUpdate()
{
return CurrentToLatestVersionComparisonResult == VersionComparisonResult.Lesser;
}
public int CompareTo(Network other)
{
return this.DisplayName.CompareTo(other.DisplayName);
}
}
/// <summary>
/// A helper data class used to get current versions from Dependency.xml files.
/// </summary>
[Serializable]
public class Versions
{
public string Unity;
public string Android;
public string Ios;
public override bool Equals(object value)
{
var versions = value as Versions;
return versions != null
&& (Unity == null || Unity.Equals(versions.Unity))
&& (Android == null || Android.Equals(versions.Android))
&& (Ios == null || Ios.Equals(versions.Ios));
}
public bool HasEqualSdkVersions(Versions versions)
{
return versions != null && versions.Android == Android && versions.Ios == Ios;
}
public override int GetHashCode()
{
return new { Unity, Android, Ios }.GetHashCode();
}
public Versions clone()
{
Versions cloneObj = new Versions();
cloneObj.Android = Android;
cloneObj.Ios = Ios;
cloneObj.Unity = Unity;
return cloneObj;
}
}
public enum VersionComparisonResult
{
Lesser = -1,
Equal = 0,
Greater = 1
}
}

View File

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

View File

@@ -0,0 +1,779 @@
using System;
using System.Collections;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public class ATIntegrationManagerWindow : EditorWindow
{
private const string windowTitle = "AnyThink Integration Manager";
private const string uninstallIconExportPath = "AnyThinkPlugin/Resources/Images/uninstall_icon.png";
private const string alertIconExportPath = "AnyThinkPlugin/Resources/Images/alert_icon.png";
private const string warningIconExportPath = "AnyThinkPlugin/Resources/Images/warning_icon.png";
private static readonly Color darkModeTextColor = new Color(0.29f, 0.6f, 0.8f);
private GUIStyle titleLabelStyle;
private GUIStyle headerLabelStyle;
private GUIStyle environmentValueStyle;
private GUIStyle wrapTextLabelStyle;
private GUIStyle linkLabelStyle;
private GUIStyle iconStyle;
private Texture2D uninstallIcon;
private Texture2D alertIcon;
private Texture2D warningIcon;
private Vector2 scrollPosition;
private static readonly Vector2 windowMinSize = new Vector2(750, 750);
private const float actionFieldWidth = 60f;
private const float upgradeAllButtonWidth = 80f;
private const float networkFieldMinWidth = 100f;
private const float versionFieldMinWidth = 190f;
private const float privacySettingLabelWidth = 200f;
private const float networkFieldWidthPercentage = 0.22f;
private const float versionFieldWidthPercentage = 0.36f; // There are two version fields. Each take 40% of the width, network field takes the remaining 20%.
private static float previousWindowWidth = windowMinSize.x;
private static GUILayoutOption networkWidthOption = GUILayout.Width(networkFieldMinWidth);
private static GUILayoutOption versionWidthOption = GUILayout.Width(versionFieldMinWidth);
private static GUILayoutOption sdkKeyTextFieldWidthOption = GUILayout.Width(520);
private static GUILayoutOption privacySettingFieldWidthOption = GUILayout.Width(400);
private static readonly GUILayoutOption fieldWidth = GUILayout.Width(actionFieldWidth);
private static readonly GUILayoutOption upgradeAllButtonFieldWidth = GUILayout.Width(upgradeAllButtonWidth);
private ATEditorCoroutine loadDataCoroutine;
private PluginData pluginData;
private bool pluginDataLoadFailed;
private bool networkButtonsEnabled = true;
private bool shouldShowGoogleWarning;
private int curSelectCountryInt;
// private int dropdownIndex = 0;
public static void ShowManager()
{
var manager = GetWindow<ATIntegrationManagerWindow>(utility: true, title: windowTitle, focus: true);
manager.minSize = windowMinSize;
}
//定义UI的Style
private void Awake()
{
titleLabelStyle = new GUIStyle(EditorStyles.label)
{
fontSize = 14,
fontStyle = FontStyle.Bold,
fixedHeight = 20
};
headerLabelStyle = new GUIStyle(EditorStyles.label)
{
fontSize = 12,
fontStyle = FontStyle.Bold,
fixedHeight = 18
};
environmentValueStyle = new GUIStyle(EditorStyles.label)
{
alignment = TextAnchor.MiddleRight
};
linkLabelStyle = new GUIStyle(EditorStyles.label)
{
wordWrap = true,
normal = { textColor = EditorGUIUtility.isProSkin ? darkModeTextColor : Color.blue }
};
wrapTextLabelStyle = new GUIStyle(EditorStyles.label)
{
wordWrap = true
};
iconStyle = new GUIStyle(EditorStyles.miniButton)
{
fixedWidth = 18,
fixedHeight = 18,
padding = new RectOffset(1, 1, 1, 1)
};
// Load uninstall icon texture.
var uninstallIconData = File.ReadAllBytes(ATSdkUtil.GetAssetPathForExportPath(uninstallIconExportPath));
uninstallIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false); // 1. Initial size doesn't matter here, will be automatically resized once the image asset is loaded. 2. Set mipChain to false, else the texture has a weird blurry effect.
uninstallIcon.LoadImage(uninstallIconData);
// Load alert icon texture.
var alertIconData = File.ReadAllBytes(ATSdkUtil.GetAssetPathForExportPath(alertIconExportPath));
alertIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false);
alertIcon.LoadImage(alertIconData);
// Load warning icon texture.
var warningIconData = File.ReadAllBytes(ATSdkUtil.GetAssetPathForExportPath(warningIconExportPath));
warningIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false);
warningIcon.LoadImage(warningIconData);
ATLog.log("Awake() >>> called");
ATAssetDatabaseManager.Instance.downloadPluginProgressCallback = OnDownloadPluginProgress;
ATAssetDatabaseManager.Instance.importPackageCompletedCallback = OnImportPackageCompleted;
ATLog.log("OnEnable() >>> called");
loadPluginData();
}
//这个方法在插件启动时会调用然后脚本重新加载时也会重新调用所以加载数据放在Awake中
private void OnEnable()
{
if (ATAssetDatabaseManager.Instance.downloadPluginProgressCallback == null)
{
ATAssetDatabaseManager.Instance.downloadPluginProgressCallback = OnDownloadPluginProgress;
}
if (ATAssetDatabaseManager.Instance.importPackageCompletedCallback == null)
{
ATAssetDatabaseManager.Instance.importPackageCompletedCallback = OnImportPackageCompleted;
}
}
private void OnDisable()
{
if (loadDataCoroutine != null)
{
loadDataCoroutine.Stop();
loadDataCoroutine = null;
}
ATIntegrationManager.Instance.CancelDownload();
EditorUtility.ClearProgressBar();
// Saves the AppLovinSettings object if it has been changed.
AssetDatabase.SaveAssets();
}
private void OnGUI()
{
// OnGUI is called on each frame draw, so we don't want to do any unnecessary calculation if we can avoid it. So only calculate it when the width actually changed.
if (Math.Abs(previousWindowWidth - position.width) > 1)
{
previousWindowWidth = position.width;
CalculateFieldWidth();
}
using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPosition, false, false))
{
scrollPosition = scrollView.scrollPosition;
GUILayout.Space(5);
EditorGUILayout.LabelField("Region (Only for Android, iOS is not affected by region)", titleLabelStyle);
DrawCountryUI();
EditorGUILayout.LabelField("AnyThink Plugin Details", titleLabelStyle);
//显示插件版本号
DrawPluginDetails();
using (new EditorGUILayout.HorizontalScope(GUILayout.ExpandHeight(false)))
{
EditorGUILayout.LabelField("Mediated Networks", titleLabelStyle);
DrawUpgradeAllButton();
}
// Draw mediated networks
DrawMediatedNetworks();
}
if (GUI.changed)
{
ATPluginSetting.Instance.SaveAsync();
}
}
/// <summary>
/// Callback method that will be called with progress updates when the plugin is being downloaded.
/// </summary>
public static void OnDownloadPluginProgress(string pluginName, float progress, bool done)
{
ATLog.logFormat("OnDownloadPluginProgress() >>> pluginName: {0}, progress: {1}, done: {2}", new object[] { pluginName, progress, done });
// Download is complete. Clear progress bar.
if (done || progress == 1)
{
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
}
// Download is in progress, update progress bar.
else
{
if (EditorUtility.DisplayCancelableProgressBar(windowTitle, string.Format("Downloading {0} plugin...", pluginName), progress))
{
ATLog.log("OnDownloadPluginProgress() >>> click cancel download");
ATIntegrationManager.Instance.CancelDownload();
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
}
}
}
private void OnImportPackageCompleted(Network network)
{
// var parentDirectory = network.Name.Equals(ATIntegrationManager.AnyThinkNetworkName) ? ATIntegrationManager.PluginParentDirectory : ATIntegrationManager.MediationSpecificPluginParentDirectory;
if (pluginData != null && network != null && network.Name.Equals(ATIntegrationManager.AnyThinkNetworkName))
{
pluginData.anyThink = network;
ATPluginSetting.Instance.CoreNetwork = network;
//更新了core包则自动更新全部network
if (NetworksRequireUpgrade())
{
startUpgradeAllNetwork();
}
}
ATIntegrationManager.Instance.UpdateCurrentVersions(network);
// UpdateShouldShowGoogleWarningIfNeeded();
}
//获取插件和SDK的版本数据
private void loadPluginData()
{
if (loadDataCoroutine != null)
{
loadDataCoroutine.Stop();
}
loadDataCoroutine = ATEditorCoroutine.startCoroutine(ATIntegrationManager.Instance.loadPluginData(data =>
{
if (data == null)
{
pluginDataLoadFailed = true;
}
else
{
ATLog.log("loadNetworksData() >>> pluginData: " + data);
pluginData = data;
pluginDataLoadFailed = false;
loadNetworksData(data);
// UpdateShouldShowGoogleWarningIfNeeded();
}
CalculateFieldWidth();
Repaint();
}));
}
//获取networks
private void loadNetworksData(PluginData pluginData)
{
ATEditorCoroutine.startCoroutine(ATIntegrationManager.Instance.loadNetworksData(pluginData, data =>
{
pluginData = data;
ATIntegrationManager.Instance.downloadCorePlugin(data);
Repaint();
}));
}
private void switchCountry(int country)
{
// ATIntegrationManager.Instance.switchCountry(pluginData, country);
var originCountry = ATConfig.getLocalCountry();
pluginData.country = country;
ATConfig.removeInstalledNetworkVersion(ATIntegrationManager.AnyThinkNetworkName, originCountry);
var networks = pluginData.mediatedNetworks;
if (networks != null)
{
foreach(var network in networks)
{
ATConfig.removeInstalledNetworkVersion(network.Name, originCountry);
}
}
ATConfig.saveLocalCountry(country);
//删除国内的core包和network
string anythinkAdsPath = ATConfig.ANYTHINK_SDK_FILES_PATH;
if (Directory.Exists(anythinkAdsPath))
{
FileUtil.DeleteFileOrDirectory(anythinkAdsPath);
}
string metaFile = anythinkAdsPath + ".meta";
if (File.Exists(metaFile))
{
FileUtil.DeleteFileOrDirectory(metaFile);
}
// AssetDatabase.Refresh();
//重新开始走network
loadPluginData();
}
private void CalculateFieldWidth()
{
var currentWidth = position.width;
var availableWidth = currentWidth - actionFieldWidth - 80; // NOTE: Magic number alert. This is the sum of all the spacing the fields and other UI elements.
var networkLabelWidth = Math.Max(networkFieldMinWidth, availableWidth * networkFieldWidthPercentage);
networkWidthOption = GUILayout.Width(networkLabelWidth);
var versionLabelWidth = Math.Max(versionFieldMinWidth, availableWidth * versionFieldWidthPercentage);
versionWidthOption = GUILayout.Width(versionLabelWidth);
const int textFieldOtherUiElementsWidth = 45; // NOTE: Magic number alert. This is the sum of all the spacing the fields and other UI elements.
var availableTextFieldWidth = currentWidth - networkLabelWidth - textFieldOtherUiElementsWidth;
sdkKeyTextFieldWidthOption = GUILayout.Width(availableTextFieldWidth);
var availableUserDescriptionTextFieldWidth = currentWidth - privacySettingLabelWidth - textFieldOtherUiElementsWidth;
privacySettingFieldWidthOption = GUILayout.Width(availableUserDescriptionTextFieldWidth);
}
private void DrawCountryUI()
{
// GUILayout.BeginHorizontal();
GUILayout.Space(4);
using (new EditorGUILayout.HorizontalScope("box"))
{
GUILayout.Space(5);
int countryInt = ATConfig.CHINA_COUNTRY; //默认是中国
if (pluginData != null)
{
countryInt = pluginData.country;
}
string[] options = new string[] { "ChinaMainland", "Overseas" };
// 创建Dropdown组件
int curDropdownIndex = ATDataUtil.isChina(countryInt) ? 0 : 1;
int dropdownIndex = EditorGUILayout.Popup("Select Region:", curDropdownIndex, options);
curSelectCountryInt = dropdownIndex == 0 ? ATConfig.CHINA_COUNTRY : ATConfig.NONCHINA_COUNTRY;
//变化才设置
if (pluginData != null && curSelectCountryInt != countryInt)
{
ATLog.log("DrawCountryUI() >>> curSelectCountryInt: " + curSelectCountryInt + " countryInt: " + countryInt);
//Unity需要更换Network
switchCountry(curSelectCountryInt);
}
GUILayout.Space(5);
}
GUILayout.Space(4);
DrawAndroidXUI();
// GUILayout.EndHorizontal();
}
private void DrawAndroidXUI()
{
if (!ATDataUtil.isChina(curSelectCountryInt)) {
return;
}
EditorGUILayout.LabelField("AndroidX (Only for Android)", titleLabelStyle);
GUILayout.Space(4);
using (new EditorGUILayout.HorizontalScope("box"))
{
GUILayout.Space(5);
bool enableAndroidX = ATPluginSetting.Instance.EnableAndroidX;
string[] options = new string[] { "Disable", "Enable" };
// 创建Dropdown组件
int lastDropdownIndex = enableAndroidX ? 1 : 0;
int curDropdownIndex = EditorGUILayout.Popup("Enable AndroidX:", lastDropdownIndex, options);
//变化才设置
if (curDropdownIndex != lastDropdownIndex)
{
ATLog.log("DrawAndroidXUI() >>> curDropdownIndex: " + curDropdownIndex + " lastDropdownIndex: " + lastDropdownIndex);
ATPluginSetting.Instance.EnableAndroidX = curDropdownIndex == 1;
}
GUILayout.Space(5);
}
GUILayout.Space(4);
}
private void DrawPluginDetails()
{
// GUILayout.BeginHorizontal();
GUILayout.Space(10);
using (new EditorGUILayout.VerticalScope("box"))
{
// Draw plugin version details
DrawHeaders("Platform", false);
if (pluginData == null)
{
DrawEmptyPluginData();
return;
}
var anythink = pluginData.anyThink;
// Immediately after downloading and importing a plugin the entire IDE reloads and current versions can be null in that case. Will just show loading text in that case.
if (pluginData.anyThink == null || pluginData.anyThink.CurrentVersions == null || pluginData.anyThink.LatestVersions == null)
{
DrawEmptyPluginData();
}
else
{
ATLog.log("DrawPluginDetails() >>> anythink.CurrentVersions: " + anythink.CurrentVersions + " LatestVersions: " + anythink.LatestVersions);
// Check if a newer version is available to enable the upgrade button.
DrawPluginDetailRow("Unity 3D", anythink.CurrentVersions.Unity, pluginData.pluginVersion);
DrawPluginDetailRow("Android", anythink.CurrentVersions.Android, anythink.LatestVersions.Android);
DrawPluginDetailRow("iOS", anythink.CurrentVersions.Ios, anythink.LatestVersions.Ios);
// BeginHorizontal combined with FlexibleSpace makes sure that the button is centered horizontally.
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
//检查插件和Android、iOS的原生sdk是否需要更新如果其中之一需要都显示更新按钮
GUI.enabled = anythink.isReqiureUpdate();
if (GUILayout.Button(new GUIContent("Upgrade"), fieldWidth))
{
//点击更新按钮的操作
ATIntegrationManager.Instance.updateAnyThinkPlugin(pluginData);
}
GUI.enabled = true;
GUILayout.Space(5);
GUILayout.EndHorizontal();
GUILayout.Space(5);
}
#if !UNITY_2018_2_OR_NEWER
EditorGUILayout.HelpBox("AnyThink Unity plugin will soon require Unity 2018.2 or newer to function. Please upgrade to a newer Unity version.", MessageType.Warning);
#endif
}
GUILayout.Space(5);
// GUILayout.EndHorizontal();
}
private void DrawHeaders(string firstColumnTitle, bool drawAction)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5);
EditorGUILayout.LabelField(firstColumnTitle, headerLabelStyle, networkWidthOption);
EditorGUILayout.LabelField("Current Version", headerLabelStyle, versionWidthOption);
GUILayout.Space(3);
EditorGUILayout.LabelField("Latest Version", headerLabelStyle, versionWidthOption);
GUILayout.Space(3);
if (drawAction)
{
GUILayout.FlexibleSpace();
GUILayout.Button("Actions", headerLabelStyle, fieldWidth);
GUILayout.Space(5);
}
}
GUILayout.Space(4);
}
private void DrawEmptyPluginData()
{
GUILayout.Space(5);
// Plugin data failed to load. Show error and retry button.
if (pluginDataLoadFailed)
{
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(5);
EditorGUILayout.LabelField("Failed to load plugin data. Please click retry or restart the integration manager.", titleLabelStyle);
if (GUILayout.Button("Retry", fieldWidth))
{
pluginDataLoadFailed = false;
loadPluginData();
}
GUILayout.Space(5);
GUILayout.EndHorizontal();
GUILayout.Space(10);
}
// Still loading, show loading label.
else
{
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("Loading data...", titleLabelStyle);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(10);
}
GUILayout.Space(5);
}
private void DrawPluginDetailRow(string platform, string currentVersion, string latestVersion)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5);
EditorGUILayout.LabelField(new GUIContent(platform), networkWidthOption);
EditorGUILayout.LabelField(new GUIContent(currentVersion), versionWidthOption);
GUILayout.Space(3);
EditorGUILayout.LabelField(new GUIContent(latestVersion), versionWidthOption);
GUILayout.Space(3);
}
GUILayout.Space(4);
}
private void DrawUpgradeAllButton()
{
GUI.enabled = NetworksRequireUpgrade();
if (GUILayout.Button(new GUIContent("Upgrade All"), upgradeAllButtonFieldWidth))
{
startUpgradeAllNetwork();
}
GUI.enabled = true;
GUILayout.Space(10);
}
private bool NetworksRequireUpgrade()
{
if (pluginData == null || pluginData.mediatedNetworks == null) return false;
var networks = pluginData.mediatedNetworks;
if (networks == null)
{
return false;
}
try
{
foreach (var network in networks)
{
if (network.CurrentVersions != null && !string.IsNullOrEmpty(network.CurrentVersions.Unity))
{
ATLog.log("NetworksRequireUpgrade() >>> name: " + network.Name + " isReqiureUpdate: " + network.isReqiureUpdate() +
" curVersion: " + network.CurrentVersions.Unity + " latestVersion: " + network.LatestVersions.Unity);
network.CurrentToLatestVersionComparisonResult = ATDataUtil.getVersionComparisonResult(network.CurrentVersions, network.LatestVersions, true);
if (network.isReqiureUpdate())
{
return true;
}
}
}
}
catch (Exception e)
{
ATLog.logError("NetworksRequireUpgrade failed: " + e.Message);
}
// return networks.Any(network => network.CurrentVersions != null && ATConfig.isNetworkInstalled(network.Name, ATConfig.getLocalCountry()) && network.isReqiureUpdate());
return false;
}
private void DrawMediatedNetworks()
{
GUILayout.BeginHorizontal();
GUILayout.Space(10);
using (new EditorGUILayout.VerticalScope("box"))
{
DrawHeaders("Network", true);
// Immediately after downloading and importing a plugin the entire IDE reloads and current versions can be null in that case. Will just show loading text in that case.
if (pluginData == null || pluginData.mediatedNetworks == null)
{
ATLog.log("DrawMediatedNetworks failed.");
DrawEmptyPluginData();
}
else
{
var networks = pluginData.mediatedNetworks;
foreach (var network in networks)
{
DrawNetworkDetailRow(network);
}
GUILayout.Space(10);
}
}
GUILayout.Space(5);
GUILayout.EndHorizontal();
}
private void DrawNetworkDetailRow(Network network)
{
if (network == null) return;
string action;
var currentVersion = "";
if (network.CurrentVersions != null)
{
currentVersion = network.CurrentVersions.Unity;
}
var latestVersion = network.LatestVersions.Unity;
bool isActionEnabled;
bool isInstalled;
if (string.IsNullOrEmpty(currentVersion))
{
action = "Install";
currentVersion = "Not Installed";
isActionEnabled = true;
isInstalled = false;
}
else
{
isInstalled = true;
// action = "Installed";
// isActionEnabled = false;
// A newer version is available
var comparison = network.CurrentToLatestVersionComparisonResult;
if (comparison == VersionComparisonResult.Lesser)
{
action = "Upgrade";
isActionEnabled = true;
}
// Current installed version is newer than latest version from DB (beta version)
else if (comparison == VersionComparisonResult.Greater)
{
action = "Installed";
isActionEnabled = false;
}
// Already on the latest version
else
{
action = "Installed";
isActionEnabled = false;
}
}
GUILayout.Space(4);
using (new EditorGUILayout.HorizontalScope(GUILayout.ExpandHeight(false)))
{
GUILayout.Space(5);
EditorGUILayout.LabelField(new GUIContent(network.DisplayName), networkWidthOption);
EditorGUILayout.LabelField(new GUIContent(currentVersion), versionWidthOption);
GUILayout.Space(3);
EditorGUILayout.LabelField(new GUIContent(latestVersion), versionWidthOption);
GUILayout.Space(3);
GUILayout.FlexibleSpace();
if (network.isReqiureUpdate())
{
GUILayout.Label(new GUIContent { image = alertIcon, tooltip = "Adapter not compatible, please update to the latest version." }, iconStyle);
}
// else if ((network.DisplayName.Equals("Admob") || network.DisplayName.Equals("GOOGLE_AD_MANAGER_NETWORK")) && shouldShowGoogleWarning)
// {
// GUILayout.Label(new GUIContent { image = warningIcon, tooltip = "You may see unexpected errors if you use different versions of the AdMob and Google Ad Manager adapter SDKs." }, iconStyle);
// }
GUI.enabled = networkButtonsEnabled && isActionEnabled;
if (GUILayout.Button(new GUIContent(action), fieldWidth))
{
// Download the plugin.jkfjkfdani
// AppLovinEditorCoroutine.StartCoroutine(AppLovinIntegrationManager.Instance.DownloadPlugin(network));
// ATIntegrationManager.Instance.downloadPlugin(network);
ATIntegrationManager.Instance.networkInstallOrUpdate(pluginData, network);
}
GUI.enabled = true;
GUILayout.Space(2);
GUI.enabled = networkButtonsEnabled && isInstalled;
if (GUILayout.Button(new GUIContent { image = uninstallIcon, tooltip = "Uninstall" }, iconStyle))
{
EditorUtility.DisplayProgressBar("Integration Manager", "Deleting " + network.Name + "...", 0.5f);
ATIntegrationManager.Instance.uninstallNetwork(network, pluginData.country);
//Refresh UI
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
}
GUI.enabled = true;
GUILayout.Space(5);
}
if (isInstalled)
{
// Custom integration for AdMob where the user can enter the Android and iOS App IDs.
if (network.Name.Equals("Admob") && network.CurrentVersions != null)
{
// Custom integration requires Google AdMob adapter version newer than android_19.0.1.0_ios_7.57.0.0.
if (ATDataUtil.CompareUnityMediationVersions(network.CurrentVersions.Unity, "android_19.0.1.0_ios_7.57.0.0") == VersionComparisonResult.Greater)
{
GUILayout.BeginHorizontal();
GUILayout.Space(20);
using (new EditorGUILayout.VerticalScope("box"))
{
string requiredVersion = "android_19.2.0.0_ios_7.61.0.0";
string warningMessage = "The current version of AppLovin MAX plugin requires Google adapter version newer than " + requiredVersion + " to enable auto-export of AdMob App ID.";
// if (isPluginMoved)
// {
// requiredVersion = "android_19.6.0.1_ios_7.69.0.0";
// warningMessage = "Looks like the MAX plugin has been moved to a different directory. This requires Google adapter version newer than " + requiredVersion + " for auto-export of AdMob App ID to work correctly.";
// }
// else
// {
// requiredVersion = "android_19.2.0.0_ios_7.61.0.0";
// warningMessage = "The current version of AppLovin MAX plugin requires Google adapter version newer than " + requiredVersion + " to enable auto-export of AdMob App ID.";
// }
GUILayout.Space(2);
if (ATDataUtil.CompareUnityMediationVersions(network.CurrentVersions.Unity, requiredVersion) == VersionComparisonResult.Greater)
{
ATPluginSetting.Instance.AdMobAndroidAppId = DrawTextField("App ID (Android)", ATPluginSetting.Instance.AdMobAndroidAppId, networkWidthOption);
ATPluginSetting.Instance.AdMobIosAppId = DrawTextField("App ID (iOS)", ATPluginSetting.Instance.AdMobIosAppId, networkWidthOption);
}
else
{
EditorGUILayout.HelpBox(warningMessage, MessageType.Warning);
}
}
GUILayout.EndHorizontal();
}
}
}
}
private string DrawTextField(string fieldTitle, string text, GUILayoutOption labelWidth, GUILayoutOption textFieldWidthOption = null)
{
GUILayout.BeginHorizontal();
GUILayout.Space(4);
EditorGUILayout.LabelField(new GUIContent(fieldTitle), labelWidth);
GUILayout.Space(4);
text = (textFieldWidthOption == null) ? GUILayout.TextField(text) : GUILayout.TextField(text, textFieldWidthOption);
GUILayout.Space(4);
GUILayout.EndHorizontal();
GUILayout.Space(4);
return text;
}
private bool DrawOtherSettingsToggle(bool value, string text)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(4);
var toggleValue = GUILayout.Toggle(value, text);
GUILayout.Space(4);
return toggleValue;
}
}
private void startUpgradeAllNetwork()
{
ATEditorCoroutine.startCoroutine(UpgradeAllNetworks());
}
private IEnumerator UpgradeAllNetworks()
{
networkButtonsEnabled = false;
EditorApplication.LockReloadAssemblies();
var networks = pluginData.mediatedNetworks;
foreach (var network in networks)
{
// if (ATConfig.isNetworkInstalled(network.Name, ATConfig.getLocalCountry()))
// {
// ATLog.log("UpgradeAllNetworks() >>> name: " + network.Name + " isReqiureUpdate: " + network.isReqiureUpdate() +
// " curVersion: " + network.CurrentVersions.Unity + " latestVersion: " + network.LatestVersions.Unity);
// network.CurrentToLatestVersionComparisonResult = ATDataUtil.getVersionComparisonResult(network.CurrentVersions, network.LatestVersions, true);
// if (network.isReqiureUpdate())
// {
// yield return ATIntegrationManager.Instance.downloadPluginWithEnumerator(network, false);
// }
// }
if (network.CurrentVersions != null && !string.IsNullOrEmpty(network.CurrentVersions.Unity))
{
ATLog.log("UpgradeAllNetworks() >>> name: " + network.Name + " isReqiureUpdate: " + network.isReqiureUpdate() +
" curVersion: " + network.CurrentVersions.Unity + " latestVersion: " + network.LatestVersions.Unity);
network.CurrentToLatestVersionComparisonResult = ATDataUtil.getVersionComparisonResult(network.CurrentVersions, network.LatestVersions, true);
if (network.isReqiureUpdate())
{
yield return ATIntegrationManager.Instance.downloadPluginWithEnumerator(network, false);
}
}
}
EditorApplication.UnlockReloadAssemblies();
networkButtonsEnabled = true;
//The pluginData becomes stale after the networks have been updated, and we should re-load it.
loadPluginData();
}
}
}

View File

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

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class ATLog {
public static void log(string msg)
{
// string msg =
Debug.Log(msg);
}
public static void log(string tag, string msg)
{
Debug.Log(tag + ": " + msg);
}
public static void logFormat(string msg, object[] args)
{
Debug.LogFormat(msg, args);
}
public static void logError(string msg)
{
Debug.LogError(msg);
}
}

View File

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

View File

@@ -0,0 +1,40 @@
//菜单栏
using UnityEditor;
using UnityEngine;
// using DownloadManager;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
#if AnyThinkSDKEditor
public class AnyThinkMenuItems : MonoBehaviour
{
/**
* The special characters at the end represent a shortcut for this action.
*
* % - ctrl on Windows, cmd on macOS
* # - shift
* & - alt
*
* So, (shift + cmd/ctrl + t) will launch the integration manager
*/
[MenuItem("AnyThink/SDK Manager %#t")]
private static void IntegrationManager()
{
ATIntegrationManagerWindow.ShowManager();
}
[MenuItem("AnyThink/Documentation")]
public static void Documentation()
{
if (ATConfig.isSelectedChina()) {
Application.OpenURL("https://docs.toponad.com/#/zh-cn/unity/unity_doc/unity_access_plugin_des_doc");
} else {
Application.OpenURL("https://docs.toponad.com/#/en-us/unity/unity_doc/unity_access_doc_new?id=_3-integration");
}
}
}
#endif
}

View File

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

View File

@@ -0,0 +1,45 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AnyThink.Scripts.IntegrationManager.Editor
{
public static class ATNetInfo {
public static string platformName = "AnyThink";
public static string ATDownloadDir = "Assets/AnyThinkAds/Dependencies/";
public static string ATDependencyDir = "Assets/AnyThinkAds/Plugins/";
public static string sdk = "sdk";
public static string Android = "Android";
public static string iOS = "iOS";
public static string localConfig = "Assets/AnyThinkPlugin/Editor/localConfig.json";
private static string unityPluginConfigUrl = "https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/unity_plugin_config.json"; //插件和nythink的版本号列表
private static string unityPluginConfigUrlDebug = "https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/unity_plugin_config_debug.json"; //插件和nythink的版本号列表
public static string packagePath = "https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/";
public static int isGlobal=1; //0:国外 //1:国内
public static string getPluginConfigUrl()
{
return ATConfig.isDebug ? unityPluginConfigUrlDebug : unityPluginConfigUrl;
}
public static string getNetworkListUrl(String ver)
{
return "https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/"+ver+"/network_new.json";
}
public static string getPluginFileName(string pluginVersion)
{
return "AnyThinkPlugin_" + pluginVersion + ".unitypackage";
}
//https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/Plugin/2.0.0/AnyThinkPlugin_2.0.0.unitypackage
public static string getPluginDownloadUrl(string pluginVersion)
{
return "https://topon-sdk-release.oss-cn-hangzhou.aliyuncs.com/Unity/Plugin/" + pluginVersion + "/" + getPluginFileName(pluginVersion);
}
}
}

View File

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

View File

@@ -0,0 +1,118 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
using AnyThink.Scripts.IntegrationManager.Editor;
using Network = AnyThink.Scripts.IntegrationManager.Editor.Network;
public class ATPluginSetting : ScriptableObject
{
public const string SettingsExportPath = "Assets/AnyThinkPlugin/Resources/Assets/ATPluginSetting.asset";
private static ATPluginSetting instance;
[SerializeField] private string adMobAndroidAppId = string.Empty;
[SerializeField] private string adMobIosAppId = string.Empty;
[SerializeField] private AnyThink.Scripts.IntegrationManager.Editor.Network coreNetwork = null;
[SerializeField] private bool enableAndroidX = false;
// [SerializeField] private int country = ATConfig.CHINA_COUNTRY;
// [SerializeField] private Dictionary<string, Versions> installedNetwork = new Dictionary<string, Versions>();
public static ATPluginSetting Instance
{
get
{
if (instance == null)
{
var settingsDir = Path.GetDirectoryName(SettingsExportPath);
if (!Directory.Exists(settingsDir))
{
Directory.CreateDirectory(settingsDir);
}
string settingsFilePath = SettingsExportPath;
instance = AssetDatabase.LoadAssetAtPath<ATPluginSetting>(settingsFilePath);
if (instance != null) return instance;
instance = CreateInstance<ATPluginSetting>();
AssetDatabase.CreateAsset(instance, settingsFilePath);
// initCoreNetwork();
}
return instance;
}
}
// private static void initCoreNetwork()
// {
// Versions curVerions = ATConfig.getInstalledNetworkVersion(ATIntegrationManager.AnyThinkNetworkName, ATConfig.getLocalCountry());
// if (curVerions != null)
// {
// AnyThink.Scripts.IntegrationManager.Editor.Network coreNetwork = new AnyThink.Scripts.IntegrationManager.Editor.Network();
// coreNetwork.CurrentVersions = curVerions;
// ATPluginSetting.Instance.CoreNetwork = coreNetwork;
// }
// }
/// <summary>
/// AdMob Android App ID.
/// </summary>
public string AdMobAndroidAppId
{
get { return Instance.adMobAndroidAppId; }
set { Instance.adMobAndroidAppId = value; }
}
/// <summary>
/// AdMob iOS App ID.
/// </summary>
public string AdMobIosAppId
{
get { return Instance.adMobIosAppId; }
set { Instance.adMobIosAppId = value; }
}
public AnyThink.Scripts.IntegrationManager.Editor.Network CoreNetwork
{
get { return Instance.coreNetwork; }
set { Instance.coreNetwork = value; }
}
// public void saveInstalledNetwork(string networkName, int country, Versions versions)
// {
// string key = networkName + "_" + country;
// if (installedNetwork.ContainsKey(key))
// {
// installedNetwork.Remove(key);
// }
// installedNetwork.Add(key, versions);
// SaveAsync();
// }
// public Versions getInstalledNetwork(string networkName, int country)
// {
// Versions versions;
// installedNetwork.TryGetValue(networkName + "_" + country, out versions);
// return versions;
// }
/// <summary>
/// Saves the instance of the settings.
/// </summary>
public void SaveAsync()
{
EditorUtility.SetDirty(instance);
}
public bool EnableAndroidX
{
get { return Instance.enableAndroidX; }
set { Instance.enableAndroidX = value; }
}
}

View File

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

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
// #if UNITY_EDITOR //是Unity编辑器才引入
using UnityEditor;
// #endif
public class ATSdkUtil
{
// #if UNITY_EDITOR
/// <summary>
/// Gets the path of the asset in the project for a given Anythink plugin export path.
/// </summary>
/// <param name="exportPath">The actual exported path of the asset.</param>
/// <returns>The exported path of the MAX plugin asset or the default export path if the asset is not found.</returns>
public static string GetAssetPathForExportPath(string exportPath)
{
var defaultPath = Path.Combine("Assets", exportPath);
var assetLabelToFind = "l:al_max_export_path-" + exportPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var assetGuids = AssetDatabase.FindAssets(assetLabelToFind);
return assetGuids.Length < 1 ? defaultPath : AssetDatabase.GUIDToAssetPath(assetGuids[0]);
}
public static bool Exists(string filePath)
{
return Directory.Exists(filePath) || File.Exists(filePath);
}
// #endif
}

View File

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

View File

@@ -0,0 +1,10 @@
{
"name": "AnyThinkPlugin.Script.IntegrationManager.Editor",
"references": [
"AnyThinkPlugin.Script"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": []
}

View File

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