repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System.Collections.Generic; using System.IO; using Facebook.Unity; using Facebook.Unity.Settings; using UnityEditor; using UnityEngine; [InitializeOnLoad] [CustomEditor(typeof(FacebookSettings))] public class FacebookSettingsEditor : Editor { private bool showFacebookInitSettings = false; private bool showAndroidUtils = false; private bool showIOSSettings = false; private bool showAppEventsSettings = false; private bool showAppLinksSettings = false; private bool showAboutSection = false; private GUIContent appNameLabel = new GUIContent( "App Name:", "For your own use and organization.\n(ex. 'dev', 'qa', 'prod')"); private GUIContent appIdLabel = new GUIContent( "Facebook App Id:", "Facebook App Ids can be found at https://developers.facebook.com/apps"); private GUIContent clientTokenLabel = new GUIContent( "Client Token:", "For login purposes. Client Token can be found at https://developers.facebook.com/apps, in Settings -> Advanced"); private GUIContent urlSuffixLabel = new GUIContent("URL Scheme Suffix [?]", "Use this to share Facebook APP ID's across multiple iOS apps. https://developers.facebook.com/docs/ios/share-appid-across-multiple-apps-ios-sdk/"); private GUIContent cookieLabel = new GUIContent("Cookie [?]", "Sets a cookie which your server-side code can use to validate a user's Facebook session"); private GUIContent loggingLabel = new GUIContent("Logging [?]", "(Web Player only) If true, outputs a verbose log to the Javascript console to facilitate debugging."); private GUIContent statusLabel = new GUIContent("Status [?]", "If 'true', attempts to initialize the Facebook object with valid session data."); private GUIContent xfbmlLabel = new GUIContent("Xfbml [?]", "(Web Player only If true) Facebook will immediately parse any XFBML elements on the Facebook Canvas page hosting the app"); private GUIContent frictionlessLabel = new GUIContent("Frictionless Requests [?]", "Use frictionless app requests, as described in their own documentation."); private GUIContent androidKeystorePathLabel = new GUIContent("Android Keystore Path [?]", "Set this field if you have a customized android keystore path"); private GUIContent packageNameLabel = new GUIContent("Package Name [?]", "aka: the bundle identifier"); private GUIContent classNameLabel = new GUIContent("Class Name [?]", "aka: the activity name"); private GUIContent debugAndroidKeyLabel = new GUIContent("Debug Android Key Hash [?]", "Copy this key to the Facebook Settings in order to test a Facebook Android app"); private GUIContent autoLogAppEventsLabel = new GUIContent("Auto Logging App Events [?]", "If true, automatically log app install, app launch and in-app purchase events to Facebook. https://developers.facebook.com/docs/app-events/"); private GUIContent advertiserIDCollectionLabel = new GUIContent("AdvertiserID Collection [?]", "If true, attempts to collect user's AdvertiserID. https://developers.facebook.com/docs/app-ads/targeting/mobile-advertiser-ids/"); private GUIContent sdkVersion = new GUIContent("SDK Version [?]", "This Unity Facebook SDK version. If you have problems or compliments please include this so we know exactly what version to look out for."); public FacebookSettingsEditor() { FacebookSettings.RegisterChangeEventCallback(this.SettingsChanged); } [MenuItem("Facebook/Edit Settings")] public static void Edit() { var instance = FacebookSettings.NullableInstance; if (instance == null) { instance = ScriptableObject.CreateInstance<FacebookSettings>(); string properPath = Path.Combine(Application.dataPath, FacebookSettings.FacebookSettingsPath); if (!Directory.Exists(properPath)) { Directory.CreateDirectory(properPath); } string fullPath = Path.Combine( Path.Combine("Assets", FacebookSettings.FacebookSettingsPath), FacebookSettings.FacebookSettingsAssetName + FacebookSettings.FacebookSettingsAssetExtension); AssetDatabase.CreateAsset(instance, fullPath); } Selection.activeObject = FacebookSettings.Instance; } [MenuItem("Facebook/Developers Page")] public static void OpenAppPage() { string url = "https://developers.facebook.com/apps/"; if (FacebookSettings.AppIds[FacebookSettings.SelectedAppIndex] != "0") { url += FacebookSettings.AppIds[FacebookSettings.SelectedAppIndex]; } Application.OpenURL(url); } [MenuItem("Facebook/SDK Documentation")] public static void OpenDocumentation() { string url = "https://developers.facebook.com/docs/unity/"; Application.OpenURL(url); } [MenuItem("Facebook/SDK Facebook Group")] public static void OpenFacebookGroup() { string url = "https://www.facebook.com/groups/491736600899443/"; Application.OpenURL(url); } [MenuItem("Facebook/Report a SDK Bug")] public static void ReportABug() { string url = "https://developers.facebook.com/bugs"; Application.OpenURL(url); } void OnEnable() { this.showAndroidUtils = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android; this.showIOSSettings = EditorUserBuildSettings.activeBuildTarget.ToString() == "iOS"; } public override void OnInspectorGUI() { EditorGUILayout.Separator(); this.AppIdGUI(); EditorGUILayout.Separator(); this.FBParamsInitGUI(); EditorGUILayout.Separator(); this.AndroidUtilGUI(); EditorGUILayout.Separator(); this.IOSUtilGUI(); EditorGUILayout.Separator(); this.AppEventsSettingsGUI(); EditorGUILayout.Separator(); this.AppLinksUtilGUI(); EditorGUILayout.Separator(); this.AboutGUI(); EditorGUILayout.Separator(); this.BuildGUI(); } private void SettingsChanged() { EditorUtility.SetDirty((FacebookSettings)target); } private void AppIdGUI() { EditorGUILayout.LabelField("Add the Facebook App Id(s) associated with this game"); if (FacebookSettings.AppIds.Count == 0 || FacebookSettings.AppId == "0") { EditorGUILayout.HelpBox("Invalid App Id", MessageType.Error); } for (int i = 0; i < FacebookSettings.AppIds.Count; ++i) { EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField(string.Format("App #{0}", i + 1)); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.appNameLabel); FacebookSettings.AppLabels[i] = EditorGUILayout.TextField(FacebookSettings.AppLabels[i]); EditorGUILayout.EndHorizontal(); GUI.changed = false; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.appIdLabel); FacebookSettings.AppIds[i] = EditorGUILayout.TextField(FacebookSettings.AppIds[i]); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.clientTokenLabel); FacebookSettings.ClientTokens[i] = EditorGUILayout.TextField(FacebookSettings.ClientTokens[i]); EditorGUILayout.EndHorizontal(); if (GUI.changed) { this.SettingsChanged(); ManifestMod.GenerateManifest(); } EditorGUILayout.EndVertical(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add Another App Id")) { FacebookSettings.AppLabels.Add("New App"); FacebookSettings.AppIds.Add("0"); FacebookSettings.ClientTokens.Add(string.Empty); FacebookSettings.AppLinkSchemes.Add(new FacebookSettings.UrlSchemes()); this.SettingsChanged(); } if (FacebookSettings.AppLabels.Count > 1) { if (GUILayout.Button("Remove Last App Id")) { FacebookSettings.AppLabels.Pop(); FacebookSettings.AppIds.Pop(); FacebookSettings.ClientTokens.Pop(); FacebookSettings.AppLinkSchemes.Pop(); this.SettingsChanged(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (FacebookSettings.AppIds.Count > 1) { EditorGUILayout.HelpBox("2) Select Facebook App Id to be compiled with this game", MessageType.None); GUI.changed = false; FacebookSettings.SelectedAppIndex = EditorGUILayout.Popup( "Selected App Id", FacebookSettings.SelectedAppIndex, FacebookSettings.AppIds.ToArray()); if (GUI.changed) { ManifestMod.GenerateManifest(); } EditorGUILayout.Space(); } else { FacebookSettings.SelectedAppIndex = 0; } } private void FBParamsInitGUI() { this.showFacebookInitSettings = EditorGUILayout.Foldout(this.showFacebookInitSettings, "FB.Init() Parameters"); if (this.showFacebookInitSettings) { FacebookSettings.Cookie = EditorGUILayout.Toggle(this.cookieLabel, FacebookSettings.Cookie); FacebookSettings.Logging = EditorGUILayout.Toggle(this.loggingLabel, FacebookSettings.Logging); FacebookSettings.Status = EditorGUILayout.Toggle(this.statusLabel, FacebookSettings.Status); FacebookSettings.Xfbml = EditorGUILayout.Toggle(this.xfbmlLabel, FacebookSettings.Xfbml); FacebookSettings.FrictionlessRequests = EditorGUILayout.Toggle(this.frictionlessLabel, FacebookSettings.FrictionlessRequests); } EditorGUILayout.Space(); } private void IOSUtilGUI() { this.showIOSSettings = EditorGUILayout.Foldout(this.showIOSSettings, "iOS Build Settings"); if (this.showIOSSettings) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.urlSuffixLabel, GUILayout.Width(135), GUILayout.Height(16)); FacebookSettings.IosURLSuffix = EditorGUILayout.TextField(FacebookSettings.IosURLSuffix); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); } private void AndroidUtilGUI() { this.showAndroidUtils = EditorGUILayout.Foldout(this.showAndroidUtils, "Android Build Facebook Settings"); if (this.showAndroidUtils) { if (!FacebookAndroidUtil.SetupProperly) { var msg = "Your Android setup is not right. Check the documentation."; switch (FacebookAndroidUtil.SetupError) { case FacebookAndroidUtil.ErrorNoSDK: msg = "You don't have the Android SDK setup! Go to " + (Application.platform == RuntimePlatform.OSXEditor ? "Unity" : "Edit") + "->Preferences... and set your Android SDK Location under External Tools"; break; case FacebookAndroidUtil.ErrorNoKeystore: msg = "Your android debug keystore file is missing! You can create new one by creating and building empty Android project in Ecplise."; break; case FacebookAndroidUtil.ErrorNoKeytool: msg = "Keytool not found. Make sure that Java is installed, and that Java tools are in your path."; break; case FacebookAndroidUtil.ErrorNoOpenSSL: msg = "OpenSSL not found. Make sure that OpenSSL is installed, and that it is in your path."; break; case FacebookAndroidUtil.ErrorKeytoolError: msg = "Unkown error while getting Debug Android Key Hash."; break; } EditorGUILayout.HelpBox(msg, MessageType.Warning); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.androidKeystorePathLabel, GUILayout.Width(180), GUILayout.Height(16)); FacebookSettings.AndroidKeystorePath = EditorGUILayout.TextField(FacebookSettings.AndroidKeystorePath); EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField( "Copy and Paste these into your \"Native Android App\" Settings on developers.facebook.com/apps"); this.SelectableLabelField(this.packageNameLabel, Utility.GetApplicationIdentifier()); this.SelectableLabelField(this.classNameLabel, ManifestMod.DeepLinkingActivityName); this.SelectableLabelField(this.debugAndroidKeyLabel, FacebookAndroidUtil.DebugKeyHash); if (GUILayout.Button("Regenerate Android Manifest")) { ManifestMod.GenerateManifest(); } } EditorGUILayout.Space(); } private void AppEventsSettingsGUI() { this.showAppEventsSettings = EditorGUILayout.Foldout(this.showAppEventsSettings, "App Events Settings"); if (this.showAppEventsSettings) { FacebookSettings.AutoLogAppEventsEnabled = EditorGUILayout.Toggle(this.autoLogAppEventsLabel, FacebookSettings.AutoLogAppEventsEnabled); FacebookSettings.AdvertiserIDCollectionEnabled = EditorGUILayout.Toggle(this.advertiserIDCollectionLabel, FacebookSettings.AdvertiserIDCollectionEnabled); } EditorGUILayout.Space(); } private void AppLinksUtilGUI() { this.showAppLinksSettings = EditorGUILayout.Foldout(this.showAppLinksSettings, "App Links Settings"); if (this.showAppLinksSettings) { for (int i = 0; i < FacebookSettings.AppLinkSchemes.Count; ++i) { EditorGUILayout.LabelField(string.Format("App Link Schemes for '{0}'", FacebookSettings.AppLabels[i])); List<string> currentAppLinkSchemes = FacebookSettings.AppLinkSchemes[i].Schemes; for (int j = 0; j < currentAppLinkSchemes.Count; ++j) { GUI.changed = false; string scheme = EditorGUILayout.TextField(currentAppLinkSchemes[j]); if (scheme != currentAppLinkSchemes[j]) { currentAppLinkSchemes[j] = scheme; this.SettingsChanged(); } if (GUI.changed) { ManifestMod.GenerateManifest(); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add a Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Add(string.Empty); this.SettingsChanged(); } if (currentAppLinkSchemes.Count > 0) { if (GUILayout.Button("Remove Last Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Pop(); } } EditorGUILayout.EndHorizontal(); } } } private void AboutGUI() { this.showAboutSection = EditorGUILayout.Foldout(this.showAboutSection, "About the Facebook SDK"); if (this.showAboutSection) { this.SelectableLabelField(this.sdkVersion, FacebookSdkVersion.Build); EditorGUILayout.Space(); } } private void SelectableLabelField(GUIContent label, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16)); EditorGUILayout.SelectableLabel(value, GUILayout.Height(16)); EditorGUILayout.EndHorizontal(); } private void BuildGUI() { if (GUILayout.Button("Build SDK Package")) { try { string outputPath = FacebookBuild.ExportPackage(); EditorUtility.DisplayDialog("Finished Exporting unityPackage", "Exported to: " + outputPath, "Okay"); } catch (System.Exception e) { EditorUtility.DisplayDialog("Error Exporting unityPackage", e.Message, "Okay"); } } } } }
417
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; public static class Utility { private static string BundleIdentifier = "bundleIdentifier"; private static string ApplicationIdentifier = "applicationIdentifier"; public static T Pop<T>(this IList<T> list) { if (!list.Any()) { throw new InvalidOperationException("Attempting to pop item on empty list."); } int index = list.Count - 1; T value = list[index]; list.RemoveAt(index); return value; } public static bool TryGetValue<T>( this IDictionary<string, object> dictionary, string key, out T value) { object resultObj; if (dictionary.TryGetValue(key, out resultObj) && resultObj is T) { value = (T)resultObj; return true; } value = default(T); return false; } public static string GetApplicationIdentifier() { Type playerSettingType = typeof(PlayerSettings); PropertyInfo info = playerSettingType.GetProperty(ApplicationIdentifier) ?? playerSettingType.GetProperty(BundleIdentifier); if (info != null) { string applicationIdentifier = (string)info.GetValue(playerSettingType, null); if (applicationIdentifier is string) { return applicationIdentifier; } } return null; } } }
79
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; [InitializeOnLoad] public class AndroidSupportLibraryResolver { static AndroidSupportLibraryResolver() { AndroidSupportLibraryResolver.setupDependencies(); } private static void setupDependencies() { // Setup the resolver using reflection as the module may not be // available at compile time. Type playServicesSupport = Google.VersionHandler.FindClass( "Google.JarResolver", "Google.JarResolver.PlayServicesSupport"); if (playServicesSupport == null) { return; } object svcSupport = Google.VersionHandler.InvokeStaticMethod( playServicesSupport, "CreateInstance", new object[] { "FacebookUnitySDK", EditorPrefs.GetString("AndroidSdkRoot"), "ProjectSettings" }); // com.android.support:support-v4 Google.VersionHandler.InvokeInstanceMethod( svcSupport, "DependOn", new object[] { "com.android.support", "support-v4", "25.3.1" }, namedArgs: new Dictionary<string, object>() { { "packageIds", new string[] { "extra-android-m2repository" } } }); AndroidSupportLibraryResolver.addSupportLibraryDependency(svcSupport, "support-v4", "25.3.1"); AndroidSupportLibraryResolver.addSupportLibraryDependency(svcSupport, "appcompat-v7", "25.3.1"); AndroidSupportLibraryResolver.addSupportLibraryDependency(svcSupport, "cardview-v7", "25.3.1"); AndroidSupportLibraryResolver.addSupportLibraryDependency(svcSupport, "customtabs", "25.3.1"); } public static void addSupportLibraryDependency( object svcSupport, String packageName, String version) { Google.VersionHandler.InvokeInstanceMethod( svcSupport, "DependOn", new object[] { "com.android.support", packageName, version }, namedArgs: new Dictionary<string, object>() { { "packageIds", new string[] { "extra-android-m2repository" } } }); } } }
126
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using Facebook.Unity.Settings; using Google; using UnityEditor; using UnityEngine; public class FacebookAndroidUtil { public const string ErrorNoSDK = "no_android_sdk"; public const string ErrorNoKeystore = "no_android_keystore"; public const string ErrorNoKeytool = "no_java_keytool"; public const string ErrorNoOpenSSL = "no_openssl"; public const string ErrorKeytoolError = "java_keytool_error"; private static string debugKeyHash; private static string setupError; public static bool SetupProperly { get { return DebugKeyHash != null; } } public static string DebugKeyHash { get { if (debugKeyHash == null) { if (!HasAndroidSDK()) { setupError = ErrorNoSDK; return null; } if (!HasAndroidKeystoreFile()) { setupError = ErrorNoKeystore; return null; } if (!DoesCommandExist("echo \"xxx\" | openssl base64")) { setupError = ErrorNoOpenSSL; return null; } if (!DoesCommandExist("keytool")) { setupError = ErrorNoKeytool; return null; } debugKeyHash = GetKeyHash("androiddebugkey", DebugKeyStorePath, "android"); } return debugKeyHash; } } public static string SetupError { get { return setupError; } } private static string DebugKeyStorePath { get { if (!string.IsNullOrEmpty(FacebookSettings.AndroidKeystorePath)) { return FacebookSettings.AndroidKeystorePath; } return (Application.platform == RuntimePlatform.WindowsEditor) ? System.Environment.GetEnvironmentVariable("HOMEDRIVE") + System.Environment.GetEnvironmentVariable("HOMEPATH") + @"\.android\debug.keystore" : System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + @"/.android/debug.keystore"; } } public static bool HasAndroidSDK() { string sdkPath = GetAndroidSdkPath(); return !string.IsNullOrEmpty(sdkPath) && System.IO.Directory.Exists(sdkPath); } public static bool HasAndroidKeystoreFile() { return System.IO.File.Exists(DebugKeyStorePath); } public static string GetAndroidSdkPath() { string sdkPath = EditorPrefs.GetString("AndroidSdkRoot"); if (string.IsNullOrEmpty(sdkPath) || EditorPrefs.GetBool("SdkUseEmbedded")) { try { sdkPath = (string)VersionHandler.InvokeStaticMethod(typeof(BuildPipeline), "GetPlaybackEngineDirectory", new object[] { BuildTarget.Android, BuildOptions.None }); } catch (Exception) { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GetName().Name == "UnityEditor.Android.Extensions") { sdkPath = Path.GetDirectoryName(assembly.Location); break; } } } } return sdkPath; } private static string GetKeyHash(string alias, string keyStore, string password) { var proc = new Process(); var arguments = @"""keytool -storepass {0} -keypass {1} -exportcert -alias {2} -keystore {3} | openssl sha1 -binary | openssl base64"""; if (Application.platform == RuntimePlatform.WindowsEditor) { proc.StartInfo.FileName = "cmd"; arguments = @"/C " + arguments; } else { proc.StartInfo.FileName = "bash"; arguments = @"-c " + arguments; } proc.StartInfo.Arguments = string.Format(arguments, password, password, alias, keyStore); proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); var keyHash = new StringBuilder(); while (!proc.HasExited) { keyHash.Append(proc.StandardOutput.ReadToEnd()); } switch (proc.ExitCode) { case 255: setupError = ErrorKeytoolError; return null; } return keyHash.ToString().TrimEnd('\n'); } private static bool DoesCommandExist(string command) { var proc = new Process(); if (Application.platform == RuntimePlatform.WindowsEditor) { proc.StartInfo.FileName = "cmd"; proc.StartInfo.Arguments = @"/C" + command; } else { proc.StartInfo.FileName = "bash"; proc.StartInfo.Arguments = @"-c " + command; } proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); if (Application.platform == RuntimePlatform.WindowsEditor) { return proc.ExitCode == 0; } else { return proc.ExitCode != 127; } } } }
212
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Xml; using Facebook.Unity; using Facebook.Unity.Settings; using UnityEditor; using UnityEngine; public class ManifestMod { public const string AppLinkActivityName = "com.facebook.unity.FBUnityAppLinkActivity"; public const string DeepLinkingActivityName = "com.facebook.unity.FBUnityDeepLinkingActivity"; public const string UnityLoginActivityName = "com.facebook.unity.FBUnityLoginActivity"; public const string UnityDialogsActivityName = "com.facebook.unity.FBUnityDialogsActivity"; public const string UnityGameRequestActivityName = "com.facebook.unity.FBUnityGameRequestActivity"; public const string UnityGamingServicesFriendFinderActivityName = "com.facebook.unity.FBUnityGamingServicesFriendFinderActivity"; public const string ApplicationIdMetaDataName = "com.facebook.sdk.ApplicationId"; public const string ClientTokenMetaDataName = "com.facebook.sdk.ClientToken"; public const string AutoLogAppEventsEnabled = "com.facebook.sdk.AutoLogAppEventsEnabled"; public const string AdvertiserIDCollectionEnabled = "com.facebook.sdk.AdvertiserIDCollectionEnabled"; public const string FacebookContentProviderName = "com.facebook.FacebookContentProvider"; public const string FacebookContentProviderAuthFormat = "com.facebook.app.FacebookContentProvider{0}"; public const string FacebookActivityName = "com.facebook.FacebookActivity"; public const string AndroidManifestPath = "Plugins/Android/AndroidManifest.xml"; public const string FacebookDefaultAndroidManifestPath = "FacebookSDK/SDK/Editor/android/DefaultAndroidManifest.xml"; public static void GenerateManifest() { var outputFile = Path.Combine(Application.dataPath, ManifestMod.AndroidManifestPath); // Create containing directory if it does not exist Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); // only copy over a fresh copy of the AndroidManifest if one does not exist if (!File.Exists(outputFile)) { ManifestMod.CreateDefaultAndroidManifest(outputFile); } UpdateManifest(outputFile); } public static bool CheckManifest() { bool result = true; var outputFile = Path.Combine(Application.dataPath, ManifestMod.AndroidManifestPath); if (!File.Exists(outputFile)) { Debug.LogError("An android manifest must be generated for the Facebook SDK to work. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\""); return false; } XmlDocument doc = new XmlDocument(); doc.Load(outputFile); if (doc == null) { Debug.LogError("Couldn't load " + outputFile); return false; } XmlNode manNode = FindChildNode(doc, "manifest"); XmlNode dict = FindChildNode(manNode, "application"); if (dict == null) { Debug.LogError("Error parsing " + outputFile); return false; } XmlElement loginElement; if (!ManifestMod.TryFindElementWithAndroidName(dict, UnityLoginActivityName, out loginElement)) { Debug.LogError(string.Format("{0} is missing from your android manifest. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\"", UnityLoginActivityName)); result = false; } var deprecatedMainActivityName = "com.facebook.unity.FBUnityPlayerActivity"; XmlElement deprecatedElement; if (ManifestMod.TryFindElementWithAndroidName(dict, deprecatedMainActivityName, out deprecatedElement)) { Debug.LogWarning(string.Format("{0} is deprecated and no longer needed for the Facebook SDK. Feel free to use your own main activity or use the default \"com.unity3d.player.UnityPlayerNativeActivity\"", deprecatedMainActivityName)); } return result; } public static void UpdateManifest(string fullPath) { string appId = FacebookSettings.AppId; string clientToken = FacebookSettings.ClientToken; if (!FacebookSettings.IsValidAppId) { Debug.LogError("You didn't specify a Facebook app ID. Please add one using the Facebook menu in the main Unity editor."); return; } XmlDocument doc = new XmlDocument(); doc.Load(fullPath); if (doc == null) { Debug.LogError("Couldn't load " + fullPath); return; } XmlNode manNode = FindChildNode(doc, "manifest"); XmlNode dict = FindChildNode(manNode, "application"); if (dict == null) { Debug.LogError("Error parsing " + fullPath); return; } string ns = dict.GetNamespaceOfPrefix("android"); // add the unity login activity XmlElement unityLoginElement = CreateUnityOverlayElement(doc, ns, UnityLoginActivityName); ManifestMod.SetOrReplaceXmlElement(dict, unityLoginElement); // add the unity dialogs activity XmlElement unityDialogsElement = CreateUnityOverlayElement(doc, ns, UnityDialogsActivityName); ManifestMod.SetOrReplaceXmlElement(dict, unityDialogsElement); XmlElement unityGamingFriendFinderElement = CreateUnityOverlayElement(doc, ns, UnityGamingServicesFriendFinderActivityName); ManifestMod.SetOrReplaceXmlElement(dict, unityGamingFriendFinderElement); ManifestMod.AddAppLinkingActivity(doc, dict, ns, FacebookSettings.AppLinkSchemes[FacebookSettings.SelectedAppIndex].Schemes); ManifestMod.AddSimpleActivity(doc, dict, ns, DeepLinkingActivityName, true); ManifestMod.AddSimpleActivity(doc, dict, ns, UnityGameRequestActivityName); // add the app id // <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="\ fb<APPID>" /> XmlElement appIdElement = doc.CreateElement("meta-data"); appIdElement.SetAttribute("name", ns, ApplicationIdMetaDataName); appIdElement.SetAttribute("value", ns, "fb" + appId); ManifestMod.SetOrReplaceXmlElement(dict, appIdElement); // add the client token // <meta-data android:name="com.facebook.sdk.ClientToken" android:value="\ <CLIENT_TOKEN>" /> XmlElement clientTokenElement = doc.CreateElement("meta-data"); clientTokenElement.SetAttribute("name", ns, ClientTokenMetaDataName); clientTokenElement.SetAttribute("value", ns, clientToken); ManifestMod.SetOrReplaceXmlElement(dict, clientTokenElement); // enable AutoLogAppEventsEnabled by default // <meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled" android:value="true"/> string autoLogAppEventsEnabled = FacebookSettings.AutoLogAppEventsEnabled.ToString().ToLower(); XmlElement autoLogAppEventsEnabledElement = doc.CreateElement("meta-data"); autoLogAppEventsEnabledElement.SetAttribute("name", ns, AutoLogAppEventsEnabled); autoLogAppEventsEnabledElement.SetAttribute("value", ns, autoLogAppEventsEnabled); ManifestMod.SetOrReplaceXmlElement(dict, autoLogAppEventsEnabledElement); // enable AdvertiserIDCollectionEnabled by default // <meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled" android:value="true"/> string advertiserIDCollectionEnabled = FacebookSettings.AdvertiserIDCollectionEnabled.ToString().ToLower(); XmlElement advertiserIDCollectionEnabledElement = doc.CreateElement("meta-data"); advertiserIDCollectionEnabledElement.SetAttribute("name", ns, AdvertiserIDCollectionEnabled); advertiserIDCollectionEnabledElement.SetAttribute("value", ns, advertiserIDCollectionEnabled); ManifestMod.SetOrReplaceXmlElement(dict, advertiserIDCollectionEnabledElement); // Add the facebook content provider // <provider // android:name="com.facebook.FacebookContentProvider" // android:authorities="com.facebook.app.FacebookContentProvider<APPID>" // android:exported="true" /> XmlElement contentProviderElement = CreateContentProviderElement(doc, ns, appId); ManifestMod.SetOrReplaceXmlElement(dict, contentProviderElement); // Remove the FacebookActivity since we can rely on it in the androidsdk aar as of v4.12 // (otherwise unity manifest merge likes fail if there's any difference at all) XmlElement facebookElement; if (TryFindElementWithAndroidName(dict, FacebookActivityName, out facebookElement)) { dict.RemoveChild(facebookElement); } // Save the document formatted XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (XmlWriter xmlWriter = XmlWriter.Create(fullPath, settings)) { doc.Save(xmlWriter); } } private static XmlNode FindChildNode(XmlNode parent, string name) { XmlNode curr = parent.FirstChild; while (curr != null) { if (curr.Name.Equals(name)) { return curr; } curr = curr.NextSibling; } return null; } private static void SetOrReplaceXmlElement( XmlNode parent, XmlElement newElement) { string attrNameValue = newElement.GetAttribute("name"); string elementType = newElement.Name; XmlElement existingElment; if (TryFindElementWithAndroidName(parent, attrNameValue, out existingElment, elementType)) { parent.ReplaceChild(newElement, existingElment); } else { parent.AppendChild(newElement); } } private static bool TryFindElementWithAndroidName( XmlNode parent, string attrNameValue, out XmlElement element, string elementType = "activity") { string ns = parent.GetNamespaceOfPrefix("android"); var curr = parent.FirstChild; while (curr != null) { var currXmlElement = curr as XmlElement; if (currXmlElement != null && currXmlElement.Name == elementType && currXmlElement.GetAttribute("name", ns) == attrNameValue) { element = currXmlElement; return true; } curr = curr.NextSibling; } element = null; return false; } private static void AddSimpleActivity(XmlDocument doc, XmlNode xmlNode, string ns, string className, bool export = false) { XmlElement element = CreateActivityElement(doc, ns, className, export); ManifestMod.SetOrReplaceXmlElement(xmlNode, element); } private static XmlElement CreateUnityOverlayElement(XmlDocument doc, string ns, string activityName) { // <activity android:name="activityName" android:configChanges="all|of|them" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"> // </activity> XmlElement activityElement = ManifestMod.CreateActivityElement(doc, ns, activityName); activityElement.SetAttribute("configChanges", ns, "fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"); activityElement.SetAttribute("theme", ns, "@android:style/Theme.Translucent.NoTitleBar.Fullscreen"); return activityElement; } private static XmlElement CreateContentProviderElement(XmlDocument doc, string ns, string appId) { XmlElement provierElement = doc.CreateElement("provider"); provierElement.SetAttribute("name", ns, FacebookContentProviderName); string authorities = string.Format(CultureInfo.InvariantCulture, FacebookContentProviderAuthFormat, appId); provierElement.SetAttribute("authorities", ns, authorities); provierElement.SetAttribute("exported", ns, "true"); return provierElement; } private static XmlElement CreateActivityElement(XmlDocument doc, string ns, string activityName, bool exported = false) { // <activity android:name="activityName" android:exported="true"> // </activity> XmlElement activityElement = doc.CreateElement("activity"); activityElement.SetAttribute("name", ns, activityName); if (exported) { activityElement.SetAttribute("exported", ns, "true"); } return activityElement; } private static void AddAppLinkingActivity(XmlDocument doc, XmlNode xmlNode, string ns, List<string> schemes) { XmlElement element = ManifestMod.CreateActivityElement(doc, ns, AppLinkActivityName, true); foreach (var scheme in schemes) { // We have to create an intent filter for each scheme since an intent filter // can have only one data element. XmlElement intentFilter = doc.CreateElement("intent-filter"); var action = doc.CreateElement("action"); action.SetAttribute("name", ns, "android.intent.action.VIEW"); intentFilter.AppendChild(action); var category = doc.CreateElement("category"); category.SetAttribute("name", ns, "android.intent.category.DEFAULT"); intentFilter.AppendChild(category); XmlElement dataElement = doc.CreateElement("data"); dataElement.SetAttribute("scheme", ns, scheme); intentFilter.AppendChild(dataElement); element.AppendChild(intentFilter); } ManifestMod.SetOrReplaceXmlElement(xmlNode, element); } private static void CreateDefaultAndroidManifest(string outputFile) { var inputFile = Path.Combine( EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml"); if (!File.Exists(inputFile)) { // Unity moved this file. Try to get it at its new location inputFile = Path.Combine( EditorApplication.applicationContentsPath, "PlaybackEngines/AndroidPlayer/Apk/AndroidManifest.xml"); } if (File.Exists(inputFile)) { File.Copy(inputFile, outputFile); return; } // On Unity 5.3+ we don't have default manifest so use our own // manifest and warn the user that they may need to modify it manually Assembly assembly = Assembly.GetExecutingAssembly(); Stream xmlStream = assembly.GetManifestResourceStream("Facebook.Unity.Editor.android.DefaultAndroidManifest.xml"); var xmlDocument = new XmlDocument(); xmlDocument.Load(xmlStream); Debug.LogWarning( string.Format( "No existing android manifest found at '{0}'. Creating a default manifest file", outputFile)); xmlDocument.Save(outputFile); } } }
381
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.IO; using System.Text.RegularExpressions; using UnityEngine; using Facebook.Unity.Editor.iOS.Xcode; public class FixupFiles { private static string didFinishLaunchingWithOptions = @"(?x) # Verbose mode (didFinishLaunchingWithOptions.+ # Find this function... (?:.*\n)+? # Match as few lines as possible until... \s*return\ )NO(\;\n # return NO; \}) # }"; public static void FixColdStart(string path) { string fullPath = Path.Combine(path, Path.Combine("Classes", "UnityAppController.mm")); string data = Load(fullPath); data = Regex.Replace( data, didFinishLaunchingWithOptions, "$1YES$2"); Save(fullPath, data); } public static void AddBuildFlag(string path) { string projPath = Path.Combine(path, Path.Combine("Unity-iPhone.xcodeproj", "project.pbxproj")); PBXProject proj = new PBXProject(); proj.ReadFromString(File.ReadAllText(projPath)); string targetGUID = proj.TargetGuidByName("Unity-iPhone"); proj.AddBuildProperty(targetGUID, "GCC_PREPROCESSOR_DEFINITIONS", " $(inherited) FBSDKCOCOAPODS=1"); proj.AddBuildProperty(targetGUID, "SWIFT_VERSION", "5.0"); proj.AddFrameworkToProject(targetGUID, "Accelerate.framework", true); File.WriteAllText(projPath, proj.WriteToString()); } protected static string Load(string fullPath) { string data; FileInfo projectFileInfo = new FileInfo(fullPath); StreamReader fs = projectFileInfo.OpenText(); data = fs.ReadToEnd(); fs.Close(); return data; } protected static void Save(string fullPath, string data) { System.IO.StreamWriter writer = new System.IO.StreamWriter(fullPath, false); writer.Write(data); writer.Close(); } private static int GetUnityVersionNumber() { string version = Application.unityVersion; string[] versionComponents = version.Split('.'); int majorVersion = 0; int minorVersion = 0; try { if (versionComponents != null && versionComponents.Length > 0 && versionComponents[0] != null) { majorVersion = Convert.ToInt32(versionComponents[0]); } if (versionComponents != null && versionComponents.Length > 1 && versionComponents[1] != null) { minorVersion = Convert.ToInt32(versionComponents[1]); } } catch (System.Exception e) { Debug.LogError("Error parsing Unity version number: " + e); } return (majorVersion * 100) + (minorVersion * 10); } } }
110
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor.iOS.Xcode { /// <summary> /// List of all the capabilities available. /// </summary> public sealed class PBXCapabilityType { public static readonly PBXCapabilityType ApplePay = new PBXCapabilityType ("com.apple.ApplePay", true); public static readonly PBXCapabilityType AppGroups = new PBXCapabilityType ("com.apple.ApplicationGroups.iOS", true); public static readonly PBXCapabilityType AssociatedDomains = new PBXCapabilityType ("com.apple.SafariKeychain", true); public static readonly PBXCapabilityType BackgroundModes = new PBXCapabilityType ("com.apple.BackgroundModes", false); public static readonly PBXCapabilityType DataProtection = new PBXCapabilityType ("com.apple.DataProtection", true); public static readonly PBXCapabilityType GameCenter = new PBXCapabilityType ("com.apple.GameCenter", false, "GameKit.framework"); public static readonly PBXCapabilityType HealthKit = new PBXCapabilityType ("com.apple.HealthKit", true, "HealthKit.framework"); public static readonly PBXCapabilityType HomeKit = new PBXCapabilityType ("com.apple.HomeKit", true, "HomeKit.framework"); public static readonly PBXCapabilityType iCloud = new PBXCapabilityType("com.apple.iCloud", true, "CloudKit.framework", true); public static readonly PBXCapabilityType InAppPurchase = new PBXCapabilityType ("com.apple.InAppPurchase", false); public static readonly PBXCapabilityType InterAppAudio = new PBXCapabilityType ("com.apple.InterAppAudio", true, "AudioToolbox.framework"); public static readonly PBXCapabilityType KeychainSharing = new PBXCapabilityType ("com.apple.KeychainSharing", true); public static readonly PBXCapabilityType Maps = new PBXCapabilityType("com.apple.Maps.iOS", false, "MapKit.framework"); public static readonly PBXCapabilityType PersonalVPN = new PBXCapabilityType("com.apple.VPNLite", true, "NetworkExtension.framework"); public static readonly PBXCapabilityType PushNotifications = new PBXCapabilityType ("com.apple.Push", true); public static readonly PBXCapabilityType Siri = new PBXCapabilityType ("com.apple.Siri", true); public static readonly PBXCapabilityType Wallet = new PBXCapabilityType ("com.apple.Wallet", true, "PassKit.framework"); public static readonly PBXCapabilityType WirelessAccessoryConfiguration = new PBXCapabilityType("com.apple.WAC", true, "ExternalAccessory.framework"); private readonly string m_ID; private readonly bool m_RequiresEntitlements; private readonly string m_Framework; private readonly bool m_OptionalFramework; public bool optionalFramework { get { return m_OptionalFramework; } } public string framework { get { return m_Framework; } } public string id { get { return m_ID; } } public bool requiresEntitlements { get { return m_RequiresEntitlements; } } public struct TargetCapabilityPair { public string targetGuid; public PBXCapabilityType capability; public TargetCapabilityPair(string guid, PBXCapabilityType type) { targetGuid = guid; capability = type; } } /// <summary> /// This private object represents what a capability changes in the PBXProject file /// </summary> /// <param name="id">The string used in the PBXProject file to identify the capability and mark it as enabled.</param> /// <param name="requiresEntitlements">This capability requires an entitlements file /// therefore we need to add this entitlements file to the code signing entitlement. /// </param> /// <param name="framework">Specify which framework need to be added to the /// project for this capability, if "" no framework are added. /// </param> /// <param name="optionalFramework">Some capability (right now only iCloud) /// adds a framework, not all the time but just when some option are checked /// this parameter indicates if one of them is checked.</param> private PBXCapabilityType(string _id, bool _requiresEntitlements, string _framework = "", bool _optionalFramework = false) { m_ID = _id; m_RequiresEntitlements = _requiresEntitlements; m_Framework = _framework; m_OptionalFramework = _optionalFramework; } public static PBXCapabilityType StringToPBXCapabilityType(string cap) { switch (cap) { case "com.apple.ApplePay": return ApplePay; case "com.apple.ApplicationGroups.iOS": return AppGroups; case "com.apple.SafariKeychain": return AssociatedDomains; case "com.apple.BackgroundModes": return BackgroundModes; case "com.apple.DataProtection": return DataProtection; case "com.apple.GameCenter": return GameCenter; case "com.apple.HealthKit": return HealthKit; case "com.apple.HomeKit": return HomeKit; case "com.apple.iCloud": return iCloud; case "com.apple.InAppPurchase": return InAppPurchase; case "com.apple.InterAppAudio": return InterAppAudio; case "com.apple.KeychainSharing": return KeychainSharing; case "com.apple.Maps.iOS": return Maps; case "com.apple.VPNLite": return PersonalVPN; case "com.apple.Push": return PushNotifications; case "com.apple.Siri": return Siri; case "com.apple.Wallet": return Wallet; case "WAC": return WirelessAccessoryConfiguration; default: return null; } } } }
154
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace Facebook.Unity.Editor.iOS.Xcode { internal class PBXPath { /// Replaces '\' with '/'. We need to apply this function to all paths that come from the user /// of the API because we store paths to pbxproj and on windows we may get path with '\' slashes /// instead of '/' slashes public static string FixSlashes(string path) { if (path == null) return null; return path.Replace('\\', '/'); } public static void Combine(string path1, PBXSourceTree tree1, string path2, PBXSourceTree tree2, out string resPath, out PBXSourceTree resTree) { if (tree2 == PBXSourceTree.Group) { resPath = Combine(path1, path2); resTree = tree1; return; } resPath = path2; resTree = tree2; } // Combines two paths public static string Combine(string path1, string path2) { if (path2.StartsWith("/")) return path2; if (path1.EndsWith("/")) return path1 + path2; if (path1 == "") return path2; if (path2 == "") return path1; return path1 + "/" + path2; } public static string GetDirectory(string path) { path = path.TrimEnd('/'); int pos = path.LastIndexOf('/'); if (pos == -1) return ""; else return path.Substring(0, pos); } public static string GetCurrentDirectory() { if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix) { throw new Exception("PBX project compatible current directory can only obtained on OSX"); } string path = Directory.GetCurrentDirectory(); path = FixSlashes(path); if (!IsPathRooted(path)) return "/" + path; return path; } public static string GetFilename(string path) { int pos = path.LastIndexOf('/'); if (pos == -1) return path; else return path.Substring(pos + 1); } public static bool IsPathRooted(string path) { if (path == null || path.Length == 0) return false; return path[0] == '/'; } public static string GetFullPath(string path) { if (IsPathRooted(path)) return path; else return Combine(GetCurrentDirectory(), path); } public static string[] Split(string path) { if (string.IsNullOrEmpty(path)) return new string[]{}; return path.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries); } } } // UnityEditor.iOS.Xcode
127
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using Facebook.Unity.Editor.iOS.Xcode.PBX; namespace Facebook.Unity.Editor.iOS.Xcode { using PBXBuildFileSection = KnownSectionBase<PBXBuildFileData>; using PBXFileReferenceSection = KnownSectionBase<PBXFileReferenceData>; using PBXGroupSection = KnownSectionBase<PBXGroupData>; using PBXContainerItemProxySection = KnownSectionBase<PBXContainerItemProxyData>; using PBXReferenceProxySection = KnownSectionBase<PBXReferenceProxyData>; using PBXSourcesBuildPhaseSection = KnownSectionBase<PBXSourcesBuildPhaseData>; using PBXFrameworksBuildPhaseSection= KnownSectionBase<PBXFrameworksBuildPhaseData>; using PBXResourcesBuildPhaseSection = KnownSectionBase<PBXResourcesBuildPhaseData>; using PBXCopyFilesBuildPhaseSection = KnownSectionBase<PBXCopyFilesBuildPhaseData>; using PBXShellScriptBuildPhaseSection = KnownSectionBase<PBXShellScriptBuildPhaseData>; using PBXVariantGroupSection = KnownSectionBase<PBXVariantGroupData>; using PBXNativeTargetSection = KnownSectionBase<PBXNativeTargetData>; using PBXTargetDependencySection = KnownSectionBase<PBXTargetDependencyData>; using XCBuildConfigurationSection = KnownSectionBase<XCBuildConfigurationData>; using XCConfigurationListSection = KnownSectionBase<XCConfigurationListData>; using UnknownSection = KnownSectionBase<PBXObjectData>; // Determines the tree the given path is relative to public enum PBXSourceTree { Absolute, // The path is absolute Source, // The path is relative to the source folder Group, // The path is relative to the folder it's in. This enum is used only internally, // do not use it as function parameter Build, // The path is relative to the build products folder Developer, // The path is relative to the developer folder Sdk // The path is relative to the sdk folder } public class PBXProject { PBXProjectData m_Data = new PBXProjectData(); // convenience accessors for public members of data. This is temporary; will be fixed by an interface change // of PBXProjectData internal PBXContainerItemProxySection containerItems { get { return m_Data.containerItems; } } internal PBXReferenceProxySection references { get { return m_Data.references; } } internal PBXSourcesBuildPhaseSection sources { get { return m_Data.sources; } } internal PBXFrameworksBuildPhaseSection frameworks { get { return m_Data.frameworks; } } internal PBXResourcesBuildPhaseSection resources { get { return m_Data.resources; } } internal PBXCopyFilesBuildPhaseSection copyFiles { get { return m_Data.copyFiles; } } internal PBXShellScriptBuildPhaseSection shellScripts { get { return m_Data.shellScripts; } } internal PBXNativeTargetSection nativeTargets { get { return m_Data.nativeTargets; } } internal PBXTargetDependencySection targetDependencies { get { return m_Data.targetDependencies; } } internal PBXVariantGroupSection variantGroups { get { return m_Data.variantGroups; } } internal XCBuildConfigurationSection buildConfigs { get { return m_Data.buildConfigs; } } internal XCConfigurationListSection buildConfigLists { get { return m_Data.buildConfigLists; } } internal PBXProjectSection project { get { return m_Data.project; } } internal PBXBuildFileData BuildFilesGet(string guid) { return m_Data.BuildFilesGet(guid); } internal void BuildFilesAdd(string targetGuid, PBXBuildFileData buildFile) { m_Data.BuildFilesAdd(targetGuid, buildFile); } internal void BuildFilesRemove(string targetGuid, string fileGuid) { m_Data.BuildFilesRemove(targetGuid, fileGuid); } internal PBXBuildFileData BuildFilesGetForSourceFile(string targetGuid, string fileGuid) { return m_Data.BuildFilesGetForSourceFile(targetGuid, fileGuid); } internal IEnumerable<PBXBuildFileData> BuildFilesGetAll() { return m_Data.BuildFilesGetAll(); } internal void FileRefsAdd(string realPath, string projectPath, PBXGroupData parent, PBXFileReferenceData fileRef) { m_Data.FileRefsAdd(realPath, projectPath, parent, fileRef); } internal PBXFileReferenceData FileRefsGet(string guid) { return m_Data.FileRefsGet(guid); } internal PBXFileReferenceData FileRefsGetByRealPath(string path, PBXSourceTree sourceTree) { return m_Data.FileRefsGetByRealPath(path, sourceTree); } internal PBXFileReferenceData FileRefsGetByProjectPath(string path) { return m_Data.FileRefsGetByProjectPath(path); } internal void FileRefsRemove(string guid) { m_Data.FileRefsRemove(guid); } internal PBXGroupData GroupsGet(string guid) { return m_Data.GroupsGet(guid); } internal PBXGroupData GroupsGetByChild(string childGuid) { return m_Data.GroupsGetByChild(childGuid); } internal PBXGroupData GroupsGetMainGroup() { return m_Data.GroupsGetMainGroup(); } internal PBXGroupData GroupsGetByProjectPath(string sourceGroup) { return m_Data.GroupsGetByProjectPath(sourceGroup); } internal void GroupsAdd(string projectPath, PBXGroupData parent, PBXGroupData gr) { m_Data.GroupsAdd(projectPath, parent, gr); } internal void GroupsAddDuplicate(PBXGroupData gr) { m_Data.GroupsAddDuplicate(gr); } internal void GroupsRemove(string guid) { m_Data.GroupsRemove(guid); } internal FileGUIDListBase BuildSectionAny(PBXNativeTargetData target, string path, bool isFolderRef) { return m_Data.BuildSectionAny(target, path, isFolderRef); } internal FileGUIDListBase BuildSectionAny(string sectionGuid) { return m_Data.BuildSectionAny(sectionGuid); } /// <summary> /// Returns the path to PBX project in the given Unity build path. This function can only /// be used in Unity-generated projects /// </summary> /// <param name="buildPath">The project build path</param> /// <returns>The path to the PBX project file that can later be opened via ReadFromFile function</returns> public static string GetPBXProjectPath(string buildPath) { return PBXPath.Combine(buildPath, "Unity-iPhone.xcodeproj/project.pbxproj"); } /// <summary> /// Returns the default main target name in Unity project. /// The returned target name can then be used to retrieve the GUID of the target via TargetGuidByName /// function. This function can only be used in Unity-generated projects. /// </summary> /// <returns>The default main target name.</returns> public static string GetUnityTargetName() { return "Unity-iPhone"; } /// <summary> /// Returns the default test target name in Unity project. /// The returned target name can then be used to retrieve the GUID of the target via TargetGuidByName /// function. This function can only be used in Unity-generated projects. /// </summary> /// <returns>The default test target name.</returns> public static string GetUnityTestTargetName() { return "Unity-iPhone Tests"; } /// <summary> /// Returns the GUID of the project. The project GUID identifies a project-wide native target which /// is used to set project-wide properties. This GUID can be passed to any functions that accepts /// target GUIDs as parameters. /// </summary> /// <returns>The GUID of the project.</returns> public string ProjectGuid() { return project.project.guid; } /// <summary> /// Returns the GUID of the native target with the given name. /// In projects produced by Unity the main target can be retrieved via GetUnityTargetName function, /// whereas the test target name can be retrieved by GetUnityTestTargetName function. /// </summary> /// <returns>The name of the native target.</returns> /// <param name="name">The GUID identifying the native target.</param> public string TargetGuidByName(string name) { foreach (var entry in nativeTargets.GetEntries()) if (entry.Value.name == name) return entry.Key; return null; } /// <summary> /// Checks if files with the given extension are known to PBXProject. /// </summary> /// <returns>Returns <c>true</c> if is the extension is known, <c>false</c> otherwise.</returns> /// <param name="ext">The file extension (leading dot is not necessary, but accepted).</param> public static bool IsKnownExtension(string ext) { return FileTypeUtils.IsKnownExtension(ext); } /// <summary> /// Checks if files with the given extension are known to PBXProject. /// Returns <c>true</c> if the extension is not known by PBXProject. /// </summary> /// <returns>Returns <c>true</c> if is the extension is known, <c>false</c> otherwise.</returns> /// <param name="ext">The file extension (leading dot is not necessary, but accepted).</param> public static bool IsBuildable(string ext) { return FileTypeUtils.IsBuildableFile(ext); } // The same file can be referred to by more than one project path. private string AddFileImpl(string path, string projectPath, PBXSourceTree tree, bool isFolderReference) { path = PBXPath.FixSlashes(path); projectPath = PBXPath.FixSlashes(projectPath); if (!isFolderReference && Path.GetExtension(path) != Path.GetExtension(projectPath)) throw new Exception("Project and real path extensions do not match"); string guid = FindFileGuidByProjectPath(projectPath); if (guid == null) guid = FindFileGuidByRealPath(path); if (guid == null) { PBXFileReferenceData fileRef; if (isFolderReference) fileRef = PBXFileReferenceData.CreateFromFolderReference(path, PBXPath.GetFilename(projectPath), tree); else fileRef = PBXFileReferenceData.CreateFromFile(path, PBXPath.GetFilename(projectPath), tree); PBXGroupData parent = CreateSourceGroup(PBXPath.GetDirectory(projectPath)); parent.children.AddGUID(fileRef.guid); FileRefsAdd(path, projectPath, parent, fileRef); guid = fileRef.guid; } return guid; } /// <summary> /// Adds a new file reference to the list of known files. /// The group structure is automatically created to correspond to the project path. /// To add the file to the list of files to build, pass the returned value to [[AddFileToBuild]]. /// </summary> /// <returns>The GUID of the added file. It can later be used to add the file for building to targets, etc.</returns> /// <param name="path">The physical path to the file on the filesystem.</param> /// <param name="projectPath">The project path to the file.</param> /// <param name="sourceTree">The source tree the path is relative to. By default it's [[PBXSourceTree.Source]]. /// The [[PBXSourceTree.Group]] tree is not supported.</param> public string AddFile(string path, string projectPath, PBXSourceTree sourceTree = PBXSourceTree.Source) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl(path, projectPath, sourceTree, false); } /// <summary> /// Adds a new folder reference to the list of known files. /// The group structure is automatically created to correspond to the project path. /// To add the folder reference to the list of files to build, pass the returned value to [[AddFileToBuild]]. /// </summary> /// <returns>The GUID of the added folder reference. It can later be used to add the file for building to targets, etc.</returns> /// <param name="path">The physical path to the folder on the filesystem.</param> /// <param name="projectPath">The project path to the folder.</param> /// <param name="sourceTree">The source tree the path is relative to. By default it's [[PBXSourceTree.Source]]. /// The [[PBXSourceTree.Group]] tree is not supported.</param> public string AddFolderReference(string path, string projectPath, PBXSourceTree sourceTree = PBXSourceTree.Source) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl(path, projectPath, sourceTree, true); } private void AddBuildFileImpl(string targetGuid, string fileGuid, bool weak, string compileFlags) { PBXNativeTargetData target = nativeTargets[targetGuid]; PBXFileReferenceData fileRef = FileRefsGet(fileGuid); string ext = Path.GetExtension(fileRef.path); if (FileTypeUtils.IsBuildable(ext, fileRef.isFolderReference) && BuildFilesGetForSourceFile(targetGuid, fileGuid) == null) { PBXBuildFileData buildFile = PBXBuildFileData.CreateFromFile(fileGuid, weak, compileFlags); BuildFilesAdd(targetGuid, buildFile); BuildSectionAny(target, ext, fileRef.isFolderReference).files.AddGUID(buildFile.guid); } } /// <summary> /// Configures file for building for the given native target. /// A projects containing multiple native targets, a single file or folder reference can be /// configured to be built in all, some or none of the targets. The file or folder reference is /// added to appropriate build section depending on the file extension. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The file guid returned by [[AddFile]] or [[AddFolderReference]].</param> public void AddFileToBuild(string targetGuid, string fileGuid) { AddBuildFileImpl(targetGuid, fileGuid, false, null); } /// <summary> /// Configures file for building for the given native target with specific compiler flags. /// The function is equivalent to [[AddFileToBuild()]] except that compile flags are specified. /// A projects containing multiple native targets, a single file or folder reference can be /// configured to be built in all, some or none of the targets. The file or folder reference is /// added to appropriate build section depending on the file extension. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The file guid returned by [[AddFile]] or [[AddFolderReference]].</param> /// <param name="compileFlags">Compile flags to use.</param> public void AddFileToBuildWithFlags(string targetGuid, string fileGuid, string compileFlags) { AddBuildFileImpl(targetGuid, fileGuid, false, compileFlags); } /// <summary> /// Configures file for building for the given native target on specific build section. /// The function is equivalent to [[AddFileToBuild()]] except that specific build section is specified. /// A projects containing multiple native targets, a single file or folder reference can be /// configured to be built in all, some or none of the targets. The file or folder reference is /// added to appropriate build section depending on the file extension. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="sectionGuid">The GUID of the section to add the file to.</param> /// <param name="fileGuid">The file guid returned by [[AddFile]] or [[AddFolderReference]].</param> public void AddFileToBuildSection(string targetGuid, string sectionGuid, string fileGuid) { PBXBuildFileData buildFile = PBXBuildFileData.CreateFromFile(fileGuid, false, null); BuildFilesAdd(targetGuid, buildFile); BuildSectionAny(sectionGuid).files.AddGUID(buildFile.guid); } /// <summary> /// Returns compile flags set for the specific file. /// Null is returned if the file has no configured compile flags or the file is not configured for /// building on the given target. /// </summary> /// <returns>The compile flags for the specified file.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The GUID of the file.</param> public List<string> GetCompileFlagsForFile(string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return null; if (buildFile.compileFlags == null) return new List<string>(); return new List<string>(buildFile.compileFlags.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)); } /// <summary> /// Sets the compilation flags for the given file in the given target. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The GUID of the file.</param> /// <param name="compileFlags">The list of compile flags or null if the flags should be unset.</param> public void SetCompileFlagsForFile(string targetGuid, string fileGuid, List<string> compileFlags) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; if (compileFlags == null) buildFile.compileFlags = null; else buildFile.compileFlags = string.Join(" ", compileFlags.ToArray()); } /// <summary> /// Adds an asset tag for the given file. /// The asset tags identify resources that will be downloaded via On Demand Resources functionality. /// A request for specific tag will initiate download of all files, configured for that tag. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The GUID of the file.</param> /// <param name="tag">The name of the asset tag.</param> public void AddAssetTagForFile(string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; if (!buildFile.assetTags.Contains(tag)) buildFile.assetTags.Add(tag); if (!project.project.knownAssetTags.Contains(tag)) project.project.knownAssetTags.Add(tag); } /// <summary> /// Removes an asset tag for the given file. /// The function does nothing if the file is not configured for building in the given target or if /// the asset tag is not present in the list of asset tags configured for file. If the file was the /// last file referring to the given tag across the Xcode project, then the tag is removed from the /// list of known tags. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The GUID of the file.</param> /// <param name="tag">The name of the asset tag.</param> public void RemoveAssetTagForFile(string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; buildFile.assetTags.Remove(tag); // remove from known tags if this was the last one foreach (var buildFile2 in BuildFilesGetAll()) { if (buildFile2.assetTags.Contains(tag)) return; } project.project.knownAssetTags.Remove(tag); } /// <summary> /// Adds the asset tag to the list of tags to download during initial installation. /// The function does nothing if there are no files that use the given asset tag across the project. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="tag">The name of the asset tag.</param> public void AddAssetTagToDefaultInstall(string targetGuid, string tag) { if (!project.project.knownAssetTags.Contains(tag)) return; AddBuildProperty(targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", tag); } /// <summary> /// Removes the asset tag from the list of tags to download during initial installation. /// The function does nothing if the tag is not already configured for downloading during /// initial installation. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="tag">The name of the asset tag.</param> public void RemoveAssetTagFromDefaultInstall(string targetGuid, string tag) { UpdateBuildProperty(targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", null, new[]{tag}); } /// <summary> /// Removes an asset tag. /// Removes the given asset tag from the list of configured asset tags for all files on all targets, /// the list of asset tags configured for initial installation and the list of known asset tags in /// the Xcode project. /// </summary> /// <param name="tag">The name of the asset tag.</param> public void RemoveAssetTag(string tag) { foreach (var buildFile in BuildFilesGetAll()) buildFile.assetTags.Remove(tag); foreach (var targetGuid in nativeTargets.GetGuids()) RemoveAssetTagFromDefaultInstall(targetGuid, tag); project.project.knownAssetTags.Remove(tag); } /// <summary> /// Checks if the project contains a file with the given physical path. /// The search is performed across all absolute source trees. /// </summary> /// <returns>Returns <c>true</c> if the project contains the file, <c>false</c> otherwise.</returns> /// <param name="path">The physical path of the file.</param> public bool ContainsFileByRealPath(string path) { return FindFileGuidByRealPath(path) != null; } /// <summary> /// Checks if the project contains a file with the given physical path. /// </summary> /// <returns>Returns <c>true</c> if the project contains the file, <c>false</c> otherwise.</returns> /// <param name="path">The physical path of the file.</param> /// <param name="sourceTree">The source tree path is relative to. The [[PBXSourceTree.Group]] tree is not supported.</param> public bool ContainsFileByRealPath(string path, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return FindFileGuidByRealPath(path, sourceTree) != null; } /// <summary> /// Checks if the project contains a file with the given project path. /// </summary> /// <returns>Returns <c>true</c> if the project contains the file, <c>false</c> otherwise.</returns> /// <param name="path">The project path of the file.</param> public bool ContainsFileByProjectPath(string path) { return FindFileGuidByProjectPath(path) != null; } /// <summary> /// Checks whether the given system framework is a dependency of a target. /// The function assumes system frameworks are located in System/Library/Frameworks folder in the SDK source tree. /// </summary> /// <returns>Returns <c>true</c> if the given framework is a dependency of the given target, /// <c>false</c> otherwise.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="framework">The name of the framework. The extension of the filename must be ".framework".</param> public bool ContainsFramework(string targetGuid, string framework) { var fileGuid = FindFileGuidByRealPath("System/Library/Frameworks/" + framework, PBXSourceTree.Sdk); if (fileGuid == null) return false; var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); return (buildFile != null); } /// <summary> /// Adds a system framework dependency for the specified target. /// The function assumes system frameworks are located in System/Library/Frameworks folder in the SDK source tree. /// The framework is added to Frameworks logical folder in the project. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="framework">The name of the framework. The extension of the filename must be ".framework".</param> /// <param name="weak"><c>true</c> if the framework is optional (i.e. weakly linked) required, /// <c>false</c> if the framework is required.</param> public void AddFrameworkToProject(string targetGuid, string framework, bool weak) { string fileGuid = AddFile("System/Library/Frameworks/" + framework, "Frameworks/" + framework, PBXSourceTree.Sdk); AddBuildFileImpl(targetGuid, fileGuid, weak, null); } /// <summary> /// Removes a system framework dependency for the specified target. /// The function assumes system frameworks are located in System/Library/Frameworks folder in the SDK source tree. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="framework">The name of the framework. The extension of the filename must be ".framework".</param> public void RemoveFrameworkFromProject(string targetGuid, string framework) { var fileGuid = FindFileGuidByRealPath("System/Library/Frameworks/" + framework, PBXSourceTree.Sdk); if (fileGuid == null) return; BuildFilesRemove(targetGuid, fileGuid); } // Allow user to add a Capability public bool AddCapability( string targetGuid, PBXCapabilityType capability, string entitlementsFilePath = null, bool addOptionalFramework = false ) { // If the capability requires entitlements then you have to provide the name of it or we don't add the capability. if (capability.requiresEntitlements && entitlementsFilePath == "") { throw new Exception( "Couldn't add the Xcode Capability " + capability.id + " to the PBXProject file because this capability requires an entitlement file." ); } var p = project.project; // If an entitlement with a different name was added for another capability // we don't add this capacity. if (p.entitlementsFile != null && entitlementsFilePath != null && p.entitlementsFile != entitlementsFilePath) { if (p.capabilities.Count > 0) throw new WarningException( "Attention, it seems that you have multiple entitlements file. Only one will be added the Project : " + p.entitlementsFile ); return false; } // Add the capability only if it doesn't already exist. if (p.capabilities.Contains(new PBXCapabilityType.TargetCapabilityPair(targetGuid, capability))) { throw new WarningException("This capability has already been added. Method ignored"); } p.capabilities.Add(new PBXCapabilityType.TargetCapabilityPair(targetGuid, capability)); // Add the required framework. if (capability.framework != "" && !capability.optionalFramework || (capability.framework != "" && capability.optionalFramework && addOptionalFramework)) { AddFrameworkToProject(targetGuid, capability.framework, false); } // Finally add the entitlement code signing if it wasn't added before. if (entitlementsFilePath != null && p.entitlementsFile == null) { p.entitlementsFile = entitlementsFilePath; AddFileImpl(entitlementsFilePath, entitlementsFilePath, PBXSourceTree.Source, false); SetBuildProperty(targetGuid, "CODE_SIGN_ENTITLEMENTS", PBXPath.FixSlashes(entitlementsFilePath)); } return true; } // The Xcode project needs a team set to be able to complete code signing or to add some capabilities. public void SetTeamId(string targetGuid, string teamId) { SetBuildProperty(targetGuid, "DEVELOPMENT_TEAM", teamId); project.project.teamIDs.Add(targetGuid, teamId); } /// <summary> /// Finds a file with the given physical path in the project, if any. /// </summary> /// <returns>The GUID of the file if the search succeeded, null otherwise.</returns> /// <param name="path">The physical path of the file.</param> /// <param name="sourceTree">The source tree path is relative to. The [[PBXSourceTree.Group]] tree is not supported.</param> public string FindFileGuidByRealPath(string path, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); path = PBXPath.FixSlashes(path); var fileRef = FileRefsGetByRealPath(path, sourceTree); if (fileRef != null) return fileRef.guid; return null; } /// <summary> /// Finds a file with the given physical path in the project, if any. /// The search is performed across all absolute source trees. /// </summary> /// <returns>The GUID of the file if the search succeeded, null otherwise.</returns> /// <param name="path">The physical path of the file.</param> public string FindFileGuidByRealPath(string path) { path = PBXPath.FixSlashes(path); foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees()) { string res = FindFileGuidByRealPath(path, tree); if (res != null) return res; } return null; } /// <summary> /// Finds a file with the given project path in the project, if any. /// </summary> /// <returns>The GUID of the file if the search succeeded, null otherwise.</returns> /// <param name="path">The project path of the file.</param> public string FindFileGuidByProjectPath(string path) { path = PBXPath.FixSlashes(path); var fileRef = FileRefsGetByProjectPath(path); if (fileRef != null) return fileRef.guid; return null; } /// <summary> /// Removes given file from the list of files to build for the given target. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="fileGuid">The GUID of the file or folder reference.</param> public void RemoveFileFromBuild(string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; BuildFilesRemove(targetGuid, fileGuid); string buildGuid = buildFile.guid; if (buildGuid != null) { foreach (var section in sources.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in resources.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in copyFiles.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in frameworks.GetEntries()) section.Value.files.RemoveGUID(buildGuid); } } /// <summary> /// Removes the given file from project. /// The file is removed from the list of files to build for each native target and also removed /// from the list of known files. /// </summary> /// <param name="fileGuid">The GUID of the file or folder reference.</param> public void RemoveFile(string fileGuid) { if (fileGuid == null) return; // remove from parent PBXGroupData parent = GroupsGetByChild(fileGuid); if (parent != null) parent.children.RemoveGUID(fileGuid); RemoveGroupIfEmpty(parent); // remove actual file foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild(target.Value.guid, fileGuid); FileRefsRemove(fileGuid); } void RemoveGroupIfEmpty(PBXGroupData gr) { if (gr.children.Count == 0 && gr != GroupsGetMainGroup()) { // remove from parent PBXGroupData parent = GroupsGetByChild(gr.guid); parent.children.RemoveGUID(gr.guid); RemoveGroupIfEmpty(parent); // remove actual group GroupsRemove(gr.guid); } } private void RemoveGroupChildrenRecursive(PBXGroupData parent) { List<string> children = new List<string>(parent.children); parent.children.Clear(); foreach (string guid in children) { PBXFileReferenceData file = FileRefsGet(guid); if (file != null) { foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild(target.Value.guid, guid); FileRefsRemove(guid); continue; } PBXGroupData gr = GroupsGet(guid); if (gr != null) { RemoveGroupChildrenRecursive(gr); GroupsRemove(gr.guid); continue; } } } internal void RemoveFilesByProjectPathRecursive(string projectPath) { projectPath = PBXPath.FixSlashes(projectPath); PBXGroupData gr = GroupsGetByProjectPath(projectPath); if (gr == null) return; RemoveGroupChildrenRecursive(gr); RemoveGroupIfEmpty(gr); } // Returns null on error internal List<string> GetGroupChildrenFiles(string projectPath) { projectPath = PBXPath.FixSlashes(projectPath); PBXGroupData gr = GroupsGetByProjectPath(projectPath); if (gr == null) return null; var res = new List<string>(); foreach (var guid in gr.children) { PBXFileReferenceData fileRef = FileRefsGet(guid); if (fileRef != null) res.Add(fileRef.name); } return res; } // Returns an empty dictionary if no group or files are found internal HashSet<string> GetGroupChildrenFilesRefs(string projectPath) { projectPath = PBXPath.FixSlashes(projectPath); PBXGroupData gr = GroupsGetByProjectPath(projectPath); if (gr == null) return new HashSet<string>(); HashSet<string> res = new HashSet<string>(); foreach (var guid in gr.children) { PBXFileReferenceData fileRef = FileRefsGet(guid); if (fileRef != null) res.Add(fileRef.path); } return res == null ? new HashSet<string> () : res; } internal HashSet<string> GetFileRefsByProjectPaths(IEnumerable<string> paths) { HashSet<string> ret = new HashSet<string>(); foreach (string path in paths) { string fixedPath = PBXPath.FixSlashes(path); var fileRef = FileRefsGetByProjectPath(fixedPath); if (fileRef != null) ret.Add(fileRef.path); } return ret; } private PBXGroupData GetPBXGroupChildByName(PBXGroupData group, string name) { foreach (string guid in group.children) { var gr = GroupsGet(guid); if (gr != null && gr.name == name) return gr; } return null; } /// Creates source group identified by sourceGroup, if needed, and returns it. /// If sourceGroup is empty or null, root group is returned internal PBXGroupData CreateSourceGroup(string sourceGroup) { sourceGroup = PBXPath.FixSlashes(sourceGroup); if (sourceGroup == null || sourceGroup == "") return GroupsGetMainGroup(); PBXGroupData gr = GroupsGetByProjectPath(sourceGroup); if (gr != null) return gr; // the group does not exist -- create new gr = GroupsGetMainGroup(); var elements = PBXPath.Split(sourceGroup); string projectPath = null; foreach (string pathEl in elements) { if (projectPath == null) projectPath = pathEl; else projectPath += "/" + pathEl; PBXGroupData child = GetPBXGroupChildByName(gr, pathEl); if (child != null) gr = child; else { PBXGroupData newGroup = PBXGroupData.Create(pathEl, pathEl, PBXSourceTree.Group); gr.children.AddGUID(newGroup.guid); GroupsAdd(projectPath, gr, newGroup); gr = newGroup; } } return gr; } /// <summary> /// Creates a new native target. /// Target-specific build configurations are automatically created for each known build configuration name. /// Note, that this is a requirement that follows from the structure of Xcode projects, not an implementation /// detail of this function. The function creates a product file reference in the "Products" project folder /// which refers to the target artifact that is built via this target. /// </summary> /// <returns>The GUID of the new target.</returns> /// <param name="name">The name of the new target.</param> /// <param name="ext">The file extension of the target artifact (leading dot is not necessary, but accepted).</param> /// <param name="type">The type of the target. For example: /// "com.apple.product-type.app-extension" - App extension, /// "com.apple.product-type.application.watchapp2" - WatchKit 2 application</param> public string AddTarget(string name, string ext, string type) { var buildConfigList = XCConfigurationListData.Create(); buildConfigLists.AddEntry(buildConfigList); // create build file reference string fullName = name + "." + FileTypeUtils.TrimExtension(ext); var productFileRef = AddFile(fullName, "Products/" + fullName, PBXSourceTree.Build); var newTarget = PBXNativeTargetData.Create(name, productFileRef, type, buildConfigList.guid); nativeTargets.AddEntry(newTarget); project.project.targets.Add(newTarget.guid); foreach (var buildConfigName in BuildConfigNames()) AddBuildConfigForTarget(newTarget.guid, buildConfigName); return newTarget.guid; } private IEnumerable<string> GetAllTargetGuids() { var targets = new List<string>(); targets.Add(project.project.guid); targets.AddRange(nativeTargets.GetGuids()); return targets; } /// <summary> /// Returns the file reference of the artifact created by building target. /// </summary> /// <returns>The file reference of the artifact created by building target.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string GetTargetProductFileRef(string targetGuid) { return nativeTargets[targetGuid].productReference; } /// <summary> /// Sets up a dependency between two targets. /// </summary> /// <param name="targetGuid">The GUID of the target that is depending on the dependency.</param> /// <param name="targetDependencyGuid">The GUID of the dependency target</param> internal void AddTargetDependency(string targetGuid, string targetDependencyGuid) { string dependencyName = nativeTargets[targetDependencyGuid].name; var containerProxy = PBXContainerItemProxyData.Create(project.project.guid, "1", targetDependencyGuid, dependencyName); containerItems.AddEntry(containerProxy); var targetDependency = PBXTargetDependencyData.Create(targetDependencyGuid, containerProxy.guid); targetDependencies.AddEntry(targetDependency); nativeTargets[targetGuid].dependencies.AddGUID(targetDependency.guid); } // Returns the GUID of the new configuration // targetGuid can be either native target or the project target. private string AddBuildConfigForTarget(string targetGuid, string name) { if (BuildConfigByName(targetGuid, name) != null) { throw new Exception(String.Format("A build configuration by name {0} already exists for target {1}", targetGuid, name)); } var buildConfig = XCBuildConfigurationData.Create(name); buildConfigs.AddEntry(buildConfig); buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs.AddGUID(buildConfig.guid); return buildConfig.guid; } private void RemoveBuildConfigForTarget(string targetGuid, string name) { var buildConfigGuid = BuildConfigByName(targetGuid, name); if (buildConfigGuid == null) return; buildConfigs.RemoveEntry(buildConfigGuid); buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs.RemoveGUID(buildConfigGuid); } /// <summary> /// Returns the GUID of build configuration with the given name for the specific target. /// Null is returned if such configuration does not exist. /// </summary> /// <returns>The GUID of the build configuration or null if it does not exist.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the build configuration.</param> public string BuildConfigByName(string targetGuid, string name) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) { var buildConfig = buildConfigs[guid]; if (buildConfig != null && buildConfig.name == name) return buildConfig.guid; } return null; } /// <summary> /// Returns the names of the build configurations available in the project. /// The number and names of the build configurations is a project-wide setting. Each target has the /// same number of build configurations and the names of these build configurations is the same. /// In other words, [[BuildConfigByName()]] will succeed for all targets in the project and all /// build configuration names returned by this function. /// </summary> /// <returns>An array of build config names.</returns> public IEnumerable<string> BuildConfigNames() { var names = new List<string>(); // We use the project target to fetch the build configs foreach (var guid in buildConfigLists[project.project.buildConfigList].buildConfigs) names.Add(buildConfigs[guid].name); return names; } /// <summary> /// Creates a new set of build configurations for all targets in the project. /// The number and names of the build configurations is a project-wide setting. Each target has the /// same number of build configurations and the names of these build configurations is the same. /// The created configurations are initially empty. Care must be taken to fill them with reasonable /// defaults. /// The function throws an exception if a build configuration with the given name already exists. /// </summary> /// <param name="name">The name of the build configuration.</param> public void AddBuildConfig(string name) { foreach (var targetGuid in GetAllTargetGuids()) AddBuildConfigForTarget(targetGuid, name); } /// <summary> /// Removes all build configurations with the given name from all targets in the project. /// The number and names of the build configurations is a project-wide setting. Each target has the /// same number of build configurations and the names of these build configurations is the same. /// The function does nothing if the build configuration with the specified name does not exist. /// </summary> /// <param name="name">The name of the build configuration.</param> public void RemoveBuildConfig(string name) { foreach (var targetGuid in GetAllTargetGuids()) RemoveBuildConfigForTarget(targetGuid, name); } /// <summary> /// Returns the GUID of sources build phase for the given target. /// </summary> /// <returns>Returns the GUID of the existing phase or null if it does not exist.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string GetSourcesBuildPhaseByTarget(string targetGuid) { var target = nativeTargets[targetGuid]; foreach (var phaseGuid in target.phases) { var phaseAny = BuildSectionAny(phaseGuid); if (phaseAny is PBXSourcesBuildPhaseData) return phaseGuid; } return null; } /// <summary> /// Creates a new sources build phase for given target. /// If the target already has sources build phase configured for it, the function returns the /// existing phase. The new phase is placed at the end of the list of build phases configured /// for the target. /// </summary> /// <returns>Returns the GUID of the new phase.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string AddSourcesBuildPhase(string targetGuid) { var phaseGuid = GetSourcesBuildPhaseByTarget(targetGuid); if (phaseGuid != null) return phaseGuid; var phase = PBXSourcesBuildPhaseData.Create(); sources.AddEntry(phase); nativeTargets[targetGuid].phases.AddGUID(phase.guid); return phase.guid; } /// <summary> /// Returns the GUID of resources build phase for the given target. /// </summary> /// <returns>Returns the GUID of the existing phase or null if it does not exist.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string GetResourcesBuildPhaseByTarget(string targetGuid) { var target = nativeTargets[targetGuid]; foreach (var phaseGuid in target.phases) { var phaseAny = BuildSectionAny(phaseGuid); if (phaseAny is PBXResourcesBuildPhaseData) return phaseGuid; } return null; } /// <summary> /// Creates a new resources build phase for given target. /// If the target already has resources build phase configured for it, the function returns the /// existing phase. The new phase is placed at the end of the list of build phases configured /// for the target. /// </summary> /// <returns>Returns the GUID of the new phase.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string AddResourcesBuildPhase(string targetGuid) { var phaseGuid = GetResourcesBuildPhaseByTarget(targetGuid); if (phaseGuid != null) return phaseGuid; var phase = PBXResourcesBuildPhaseData.Create(); resources.AddEntry(phase); nativeTargets[targetGuid].phases.AddGUID(phase.guid); return phase.guid; } /// <summary> /// Returns the GUID of frameworks build phase for the given target. /// </summary> /// <returns>Returns the GUID of the existing phase or null if it does not exist.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string GetFrameworksBuildPhaseByTarget(string targetGuid) { var target = nativeTargets[targetGuid]; foreach (var phaseGuid in target.phases) { var phaseAny = BuildSectionAny(phaseGuid); if (phaseAny is PBXFrameworksBuildPhaseData) return phaseGuid; } return null; } /// <summary> /// Creates a new frameworks build phase for given target. /// If the target already has frameworks build phase configured for it, the function returns the /// existing phase. The new phase is placed at the end of the list of build phases configured /// for the target. /// </summary> /// <returns>Returns the GUID of the new phase.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> public string AddFrameworksBuildPhase(string targetGuid) { var phaseGuid = GetFrameworksBuildPhaseByTarget(targetGuid); if (phaseGuid != null) return phaseGuid; var phase = PBXFrameworksBuildPhaseData.Create(); frameworks.AddEntry(phase); nativeTargets[targetGuid].phases.AddGUID(phase.guid); return phase.guid; } /// <summary> /// Returns the GUID of matching copy files build phase for the given target. /// The parameters of existing copy files build phase are matched to the arguments of this /// function and the GUID of the phase is returned only if a matching build phase is found. /// </summary> /// <returns>Returns the GUID of the matching phase or null if it does not exist.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the phase.</param> /// <param name="dstPath">The destination path.</param> /// <param name="subfolderSpec">The "subfolder spec". The following usages are known: /// "10" for embedding frameworks; /// "13" for embedding app extension content; /// "16" for embedding watch content</param> public string GetCopyFilesBuildPhaseByTarget(string targetGuid, string name, string dstPath, string subfolderSpec) { var target = nativeTargets[targetGuid]; foreach (var phaseGuid in target.phases) { var phaseAny = BuildSectionAny(phaseGuid); if (phaseAny is PBXCopyFilesBuildPhaseData) { var copyPhase = (PBXCopyFilesBuildPhaseData) phaseAny; if (copyPhase.name == name && copyPhase.dstPath == dstPath && copyPhase.dstSubfolderSpec == subfolderSpec) { return phaseGuid; } } } return null; } /// <summary> /// Creates a new copy files build phase for given target. /// If the target already has copy files build phase with the same name, dstPath and subfolderSpec /// configured for it, the function returns the existing phase. /// The new phase is placed at the end of the list of build phases configured for the target. /// </summary> /// <returns>Returns the GUID of the new phase.</returns> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the phase.</param> /// <param name="dstPath">The destination path.</param> /// <param name="subfolderSpec">The "subfolder spec". The following usages are known: /// "10" for embedding frameworks; /// "13" for embedding app extension content; /// "16" for embedding watch content</param> public string AddCopyFilesBuildPhase(string targetGuid, string name, string dstPath, string subfolderSpec) { var phaseGuid = GetCopyFilesBuildPhaseByTarget(targetGuid, name, dstPath, subfolderSpec); if (phaseGuid != null) return phaseGuid; var phase = PBXCopyFilesBuildPhaseData.Create(name, dstPath, subfolderSpec); copyFiles.AddEntry(phase); nativeTargets[targetGuid].phases.AddGUID(phase.guid); return phase.guid; } internal string GetConfigListForTarget(string targetGuid) { if (targetGuid == project.project.guid) return project.project.buildConfigList; else return nativeTargets[targetGuid].buildConfigList; } // Sets the baseConfigurationReference key for a XCBuildConfiguration. // If the argument is null, the base configuration is removed. internal void SetBaseReferenceForConfig(string configGuid, string baseReference) { buildConfigs[configGuid].baseConfigurationReference = baseReference; } internal PBXBuildFileData FindFrameworkByFileGuid(PBXCopyFilesBuildPhaseData phase, string fileGuid) { foreach (string buildFileDataGuid in phase.files) { var buildFile = BuildFilesGet(buildFileDataGuid); if (buildFile.fileRef == fileGuid) return buildFile; } return null; } /// <summary> /// Adds a value to build property list in all build configurations for the specified target. /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void AddBuildProperty(string targetGuid, string name, string value) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) AddBuildPropertyForConfig(guid, name, value); } /// <summary> /// Adds a value to build property list in all build configurations for the specified targets. /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="targetGuids">The GUIDs of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void AddBuildProperty(IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) AddBuildProperty(t, name, value); } /// <summary> /// Adds a value to build property list of the given build configuration /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="configGuid">The GUID of the build configuration as returned by [[BuildConfigByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void AddBuildPropertyForConfig(string configGuid, string name, string value) { buildConfigs[configGuid].AddProperty(name, value); } /// <summary> /// Adds a value to build property list of the given build configurations /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="configGuids">The GUIDs of the build configurations as returned by [[BuildConfigByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void AddBuildPropertyForConfig(IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) AddBuildPropertyForConfig(guid, name, value); } /// <summary> /// Adds a value to build property list in all build configurations for the specified target. /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="targetGuid">The GUID of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void SetBuildProperty(string targetGuid, string name, string value) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) SetBuildPropertyForConfig(guid, name, value); } /// <summary> /// Adds a value to build property list in all build configurations for the specified targets. /// Duplicate build properties are ignored. Values for names "LIBRARY_SEARCH_PATHS" and /// "FRAMEWORK_SEARCH_PATHS" are quoted if they contain spaces. /// </summary> /// <param name="targetGuids">The GUIDs of the target as returned by [[TargetGuidByName()]].</param> /// <param name="name">The name of the build property.</param> /// <param name="value">The value of the build property.</param> public void SetBuildProperty(IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) SetBuildProperty(t, name, value); } public void SetBuildPropertyForConfig(string configGuid, string name, string value) { buildConfigs[configGuid].SetProperty(name, value); } public void SetBuildPropertyForConfig(IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) SetBuildPropertyForConfig(guid, name, value); } internal void RemoveBuildProperty(string targetGuid, string name) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) RemoveBuildPropertyForConfig(guid, name); } internal void RemoveBuildProperty(IEnumerable<string> targetGuids, string name) { foreach (string t in targetGuids) RemoveBuildProperty(t, name); } internal void RemoveBuildPropertyForConfig(string configGuid, string name) { buildConfigs[configGuid].RemoveProperty(name); } internal void RemoveBuildPropertyForConfig(IEnumerable<string> configGuids, string name) { foreach (string guid in configGuids) RemoveBuildPropertyForConfig(guid, name); } internal void RemoveBuildPropertyValueList(string targetGuid, string name, IEnumerable<string> valueList) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) RemoveBuildPropertyValueListForConfig(guid, name, valueList); } internal void RemoveBuildPropertyValueList(IEnumerable<string> targetGuids, string name, IEnumerable<string> valueList) { foreach (string t in targetGuids) RemoveBuildPropertyValueList(t, name, valueList); } internal void RemoveBuildPropertyValueListForConfig(string configGuid, string name, IEnumerable<string> valueList) { buildConfigs[configGuid].RemovePropertyValueList(name, valueList); } internal void RemoveBuildPropertyValueListForConfig(IEnumerable<string> configGuids, string name, IEnumerable<string> valueList) { foreach (string guid in configGuids) RemoveBuildPropertyValueListForConfig(guid, name, valueList); } /// Interprets the value of the given property as a set of space-delimited strings, then /// removes strings equal to items to removeValues and adds strings in addValues. public void UpdateBuildProperty(string targetGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in buildConfigLists[GetConfigListForTarget(targetGuid)].buildConfigs) UpdateBuildPropertyForConfig(guid, name, addValues, removeValues); } public void UpdateBuildProperty(IEnumerable<string> targetGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string t in targetGuids) UpdateBuildProperty(t, name, addValues, removeValues); } public void UpdateBuildPropertyForConfig(string configGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { var config = buildConfigs[configGuid]; if (config != null) { if (removeValues != null) foreach (var v in removeValues) config.RemovePropertyValue(name, v); if (addValues != null) foreach (var v in addValues) config.AddProperty(name, v); } } public void UpdateBuildPropertyForConfig(IEnumerable<string> configGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in configGuids) UpdateBuildProperty(guid, name, addValues, removeValues); } internal string ShellScriptByName(string targetGuid, string name) { foreach (var phase in nativeTargets[targetGuid].phases) { var script = shellScripts[phase]; if (script != null && script.name == name) return script.guid; } return null; } internal void AppendShellScriptBuildPhase(string targetGuid, string name, string shellPath, string shellScript) { PBXShellScriptBuildPhaseData shellScriptPhase = PBXShellScriptBuildPhaseData.Create(name, shellPath, shellScript); shellScripts.AddEntry(shellScriptPhase); nativeTargets[targetGuid].phases.AddGUID(shellScriptPhase.guid); } internal void AppendShellScriptBuildPhase(IEnumerable<string> targetGuids, string name, string shellPath, string shellScript) { PBXShellScriptBuildPhaseData shellScriptPhase = PBXShellScriptBuildPhaseData.Create(name, shellPath, shellScript); shellScripts.AddEntry(shellScriptPhase); foreach (string guid in targetGuids) { nativeTargets[guid].phases.AddGUID(shellScriptPhase.guid); } } public void ReadFromFile(string path) { ReadFromString(File.ReadAllText(path)); } public void ReadFromString(string src) { TextReader sr = new StringReader(src); ReadFromStream(sr); } public void ReadFromStream(TextReader sr) { m_Data.ReadFromStream(sr); } public void WriteToFile(string path) { File.WriteAllText(path, WriteToString()); } public void WriteToStream(TextWriter sw) { sw.Write(WriteToString()); } public string WriteToString() { return m_Data.WriteToString(); } internal PBXProjectObjectData GetProjectInternal() { return project.project; } /* * Allows the setting of target attributes in the project section such as Provisioning Style and Team ID for each target * * The Target Attributes are structured like so: * attributes = { * TargetAttributes = { * 1D6058900D05DD3D006BFB54 = { * DevelopmentTeam = Z6SFPV59E3; * ProvisioningStyle = Manual; * }; * 5623C57217FDCB0800090B9E = { * DevelopmentTeam = Z6SFPV59E3; * ProvisioningStyle = Manual; * TestTargetID = 1D6058900D05DD3D006BFB54; * }; * }; * }; */ internal void SetTargetAttributes(string key, string value) { PBXElementDict properties = project.project.GetPropertiesRaw(); PBXElementDict attributes; PBXElementDict targetAttributes; if (properties.Contains("attributes")) { attributes = properties["attributes"] as PBXElementDict; } else { attributes = properties.CreateDict("attributes"); } if (attributes.Contains("TargetAttributes")) { targetAttributes = attributes["TargetAttributes"] as PBXElementDict; } else { targetAttributes = attributes.CreateDict("TargetAttributes"); } foreach (KeyValuePair<string, PBXNativeTargetData> target in nativeTargets.GetEntries()) { PBXElementDict targetAttributesRaw; if (targetAttributes.Contains(target.Key)) { targetAttributesRaw = targetAttributes[target.Key].AsDict(); } else { targetAttributesRaw = targetAttributes.CreateDict(target.Key); } targetAttributesRaw.SetString(key, value); } project.project.UpdateVars(); } } } // namespace UnityEditor.iOS.Xcode
1,458
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System; using Facebook.Unity.Editor.iOS.Xcode.PBX; namespace Facebook.Unity.Editor.iOS.Xcode { using PBXBuildFileSection = KnownSectionBase<PBXBuildFileData>; using PBXFileReferenceSection = KnownSectionBase<PBXFileReferenceData>; using PBXGroupSection = KnownSectionBase<PBXGroupData>; using PBXContainerItemProxySection = KnownSectionBase<PBXContainerItemProxyData>; using PBXReferenceProxySection = KnownSectionBase<PBXReferenceProxyData>; using PBXSourcesBuildPhaseSection = KnownSectionBase<PBXSourcesBuildPhaseData>; using PBXFrameworksBuildPhaseSection= KnownSectionBase<PBXFrameworksBuildPhaseData>; using PBXResourcesBuildPhaseSection = KnownSectionBase<PBXResourcesBuildPhaseData>; using PBXCopyFilesBuildPhaseSection = KnownSectionBase<PBXCopyFilesBuildPhaseData>; using PBXShellScriptBuildPhaseSection = KnownSectionBase<PBXShellScriptBuildPhaseData>; using PBXVariantGroupSection = KnownSectionBase<PBXVariantGroupData>; using PBXNativeTargetSection = KnownSectionBase<PBXNativeTargetData>; using PBXTargetDependencySection = KnownSectionBase<PBXTargetDependencyData>; using XCBuildConfigurationSection = KnownSectionBase<XCBuildConfigurationData>; using XCConfigurationListSection = KnownSectionBase<XCConfigurationListData>; using UnknownSection = KnownSectionBase<PBXObjectData>; internal class PBXProjectData { private Dictionary<string, SectionBase> m_Section = null; private PBXElementDict m_RootElements = null; private PBXElementDict m_UnknownObjects = null; private string m_ObjectVersion = null; private List<string> m_SectionOrder = null; private Dictionary<string, UnknownSection> m_UnknownSections; private PBXBuildFileSection buildFiles = null; // use BuildFiles* methods instead of manipulating directly private PBXFileReferenceSection fileRefs = null; // use FileRefs* methods instead of manipulating directly private PBXGroupSection groups = null; // use Groups* methods instead of manipulating directly public PBXContainerItemProxySection containerItems = null; public PBXReferenceProxySection references = null; public PBXSourcesBuildPhaseSection sources = null; public PBXFrameworksBuildPhaseSection frameworks = null; public PBXResourcesBuildPhaseSection resources = null; public PBXCopyFilesBuildPhaseSection copyFiles = null; public PBXShellScriptBuildPhaseSection shellScripts = null; public PBXNativeTargetSection nativeTargets = null; public PBXTargetDependencySection targetDependencies = null; public PBXVariantGroupSection variantGroups = null; public XCBuildConfigurationSection buildConfigs = null; public XCConfigurationListSection buildConfigLists = null; public PBXProjectSection project = null; // FIXME: create a separate PBXObject tree to represent these relationships // A build file can be represented only once in all *BuildPhaseSection sections, thus // we can simplify the cache by not caring about the file extension private Dictionary<string, Dictionary<string, PBXBuildFileData>> m_FileGuidToBuildFileMap = null; private Dictionary<string, PBXFileReferenceData> m_ProjectPathToFileRefMap = null; private Dictionary<string, string> m_FileRefGuidToProjectPathMap = null; private Dictionary<PBXSourceTree, Dictionary<string, PBXFileReferenceData>> m_RealPathToFileRefMap = null; private Dictionary<string, PBXGroupData> m_ProjectPathToGroupMap = null; private Dictionary<string, string> m_GroupGuidToProjectPathMap = null; private Dictionary<string, PBXGroupData> m_GuidToParentGroupMap = null; public PBXBuildFileData BuildFilesGet(string guid) { return buildFiles[guid]; } // targetGuid is the guid of the target that contains the section that contains the buildFile public void BuildFilesAdd(string targetGuid, PBXBuildFileData buildFile) { if (!m_FileGuidToBuildFileMap.ContainsKey(targetGuid)) m_FileGuidToBuildFileMap[targetGuid] = new Dictionary<string, PBXBuildFileData>(); m_FileGuidToBuildFileMap[targetGuid][buildFile.fileRef] = buildFile; buildFiles.AddEntry(buildFile); } public void BuildFilesRemove(string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile != null) { m_FileGuidToBuildFileMap[targetGuid].Remove(buildFile.fileRef); buildFiles.RemoveEntry(buildFile.guid); } } public PBXBuildFileData BuildFilesGetForSourceFile(string targetGuid, string fileGuid) { if (!m_FileGuidToBuildFileMap.ContainsKey(targetGuid)) return null; if (!m_FileGuidToBuildFileMap[targetGuid].ContainsKey(fileGuid)) return null; return m_FileGuidToBuildFileMap[targetGuid][fileGuid]; } public IEnumerable<PBXBuildFileData> BuildFilesGetAll() { return buildFiles.GetObjects(); } public void FileRefsAdd(string realPath, string projectPath, PBXGroupData parent, PBXFileReferenceData fileRef) { fileRefs.AddEntry(fileRef); m_ProjectPathToFileRefMap.Add(projectPath, fileRef); m_FileRefGuidToProjectPathMap.Add(fileRef.guid, projectPath); m_RealPathToFileRefMap[fileRef.tree].Add(realPath, fileRef); // FIXME m_GuidToParentGroupMap.Add(fileRef.guid, parent); } public PBXFileReferenceData FileRefsGet(string guid) { return fileRefs[guid]; } public PBXFileReferenceData FileRefsGetByRealPath(string path, PBXSourceTree sourceTree) { if (m_RealPathToFileRefMap[sourceTree].ContainsKey(path)) return m_RealPathToFileRefMap[sourceTree][path]; return null; } public PBXFileReferenceData FileRefsGetByProjectPath(string path) { if (m_ProjectPathToFileRefMap.ContainsKey(path)) return m_ProjectPathToFileRefMap[path]; return null; } public void FileRefsRemove(string guid) { PBXFileReferenceData fileRef = fileRefs[guid]; fileRefs.RemoveEntry(guid); m_ProjectPathToFileRefMap.Remove(m_FileRefGuidToProjectPathMap[guid]); m_FileRefGuidToProjectPathMap.Remove(guid); foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees()) m_RealPathToFileRefMap[tree].Remove(fileRef.path); m_GuidToParentGroupMap.Remove(guid); } public PBXGroupData GroupsGet(string guid) { return groups[guid]; } public PBXGroupData GroupsGetByChild(string childGuid) { return m_GuidToParentGroupMap[childGuid]; } public PBXGroupData GroupsGetMainGroup() { return groups[project.project.mainGroup]; } /// Returns the source group identified by sourceGroup. If sourceGroup is empty or null, /// root group is returned. If no group is found, null is returned. public PBXGroupData GroupsGetByProjectPath(string sourceGroup) { if (m_ProjectPathToGroupMap.ContainsKey(sourceGroup)) return m_ProjectPathToGroupMap[sourceGroup]; return null; } public void GroupsAdd(string projectPath, PBXGroupData parent, PBXGroupData gr) { m_ProjectPathToGroupMap.Add(projectPath, gr); m_GroupGuidToProjectPathMap.Add(gr.guid, projectPath); m_GuidToParentGroupMap.Add(gr.guid, parent); groups.AddEntry(gr); } public void GroupsAddDuplicate(PBXGroupData gr) { groups.AddEntry(gr); } public void GroupsRemove(string guid) { m_ProjectPathToGroupMap.Remove(m_GroupGuidToProjectPathMap[guid]); m_GroupGuidToProjectPathMap.Remove(guid); m_GuidToParentGroupMap.Remove(guid); groups.RemoveEntry(guid); } // This function returns a build section that a particular file should be automatically added to. // Returns null for non-buildable file types. // Throws an exception if the file should be added to a section, but that particular section does not exist for given target // Note that for unknown file types we add them to resource build sections public FileGUIDListBase BuildSectionAny(PBXNativeTargetData target, string path, bool isFolderRef) { string ext = Path.GetExtension(path); var phase = FileTypeUtils.GetFileType(ext, isFolderRef); switch (phase) { case PBXFileType.Framework: foreach (var guid in target.phases) if (frameworks.HasEntry(guid)) return frameworks[guid]; break; case PBXFileType.Resource: foreach (var guid in target.phases) if (resources.HasEntry(guid)) return resources[guid]; break; case PBXFileType.Source: foreach (var guid in target.phases) if (sources.HasEntry(guid)) return sources[guid]; break; case PBXFileType.CopyFile: foreach (var guid in target.phases) if (copyFiles.HasEntry(guid)) return copyFiles[guid]; break; case PBXFileType.ShellScript: foreach (var guid in target.phases) if (shellScripts.HasEntry(guid)) return shellScripts[guid]; break; case PBXFileType.NotBuildable: return null; } throw new Exception(String.Format("The given path {0} does not refer to a file in a known build section", path)); } public FileGUIDListBase BuildSectionAny(string sectionGuid) { if (frameworks.HasEntry(sectionGuid)) return frameworks[sectionGuid]; if (resources.HasEntry(sectionGuid)) return resources[sectionGuid]; if (sources.HasEntry(sectionGuid)) return sources[sectionGuid]; if (copyFiles.HasEntry(sectionGuid)) return copyFiles[sectionGuid]; if (shellScripts.HasEntry(sectionGuid)) return shellScripts[sectionGuid]; return null; } void RefreshBuildFilesMapForBuildFileGuidList(Dictionary<string, PBXBuildFileData> mapForTarget, FileGUIDListBase list) { foreach (string guid in list.files) { var buildFile = buildFiles[guid]; mapForTarget[buildFile.fileRef] = buildFile; } } void RefreshMapsForGroupChildren(string projectPath, string realPath, PBXSourceTree realPathTree, PBXGroupData parent) { var children = new List<string>(parent.children); foreach (string guid in children) { PBXFileReferenceData fileRef = fileRefs[guid]; string pPath; string rPath; PBXSourceTree rTree; if (fileRef != null) { pPath = PBXPath.Combine(projectPath, fileRef.name); PBXPath.Combine(realPath, realPathTree, fileRef.path, fileRef.tree, out rPath, out rTree); if (!m_ProjectPathToFileRefMap.ContainsKey(pPath)) { m_ProjectPathToFileRefMap.Add(pPath, fileRef); } if (!m_FileRefGuidToProjectPathMap.ContainsKey(fileRef.guid)) { m_FileRefGuidToProjectPathMap.Add(fileRef.guid, pPath); } if (!m_RealPathToFileRefMap[rTree].ContainsKey(rPath)) { m_RealPathToFileRefMap[rTree].Add(rPath, fileRef); } if (!m_GuidToParentGroupMap.ContainsKey(guid)) { m_GuidToParentGroupMap.Add(guid, parent); } continue; } PBXGroupData gr = groups[guid]; if (gr != null) { pPath = PBXPath.Combine(projectPath, gr.name); PBXPath.Combine(realPath, realPathTree, gr.path, gr.tree, out rPath, out rTree); if (!m_ProjectPathToGroupMap.ContainsKey(pPath)) { m_ProjectPathToGroupMap.Add(pPath, gr); } if (!m_GroupGuidToProjectPathMap.ContainsKey(gr.guid)) { m_GroupGuidToProjectPathMap.Add(gr.guid, pPath); } if (!m_GuidToParentGroupMap.ContainsKey(guid)) { m_GuidToParentGroupMap.Add(guid, parent); } RefreshMapsForGroupChildren(pPath, rPath, rTree, gr); } } } void RefreshAuxMaps() { foreach (var targetEntry in nativeTargets.GetEntries()) { var map = new Dictionary<string, PBXBuildFileData>(); foreach (string phaseGuid in targetEntry.Value.phases) { if (frameworks.HasEntry(phaseGuid)) RefreshBuildFilesMapForBuildFileGuidList(map, frameworks[phaseGuid]); if (resources.HasEntry(phaseGuid)) RefreshBuildFilesMapForBuildFileGuidList(map, resources[phaseGuid]); if (sources.HasEntry(phaseGuid)) RefreshBuildFilesMapForBuildFileGuidList(map, sources[phaseGuid]); if (copyFiles.HasEntry(phaseGuid)) RefreshBuildFilesMapForBuildFileGuidList(map, copyFiles[phaseGuid]); } m_FileGuidToBuildFileMap[targetEntry.Key] = map; } RefreshMapsForGroupChildren("", "", PBXSourceTree.Source, GroupsGetMainGroup()); } public void Clear() { buildFiles = new PBXBuildFileSection("PBXBuildFile"); fileRefs = new PBXFileReferenceSection("PBXFileReference"); groups = new PBXGroupSection("PBXGroup"); containerItems = new PBXContainerItemProxySection("PBXContainerItemProxy"); references = new PBXReferenceProxySection("PBXReferenceProxy"); sources = new PBXSourcesBuildPhaseSection("PBXSourcesBuildPhase"); frameworks = new PBXFrameworksBuildPhaseSection("PBXFrameworksBuildPhase"); resources = new PBXResourcesBuildPhaseSection("PBXResourcesBuildPhase"); copyFiles = new PBXCopyFilesBuildPhaseSection("PBXCopyFilesBuildPhase"); shellScripts = new PBXShellScriptBuildPhaseSection("PBXShellScriptBuildPhase"); nativeTargets = new PBXNativeTargetSection("PBXNativeTarget"); targetDependencies = new PBXTargetDependencySection("PBXTargetDependency"); variantGroups = new PBXVariantGroupSection("PBXVariantGroup"); buildConfigs = new XCBuildConfigurationSection("XCBuildConfiguration"); buildConfigLists = new XCConfigurationListSection("XCConfigurationList"); project = new PBXProjectSection(); m_UnknownSections = new Dictionary<string, UnknownSection>(); m_Section = new Dictionary<string, SectionBase> { { "PBXBuildFile", buildFiles }, { "PBXFileReference", fileRefs }, { "PBXGroup", groups }, { "PBXContainerItemProxy", containerItems }, { "PBXReferenceProxy", references }, { "PBXSourcesBuildPhase", sources }, { "PBXFrameworksBuildPhase", frameworks }, { "PBXResourcesBuildPhase", resources }, { "PBXCopyFilesBuildPhase", copyFiles }, { "PBXShellScriptBuildPhase", shellScripts }, { "PBXNativeTarget", nativeTargets }, { "PBXTargetDependency", targetDependencies }, { "PBXVariantGroup", variantGroups }, { "XCBuildConfiguration", buildConfigs }, { "XCConfigurationList", buildConfigLists }, { "PBXProject", project }, }; m_RootElements = new PBXElementDict(); m_UnknownObjects = new PBXElementDict(); m_ObjectVersion = null; m_SectionOrder = new List<string>{ "PBXBuildFile", "PBXContainerItemProxy", "PBXCopyFilesBuildPhase", "PBXFileReference", "PBXFrameworksBuildPhase", "PBXGroup", "PBXNativeTarget", "PBXProject", "PBXReferenceProxy", "PBXResourcesBuildPhase", "PBXShellScriptBuildPhase", "PBXSourcesBuildPhase", "PBXTargetDependency", "PBXVariantGroup", "XCBuildConfiguration", "XCConfigurationList" }; m_FileGuidToBuildFileMap = new Dictionary<string, Dictionary<string, PBXBuildFileData>>(); m_ProjectPathToFileRefMap = new Dictionary<string, PBXFileReferenceData>(); m_FileRefGuidToProjectPathMap = new Dictionary<string, string>(); m_RealPathToFileRefMap = new Dictionary<PBXSourceTree, Dictionary<string, PBXFileReferenceData>>(); foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees()) m_RealPathToFileRefMap.Add(tree, new Dictionary<string, PBXFileReferenceData>()); m_ProjectPathToGroupMap = new Dictionary<string, PBXGroupData>(); m_GroupGuidToProjectPathMap = new Dictionary<string, string>(); m_GuidToParentGroupMap = new Dictionary<string, PBXGroupData>(); } private void BuildCommentMapForBuildFiles(GUIDToCommentMap comments, List<string> guids, string sectName) { foreach (var guid in guids) { var buildFile = BuildFilesGet(guid); if (buildFile != null) { var fileRef = FileRefsGet(buildFile.fileRef); if (fileRef != null) comments.Add(guid, String.Format("{0} in {1}", fileRef.name, sectName)); else { var reference = references[buildFile.fileRef]; if (reference != null) comments.Add(guid, String.Format("{0} in {1}", reference.path, sectName)); } } } } private GUIDToCommentMap BuildCommentMap() { GUIDToCommentMap comments = new GUIDToCommentMap(); // buildFiles are handled below // filerefs are handled below foreach (var e in groups.GetObjects()) comments.Add(e.guid, e.name); foreach (var e in containerItems.GetObjects()) comments.Add(e.guid, "PBXContainerItemProxy"); foreach (var e in references.GetObjects()) comments.Add(e.guid, e.path); foreach (var e in sources.GetObjects()) { comments.Add(e.guid, "Sources"); BuildCommentMapForBuildFiles(comments, e.files, "Sources"); } foreach (var e in resources.GetObjects()) { comments.Add(e.guid, "Resources"); BuildCommentMapForBuildFiles(comments, e.files, "Resources"); } foreach (var e in frameworks.GetObjects()) { comments.Add(e.guid, "Frameworks"); BuildCommentMapForBuildFiles(comments, e.files, "Frameworks"); } foreach (var e in copyFiles.GetObjects()) { string sectName = e.name; if (sectName == null) sectName = "CopyFiles"; comments.Add(e.guid, sectName); BuildCommentMapForBuildFiles(comments, e.files, sectName); } foreach (var e in shellScripts.GetObjects()) comments.Add(e.guid, "ShellScript"); foreach (var e in targetDependencies.GetObjects()) comments.Add(e.guid, "PBXTargetDependency"); foreach (var e in nativeTargets.GetObjects()) { comments.Add(e.guid, e.name); comments.Add(e.buildConfigList, String.Format("Build configuration list for PBXNativeTarget \"{0}\"", e.name)); } foreach (var e in variantGroups.GetObjects()) comments.Add(e.guid, e.name); foreach (var e in buildConfigs.GetObjects()) comments.Add(e.guid, e.name); foreach (var e in project.GetObjects()) { comments.Add(e.guid, "Project object"); comments.Add( e.buildConfigList, "Build configuration list for PBXProject \"Unity-iPhone\""); // FIXME: project name is hardcoded } foreach (var e in fileRefs.GetObjects()) comments.Add(e.guid, e.name); if (m_RootElements.Contains("rootObject") && m_RootElements["rootObject"] is PBXElementString) comments.Add(m_RootElements["rootObject"].AsString(), "Project object"); return comments; } private static PBXElementDict ParseContent(string content) { TokenList tokens = Lexer.Tokenize(content); var parser = new Parser(tokens); TreeAST ast = parser.ParseTree(); return Serializer.ParseTreeAST(ast, tokens, content); } public void ReadFromStream(TextReader sr) { Clear(); m_RootElements = ParseContent(sr.ReadToEnd()); if (!m_RootElements.Contains("objects")) throw new Exception("Invalid PBX project file: no objects element"); var objects = m_RootElements["objects"].AsDict(); m_RootElements.Remove("objects"); m_RootElements.SetString("objects", "OBJMARKER"); if (m_RootElements.Contains("objectVersion")) { m_ObjectVersion = m_RootElements["objectVersion"].AsString(); m_RootElements.Remove("objectVersion"); } var allGuids = new List<string>(); string prevSectionName = null; foreach (var kv in objects.values) { allGuids.Add(kv.Key); var el = kv.Value; if (!(el is PBXElementDict) || !el.AsDict().Contains("isa")) { m_UnknownObjects.values.Add(kv.Key, el); continue; } var dict = el.AsDict(); var sectionName = dict["isa"].AsString(); if (m_Section.ContainsKey(sectionName)) { var section = m_Section[sectionName]; section.AddObject(kv.Key, dict); } else { UnknownSection section; if (m_UnknownSections.ContainsKey(sectionName)) section = m_UnknownSections[sectionName]; else { section = new UnknownSection(sectionName); m_UnknownSections.Add(sectionName, section); } section.AddObject(kv.Key, dict); // update section order if (!m_SectionOrder.Contains(sectionName)) { int pos = 0; if (prevSectionName != null) { // this never fails, because we already added any previous unknown sections // to m_SectionOrder pos = m_SectionOrder.FindIndex(x => x == prevSectionName); pos += 1; } m_SectionOrder.Insert(pos, sectionName); } } prevSectionName = sectionName; } RepairStructure(allGuids); RefreshAuxMaps(); } public string WriteToString() { var commentMap = BuildCommentMap(); var emptyChecker = new PropertyCommentChecker(); var emptyCommentMap = new GUIDToCommentMap(); // since we need to add custom comments, the serialization is much more complex StringBuilder objectsSb = new StringBuilder(); if (m_ObjectVersion != null) // objectVersion comes right before objects objectsSb.AppendFormat("objectVersion = {0};\n\t", m_ObjectVersion); objectsSb.Append("objects = {"); foreach (string sectionName in m_SectionOrder) { if (m_Section.ContainsKey(sectionName)) m_Section[sectionName].WriteSection(objectsSb, commentMap); else if (m_UnknownSections.ContainsKey(sectionName)) m_UnknownSections[sectionName].WriteSection(objectsSb, commentMap); } foreach (var kv in m_UnknownObjects.values) Serializer.WriteDictKeyValue(objectsSb, kv.Key, kv.Value, 2, false, emptyChecker, emptyCommentMap); objectsSb.Append("\n\t};"); StringBuilder contentSb = new StringBuilder(); contentSb.Append("// !$*UTF8*$!\n"); Serializer.WriteDict(contentSb, m_RootElements, 0, false, new PropertyCommentChecker(new string[]{"rootObject/*"}), commentMap); contentSb.Append("\n"); string content = contentSb.ToString(); content = content.Replace("objects = OBJMARKER;", objectsSb.ToString()); return content; } // This method walks the project structure and removes invalid entries. void RepairStructure(List<string> allGuids) { var guidSet = new Dictionary<string, bool>(); // emulate HashSet on .Net 2.0 foreach (var guid in allGuids) guidSet.Add(guid, false); while (RepairStructureImpl(guidSet) == true) ; } /* Iterates the given guid list and removes all guids that are not in allGuids dictionary. */ static void RemoveMissingGuidsFromGuidList(PBX.GUIDList guidList, Dictionary<string, bool> allGuids) { List<string> guidsToRemove = null; foreach (var guid in guidList) { if (!allGuids.ContainsKey(guid)) { if (guidsToRemove == null) guidsToRemove = new List<string>(); guidsToRemove.Add(guid); } } if (guidsToRemove != null) { foreach (var guid in guidsToRemove) guidList.RemoveGUID(guid); } } /* Removes objects from the given @a section for which @a checker returns true. Also removes the guids of the removed elements from allGuids dictionary. Returns true if any objects were removed. */ static bool RemoveObjectsFromSection<T>(KnownSectionBase<T> section, Dictionary<string, bool> allGuids, Func<T, bool> checker) where T : PBXObjectData, new() { List<string> guidsToRemove = null; foreach (var kv in section.GetEntries()) { if (checker(kv.Value)) { if (guidsToRemove == null) guidsToRemove = new List<string>(); guidsToRemove.Add(kv.Key); } } if (guidsToRemove != null) { foreach (var guid in guidsToRemove) { section.RemoveEntry(guid); allGuids.Remove(guid); } return true; } return false; } // Returns true if changes were done and one should call RepairStructureImpl again bool RepairStructureImpl(Dictionary<string, bool> allGuids) { bool changed = false; // PBXBuildFile changed |= RemoveObjectsFromSection(buildFiles, allGuids, o => (o.fileRef == null || !allGuids.ContainsKey(o.fileRef))); // PBXFileReference / fileRefs not cleaned // PBXGroup changed |= RemoveObjectsFromSection(groups, allGuids, o => o.children == null); foreach (var o in groups.GetObjects()) RemoveMissingGuidsFromGuidList(o.children, allGuids); // PBXContainerItem / containerItems not cleaned // PBXReferenceProxy / references not cleaned // PBXSourcesBuildPhase changed |= RemoveObjectsFromSection(sources, allGuids, o => o.files == null); foreach (var o in sources.GetObjects()) RemoveMissingGuidsFromGuidList(o.files, allGuids); // PBXFrameworksBuildPhase changed |= RemoveObjectsFromSection(frameworks, allGuids, o => o.files == null); foreach (var o in frameworks.GetObjects()) RemoveMissingGuidsFromGuidList(o.files, allGuids); // PBXResourcesBuildPhase changed |= RemoveObjectsFromSection(resources, allGuids, o => o.files == null); foreach (var o in resources.GetObjects()) RemoveMissingGuidsFromGuidList(o.files, allGuids); // PBXCopyFilesBuildPhase changed |= RemoveObjectsFromSection(copyFiles, allGuids, o => o.files == null); foreach (var o in copyFiles.GetObjects()) RemoveMissingGuidsFromGuidList(o.files, allGuids); // PBXShellScriptsBuildPhase changed |= RemoveObjectsFromSection(shellScripts, allGuids, o => o.files == null); foreach (var o in shellScripts.GetObjects()) RemoveMissingGuidsFromGuidList(o.files, allGuids); // PBXNativeTarget changed |= RemoveObjectsFromSection(nativeTargets, allGuids, o => o.phases == null); foreach (var o in nativeTargets.GetObjects()) RemoveMissingGuidsFromGuidList(o.phases, allGuids); // PBXTargetDependency / targetDependencies not cleaned // PBXVariantGroup changed |= RemoveObjectsFromSection(variantGroups, allGuids, o => o.children == null); foreach (var o in variantGroups.GetObjects()) RemoveMissingGuidsFromGuidList(o.children, allGuids); // XCBuildConfiguration / buildConfigs not cleaned // XCConfigurationList changed |= RemoveObjectsFromSection(buildConfigLists, allGuids, o => o.buildConfigs == null); foreach (var o in buildConfigLists.GetObjects()) RemoveMissingGuidsFromGuidList(o.buildConfigs, allGuids); // PBXProject project not cleaned return changed; } } } // namespace UnityEditor.iOS.Xcode
733
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; public class PListDict : Dictionary<string, object> { public PListDict() { } public PListDict(PListDict dict) : base(dict) { } public PListDict(XElement dict) { this.Load(dict); } public void Load(XElement dict) { var dictElements = dict.Elements(); this.ParseDictForLoad(this, dictElements); } public void Save(string fileName, XDeclaration declaration, XDocumentType docType) { XElement plistNode = new XElement("plist", this.ParseDictForSave(this)); plistNode.SetAttributeValue("version", "1.0"); XDocument file = new XDocument(declaration, docType); file.Add(plistNode); file.Save(fileName); } public XElement ParseValueForSave(object node) { if (node is string) { return new XElement("string", node); } else if (node is bool) { return new XElement(node.ToString().ToLower()); } else if (node is int) { return new XElement("integer", node); } else if (node is float) { return new XElement("real", node); } else if (node is IList<object>) { return this.ParseArrayForSave(node); } else if (node is PListDict) { return this.ParseDictForSave((PListDict)node); } else if (node == null) { return null; } throw new NotSupportedException("Unexpected type: " + node.GetType().FullName); } private void ParseDictForLoad(PListDict dict, IEnumerable<XElement> elements) { for (int i = 0; i < elements.Count(); i += 2) { XElement key = elements.ElementAt(i); XElement val = elements.ElementAt(i + 1); dict[key.Value] = this.ParseValueForLoad(val); } } private IList<object> ParseArrayForLoad(IEnumerable<XElement> elements) { var list = new List<object>(); foreach (XElement e in elements) { object one = this.ParseValueForLoad(e); list.Add(one); } return list; } private object ParseValueForLoad(XElement val) { switch (val.Name.ToString()) { case "string": return val.Value; case "integer": return int.Parse(val.Value); case "real": return float.Parse(val.Value); case "true": return true; case "false": return false; case "dict": PListDict plist = new PListDict(); this.ParseDictForLoad(plist, val.Elements()); return plist; case "array": return this.ParseArrayForLoad(val.Elements()); default: throw new ArgumentException("Format unsupported, Parser update needed"); } } private XElement ParseDictForSave(PListDict dict) { XElement dictNode = new XElement("dict"); foreach (string key in dict.Keys) { dictNode.Add(new XElement("key", key)); dictNode.Add(this.ParseValueForSave(dict[key])); } return dictNode; } private XElement ParseArrayForSave(object node) { XElement arrayNode = new XElement("array"); var array = (IList<object>)node; for (int i = 0; i < array.Count; i++) { arrayNode.Add(this.ParseValueForSave(array[i])); } return arrayNode; } } }
164
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Linq; using Facebook.Unity.Settings; internal class PListParser { private const string LSApplicationQueriesSchemesKey = "LSApplicationQueriesSchemes"; private const string CFBundleURLTypesKey = "CFBundleURLTypes"; private const string CFBundleURLSchemesKey = "CFBundleURLSchemes"; private const string CFBundleURLName = "CFBundleURLName"; private const string FacebookCFBundleURLName = "facebook-unity-sdk"; private const string FacebookAppIDKey = "FacebookAppID"; private const string FacebookAppIDPrefix = "fb"; private const string FacebookClientTokenKey = "FacebookClientToken"; private const string AutoLogAppEventsEnabled = "FacebookAutoLogAppEventsEnabled"; private const string AdvertiserIDCollectionEnabled = "FacebookAdvertiserIDCollectionEnabled"; private static readonly IList<object> FacebookLSApplicationQueriesSchemes = new List<object>() { "fbapi", "fb-messenger-api", "fbauth2", "fbshareextension" }; private static readonly PListDict FacebookUrlSchemes = new PListDict() { { PListParser.CFBundleURLName, PListParser.FacebookCFBundleURLName }, }; private string filePath; public PListParser(string fullPath) { this.filePath = fullPath; XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = false; XmlReader plistReader = XmlReader.Create(this.filePath, settings); XDocument doc = XDocument.Load(plistReader); XElement plist = doc.Element("plist"); XElement dict = plist.Element("dict"); this.XMLDict = new PListDict(dict); plistReader.Close(); } public PListDict XMLDict { get; set; } public void UpdateFBSettings(string appID, string clientToken, string urlSuffix, ICollection<string> appLinkSchemes) { // Set the facbook app ID this.XMLDict[PListParser.FacebookAppIDKey] = appID; // Set the client token this.XMLDict[PListParser.FacebookClientTokenKey] = clientToken; // Set the Auto Log AppEvents Enabled this.XMLDict[PListParser.AutoLogAppEventsEnabled] = FacebookSettings.AutoLogAppEventsEnabled; // Set the AdvertiserID Collection Enabled this.XMLDict[PListParser.AdvertiserIDCollectionEnabled] = FacebookSettings.AdvertiserIDCollectionEnabled; // Set the requried schemas for this app SetCFBundleURLSchemes(this.XMLDict, appID, urlSuffix, appLinkSchemes); // iOS 9+ Support WhitelistFacebookApps(this.XMLDict); } public void WriteToFile() { // Corrected header of the plist string publicId = "-//Apple//DTD PLIST 1.0//EN"; string stringId = "http://www.apple.com/DTDs/PropertyList-1.0.dtd"; string internalSubset = null; XDeclaration declaration = new XDeclaration("1.0", Encoding.UTF8.EncodingName, null); XDocumentType docType = new XDocumentType("plist", publicId, stringId, internalSubset); this.XMLDict.Save(this.filePath, declaration, docType); } private static void WhitelistFacebookApps(PListDict plistDict) { if (!ContainsKeyWithValueType(plistDict, PListParser.LSApplicationQueriesSchemesKey, typeof(IList<object>))) { // We don't have a LSApplicationQueriesSchemes entry. We can easily add one plistDict[PListParser.LSApplicationQueriesSchemesKey] = PListParser.FacebookLSApplicationQueriesSchemes; return; } var applicationQueriesSchemes = (IList<object>)plistDict[PListParser.LSApplicationQueriesSchemesKey]; foreach (var scheme in PListParser.FacebookLSApplicationQueriesSchemes) { if (!applicationQueriesSchemes.Contains(scheme)) { applicationQueriesSchemes.Add(scheme); } } } private static void SetCFBundleURLSchemes( PListDict plistDict, string appID, string urlSuffix, ICollection<string> appLinkSchemes) { IList<object> currentSchemas; if (ContainsKeyWithValueType(plistDict, PListParser.CFBundleURLTypesKey, typeof(IList<object>))) { currentSchemas = (IList<object>)plistDict[PListParser.CFBundleURLTypesKey]; } else { // Didn't find any CFBundleURLTypes, let's create one currentSchemas = new List<object>(); plistDict[PListParser.CFBundleURLTypesKey] = currentSchemas; } PListDict facebookBundleUrlSchemes = PListParser.GetFacebookUrlSchemes(currentSchemas); // Clear and set the CFBundleURLSchemes for the facebook schemes var facebookUrlSchemes = new List<object>(); facebookBundleUrlSchemes[PListParser.CFBundleURLSchemesKey] = facebookUrlSchemes; AddAppID(facebookUrlSchemes, appID, urlSuffix); AddAppLinkSchemes(facebookUrlSchemes, appLinkSchemes); } private static PListDict GetFacebookUrlSchemes(ICollection<object> plistSchemes) { foreach (var plistScheme in plistSchemes) { var bundleTypeNode = plistScheme as PListDict; if (bundleTypeNode != null) { // Check to see if the url scheme name is facebook string bundleURLName; if (bundleTypeNode.TryGetValue<string>(PListParser.CFBundleURLName, out bundleURLName) && bundleURLName == PListParser.FacebookCFBundleURLName) { return bundleTypeNode; } } } // We didn't find a facebook scheme so lets create one PListDict facebookUrlSchemes = new PListDict(PListParser.FacebookUrlSchemes); plistSchemes.Add(facebookUrlSchemes); return facebookUrlSchemes; } private static void AddAppID(ICollection<object> schemesCollection, string appID, string urlSuffix) { string modifiedID = PListParser.FacebookAppIDPrefix + appID; if (!string.IsNullOrEmpty(urlSuffix)) { modifiedID += urlSuffix; } schemesCollection.Add((object)modifiedID); } private static void AddAppLinkSchemes(ICollection<object> schemesCollection, ICollection<string> appLinkSchemes) { foreach (var appLinkScheme in appLinkSchemes) { schemesCollection.Add(appLinkScheme); } } private static bool ContainsKeyWithValueType(IDictionary<string, object> dictionary, string key, Type type) { if (dictionary.ContainsKey(key) && type.IsAssignableFrom(dictionary[key].GetType())) { return true; } return false; } } }
207
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Collections; using System; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { class PBXElement { protected PBXElement() {} // convenience methods public string AsString() { return ((PBXElementString)this).value; } public PBXElementArray AsArray() { return (PBXElementArray)this; } public PBXElementDict AsDict() { return (PBXElementDict)this; } public PBXElement this[string key] { get { return AsDict()[key]; } set { AsDict()[key] = value; } } } class PBXElementString : PBXElement { public PBXElementString(string v) { value = v; } public string value; } class PBXElementDict : PBXElement { public PBXElementDict() : base() {} private Dictionary<string, PBXElement> m_PrivateValue = new Dictionary<string, PBXElement>(); public IDictionary<string, PBXElement> values { get { return m_PrivateValue; }} new public PBXElement this[string key] { get { if (values.ContainsKey(key)) return values[key]; return null; } set { this.values[key] = value; } } public bool Contains(string key) { return values.ContainsKey(key); } public void Remove(string key) { values.Remove(key); } public void SetString(string key, string val) { values[key] = new PBXElementString(val); } public PBXElementArray CreateArray(string key) { var v = new PBXElementArray(); values[key] = v; return v; } public PBXElementDict CreateDict(string key) { var v = new PBXElementDict(); values[key] = v; return v; } } class PBXElementArray : PBXElement { public PBXElementArray() : base() {} public List<PBXElement> values = new List<PBXElement>(); // convenience methods public void AddString(string val) { values.Add(new PBXElementString(val)); } public PBXElementArray AddArray() { var v = new PBXElementArray(); values.Add(v); return v; } public PBXElementDict AddDict() { var v = new PBXElementDict(); values.Add(v); return v; } } } // namespace UnityEditor.iOS.Xcode
125
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { enum TokenType { EOF, Invalid, String, QuotedString, Comment, Semicolon, // ; Comma, // , Eq, // = LParen, // ( RParen, // ) LBrace, // { RBrace, // } } class Token { public TokenType type; // the line of the input stream the token starts in (0-based) public int line; // start and past-the-end positions of the token in the input stream public int begin, end; } class TokenList : List<Token> { } class Lexer { string text; int pos; int length; int line; public static TokenList Tokenize(string text) { var lexer = new Lexer(); lexer.SetText(text); return lexer.ScanAll(); } public void SetText(string text) { this.text = text + " "; // to prevent out-of-bounds access during look ahead pos = 0; length = text.Length; line = 0; } public TokenList ScanAll() { var tokens = new TokenList(); while (true) { var tok = new Token(); ScanOne(tok); tokens.Add(tok); if (tok.type == TokenType.EOF) break; } return tokens; } void UpdateNewlineStats(char ch) { if (ch == '\n') line++; } // tokens list is modified in the case when we add BrokenLine token and need to remove already // added tokens for the current line void ScanOne(Token tok) { while (true) { while (pos < length && Char.IsWhiteSpace(text[pos])) { UpdateNewlineStats(text[pos]); pos++; } if (pos >= length) { tok.type = TokenType.EOF; break; } char ch = text[pos]; char ch2 = text[pos+1]; if (ch == '\"') ScanQuotedString(tok); else if (ch == '/' && ch2 == '*') ScanMultilineComment(tok); else if (ch == '/' && ch2 == '/') ScanComment(tok); else if (IsOperator(ch)) ScanOperator(tok); else ScanString(tok); // be more robust and accept whatever is left return; } } void ScanString(Token tok) { tok.type = TokenType.String; tok.begin = pos; while (pos < length) { char ch = text[pos]; char ch2 = text[pos+1]; if (Char.IsWhiteSpace(ch)) break; else if (ch == '\"') break; else if (ch == '/' && ch2 == '*') break; else if (ch == '/' && ch2 == '/') break; else if (IsOperator(ch)) break; pos++; } tok.end = pos; tok.line = line; } void ScanQuotedString(Token tok) { tok.type = TokenType.QuotedString; tok.begin = pos; pos++; while (pos < length) { // ignore escaped quotes if (text[pos] == '\\' && text[pos+1] == '\"') { pos += 2; continue; } // note that we close unclosed quotes if (text[pos] == '\"') break; UpdateNewlineStats(text[pos]); pos++; } pos++; tok.end = pos; tok.line = line; } void ScanMultilineComment(Token tok) { tok.type = TokenType.Comment; tok.begin = pos; pos += 2; while (pos < length) { if (text[pos] == '*' && text[pos+1] == '/') break; // we support multiline comments UpdateNewlineStats(text[pos]); pos++; } pos += 2; tok.end = pos; tok.line = line; } void ScanComment(Token tok) { tok.type = TokenType.Comment; tok.begin = pos; pos += 2; while (pos < length) { if (text[pos] == '\n') break; pos++; } UpdateNewlineStats(text[pos]); pos++; tok.end = pos; tok.line = line; } bool IsOperator(char ch) { if (ch == ';' || ch == ',' || ch == '=' || ch == '(' || ch == ')' || ch == '{' || ch == '}') return true; return false; } void ScanOperator(Token tok) { switch (text[pos]) { case ';': ScanOperatorSpecific(tok, TokenType.Semicolon); return; case ',': ScanOperatorSpecific(tok, TokenType.Comma); return; case '=': ScanOperatorSpecific(tok, TokenType.Eq); return; case '(': ScanOperatorSpecific(tok, TokenType.LParen); return; case ')': ScanOperatorSpecific(tok, TokenType.RParen); return; case '{': ScanOperatorSpecific(tok, TokenType.LBrace); return; case '}': ScanOperatorSpecific(tok, TokenType.RBrace); return; default: return; } } void ScanOperatorSpecific(Token tok, TokenType type) { tok.type = type; tok.begin = pos; pos++; tok.end = pos; tok.line = line; } } } // namespace UnityEditor.iOS.Xcode
263
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { internal class PBXObjectData { public string guid; protected PBXElementDict m_Properties = new PBXElementDict(); internal void SetPropertiesWhenSerializing(PBXElementDict props) { m_Properties = props; } internal PBXElementDict GetPropertiesWhenSerializing() { return m_Properties; } /* Returns the internal properties dictionary which the user may manipulate directly. If any of the properties are modified, UpdateVars() must be called before any other operation affecting the given Xcode document is executed. */ internal PBXElementDict GetPropertiesRaw() { UpdateProps(); return m_Properties; } // returns null if it does not exist protected string GetPropertyString(string name) { var prop = m_Properties[name]; if (prop == null) return null; return prop.AsString(); } protected void SetPropertyString(string name, string value) { if (value == null) m_Properties.Remove(name); else m_Properties.SetString(name, value); } protected List<string> GetPropertyList(string name) { var prop = m_Properties[name]; if (prop == null) return null; var list = new List<string>(); foreach (var el in prop.AsArray().values) list.Add(el.AsString()); return list; } protected void SetPropertyList(string name, List<string> value) { if (value == null) m_Properties.Remove(name); else { var array = m_Properties.CreateArray(name); foreach (string val in value) array.AddString(val); } } private static PropertyCommentChecker checkerData = new PropertyCommentChecker(); internal virtual PropertyCommentChecker checker { get { return checkerData; } } internal virtual bool shouldCompact { get { return false; } } public virtual void UpdateProps() {} // Updates the props from cached variables public virtual void UpdateVars() {} // Updates the cached variables from underlying props } internal class PBXBuildFileData : PBXObjectData { public string fileRef; public string compileFlags; public bool weak; public bool codeSignOnCopy; public bool removeHeadersOnCopy; public List<string> assetTags; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "fileRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } internal override bool shouldCompact { get { return true; } } public static PBXBuildFileData CreateFromFile(string fileRefGUID, bool weak, string compileFlags) { PBXBuildFileData buildFile = new PBXBuildFileData(); buildFile.guid = PBXGUID.Generate(); buildFile.SetPropertyString("isa", "PBXBuildFile"); buildFile.fileRef = fileRefGUID; buildFile.compileFlags = compileFlags; buildFile.weak = weak; buildFile.codeSignOnCopy = false; buildFile.removeHeadersOnCopy = false; buildFile.assetTags = new List<string>(); return buildFile; } PBXElementDict UpdatePropsAttribute(PBXElementDict settings, bool value, string attributeName) { PBXElementArray attrs = null; if (value) { if (settings == null) settings = m_Properties.CreateDict("settings"); } if (settings != null && settings.Contains("ATTRIBUTES")) attrs = settings["ATTRIBUTES"].AsArray(); if (value) { if (attrs == null) attrs = settings.CreateArray("ATTRIBUTES"); bool exists = attrs.values.Any(attr => { return attr is PBXElementString && attr.AsString() == attributeName; }); if (!exists) attrs.AddString(attributeName); } else { if (attrs != null) { attrs.values.RemoveAll(el => (el is PBXElementString && el.AsString() == attributeName)); if (attrs.values.Count == 0) settings.Remove("ATTRIBUTES"); } } return settings; } public override void UpdateProps() { SetPropertyString("fileRef", fileRef); PBXElementDict settings = null; if (m_Properties.Contains("settings")) settings = m_Properties["settings"].AsDict(); if (compileFlags != null && compileFlags != "") { if (settings == null) settings = m_Properties.CreateDict("settings"); settings.SetString("COMPILER_FLAGS", compileFlags); } else { if (settings != null) settings.Remove("COMPILER_FLAGS"); } settings = UpdatePropsAttribute(settings, weak, "Weak"); settings = UpdatePropsAttribute(settings, codeSignOnCopy, "CodeSignOnCopy"); settings = UpdatePropsAttribute(settings, removeHeadersOnCopy, "RemoveHeadersOnCopy"); if (assetTags.Count > 0) { if (settings == null) settings = m_Properties.CreateDict("settings"); var tagsArray = settings.CreateArray("ASSET_TAGS"); foreach (string tag in assetTags) tagsArray.AddString(tag); } else { if (settings != null) settings.Remove("ASSET_TAGS"); } if (settings != null && settings.values.Count == 0) m_Properties.Remove("settings"); } public override void UpdateVars() { fileRef = GetPropertyString("fileRef"); compileFlags = null; weak = false; assetTags = new List<string>(); if (m_Properties.Contains("settings")) { var dict = m_Properties["settings"].AsDict(); if (dict.Contains("COMPILER_FLAGS")) compileFlags = dict["COMPILER_FLAGS"].AsString(); if (dict.Contains("ATTRIBUTES")) { var attrs = dict["ATTRIBUTES"].AsArray(); foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") weak = true; if (value is PBXElementString && value.AsString() == "CodeSignOnCopy") codeSignOnCopy = true; if (value is PBXElementString && value.AsString() == "RemoveHeadersOnCopy") removeHeadersOnCopy = true; } } if (dict.Contains("ASSET_TAGS")) { var tags = dict["ASSET_TAGS"].AsArray(); foreach (var value in tags.values) assetTags.Add(value.AsString()); } } } } internal class PBXFileReferenceData : PBXObjectData { string m_Path = null; string m_ExplicitFileType = null; string m_LastKnownFileType = null; public string path { get { return m_Path; } set { m_ExplicitFileType = null; m_LastKnownFileType = null; m_Path = value; } } public string name; public PBXSourceTree tree; public bool isFolderReference { get { return m_LastKnownFileType != null && m_LastKnownFileType == "folder"; } } internal override bool shouldCompact { get { return true; } } public static PBXFileReferenceData CreateFromFile(string path, string projectFileName, PBXSourceTree tree) { string guid = PBXGUID.Generate(); PBXFileReferenceData fileRef = new PBXFileReferenceData(); fileRef.SetPropertyString("isa", "PBXFileReference"); fileRef.guid = guid; fileRef.path = path; fileRef.name = projectFileName; fileRef.tree = tree; return fileRef; } public static PBXFileReferenceData CreateFromFolderReference(string path, string projectFileName, PBXSourceTree tree) { var fileRef = CreateFromFile(path, projectFileName, tree); fileRef.m_LastKnownFileType = "folder"; return fileRef; } public override void UpdateProps() { string ext = null; if (m_ExplicitFileType != null) SetPropertyString("explicitFileType", m_ExplicitFileType); else if (m_LastKnownFileType != null) SetPropertyString("lastKnownFileType", m_LastKnownFileType); else { if (name != null) ext = Path.GetExtension(name); else if (m_Path != null) ext = Path.GetExtension(m_Path); if (ext != null) { if (FileTypeUtils.IsFileTypeExplicit(ext)) SetPropertyString("explicitFileType", FileTypeUtils.GetTypeName(ext)); else SetPropertyString("lastKnownFileType", FileTypeUtils.GetTypeName(ext)); } } if (m_Path == name) SetPropertyString("name", null); else SetPropertyString("name", name); if (m_Path == null) SetPropertyString("path", ""); else SetPropertyString("path", m_Path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { name = GetPropertyString("name"); m_Path = GetPropertyString("path"); if (name == null) name = m_Path; if (m_Path == null) m_Path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); m_ExplicitFileType = GetPropertyString("explicitFileType"); m_LastKnownFileType = GetPropertyString("lastKnownFileType"); } } class GUIDList : IEnumerable<string> { private List<string> m_List = new List<string>(); public GUIDList() {} public GUIDList(List<string> data) { m_List = data; } public static implicit operator List<string>(GUIDList list) { return list.m_List; } public static implicit operator GUIDList(List<string> data) { return new GUIDList(data); } public void AddGUID(string guid) { m_List.Add(guid); } public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); } public bool Contains(string guid) { return m_List.Contains(guid); } public int Count { get { return m_List.Count; } } public void Clear() { m_List.Clear(); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return m_List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return m_List.GetEnumerator(); } } internal class XCConfigurationListData : PBXObjectData { public GUIDList buildConfigs; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurations/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static XCConfigurationListData Create() { var res = new XCConfigurationListData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCConfigurationList"); res.buildConfigs = new GUIDList(); res.SetPropertyString("defaultConfigurationIsVisible", "0"); return res; } public override void UpdateProps() { SetPropertyList("buildConfigurations", buildConfigs); } public override void UpdateVars() { buildConfigs = GetPropertyList("buildConfigurations"); } } internal class PBXGroupData : PBXObjectData { public GUIDList children; public PBXSourceTree tree; public string name, path; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "children/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } // name must not contain '/' public static PBXGroupData Create(string name, string path, PBXSourceTree tree) { if (name.Contains("/")) throw new Exception("Group name must not contain '/'"); PBXGroupData gr = new PBXGroupData(); gr.guid = PBXGUID.Generate(); gr.SetPropertyString("isa", "PBXGroup"); gr.name = name; gr.path = path; gr.tree = PBXSourceTree.Group; gr.children = new GUIDList(); return gr; } public static PBXGroupData CreateRelative(string name) { return Create(name, name, PBXSourceTree.Group); } public override void UpdateProps() { // The name property is set only if it is different from the path property SetPropertyList("children", children); if (name == path) SetPropertyString("name", null); else SetPropertyString("name", name); if (path == "") SetPropertyString("path", null); else SetPropertyString("path", path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { children = GetPropertyList("children"); path = GetPropertyString("path"); name = GetPropertyString("name"); if (name == null) name = path; if (path == null) path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); } } internal class PBXVariantGroupData : PBXGroupData { } internal class PBXNativeTargetData : PBXObjectData { public GUIDList phases; public string buildConfigList; // guid public string name; public GUIDList dependencies; public string productReference; // guid private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildPhases/*", "buildRules/*", "dependencies/*", "productReference/*", "buildConfigurationList/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXNativeTargetData Create(string name, string productRef, string productType, string buildConfigList) { var res = new PBXNativeTargetData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXNativeTarget"); res.buildConfigList = buildConfigList; res.phases = new GUIDList(); res.SetPropertyList("buildRules", new List<string>()); res.dependencies = new GUIDList(); res.name = name; res.productReference = productRef; res.SetPropertyString("productName", name); res.SetPropertyString("productReference", productRef); res.SetPropertyString("productType", productType); return res; } public override void UpdateProps() { SetPropertyString("buildConfigurationList", buildConfigList); SetPropertyString("name", name); SetPropertyString("productReference", productReference); SetPropertyList("buildPhases", phases); SetPropertyList("dependencies", dependencies); } public override void UpdateVars() { buildConfigList = GetPropertyString("buildConfigurationList"); name = GetPropertyString("name"); productReference = GetPropertyString("productReference"); phases = GetPropertyList("buildPhases"); dependencies = GetPropertyList("dependencies"); } } internal class FileGUIDListBase : PBXObjectData { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class PBXSourcesBuildPhaseData : FileGUIDListBase { public static PBXSourcesBuildPhaseData Create() { var res = new PBXSourcesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXSourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXFrameworksBuildPhaseData : FileGUIDListBase { public static PBXFrameworksBuildPhaseData Create() { var res = new PBXFrameworksBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXFrameworksBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXResourcesBuildPhaseData : FileGUIDListBase { public static PBXResourcesBuildPhaseData Create() { var res = new PBXResourcesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXResourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXCopyFilesBuildPhaseData : FileGUIDListBase { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string name; public string dstPath; public string dstSubfolderSpec; // name may be null public static PBXCopyFilesBuildPhaseData Create(string name, string dstPath, string subfolderSpec) { var res = new PBXCopyFilesBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXCopyFilesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.dstPath = dstPath; res.dstSubfolderSpec = subfolderSpec; res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); res.name = name; return res; } public override void UpdateProps() { SetPropertyList("files", files); SetPropertyString("name", name); SetPropertyString("dstPath", dstPath); SetPropertyString("dstSubfolderSpec", dstSubfolderSpec); } public override void UpdateVars() { files = GetPropertyList("files"); name = GetPropertyString("name"); dstPath = GetPropertyString("dstPath"); dstSubfolderSpec = GetPropertyString("dstSubfolderSpec"); } } internal class PBXShellScriptBuildPhaseData : FileGUIDListBase { public string name; public string shellPath; public string shellScript; public static PBXShellScriptBuildPhaseData Create(string name, string shellPath, string shellScript) { var res = new PBXShellScriptBuildPhaseData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXShellScriptBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); res.name = name; res.shellPath = shellPath; res.shellScript = shellScript; return res; } public override void UpdateProps() { base.UpdateProps(); SetPropertyString("name", name); SetPropertyString("shellPath", shellPath); SetPropertyString("shellScript", shellScript); } public override void UpdateVars() { base.UpdateVars(); name = GetPropertyString("name"); shellPath = GetPropertyString("shellPath"); shellScript = GetPropertyString("shellScript"); } } internal class BuildConfigEntryData { public string name; public List<string> val = new List<string>(); public static string ExtractValue(string src) { return PBXStream.UnquoteString(src.Trim().TrimEnd(',')); } public void AddValue(string value) { if (!val.Contains(value)) val.Add(value); } public void RemoveValue(string value) { val.RemoveAll(v => v == value); } public void RemoveValueList(IEnumerable<string> values) { List<string> valueList = new List<string>(values); if (valueList.Count == 0) return; for (int i = 0; i < val.Count - valueList.Count; i++) { bool match = true; for (int j = 0; j < valueList.Count; j++) { if (val[i + j] != valueList[j]) { match = false; break; } } if (match) { val.RemoveRange(i, valueList.Count); return; } } } public static BuildConfigEntryData FromNameValue(string name, string value) { BuildConfigEntryData ret = new BuildConfigEntryData(); ret.name = name; ret.AddValue(value); return ret; } } internal class XCBuildConfigurationData : PBXObjectData { protected SortedDictionary<string, BuildConfigEntryData> entries = new SortedDictionary<string, BuildConfigEntryData>(); public string name { get { return GetPropertyString("name"); } } public string baseConfigurationReference; // may be null // Note that QuoteStringIfNeeded does its own escaping. Double-escaping with quotes is // required to please Xcode that does not handle paths with spaces if they are not // enclosed in quotes. static string EscapeWithQuotesIfNeeded(string name, string value) { if (name != "LIBRARY_SEARCH_PATHS" && name != "FRAMEWORK_SEARCH_PATHS") return value; if (!value.Contains(" ")) return value; if (value.First() == '\"' && value.Last() == '\"') return value; return "\"" + value + "\""; } public void SetProperty(string name, string value) { entries[name] = BuildConfigEntryData.FromNameValue(name, EscapeWithQuotesIfNeeded(name, value)); } public void AddProperty(string name, string value) { if (entries.ContainsKey(name)) entries[name].AddValue(EscapeWithQuotesIfNeeded(name, value)); else SetProperty(name, value); } public void RemoveProperty(string name) { if (entries.ContainsKey(name)) entries.Remove(name); } public void RemovePropertyValue(string name, string value) { if (entries.ContainsKey(name)) entries[name].RemoveValue(EscapeWithQuotesIfNeeded(name, value)); } public void RemovePropertyValueList(string name, IEnumerable<string> valueList) { if (entries.ContainsKey(name)) entries[name].RemoveValueList(valueList); } // name should be either release or debug public static XCBuildConfigurationData Create(string name) { var res = new XCBuildConfigurationData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCBuildConfiguration"); res.SetPropertyString("name", name); return res; } public override void UpdateProps() { SetPropertyString("baseConfigurationReference", baseConfigurationReference); var dict = m_Properties.CreateDict("buildSettings"); foreach (var kv in entries) { if (kv.Value.val.Count == 0) continue; else if (kv.Value.val.Count == 1) dict.SetString(kv.Key, kv.Value.val[0]); else // kv.Value.val.Count > 1 { var array = dict.CreateArray(kv.Key); foreach (var value in kv.Value.val) array.AddString(value); } } } public override void UpdateVars() { baseConfigurationReference = GetPropertyString("baseConfigurationReference"); entries = new SortedDictionary<string, BuildConfigEntryData>(); if (m_Properties.Contains("buildSettings")) { var dict = m_Properties["buildSettings"].AsDict(); foreach (var key in dict.values.Keys) { var value = dict[key]; if (value is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(value.AsString()); else entries.Add(key, BuildConfigEntryData.FromNameValue(key, value.AsString())); } else if (value is PBXElementArray) { foreach (var pvalue in value.AsArray().values) { if (pvalue is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(pvalue.AsString()); else entries.Add(key, BuildConfigEntryData.FromNameValue(key, pvalue.AsString())); } } } } } } } internal class PBXContainerItemProxyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "containerPortal/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXContainerItemProxyData Create(string containerRef, string proxyType, string remoteGlobalGUID, string remoteInfo) { var res = new PBXContainerItemProxyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXContainerItemProxy"); res.SetPropertyString("containerPortal", containerRef); // guid res.SetPropertyString("proxyType", proxyType); res.SetPropertyString("remoteGlobalIDString", remoteGlobalGUID); // guid res.SetPropertyString("remoteInfo", remoteInfo); return res; } } internal class PBXReferenceProxyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "remoteRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string path { get { return GetPropertyString("path"); } } public static PBXReferenceProxyData Create(string path, string fileType, string remoteRef, string sourceTree) { var res = new PBXReferenceProxyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXReferenceProxy"); res.SetPropertyString("path", path); res.SetPropertyString("fileType", fileType); res.SetPropertyString("remoteRef", remoteRef); res.SetPropertyString("sourceTree", sourceTree); return res; } } internal class PBXTargetDependencyData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "target/*", "targetProxy/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXTargetDependencyData Create(string target, string targetProxy) { var res = new PBXTargetDependencyData(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXTargetDependency"); res.SetPropertyString("target", target); res.SetPropertyString("targetProxy", targetProxy); return res; } } internal class ProjectReference { public string group; // guid public string projectRef; // guid public static ProjectReference Create(string group, string projectRef) { var res = new ProjectReference(); res.group = group; res.projectRef = projectRef; return res; } } internal class PBXProjectObjectData : PBXObjectData { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurationList/*", "mainGroup/*", "projectReferences/*/ProductGroup/*", "projectReferences/*/ProjectRef/*", "targets/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public List<ProjectReference> projectReferences = new List<ProjectReference>(); public string mainGroup { get { return GetPropertyString("mainGroup"); } } public List<string> targets = new List<string>(); public List<string> knownAssetTags = new List<string>(); public string buildConfigList; // the name of the entitlements file required for some capabilities. public string entitlementsFile; public List<PBXCapabilityType.TargetCapabilityPair> capabilities = new List<PBXCapabilityType.TargetCapabilityPair>(); public Dictionary<string, string> teamIDs = new Dictionary<string, string>(); public void AddReference(string productGroup, string projectRef) { projectReferences.Add(ProjectReference.Create(productGroup, projectRef)); } public override void UpdateProps() { m_Properties.values.Remove("projectReferences"); if (projectReferences.Count > 0) { var array = m_Properties.CreateArray("projectReferences"); foreach (var value in projectReferences) { var dict = array.AddDict(); dict.SetString("ProductGroup", value.group); dict.SetString("ProjectRef", value.projectRef); } }; SetPropertyList("targets", targets); SetPropertyString("buildConfigurationList", buildConfigList); if (knownAssetTags.Count > 0) { PBXElementDict attrs; if (m_Properties.Contains("attributes")) attrs = m_Properties["attributes"].AsDict(); else attrs = m_Properties.CreateDict("attributes"); var tags = attrs.CreateArray("knownAssetTags"); foreach (var tag in knownAssetTags) tags.AddString(tag); } // Enable the capabilities. foreach (var cap in capabilities) { var attrs = m_Properties.Contains("attributes") ? m_Properties["attributes"].AsDict() : m_Properties.CreateDict("attributes"); var targAttr = attrs.Contains("TargetAttributes") ? attrs["TargetAttributes"].AsDict() : attrs.CreateDict("TargetAttributes"); var target = targAttr.Contains(cap.targetGuid) ? targAttr[cap.targetGuid].AsDict() : targAttr.CreateDict(cap.targetGuid); var sysCap = target.Contains("SystemCapabilities") ? target["SystemCapabilities"].AsDict() : target.CreateDict("SystemCapabilities"); var capabilityId = cap.capability.id; var currentCapability = sysCap.Contains(capabilityId) ? sysCap[capabilityId].AsDict() : sysCap.CreateDict(capabilityId); currentCapability.SetString("enabled", "1"); } // Set the team id foreach (KeyValuePair<string, string> teamID in teamIDs) { var attrs = m_Properties.Contains("attributes") ? m_Properties["attributes"].AsDict() : m_Properties.CreateDict("attributes"); var targAttr = attrs.Contains("TargetAttributes") ? attrs["TargetAttributes"].AsDict() : attrs.CreateDict("TargetAttributes"); var target = targAttr.Contains(teamID.Key) ? targAttr[teamID.Key].AsDict() : targAttr.CreateDict(teamID.Key); target.SetString("DevelopmentTeam", teamID.Value); } } public override void UpdateVars() { projectReferences = new List<ProjectReference>(); if (m_Properties.Contains("projectReferences")) { var el = m_Properties["projectReferences"].AsArray(); foreach (var value in el.values) { PBXElementDict dict = value.AsDict(); if (dict.Contains("ProductGroup") && dict.Contains("ProjectRef")) { string group = dict["ProductGroup"].AsString(); string projectRef = dict["ProjectRef"].AsString(); projectReferences.Add(ProjectReference.Create(group, projectRef)); } } } targets = GetPropertyList("targets"); buildConfigList = GetPropertyString("buildConfigurationList"); // update knownAssetTags knownAssetTags = new List<string>(); if (m_Properties.Contains("attributes")) { var el = m_Properties["attributes"].AsDict(); if (el.Contains("knownAssetTags")) { var tags = el["knownAssetTags"].AsArray(); foreach (var tag in tags.values) knownAssetTags.Add(tag.AsString()); } capabilities = new List<PBXCapabilityType.TargetCapabilityPair>(); teamIDs = new Dictionary<string, string>(); if (el.Contains("TargetAttributes")) { var targetAttr = el["TargetAttributes"].AsDict(); foreach (var attr in targetAttr.values) { if (attr.Key == "DevelopmentTeam") { teamIDs.Add(attr.Key, attr.Value.AsString()); } if (attr.Key == "SystemCapabilities") { var caps = el["SystemCapabilities"].AsDict(); foreach (var cap in caps.values) capabilities.Add( new PBXCapabilityType.TargetCapabilityPair( attr.Key, PBXCapabilityType.StringToPBXCapabilityType( cap.Value.AsString() ) ) ); } } } } } } } // namespace UnityEditor.iOS.Xcode
1,069
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { class ValueAST {} // IdentifierAST := <quoted string> \ <string> class IdentifierAST : ValueAST { public int value = 0; // token id } // TreeAST := '{' KeyValuePairList '}' // KeyValuePairList := KeyValuePair ',' KeyValuePairList // KeyValuePair ',' // (empty) class TreeAST : ValueAST { public List<KeyValueAST> values = new List<KeyValueAST>(); } // ListAST := '(' ValueList ')' // ValueList := ValueAST ',' ValueList // ValueAST ',' // (empty) class ArrayAST : ValueAST { public List<ValueAST> values = new List<ValueAST>(); } // KeyValueAST := IdentifierAST '=' ValueAST ';' // ValueAST := IdentifierAST | TreeAST | ListAST class KeyValueAST { public IdentifierAST key = null; public ValueAST value = null; // either IdentifierAST, TreeAST or ListAST } class Parser { TokenList tokens; int currPos; public Parser(TokenList tokens) { this.tokens = tokens; currPos = SkipComments(0); } int SkipComments(int pos) { while (pos < tokens.Count && tokens[pos].type == TokenType.Comment) { pos++; } return pos; } // returns new position int IncInternal(int pos) { if (pos >= tokens.Count) return pos; pos++; return SkipComments(pos); } // Increments current pointer if not past the end, returns previous pos int Inc() { int prev = currPos; currPos = IncInternal(currPos); return prev; } // Returns the token type of the current token TokenType Tok() { if (currPos >= tokens.Count) return TokenType.EOF; return tokens[currPos].type; } void SkipIf(TokenType type) { if (Tok() == type) Inc(); } string GetErrorMsg() { return "Invalid PBX project (parsing line " + tokens[currPos].line + ")"; } public IdentifierAST ParseIdentifier() { if (Tok() != TokenType.String && Tok() != TokenType.QuotedString) throw new Exception(GetErrorMsg()); var ast = new IdentifierAST(); ast.value = Inc(); return ast; } public TreeAST ParseTree() { if (Tok() != TokenType.LBrace) throw new Exception(GetErrorMsg()); Inc(); var ast = new TreeAST(); while (Tok() != TokenType.RBrace && Tok() != TokenType.EOF) { ast.values.Add(ParseKeyValue()); } SkipIf(TokenType.RBrace); return ast; } public ArrayAST ParseList() { if (Tok() != TokenType.LParen) throw new Exception(GetErrorMsg()); Inc(); var ast = new ArrayAST(); while (Tok() != TokenType.RParen && Tok() != TokenType.EOF) { ast.values.Add(ParseValue()); SkipIf(TokenType.Comma); } SkipIf(TokenType.RParen); return ast; } // throws on error public KeyValueAST ParseKeyValue() { var ast = new KeyValueAST(); ast.key = ParseIdentifier(); if (Tok() != TokenType.Eq) throw new Exception(GetErrorMsg()); Inc(); // skip '=' ast.value = ParseValue(); SkipIf(TokenType.Semicolon); return ast; } // throws on error public ValueAST ParseValue() { if (Tok() == TokenType.String || Tok() == TokenType.QuotedString) return ParseIdentifier(); else if (Tok() == TokenType.LBrace) return ParseTree(); else if (Tok() == TokenType.LParen) return ParseList(); throw new Exception(GetErrorMsg()); } } } // namespace UnityEditor.iOS.Xcode
190
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; // Base classes for section handling namespace Facebook.Unity.Editor.iOS.Xcode.PBX { // common base internal abstract class SectionBase { public abstract void AddObject(string key, PBXElementDict value); public abstract void WriteSection(StringBuilder sb, GUIDToCommentMap comments); } // known section: contains objects that we care about internal class KnownSectionBase<T> : SectionBase where T : PBXObjectData, new() { private Dictionary<string, T> m_Entries = new Dictionary<string, T>(); private string m_Name; public KnownSectionBase(string sectionName) { m_Name = sectionName; } public IEnumerable<KeyValuePair<string, T>> GetEntries() { return m_Entries; } public IEnumerable<string> GetGuids() { return m_Entries.Keys; } public IEnumerable<T> GetObjects() { return m_Entries.Values; } public override void AddObject(string key, PBXElementDict value) { T obj = new T(); obj.guid = key; obj.SetPropertiesWhenSerializing(value); obj.UpdateVars(); m_Entries[obj.guid] = obj; } public override void WriteSection(StringBuilder sb, GUIDToCommentMap comments) { if (m_Entries.Count == 0) return; // do not write empty sections sb.AppendFormat("\n\n/* Begin {0} section */", m_Name); var keys = new List<string>(m_Entries.Keys); keys.Sort(StringComparer.Ordinal); foreach (string key in keys) { T obj = m_Entries[key]; obj.UpdateProps(); sb.Append("\n\t\t"); comments.WriteStringBuilder(sb, obj.guid); sb.Append(" = "); Serializer.WriteDict(sb, obj.GetPropertiesWhenSerializing(), 2, obj.shouldCompact, obj.checker, comments); sb.Append(";"); } sb.AppendFormat("\n/* End {0} section */", m_Name); } // returns null if not found public T this[string guid] { get { if (m_Entries.ContainsKey(guid)) return m_Entries[guid]; return null; } } public bool HasEntry(string guid) { return m_Entries.ContainsKey(guid); } public void AddEntry(T obj) { m_Entries[obj.guid] = obj; } public void RemoveEntry(string guid) { if (m_Entries.ContainsKey(guid)) m_Entries.Remove(guid); } } // we assume there is only one PBXProject entry internal class PBXProjectSection : KnownSectionBase<PBXProjectObjectData> { public PBXProjectSection() : base("PBXProject") { } public PBXProjectObjectData project { get { foreach (var kv in GetEntries()) return kv.Value; return null; } } } } // UnityEditor.iOS.Xcode
143
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Linq; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { class PropertyCommentChecker { private int m_Level; private bool m_All; private List<List<string>> m_Props; /* The argument is an array of matcher strings each of which determine whether a property with a certain path needs to be decorated with a comment. A path is a number of path elements concatenated by '/'. The last path element is either: the key if we're referring to a dict key the value if we're referring to a value in an array the value if we're referring to a value in a dict All other path elements are either: the key if the container is dict '*' if the container is array Path matcher has the same structure as a path, except that any of the elements may be '*'. Matcher matches a path if both have the same number of elements and for each pair matcher element is the same as path element or is '*'. a/b/c matches a/b/c but not a/b nor a/b/c/d a/* /c matches a/d/c but not a/b nor a/b/c/d * /* /* matches any path from three elements */ protected PropertyCommentChecker(int level, List<List<string>> props) { m_Level = level; m_All = false; m_Props = props; } public PropertyCommentChecker() { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); } public PropertyCommentChecker(IEnumerable<string> props) { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); foreach (var prop in props) { m_Props.Add(new List<string>(prop.Split('/'))); } } bool CheckContained(string prop) { if (m_All) return true; foreach (var list in m_Props) { if (list.Count == m_Level+1) { if (list[m_Level] == prop) return true; if (list[m_Level] == "*") { m_All = true; // short-circuit all at this level return true; } } } return false; } public bool CheckStringValueInArray(string value) { return CheckContained(value); } public bool CheckKeyInDict(string key) { return CheckContained(key); } public bool CheckStringValueInDict(string key, string value) { foreach (var list in m_Props) { if (list.Count == m_Level + 2) { if ((list[m_Level] == "*" || list[m_Level] == key) && list[m_Level+1] == "*" || list[m_Level+1] == value) return true; } } return false; } public PropertyCommentChecker NextLevel(string prop) { var newList = new List<List<string>>(); foreach (var list in m_Props) { if (list.Count <= m_Level+1) continue; if (list[m_Level] == "*" || list[m_Level] == prop) newList.Add(list); } return new PropertyCommentChecker(m_Level + 1, newList); } } class Serializer { public static PBXElementDict ParseTreeAST(TreeAST ast, TokenList tokens, string text) { var el = new PBXElementDict(); foreach (var kv in ast.values) { PBXElementString key = ParseIdentifierAST(kv.key, tokens, text); PBXElement value = ParseValueAST(kv.value, tokens, text); el[key.value] = value; } return el; } public static PBXElementArray ParseArrayAST(ArrayAST ast, TokenList tokens, string text) { var el = new PBXElementArray(); foreach (var v in ast.values) { el.values.Add(ParseValueAST(v, tokens, text)); } return el; } public static PBXElement ParseValueAST(ValueAST ast, TokenList tokens, string text) { if (ast is TreeAST) return ParseTreeAST((TreeAST)ast, tokens, text); if (ast is ArrayAST) return ParseArrayAST((ArrayAST)ast, tokens, text); if (ast is IdentifierAST) return ParseIdentifierAST((IdentifierAST)ast, tokens, text); return null; } public static PBXElementString ParseIdentifierAST(IdentifierAST ast, TokenList tokens, string text) { Token tok = tokens[ast.value]; string value; switch (tok.type) { case TokenType.String: value = text.Substring(tok.begin, tok.end - tok.begin); return new PBXElementString(value); case TokenType.QuotedString: value = text.Substring(tok.begin, tok.end - tok.begin); value = PBXStream.UnquoteString(value); return new PBXElementString(value); default: throw new Exception("Internal parser error"); } } static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; static string GetIndent(int indent) { return k_Indent.Substring(0, indent); } static void WriteStringImpl(StringBuilder sb, string s, bool comment, GUIDToCommentMap comments) { if (comment) comments.WriteStringBuilder(sb, s); else sb.Append(PBXStream.QuoteStringIfNeeded(s)); } public static void WriteDictKeyValue(StringBuilder sb, string key, PBXElement value, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } WriteStringImpl(sb, key, checker.CheckKeyInDict(key), comments); sb.Append(" = "); if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInDict(key, value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent, compact, checker.NextLevel(key), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent, compact, checker.NextLevel(key), comments); sb.Append(";"); if (compact) sb.Append(" "); } public static void WriteDict(StringBuilder sb, PBXElementDict el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("{"); if (el.Contains("isa")) WriteDictKeyValue(sb, "isa", el["isa"], indent+1, compact, checker, comments); var keys = new List<string>(el.values.Keys); keys.Sort(StringComparer.Ordinal); foreach (var key in keys) { if (key != "isa") WriteDictKeyValue(sb, key, el[key], indent+1, compact, checker, comments); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append("}"); } public static void WriteArray(StringBuilder sb, PBXElementArray el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("("); foreach (var value in el.values) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent+1)); } if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInArray(value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent+1, compact, checker.NextLevel("*"), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent+1, compact, checker.NextLevel("*"), comments); sb.Append(","); if (compact) sb.Append(" "); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append(")"); } } } // namespace UnityEditor.iOS.Xcode
279
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace Facebook.Unity.Editor.iOS.Xcode.PBX { internal class GUIDToCommentMap { private Dictionary<string, string> m_Dict = new Dictionary<string, string>(); public string this[string guid] { get { if (m_Dict.ContainsKey(guid)) return m_Dict[guid]; return null; } } public void Add(string guid, string comment) { if (m_Dict.ContainsKey(guid)) return; m_Dict.Add(guid, comment); } public void Remove(string guid) { m_Dict.Remove(guid); } public string Write(string guid) { string comment = this[guid]; if (comment == null) return guid; return String.Format("{0} /* {1} */", guid, comment); } public void WriteStringBuilder(StringBuilder sb, string guid) { string comment = this[guid]; if (comment == null) sb.Append(guid); else { // {0} /* {1} */ sb.Append(guid).Append(" /* ").Append(comment).Append(" */"); } } } internal class PBXGUID { internal delegate string GuidGenerator(); // We allow changing Guid generator to make testing of PBXProject possible private static GuidGenerator guidGenerator = DefaultGuidGenerator; internal static string DefaultGuidGenerator() { return Guid.NewGuid().ToString("N").Substring(8).ToUpper(); } internal static void SetGuidGenerator(GuidGenerator generator) { guidGenerator = generator; } // Generates a GUID. public static string Generate() { return guidGenerator(); } } internal class PBXRegex { public static string GuidRegexString = "[A-Fa-f0-9]{24}"; } internal class PBXStream { static bool DontNeedQuotes(string src) { // using a regex instead of explicit matching slows down common cases by 40% if (src.Length == 0) return false; bool hasSlash = false; for (int i = 0; i < src.Length; ++i) { char c = src[i]; if (Char.IsLetterOrDigit(c) || c == '.' || c == '*' || c == '_') continue; if (c == '/') { hasSlash = true; continue; } return false; } if (hasSlash) { if (src.Contains("//") || src.Contains("/*") || src.Contains("*/")) return false; } return true; } // Quotes the given string if it contains special characters. Note: if the string already // contains quotes, then they are escaped and the entire string quoted again public static string QuoteStringIfNeeded(string src) { if (DontNeedQuotes(src)) return src; return "\"" + src.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\""; } // If the given string is quoted, removes the quotes and unescapes any quotes within the string public static string UnquoteString(string src) { if (!src.StartsWith("\"") || !src.EndsWith("\"")) return src; return src.Substring(1, src.Length - 2) .Replace("\\\\", "\u569f").Replace("\\\"", "\"") .Replace("\\n", "\n").Replace("\u569f", "\\"); // U+569f is a rarely used Chinese character } } internal enum PBXFileType { NotBuildable, Framework, Source, Resource, CopyFile, ShellScript } internal class FileTypeUtils { internal class FileTypeDesc { public FileTypeDesc(string typeName, PBXFileType type) { this.name = typeName; this.type = type; this.isExplicit = false; } public FileTypeDesc(string typeName, PBXFileType type, bool isExplicit) { this.name = typeName; this.type = type; this.isExplicit = isExplicit; } public string name; public PBXFileType type; public bool isExplicit; } private static readonly Dictionary<string, FileTypeDesc> types = new Dictionary<string, FileTypeDesc> { { "a", new FileTypeDesc("archive.ar", PBXFileType.Framework) }, { "aif", new FileTypeDesc("sound.aif", PBXFileType.Resource) }, { "app", new FileTypeDesc("wrapper.application", PBXFileType.NotBuildable, true) }, { "appex", new FileTypeDesc("wrapper.app-extension", PBXFileType.CopyFile) }, { "bin", new FileTypeDesc("archive.macbinary", PBXFileType.Resource) }, { "s", new FileTypeDesc("sourcecode.asm", PBXFileType.Source) }, { "c", new FileTypeDesc("sourcecode.c.c", PBXFileType.Source) }, { "cc", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) }, { "cpp", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) }, { "swift", new FileTypeDesc("sourcecode.swift", PBXFileType.Source) }, { "dll", new FileTypeDesc("file", PBXFileType.NotBuildable) }, { "framework", new FileTypeDesc("wrapper.framework", PBXFileType.Framework) }, { "h", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) }, { "pch", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) }, { "icns", new FileTypeDesc("image.icns", PBXFileType.Resource) }, { "xcassets", new FileTypeDesc("folder.assetcatalog", PBXFileType.Resource) }, { "inc", new FileTypeDesc("sourcecode.inc", PBXFileType.NotBuildable) }, { "m", new FileTypeDesc("sourcecode.c.objc", PBXFileType.Source) }, { "mm", new FileTypeDesc("sourcecode.cpp.objcpp", PBXFileType.Source ) }, { "mp3", new FileTypeDesc("sound.mp3", PBXFileType.Resource) }, { "nib", new FileTypeDesc("wrapper.nib", PBXFileType.Resource) }, { "plist", new FileTypeDesc("text.plist.xml", PBXFileType.Resource) }, { "png", new FileTypeDesc("image.png", PBXFileType.Resource) }, { "rtf", new FileTypeDesc("text.rtf", PBXFileType.Resource) }, { "tiff", new FileTypeDesc("image.tiff", PBXFileType.Resource) }, { "txt", new FileTypeDesc("text", PBXFileType.Resource) }, { "json", new FileTypeDesc("text.json", PBXFileType.Resource) }, { "xcodeproj", new FileTypeDesc("wrapper.pb-project", PBXFileType.NotBuildable) }, { "xib", new FileTypeDesc("file.xib", PBXFileType.Resource) }, { "strings", new FileTypeDesc("text.plist.strings", PBXFileType.Resource) }, { "storyboard",new FileTypeDesc("file.storyboard", PBXFileType.Resource) }, { "bundle", new FileTypeDesc("wrapper.plug-in", PBXFileType.Resource) }, { "dylib", new FileTypeDesc("compiled.mach-o.dylib", PBXFileType.Framework) }, { "tbd", new FileTypeDesc("sourcecode.text-based-dylib-definition", PBXFileType.Framework) }, { "wav", new FileTypeDesc("sound.wav", PBXFileType.Resource) } }; public static string TrimExtension(string ext) { return ext.TrimStart('.'); } public static bool IsKnownExtension(string ext) { ext = TrimExtension(ext); return types.ContainsKey(ext); } internal static bool IsFileTypeExplicit(string ext) { ext = TrimExtension(ext); if (types.ContainsKey(ext)) return types[ext].isExplicit; return false; } public static PBXFileType GetFileType(string ext, bool isFolderRef) { ext = TrimExtension(ext); if (isFolderRef) return PBXFileType.Resource; if (!types.ContainsKey(ext)) return PBXFileType.Resource; return types[ext].type; } public static string GetTypeName(string ext) { ext = TrimExtension(ext); if (types.ContainsKey(ext)) return types[ext].name; // Xcode actually checks the file contents to determine the file type. // Text files have "text" type and all other files have "file" type. // Since we can't reasonably determine whether the file in question is // a text file, we just take the safe route and return "file" type. return "file"; } public static bool IsBuildableFile(string ext) { ext = TrimExtension(ext); if (!types.ContainsKey(ext)) return true; if (types[ext].type != PBXFileType.NotBuildable) return true; return false; } public static bool IsBuildable(string ext, bool isFolderReference) { ext = TrimExtension(ext); if (isFolderReference) return true; return IsBuildableFile(ext); } private static readonly Dictionary<PBXSourceTree, string> sourceTree = new Dictionary<PBXSourceTree, string> { { PBXSourceTree.Absolute, "<absolute>" }, { PBXSourceTree.Group, "<group>" }, { PBXSourceTree.Build, "BUILT_PRODUCTS_DIR" }, { PBXSourceTree.Developer, "DEVELOPER_DIR" }, { PBXSourceTree.Sdk, "SDKROOT" }, { PBXSourceTree.Source, "SOURCE_ROOT" }, }; private static readonly Dictionary<string, PBXSourceTree> stringToSourceTreeMap = new Dictionary<string, PBXSourceTree> { { "<absolute>", PBXSourceTree.Absolute }, { "<group>", PBXSourceTree.Group }, { "BUILT_PRODUCTS_DIR", PBXSourceTree.Build }, { "DEVELOPER_DIR", PBXSourceTree.Developer }, { "SDKROOT", PBXSourceTree.Sdk }, { "SOURCE_ROOT", PBXSourceTree.Source }, }; internal static string SourceTreeDesc(PBXSourceTree tree) { return sourceTree[tree]; } // returns PBXSourceTree.Source on error internal static PBXSourceTree ParseSourceTree(string tree) { if (stringToSourceTreeMap.ContainsKey(tree)) return stringToSourceTreeMap[tree]; return PBXSourceTree.Source; } internal static List<PBXSourceTree> AllAbsoluteSourceTrees() { return new List<PBXSourceTree>{PBXSourceTree.Absolute, PBXSourceTree.Build, PBXSourceTree.Developer, PBXSourceTree.Sdk, PBXSourceTree.Source}; } } } // UnityEditor.iOS.Xcode
328
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.1")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.IOS { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Facebook.Unity.Mobile.IOS; internal class IOSWrapper : IIOSWrapper { public void Init( string appId, bool frictionlessRequests, string urlSuffix, string unityUserAgentSuffix) { IOSWrapper.IOSFBInit( appId, frictionlessRequests, urlSuffix, unityUserAgentSuffix); } public void EnableProfileUpdatesOnAccessTokenChange(bool enable) { IOSWrapper.IOSFBEnableProfileUpdatesOnAccessTokenChange(enable); } public void LoginWithTrackingPreference( int requestId, string scope, string tracking, string nonce) { IOSWrapper.IOSFBLoginWithTrackingPreference(requestId, scope, tracking, nonce); } public void LogInWithReadPermissions( int requestId, string scope) { IOSWrapper.IOSFBLogInWithReadPermissions( requestId, scope); } public void LogInWithPublishPermissions( int requestId, string scope) { IOSWrapper.IOSFBLogInWithPublishPermissions( requestId, scope); } public void LogOut() { IOSWrapper.IOSFBLogOut(); } public void SetPushNotificationsDeviceTokenString(string token) { IOSWrapper.IOSFBSetPushNotificationsDeviceTokenString(token); } public void SetShareDialogMode(int mode) { IOSWrapper.IOSFBSetShareDialogMode(mode); } public void ShareLink( int requestId, string contentURL, string contentTitle, string contentDescription, string photoURL) { IOSWrapper.IOSFBShareLink( requestId, contentURL, contentTitle, contentDescription, photoURL); } public void FeedShare( int requestId, string toId, string link, string linkName, string linkCaption, string linkDescription, string picture, string mediaSource) { IOSWrapper.IOSFBFeedShare( requestId, toId, link, linkName, linkCaption, linkDescription, picture, mediaSource); } public void AppRequest( int requestId, string message, string actionType, string objectId, string[] to = null, int toLength = 0, string filters = "", string[] excludeIds = null, int excludeIdsLength = 0, bool hasMaxRecipients = false, int maxRecipients = 0, string data = "", string title = "") { IOSWrapper.IOSFBAppRequest( requestId, message, actionType, objectId, to, toLength, filters, excludeIds, excludeIdsLength, hasMaxRecipients, maxRecipients, data, title); } public void OpenFriendFinderDialog( int requestId) { IOSWrapper.IOSFBOpenGamingServicesFriendFinder(requestId); } public void FBAppEventsActivateApp() { IOSWrapper.IOSFBAppEventsActivateApp(); } public void CreateGamingContext(int requestId, string playerID) { IOSWrapper.IOSFBCreateGamingContext(requestId, playerID); } public void SwitchGamingContext(int requestId, string gamingContextID) { IOSWrapper.IOSFBSwitchGamingContext(requestId, gamingContextID); } public void ChooseGamingContext( int requestId, string filter, int minSize, int maxSize) { IOSWrapper.IOSFBChooseGamingContext(requestId, filter, minSize, maxSize); } public void GetCurrentGamingContext(int requestId) { IOSWrapper.IOSFBGetCurrentGamingContext(requestId); } public void LogAppEvent( string logEvent, double valueToSum, int numParams, string[] paramKeys, string[] paramVals) { IOSWrapper.IOSFBAppEventsLogEvent( logEvent, valueToSum, numParams, paramKeys, paramVals); } public void LogPurchaseAppEvent( double logPurchase, string currency, int numParams, string[] paramKeys, string[] paramVals) { IOSWrapper.IOSFBAppEventsLogPurchase( logPurchase, currency, numParams, paramKeys, paramVals); } public void FBAppEventsSetLimitEventUsage(bool limitEventUsage) { IOSWrapper.IOSFBAppEventsSetLimitEventUsage(limitEventUsage); } public void FBAutoLogAppEventsEnabled(bool autoLogAppEventsEnabled) { IOSWrapper.IOSFBAutoLogAppEventsEnabled(autoLogAppEventsEnabled); } public void FBAdvertiserIDCollectionEnabled(bool advertiserIDCollectionEnabled) { IOSWrapper.IOSFBAdvertiserIDCollectionEnabled(advertiserIDCollectionEnabled); } public bool FBAdvertiserTrackingEnabled(bool advertiserTrackingEnabled) { return IOSWrapper.IOSFBAdvertiserTrackingEnabled(advertiserTrackingEnabled); } public void GetAppLink(int requestId) { IOSWrapper.IOSFBGetAppLink(requestId); } public string FBSdkVersion() { return IOSWrapper.IOSFBSdkVersion(); } public void FBSetUserID(string userID) { IOSWrapper.IOSFBSetUserID(userID); } public string FBGetUserID() { return IOSWrapper.IOSFBGetUserID(); } public void SetDataProcessingOptions(string[] options, int country, int state) { IOSWrapper.IOSFBSetDataProcessingOptions(options, options.Length, country, state); } public AuthenticationToken CurrentAuthenticationToken() { String authenticationTokenString = IOSWrapper.IOSFBCurrentAuthenticationToken(); if (String.IsNullOrEmpty(authenticationTokenString)) { return null; } try { IDictionary<string, string> token = Utilities.ParseStringDictionaryFromString(authenticationTokenString); string tokenString; string nonce; token.TryGetValue("auth_token_string", out tokenString); token.TryGetValue("auth_nonce", out nonce); return new AuthenticationToken(tokenString, nonce); } catch (Exception) { return null; } } public Profile CurrentProfile() { String profileString = IOSWrapper.IOSFBCurrentProfile(); if (String.IsNullOrEmpty(profileString)) { return null; } try { IDictionary<string, string> profile = Utilities.ParseStringDictionaryFromString(profileString); string userID; string firstName; string middleName; string lastName; string name; string email; string imageURL; string linkURL; string friendIDs; string birthday; string gender; profile.TryGetValue("userID", out userID); profile.TryGetValue("firstName", out firstName); profile.TryGetValue("middleName", out middleName); profile.TryGetValue("lastName", out lastName); profile.TryGetValue("name", out name); profile.TryGetValue("email", out email); profile.TryGetValue("imageURL", out imageURL); profile.TryGetValue("linkURL", out linkURL); profile.TryGetValue("friendIDs", out friendIDs); profile.TryGetValue("birthday", out birthday); profile.TryGetValue("gender", out gender); UserAgeRange ageRange = UserAgeRange.AgeRangeFromDictionary(profile); FBLocation hometown = FBLocation.FromDictionary("hometown", profile); FBLocation location = FBLocation.FromDictionary("location", profile); return new Profile( userID, firstName, middleName, lastName, name, email, imageURL, linkURL, friendIDs?.Split(','), birthday, ageRange, hometown, location, gender); } catch (Exception) { return null; } } public void GetTournaments(int requestId) { IOSWrapper.IOSFBGetTournaments(requestId); } public void UpdateTournament(string tournamentId, int score, int requestId) { IOSWrapper.IOSFBUpdateTournament(tournamentId, score, requestId); } public void UpdateAndShareTournament( string tournamentId, int score, int requestId) { IOSWrapper.IOSFBUpdateAndShareTournament( tournamentId, score, requestId ); } public void CreateAndShareTournament( int initialScore, string title, TournamentSortOrder sortOrder, TournamentScoreFormat scoreFormat, long endTime, string payload, int requestId) { IOSWrapper.IOSFBCreateAndShareTournament( initialScore, title, (int)sortOrder, (int)scoreFormat, endTime, payload, requestId ); } public void UploadImageToMediaLibrary( int requestId, string caption, string imageUri, bool shouldLaunchMediaDialog) { IOSWrapper.IOSFBUploadImageToMediaLibrary( requestId, caption, imageUri, shouldLaunchMediaDialog); } public void UploadVideoToMediaLibrary( int requestId, string caption, string videoUri) { IOSWrapper.IOSFBUploadVideoToMediaLibrary( requestId, caption, videoUri); } public void FetchDeferredAppLink(int requestId) { IOSWrapper.IOSFBFetchDeferredAppLink(requestId); } public void RefreshCurrentAccessToken(int requestId) { IOSWrapper.IOSFBRefreshCurrentAccessToken(requestId); } [DllImport("__Internal")] private static extern void IOSFBInit( string appId, bool frictionlessRequests, string urlSuffix, string unityUserAgentSuffix); [DllImport("__Internal")] private static extern void IOSFBEnableProfileUpdatesOnAccessTokenChange(bool enable); [DllImport("__Internal")] private static extern void IOSFBLogInWithReadPermissions( int requestId, string scope); [DllImport("__Internal")] private static extern void IOSFBLoginWithTrackingPreference( int requestId, string scope, string tracking, string nonce); [DllImport("__Internal")] private static extern void IOSFBLogInWithPublishPermissions( int requestId, string scope); [DllImport("__Internal")] private static extern void IOSFBLogOut(); [DllImport("__Internal")] private static extern void IOSFBSetPushNotificationsDeviceTokenString(string token); [DllImport("__Internal")] private static extern void IOSFBSetShareDialogMode(int mode); [DllImport("__Internal")] private static extern void IOSFBShareLink( int requestId, string contentURL, string contentTitle, string contentDescription, string photoURL); [DllImport("__Internal")] private static extern void IOSFBFeedShare( int requestId, string toId, string link, string linkName, string linkCaption, string linkDescription, string picture, string mediaSource); [DllImport("__Internal")] private static extern void IOSFBAppRequest( int requestId, string message, string actionType, string objectId, string[] to = null, int toLength = 0, string filters = "", string[] excludeIds = null, int excludeIdsLength = 0, bool hasMaxRecipients = false, int maxRecipients = 0, string data = "", string title = ""); [DllImport("__Internal")] private static extern void IOSFBAppEventsActivateApp(); [DllImport("__Internal")] private static extern void IOSFBAppEventsLogEvent( string logEvent, double valueToSum, int numParams, string[] paramKeys, string[] paramVals); [DllImport("__Internal")] private static extern void IOSFBAppEventsLogPurchase( double logPurchase, string currency, int numParams, string[] paramKeys, string[] paramVals); [DllImport("__Internal")] private static extern void IOSFBAppEventsSetLimitEventUsage(bool limitEventUsage); [DllImport("__Internal")] private static extern void IOSFBAutoLogAppEventsEnabled(bool autoLogAppEventsEnabled); [DllImport("__Internal")] private static extern void IOSFBAdvertiserIDCollectionEnabled(bool advertiserIDCollectionEnabledID); [DllImport("__Internal")] private static extern bool IOSFBAdvertiserTrackingEnabled(bool advertiserTrackingEnabled); [DllImport("__Internal")] private static extern void IOSFBGetAppLink(int requestID); [DllImport("__Internal")] private static extern string IOSFBSdkVersion(); [DllImport("__Internal")] private static extern void IOSFBFetchDeferredAppLink(int requestID); [DllImport("__Internal")] private static extern void IOSFBRefreshCurrentAccessToken(int requestID); [DllImport("__Internal")] private static extern void IOSFBSetUserID(string userID); [DllImport("__Internal")] private static extern void IOSFBOpenGamingServicesFriendFinder(int requestID); [DllImport("__Internal")] private static extern void IOSFBUploadImageToMediaLibrary( int requestID, string caption, string imageUri, bool shouldLaunchMediaDialog); [DllImport("__Internal")] private static extern void IOSFBUploadVideoToMediaLibrary( int requestID, string caption, string videoUri); [DllImport("__Internal")] private static extern void IOSFBGetTournaments(int requestID); [DllImport("__Internal")] private static extern void IOSFBUpdateTournament(string tournamentID, int score, int requestID); [DllImport("__Internal")] private static extern void IOSFBUpdateAndShareTournament(string tournamentID, int score, int requestID); [DllImport("__Internal")] private static extern void IOSFBCreateAndShareTournament( int initialScore, string title, int sortOrder, int scoreFormat, long endTime, string payload, int requestID); [DllImport("__Internal")] private static extern void IOSFBCreateGamingContext( int requestID, string playerID); [DllImport("__Internal")] private static extern void IOSFBSwitchGamingContext( int requestID, string contextID); [DllImport("__Internal")] private static extern void IOSFBChooseGamingContext( int requestID, string filter, int minSize, int maxSize); [DllImport("__Internal")] private static extern void IOSFBGetCurrentGamingContext( int requestID); [DllImport("__Internal")] private static extern string IOSFBGetUserID(); [DllImport("__Internal")] private static extern void IOSFBSetDataProcessingOptions( string[] options, int numOptions, int country, int state); [DllImport("__Internal")] private static extern string IOSFBCurrentAuthenticationToken(); [DllImport("__Internal")] private static extern string IOSFBCurrentProfile(); } }
614
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.1")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.IOS { public class IOSWrapper { } }
27
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.0")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Settings { using System.Collections.Generic; using UnityEngine; /// <summary> /// Facebook settings. /// </summary> public class FacebookSettings : ScriptableObject { public const string FacebookSettingsAssetName = "FacebookSettings"; public const string FacebookSettingsPath = "FacebookSDK/SDK/Resources"; public const string FacebookSettingsAssetExtension = ".asset"; public enum BuildTarget { StandaloneOSX, StandaloneWindows, iOS, Android, StandaloneWindows64, WebGL, WSAPlayer, StandaloneLinux64, PS4, XboxOne, tvOS, Switch, Stadia, CloudRendering, PS5, none, } private static List<OnChangeCallback> onChangeCallbacks = new List<OnChangeCallback>(); private static FacebookSettings instance; [SerializeField] private int selectedAppIndex = 0; [SerializeField] private List<string> clientTokens = new List<string> { string.Empty }; [SerializeField] private List<string> appIds = new List<string> { "0" }; [SerializeField] private List<string> appLabels = new List<string> { "App Name" }; [SerializeField] private bool cookie = true; [SerializeField] private bool logging = true; [SerializeField] private bool status = true; [SerializeField] private bool xfbml = false; [SerializeField] private bool frictionlessRequests = true; [SerializeField] private string androidKeystorePath = string.Empty; [SerializeField] private string iosURLSuffix = string.Empty; [SerializeField] private List<UrlSchemes> appLinkSchemes = new List<UrlSchemes>() { new UrlSchemes() }; [SerializeField] private string uploadAccessToken = string.Empty; // App Events Settings [SerializeField] private bool autoLogAppEventsEnabled = true; [SerializeField] private bool advertiserIDCollectionEnabled = true; public delegate void OnChangeCallback(); private BuildTarget editorBuildTargetName = BuildTarget.none; /// <summary> /// Gets or sets the current editor build target /// </summary> /// <value>Build target name</value> public static BuildTarget EditorBuildTarget { get { return Instance.editorBuildTargetName; } set { Instance.editorBuildTargetName = value; } } /// <summary> /// Gets or sets the index of the selected app. /// </summary> /// <value>The index of the selected app.</value> public static int SelectedAppIndex { get { return Instance.selectedAppIndex; } set { if (Instance.selectedAppIndex != value) { Instance.selectedAppIndex = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the app identifiers. /// </summary> /// <value>The app identifiers.</value> public static List<string> AppIds { get { return Instance.appIds; } set { if (Instance.appIds != value) { Instance.appIds = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the app labels. /// </summary> /// <value>The app labels.</value> public static List<string> AppLabels { get { return Instance.appLabels; } set { if (Instance.appLabels != value) { Instance.appLabels = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the app client token. /// </summary> /// <value>The app client token.</value> public static List<string> ClientTokens { get { return Instance.clientTokens; } set { if (Instance.clientTokens != value) { Instance.clientTokens = value; SettingsChanged(); } } } /// <summary> /// Gets the app identifier. /// </summary> /// <value>The app identifier.</value> public static string AppId { get { return AppIds[SelectedAppIndex].Trim(); } } /// <summary> /// Gets the app client token. /// </summary> /// <value>The app identifier.</value> public static string ClientToken { get { return ClientTokens[SelectedAppIndex].Trim(); } } /// <summary> /// Gets a value indicating whether the app id is valid app identifier. /// </summary> /// <value><c>true</c> if is valid app identifier; otherwise, <c>false</c>.</value> public static bool IsValidAppId { get { return FacebookSettings.AppId != null && FacebookSettings.AppId.Length > 0 && !FacebookSettings.AppId.Equals("0"); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Facebook.Unity.FacebookSettings"/> is cookie. /// </summary> /// <value><c>true</c> if cookie; otherwise, <c>false</c>.</value> public static bool Cookie { get { return Instance.cookie; } set { if (Instance.cookie != value) { Instance.cookie = value; SettingsChanged(); } } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Facebook.Unity.FacebookSettings"/> is logging. /// </summary> /// <value><c>true</c> if logging; otherwise, <c>false</c>.</value> public static bool Logging { get { return Instance.logging; } set { if (Instance.logging != value) { Instance.logging = value; SettingsChanged(); } } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Facebook.Unity.FacebookSettings"/> is status. /// </summary> /// <value><c>true</c> if status; otherwise, <c>false</c>.</value> public static bool Status { get { return Instance.status; } set { if (Instance.status != value) { Instance.status = value; SettingsChanged(); } } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Facebook.Unity.FacebookSettings"/> is xfbml. /// </summary> /// <value><c>true</c> if xfbml; otherwise, <c>false</c>.</value> public static bool Xfbml { get { return Instance.xfbml; } set { if (Instance.xfbml != value) { Instance.xfbml = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the android keystore path. /// </summary> /// <value>The android keystore path.</value> public static string AndroidKeystorePath { get { return Instance.androidKeystorePath; } set { if (Instance.androidKeystorePath != value) { Instance.androidKeystorePath = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the ios URL suffix. /// </summary> /// <value>The ios URL suffix.</value> public static string IosURLSuffix { get { return Instance.iosURLSuffix; } set { if (Instance.iosURLSuffix != value) { Instance.iosURLSuffix = value; SettingsChanged(); } } } /// <summary> /// Gets the channel URL. /// </summary> /// <value>The channel URL.</value> public static string ChannelUrl { get { return "/channel.html"; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Facebook.Unity.FacebookSettings"/> frictionless requests. /// </summary> /// <value><c>true</c> if frictionless requests; otherwise, <c>false</c>.</value> public static bool FrictionlessRequests { get { return Instance.frictionlessRequests; } set { if (Instance.frictionlessRequests != value) { Instance.frictionlessRequests = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the app link schemes. /// </summary> /// <value>A list of app link schemese for each app.</value> public static List<UrlSchemes> AppLinkSchemes { get { return Instance.appLinkSchemes; } set { if (Instance.appLinkSchemes != value) { Instance.appLinkSchemes = value; SettingsChanged(); } } } /// <summary> /// Gets or sets the upload access token. /// </summary> /// <value>The access token to upload build to Facebook hosting.</value> public static string UploadAccessToken { get { return Instance.uploadAccessToken; } set { if (Instance.uploadAccessToken != value) { Instance.uploadAccessToken = value; SettingsChanged(); } } } /// <summary> /// Gets or sets a value indicating whether App Events can be automatically logged. /// </summary> /// <value><c>true</c> if auto logging; otherwise, <c>false</c>.</value> public static bool AutoLogAppEventsEnabled { get { return Instance.autoLogAppEventsEnabled; } set { if (Instance.autoLogAppEventsEnabled != value) { Instance.autoLogAppEventsEnabled = value; SettingsChanged(); } } } /// <summary> /// Gets or sets a value indicating whether advertiserID can be collected. /// </summary> /// <value><c>true</c> if advertiserID can be collected; otherwise, <c>false</c>.</value> public static bool AdvertiserIDCollectionEnabled { get { return Instance.advertiserIDCollectionEnabled; } set { if (Instance.advertiserIDCollectionEnabled != value) { Instance.advertiserIDCollectionEnabled = value; SettingsChanged(); } } } public static FacebookSettings Instance { get { instance = NullableInstance; if (instance == null) { // If not found, autocreate the asset object. instance = ScriptableObject.CreateInstance<FacebookSettings>(); } return instance; } } public static FacebookSettings NullableInstance { get { if (instance == null) { instance = Resources.Load(FacebookSettingsAssetName) as FacebookSettings; } return instance; } } public static void RegisterChangeEventCallback(OnChangeCallback callback) { onChangeCallbacks.Add(callback); } public static void UnregisterChangeEventCallback(OnChangeCallback callback) { onChangeCallbacks.Remove(callback); } private static void SettingsChanged() { onChangeCallbacks.ForEach(callback => callback()); } /// <summary> /// Unity doesn't seralize lists of lists so create a serializable type to wrapp the list for use. /// </summary> [System.Serializable] public class UrlSchemes { [SerializeField] private List<string> list; /// <summary> /// Initializes a new instance of the <see cref="UrlSchemes"/> class. /// </summary> /// <param name="schemes">Url schemes.</param> public UrlSchemes(List<string> schemes = null) { this.list = schemes == null ? new List<string>() : schemes; } /// <summary> /// Gets or sets the schemes. /// </summary> /// <value>The schemes.</value> public List<string> Schemes { get { return this.list; } set { this.list = value; } } } } }
557
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.1")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using NUnit.Framework; public abstract class AppEvents : FacebookTestClass { [Test] public virtual void TestAppEventCall() { FB.LogAppEvent( "test_event", null, new Dictionary<string, object>() { { "key0", "value0" }, { "key1", "value1" }, }); Assert.AreEqual(1, this.Mock.GetMethodCallCount("LogAppEvent")); } } }
45
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using NUnit.Framework; public abstract class AppLinks : FacebookTestClass { [Test] public void TestGetAppLink() { IAppLinkResult result = null; FB.GetAppLink( delegate(IAppLinkResult r) { result = r; }); Assert.IsNotNull(result); } } }
40
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using NUnit.Framework; public abstract class AppRequest : FacebookTestClass { [Test] public void TestAppRequest() { IAppRequestResult result = null; string mockRequestId = "1234567890"; var toList = new List<string>() { "1234567890", "9999999999" }; this.Mock.ResultExtras = new Dictionary<string, object>() { { AppRequestResult.RequestIDKey, mockRequestId }, { AppRequestResult.ToKey, string.Join(",", toList) }, }; FB.AppRequest( "Test message", callback: delegate(IAppRequestResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(result.RequestID, mockRequestId); Assert.IsTrue(new HashSet<string>(toList).SetEquals(result.To)); } } }
56
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using Facebook.Unity.Canvas; using Facebook.Unity.Editor; using Facebook.Unity.Mobile.Android; using Facebook.Unity.Mobile.IOS; using Facebook.Unity.Tests.Canvas; using Facebook.Unity.Tests.Editor; using Facebook.Unity.Tests.Mobile.Android; using Facebook.Unity.Tests.Mobile.IOS; using NSubstitute; using NUnit.Framework; public abstract class FacebookTestClass { internal MockWrapper Mock { get; set; } [SetUp] public void Init() { FacebookLogger.Instance = new FacebookTestLogger(); Type type = this.GetType(); var callbackManager = new CallbackManager(); if (Attribute.GetCustomAttribute(type, typeof(AndroidTestAttribute)) != null) { var mockWrapper = new MockAndroid(); Constants.CurrentPlatform = FacebookUnityPlatform.Android; var facebook = new AndroidFacebook(mockWrapper, callbackManager); this.Mock = mockWrapper; this.Mock.Facebook = facebook; FB.FacebookImpl = facebook; } else if (Attribute.GetCustomAttribute(type, typeof(IOSTestAttribute)) != null) { var mockWrapper = new MockIOS(); Constants.CurrentPlatform = FacebookUnityPlatform.IOS; var facebook = new IOSFacebook(mockWrapper, callbackManager); this.Mock = mockWrapper; this.Mock.Facebook = facebook; FB.FacebookImpl = facebook; } else if (Attribute.GetCustomAttribute(type, typeof(CanvasTestAttribute)) != null) { var mockWrapper = new MockCanvas(); Constants.CurrentPlatform = FacebookUnityPlatform.WebGL; var facebook = new CanvasFacebook(mockWrapper, callbackManager); this.Mock = mockWrapper; this.Mock.Facebook = facebook; FB.FacebookImpl = facebook; } else if (Attribute.GetCustomAttribute(type, typeof(EditorTestAttribute)) != null) { var mockWrapper = new MockEditor(); // The editor works for all platforms but claim to be android for testing. Constants.CurrentPlatform = FacebookUnityPlatform.Android; var facebook = new EditorFacebook(mockWrapper, callbackManager); this.Mock = mockWrapper; this.Mock.Facebook = facebook; FB.FacebookImpl = facebook; } else { throw new Exception("Failed to specify platform specified on test class"); } this.OnInit(); } protected virtual void OnInit() { } private class FacebookTestLogger : IFacebookLogger { public void Log(string msg) { Console.WriteLine(msg); } public void Info(string msg) { Console.WriteLine(msg); } public void Warn(string msg) { Console.WriteLine(msg); } public void Error(string msg) { Console.WriteLine(msg); } } } }
119
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using NUnit.Framework; public abstract class FeedShare : FacebookTestClass { [Test] public void SimpleFeedShare() { IShareResult result = null; FB.FeedShare( link: new Uri("https://www.facebook.com"), callback: delegate(IShareResult r) { result = r; }); Assert.IsNotNull(result); } } }
42
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Linq; using NUnit.Framework; public abstract class Init : FacebookTestClass { [Test] public void BasicInit() { bool initComplete = false; this.CallInit( delegate { initComplete = true; }); Assert.IsTrue(initComplete); } [Test] public void InitWithLoginData() { this.Mock.ResultExtras = MockResults.GetLoginResult(1, "email", null); AccessToken.CurrentAccessToken = null; bool initComplete = false; this.CallInit( delegate { initComplete = true; }); Assert.IsTrue(initComplete); AccessToken token = AccessToken.CurrentAccessToken; Assert.IsNotNull(token); long diff = token.ExpirationTime.TotalSeconds() - MockResults.MockExpirationTimeValue.TotalSeconds(); Assert.IsTrue(Math.Abs(diff) < 5); Assert.AreEqual(MockResults.MockTokenStringValue, token.TokenString); Assert.AreEqual(MockResults.MockUserIDValue, token.UserId); Assert.AreEqual(1, token.Permissions.Count()); } protected abstract void CallInit(InitDelegate callback); } }
69
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; public abstract class Login : FacebookTestClass { protected readonly string[] ReadPermissions = new string[] { Constants.EmailPermission, Constants.UserLikesPermission }; protected readonly string[] PublishPermissions = new string[] { Constants.PublishActionsPermission, Constants.PublishPagesPermission }; [Test] public void BasicLoginWithReadTest() { ILoginResult result = null; FB.LogInWithReadPermissions( null, delegate(ILoginResult r) { result = r; }); Login.ValidateToken(result, MockResults.DefaultPermissions); } [Test] public void BasicLoginWithReadPermissionsTest() { ILoginResult result = null; FB.LogInWithReadPermissions( this.ReadPermissions, delegate(ILoginResult r) { result = r; }); Login.ValidateToken(result, this.ReadPermissions); } [Test] public void BasicLoginWithPublishTest() { ILoginResult result = null; FB.LogInWithPublishPermissions( this.PublishPermissions, delegate(ILoginResult r) { result = r; }); Login.ValidateToken(result, this.PublishPermissions); } [Test] public void IsLoggedInNullAccessToken() { AccessToken.CurrentAccessToken = null; Assert.IsFalse(FB.IsLoggedIn); } [Test] public void IsLoggedInValidExpiration() { AccessToken.CurrentAccessToken = new AccessToken( "faketokenstring", "1", DateTime.UtcNow.AddDays(1), new List<string>(), null, "facebook"); Assert.IsTrue(FB.IsLoggedIn); } [Test] public void IsLoggedInValidExpiredToken() { AccessToken.CurrentAccessToken = new AccessToken( "faketokenstring", "1", DateTime.UtcNow.AddDays(-1), new List<string>(), null, "facebook"); Assert.IsFalse(FB.IsLoggedIn); } protected override void OnInit() { base.OnInit(); // Before each test clear the state of the access token AccessToken.CurrentAccessToken = null; } private static void ValidateToken(ILoginResult loginResult, IEnumerable<string> permissions) { Assert.IsNotNull(loginResult); AccessToken token = AccessToken.CurrentAccessToken; Assert.AreSame(loginResult.AccessToken, loginResult.AccessToken); Assert.IsNotNull(token); // For canvas we can be off by about a second since the token value for expiration time is // returned in the format seconds until expired from now. long diff = token.ExpirationTime.TotalSeconds() - MockResults.MockExpirationTimeValue.TotalSeconds(); Assert.IsTrue(Math.Abs(diff) < 5); Assert.AreEqual(MockResults.MockTokenStringValue, token.TokenString); Assert.AreEqual(MockResults.MockUserIDValue, token.UserId); Assert.AreEqual(permissions.Count(), token.Permissions.Count()); diff = token.LastRefresh.Value.TotalSeconds() - MockResults.MockLastRefresh.TotalSeconds(); Assert.IsTrue(Math.Abs(diff) < 5); foreach (var perm in permissions) { Assert.IsTrue(token.Permissions.Contains(perm)); } } } }
147
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using System.Linq; internal static class MockResults { private const string MockTokenString = "This is a test token string"; private const string MockUserID = "100000000000000"; private const string MockGroupID = "123456789"; private static DateTime mockLastRefresh = DateTime.UtcNow; private static DateTime mockExpirationTime = DateTime.UtcNow.AddDays(60); public static DateTime MockExpirationTimeValue { get { return MockResults.mockExpirationTime; } } public static string MockTokenStringValue { get { return MockResults.MockTokenString; } } public static string MockUserIDValue { get { return MockResults.MockUserID; } } public static IEnumerable<string> DefaultPermissions { get { return new string[] { "email", "public_profile" }; } } public static string MockGroupIDValue { get { return MockResults.MockGroupID; } } public static DateTime MockLastRefresh { get { return MockResults.mockLastRefresh; } } public static IDictionary<string, object> GetLoginResult( int requestID, string permissions, IDictionary<string, object> extras) { return MockResults.GetLoginResult( requestID, string.IsNullOrEmpty(permissions) ? null : permissions.Split(','), extras); } public static IDictionary<string, object> GetLoginResult( int requestID, IEnumerable<string> permissions, IDictionary<string, object> extras) { if (permissions == null || !permissions.Any()) { permissions = MockResults.DefaultPermissions; } var result = MockResults.GetGenericResult(requestID, extras); object expirationTime; if (Constants.IsWeb) { expirationTime = (long)(MockResults.MockExpirationTimeValue - DateTime.UtcNow).TotalSeconds; } else { expirationTime = MockResults.MockExpirationTimeValue.TotalSeconds().ToString(); } result.TrySetKey(LoginResult.ExpirationTimestampKey, expirationTime); result.TrySetKey(LoginResult.UserIdKey, MockResults.MockUserIDValue); result.TrySetKey(LoginResult.AccessTokenKey, MockResults.MockTokenStringValue); result.TrySetKey(LoginResult.PermissionsKey, string.Join(",", permissions)); result.TrySetKey(LoginResult.LastRefreshKey, MockResults.mockLastRefresh.TotalSeconds().ToString()); return result; } public static IDictionary<string, object> GetGroupCreateResult(int requestID, IDictionary<string, object> extras) { var result = MockResults.GetGenericResult(requestID, extras); result.TrySetKey(GroupCreateResult.IDKey, MockResults.MockGroupIDValue); return result; } public static IDictionary<string, object> GetGenericResult(int requestID, IDictionary<string, object> extras) { return MockResults.GetResultDictionary(requestID, extras); } public static IDictionary<string, object> GetResultDictionary(int requestID, IDictionary<string, object> extras) { var result = new Dictionary<string, object>() { { Constants.CallbackIdKey, requestID.ToString() } }; if (extras != null) { result.AddAllKVPFrom(extras); } return result; } } }
153
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using System.Diagnostics; using Facebook.Unity.Canvas; using Facebook.Unity.Mobile; internal class MockWrapper { private IDictionary<string, object> resultExtras; private IDictionary<string, int> methodCallCounts = new Dictionary<string, int>(); // These extras are cleared on first access to avoid appending to // multiple calls public IDictionary<string, object> ResultExtras { get { var result = this.resultExtras; this.resultExtras = null; return result; } set { this.resultExtras = value; } } internal IFacebookResultHandler Facebook { get; set; } internal ICanvasFacebookResultHandler CanvasFacebook { get { return this.Facebook as ICanvasFacebookResultHandler; } } internal IMobileFacebookResultHandler MobileFacebook { get { return this.Facebook as IMobileFacebookResultHandler; } } public int GetMethodCallCount(string methodName) { int count; if (this.methodCallCounts.TryGetValue(methodName, out count)) { return count; } return 0; } protected IDictionary<string, object> GetResultDictionary(int requestId) { var result = new Dictionary<string, object>() { { Constants.CallbackIdKey, requestId.ToString() } }; var extras = this.ResultExtras; if (extras != null) { result.AddAllKVPFrom(extras); } return result; } protected void LogMethodCall() { var st = new StackTrace(); StackFrame sf = st.GetFrame(1); string methodName = sf.GetMethod().Name; this.LogMethodCall(methodName); } protected void LogMethodCall(string methodName) { int count; if (this.methodCallCounts.TryGetValue(methodName, out count)) { this.methodCallCounts[methodName] = ++count; } else { this.methodCallCounts[methodName] = 1; } } } }
119
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; using NUnit.Framework; public abstract class ShareLink : FacebookTestClass { [Test] public void SimpleLinkShare() { IShareResult result = null; var extras = new Dictionary<string, object>() { { ShareResult.PostIDKey, "12345" }, }; this.Mock.ResultExtras = extras; FB.ShareLink( new Uri("http://www.test.com/"), "test title", "test description", new Uri("http://www.photo.com/"), delegate(IShareResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(extras[ShareResult.PostIDKey], result.PostId); } } }
55
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Collections.Generic; public static class TestUtilities { public static long TimeInSeconds(this DateTime dateTime) { TimeSpan t = dateTime - new DateTime(1970, 1, 1); long secondsSinceEpoch = (long)t.TotalSeconds; return secondsSinceEpoch; } public static string ToJson(this IDictionary<string, object> dictionary) { return MiniJSON.Json.Serialize(dictionary); } public static void AddAllKVPFrom<T1, T2>(this IDictionary<T1, T2> dest, IDictionary<T1, T2> source) { foreach (T1 key in source.Keys) { dest[key] = source[key]; } } /// <summary> /// Sets the value for the specified key if the dictionary does not already contain a value /// for this key. /// </summary> public static bool TrySetKey<T1, T2>(this IDictionary<T1, T2> dictionary, T1 key, T2 value) { if (dictionary.ContainsKey(key)) { return false; } dictionary[key] = value; return true; } } }
64
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System.Globalization; using Facebook.Unity.Mobile.Android; using NUnit.Framework; using NUnit.Mocks; public abstract class UserAgent : FacebookTestClass { public void VerifyUserAgent(string expected) { #pragma warning disable CS0618 // Type or member is obsolete var mock = new DynamicMock(typeof(IAndroidWrapper)); #pragma warning restore CS0618 // Type or member is obsolete mock.ExpectAndReturn("CallStatic", "1.0.0", "GetSdkVersion"); Assert.AreEqual( string.Format( CultureInfo.InvariantCulture, expected, FacebookSdkVersion.Build), Constants.GraphApiUserAgent); } } }
45
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests { using System; using System.Diagnostics; using System.IO; using System.Reflection; using NUnit.Framework; [TestFixture] public class VersionNumberCheck { private const string UnityPluginSubPath = "UnitySDK/Assets/FacebookSDK/Plugins/"; private static string unityRepoPath = Directory .GetParent(TestContext.CurrentContext.TestDirectory) .Parent .Parent .FullName; private static string unityPluginPath = Path.Combine(unityRepoPath, UnityPluginSubPath); private static string coreDLLSubPath = Path.Combine(unityPluginPath, "Facebook.Unity.dll"); private static string editorDLLSubPath = Path.Combine(unityPluginPath, "Editor/Facebook.Unity.Editor.dll"); [Test] public void ValidateDLLVersions() { VersionNumberCheck.CheckVersionOfDll(VersionNumberCheck.coreDLLSubPath); VersionNumberCheck.CheckVersionOfDll(VersionNumberCheck.editorDLLSubPath); } private static void CheckVersionOfDll(string dllPath) { FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(dllPath); // We only worry about version numbers x.y.z but c# appends a 4th build number for local // builds that we don't use. Assert.AreEqual(FacebookSdkVersion.Build + ".0", fileVersionInfo.FileVersion, dllPath); } } }
61
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class AppEvents : Facebook.Unity.Tests.AppEvents { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class AppLinks : Facebook.Unity.Tests.AppLinks { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class AppRequest : Facebook.Unity.Tests.AppRequest { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using System; internal class CanvasTestAttribute : Attribute { public CanvasTestAttribute() { } } }
32
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class FeedShare : Facebook.Unity.Tests.FeedShare { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using Facebook.Unity.Canvas; using NUnit.Framework; [CanvasTest] [TestFixture] public class Init : Facebook.Unity.Tests.Init { protected override void CallInit(InitDelegate callback) { ((CanvasFacebook)this.Mock.Facebook).Init( "123456789", true, true, true, false, null, null, false, "en_US", false, null, callback); } } }
48
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class Login : Facebook.Unity.Tests.Login { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using System; using System.Collections.Generic; using Facebook.Unity.Canvas; using MiniJSON; internal class MockCanvas : MockWrapper, ICanvasJSWrapper { internal const string MethodAppRequests = "apprequests"; internal const string MethodFeed = "feed"; internal const string MethodPay = "pay"; public string IntegrationMethodJs { get { return "alert(\"MockCanvasTest\");"; } } public string GetSDKVersion() { return "1.0.0"; } public void DisableFullScreen() { this.LogMethodCall(); } public void Init(string connectFacebookUrl, string locale, int debug, string initParams, int status) { this.LogMethodCall(); // Handle testing of init returning access token. It would be nice // to not have init return the access token but this could be // a breaking change for people who read the raw result ResultContainer resultContainer; IDictionary<string, object> resultExtras = this.ResultExtras; if (resultExtras != null) { var result = MockResults.GetGenericResult(0, resultExtras); resultContainer = new ResultContainer(result); } else { resultContainer = new ResultContainer(string.Empty); } this.Facebook.OnInitComplete(resultContainer); } public void Login(IEnumerable<string> scope, string callback_id) { this.LogMethodCall(); var result = MockResults.GetLoginResult(int.Parse(callback_id), scope.ToCommaSeparateList(), this.ResultExtras); this.Facebook.OnLoginComplete(new ResultContainer(result)); } public void Logout() { this.LogMethodCall(); } public void ActivateApp() { this.LogMethodCall(); } public void LogAppEvent(string eventName, float? valueToSum, string parameters) { this.LogMethodCall(); } public void LogPurchase(float purchaseAmount, string currency, string parameters) { this.LogMethodCall(); } public void Ui(string x, string uid, string callbackMethodName) { this.LogMethodCall(); int cbid = Convert.ToInt32(uid); var methodArguments = Json.Deserialize(x) as IDictionary<string, object>; string methodName; if (null != methodArguments && methodArguments.TryGetValue<string>("method", out methodName)) { if (methodName.Equals(MethodAppRequests)) { var result = MockResults.GetGenericResult(cbid, this.ResultExtras); this.Facebook.OnAppRequestsComplete(new ResultContainer(result)); } else if (methodName.Equals(MethodFeed)) { var result = MockResults.GetGenericResult(cbid, this.ResultExtras); this.Facebook.OnShareLinkComplete(new ResultContainer(result)); } else if (methodName.Equals(MethodPay)) { var result = MockResults.GetGenericResult(cbid, this.ResultExtras); this.CanvasFacebook.OnPayComplete(new ResultContainer(result)); } } } public void InitScreenPosition() { this.LogMethodCall(); } } }
135
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using System.Collections.Generic; using NUnit.Framework; [CanvasTest] [TestFixture] public class Pay : FacebookTestClass { [Test] public void SimplePayTest() { IPayResult result = null; FB.Canvas.Pay( "testProduct", callback: delegate(IPayResult r) { result = r; }); Assert.IsNotNull(result); } [Test] public void CancelPayTest() { IPayResult result = null; var extras = new Dictionary<string, object>() { { ResultBase.ErrorCodeKey, ResultBase.CancelDialogCode }, }; this.Mock.ResultExtras = extras; FB.Canvas.Pay( "testProduct", callback: delegate(IPayResult r) { result = r; }); Assert.IsNotNull(result); Assert.IsTrue(result.Cancelled); } [Test] public void ErrorPayTest() { IPayResult result = null; var extras = new Dictionary<string, object>() { { ResultBase.ErrorCodeKey, 1L }, { ResultBase.ErrorMessageKey, "Test error message" }, }; this.Mock.ResultExtras = extras; FB.Canvas.Pay( "testProduct", callback: delegate(IPayResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(result.ErrorCode, extras[PayResult.ErrorCodeKey]); Assert.AreEqual(result.Error, extras[PayResult.ErrorMessageKey]); } } }
88
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using NUnit.Framework; [CanvasTest] [TestFixture] public class ShareLink : Facebook.Unity.Tests.ShareLink { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Canvas { using System.Globalization; using Facebook.Unity.Canvas; using NUnit.Framework; [CanvasTest] [TestFixture] public class UserAgent : Facebook.Unity.Tests.UserAgent { [Test] public void VerifyUserAgentWebGL() { string expected = string.Format( CultureInfo.InvariantCulture, "FBJSSDK/1.0.0 FBUnityWebGL/{0} FBUnitySDK/{0}", FacebookSdkVersion.Build); this.VerifyUserAgent(expected); } } }
43
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class AccessTokenRefresh : Facebook.Unity.Tests.Mobile.AccessTokenRefresh { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class AppLinks : Facebook.Unity.Tests.Mobile.AppLinks { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class AppRequest : Facebook.Unity.Tests.AppRequest { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using System; internal class EditorTestAttribute : Attribute { public EditorTestAttribute() { } } }
32
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class FeedShare : Facebook.Unity.Tests.FeedShare { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using Facebook.Unity.Editor; using NUnit.Framework; [EditorTest] [TestFixture] public class Init : Facebook.Unity.Tests.Init { protected override void CallInit(InitDelegate callback) { ((EditorFacebook)this.Mock.Facebook).Init(callback); } } }
36
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class Login : Facebook.Unity.Tests.Mobile.Login { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using System; using System.Collections.Generic; using Facebook.Unity.Editor; internal class MockEditor : MockWrapper, IEditorWrapper { public void Init() { IDictionary<string, object> resultExtra = this.ResultExtras; if (resultExtra != null) { this.Facebook.OnInitComplete( new ResultContainer(MockResults.GetGenericResult(0, resultExtra))); } else { this.Facebook.OnInitComplete( new ResultContainer(string.Empty)); } } public void ShowLoginMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId, string permissions) { var result = MockResults.GetLoginResult(int.Parse(callbackId), permissions, this.ResultExtras); callback(new ResultContainer(result)); } public void ShowAppRequestMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId) { var result = MockResults.GetGenericResult(int.Parse(callbackId), this.ResultExtras); callback(new ResultContainer(result)); } public void ShowPayMockDialog( Utilities.Callback<ResultContainer> callback, string callbackId) { var result = MockResults.GetGenericResult(int.Parse(callbackId), this.ResultExtras); callback(new ResultContainer(result)); } public void ShowMockShareDialog( Utilities.Callback<ResultContainer> callback, string subTitle, string callbackId) { var result = MockResults.GetGenericResult(int.Parse(callbackId), this.ResultExtras); callback(new ResultContainer(result)); } public void ShowMockFriendFinderDialog( Utilities.Callback<ResultContainer> callback, string subTitle, string callbackId) { var result = MockResults.GetGenericResult(int.Parse(callbackId), this.ResultExtras); callback(new ResultContainer(result)); } } }
88
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using NUnit.Framework; [EditorTest] [TestFixture] public class ShareLink : Facebook.Unity.Tests.ShareLink { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Editor { using System.Globalization; using NUnit.Framework; [EditorTest] [TestFixture] public class UserAgent : Facebook.Unity.Tests.UserAgent { [Test] public void VerifyUserAgent() { string expected = string.Format( CultureInfo.InvariantCulture, "FBUnityEditorSDK/{0} FBUnitySDK/{0}", FacebookSdkVersion.Build); this.VerifyUserAgent(expected); } } }
42
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile { using NUnit.Framework; public abstract class AccessTokenRefresh : FacebookTestClass { [Test] public void TestRefreshAccessToken() { IAccessTokenRefreshResult result = null; FB.Mobile.RefreshCurrentAccessToken((r) => result = r); Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); } } }
37
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile { using System; using System.Collections.Generic; using NUnit.Framework; public abstract class AppLinks : Facebook.Unity.Tests.AppLinks { [Test] public void TestEmptyDefferedAppLink() { IAppLinkResult result = null; string mockRef = "mockref"; string mockTargetUrl = "mocktargeturl"; var mockExtras = new Dictionary<string, object>() { { "com.facebook.platform.APPLINK_NATIVE_CLASS", string.Empty }, }; this.Mock.ResultExtras = new Dictionary<string, object>() { { Constants.RefKey, mockRef }, { Constants.TargetUrlKey, mockTargetUrl }, { Constants.ExtrasKey, mockExtras }, }; FB.GetAppLink( delegate(IAppLinkResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(mockRef, result.Ref); Assert.AreEqual(mockTargetUrl, result.TargetUrl); Assert.AreEqual(mockExtras.ToJson(), result.Extras.ToJson()); } [Test] public void TestSimpleDeepLink() { IAppLinkResult result = null; string mockUrl = "mockurl"; string mockRef = "mockref"; string mockTargetUrl = "mocktargeturl"; this.Mock.ResultExtras = new Dictionary<string, object>() { { Constants.RefKey, mockRef }, { Constants.TargetUrlKey, mockTargetUrl }, { Constants.UrlKey, mockUrl }, }; FB.GetAppLink( delegate(IAppLinkResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(mockRef, result.Ref); Assert.AreEqual(mockTargetUrl, result.TargetUrl); Assert.AreEqual(mockUrl, result.Url); } [Test] public void TestAppLink() { IAppLinkResult result = null; string mockUrl = "mockurl"; this.Mock.ResultExtras = new Dictionary<string, object>() { { Constants.UrlKey, mockUrl }, }; FB.GetAppLink( delegate(IAppLinkResult r) { result = r; }); Assert.IsNotNull(result); Assert.AreEqual(mockUrl, result.Url); } } }
108
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile { using System; using System.Collections.Generic; using NUnit.Framework; public abstract class Login : Facebook.Unity.Tests.Login { [Test] public void TestMaxInt64ExpiredTime() { ILoginResult result = null; this.Mock.ResultExtras = new Dictionary<string, object>() { { LoginResult.ExpirationTimestampKey, "9223372036854775" }, }; FB.LogInWithReadPermissions( this.ReadPermissions, delegate(ILoginResult r) { result = r; }); Assert.IsNotNull(result); Assert.IsNotNull(AccessToken.CurrentAccessToken); Assert.AreEqual(DateTime.MaxValue, AccessToken.CurrentAccessToken.ExpirationTime); } [Test] public void TestZeroExpiredTime() { ILoginResult result = null; this.Mock.ResultExtras = new Dictionary<string, object>() { { LoginResult.ExpirationTimestampKey, "0" }, }; FB.LogInWithReadPermissions( this.ReadPermissions, delegate(ILoginResult r) { result = r; }); Assert.IsNotNull(result); Assert.IsNotNull(AccessToken.CurrentAccessToken); Assert.AreEqual(DateTime.MaxValue, AccessToken.CurrentAccessToken.ExpirationTime); } } }
70
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class AccessTokenRefresh : Facebook.Unity.Tests.Mobile.AccessTokenRefresh { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using System; internal class AndroidTestAttribute : Attribute { } }
29
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class AppEvents : Facebook.Unity.Tests.AppEvents { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class AppLinks : Facebook.Unity.Tests.Mobile.AppLinks { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class AppRequest : Facebook.Unity.Tests.AppRequest { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class FeedShare : Facebook.Unity.Tests.FeedShare { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using Facebook.Unity.Mobile.Android; using NUnit.Framework; [AndroidTest] [TestFixture] public class Init : Facebook.Unity.Tests.Init { protected override void CallInit(InitDelegate callback) { ((AndroidFacebook)this.Mock.Facebook).Init("123456789", "token", null, callback); } } }
36
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class Login : Facebook.Unity.Tests.Mobile.Login { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using System; using System.Collections.Generic; using Facebook.Unity.Mobile.Android; using NUnit.Framework; internal class MockAndroid : MockWrapper, IAndroidWrapper { public T CallStatic<T>(string methodName) { if (methodName == "GetSdkVersion") { object result = "1.0.0"; return (T)result; } else if (methodName == "GetUserID") { object result = "userid"; return (T)result; } throw new NotImplementedException(); } public void CallStatic(string methodName, params object[] args) { this.LogMethodCall(methodName); Utilities.Callback<ResultContainer> callback = null; IDictionary<string, object> result; IDictionary<string, object> methodArguments = null; int callbackID = -1; if (args.Length == 1) { var jsonParams = (string)args[0]; if (jsonParams != null) { methodArguments = MiniJSON.Json.Deserialize(jsonParams) as IDictionary<string, object>; string callbackStr; if (methodArguments != null && methodArguments.TryGetValue(Constants.CallbackIdKey, out callbackStr)) { callbackID = int.Parse(callbackStr); } } } if (callbackID == -1 && methodName != "Init") { // There was no callback so just return; return; } if (methodName == "Init") { callback = this.MobileFacebook.OnInitComplete; result = MockResults.GetGenericResult(0, this.ResultExtras); } else if (methodName == "GetAppLink") { callback = this.Facebook.OnGetAppLinkComplete; result = MockResults.GetGenericResult(callbackID, this.ResultExtras); } else if (methodName == "AppRequest") { callback = this.Facebook.OnAppRequestsComplete; result = MockResults.GetGenericResult(callbackID, this.ResultExtras); } else if (methodName == "FeedShare") { callback = this.Facebook.OnShareLinkComplete; result = MockResults.GetGenericResult(callbackID, this.ResultExtras); } else if (methodName == "ShareLink") { callback = this.Facebook.OnShareLinkComplete; result = MockResults.GetGenericResult(callbackID, this.ResultExtras); } else if (methodName == "LoginWithPublishPermissions" || methodName == "LoginWithReadPermissions") { callback = this.Facebook.OnLoginComplete; string permissions; methodArguments.TryGetValue(AndroidFacebook.LoginPermissionsKey, out permissions); result = MockResults.GetLoginResult( callbackID, permissions, this.ResultExtras); } else if (methodName == "RefreshCurrentAccessToken") { callback = this.MobileFacebook.OnRefreshCurrentAccessTokenComplete; result = MockResults.GetLoginResult( callbackID, string.Empty, this.ResultExtras); } else { throw new NotImplementedException("Not implemented for " + methodName); } callback(new ResultContainer(result)); } } }
125
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using NUnit.Framework; [AndroidTest] [TestFixture] public class ShareLink : Facebook.Unity.Tests.ShareLink { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.Android { using System.Globalization; using NUnit.Framework; [AndroidTest] [TestFixture] public class UserAgent : Facebook.Unity.Tests.UserAgent { [Test] public void VerifyUserAgent() { string expected = string.Format( CultureInfo.InvariantCulture, "FBAndroidSDK/1.0.0 FBUnitySDK/{0}", FacebookSdkVersion.Build); this.VerifyUserAgent(expected); } } }
42
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class AccessTokenRefresh : Facebook.Unity.Tests.Mobile.AccessTokenRefresh { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class AppEvents : Facebook.Unity.Tests.AppEvents { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class AppLinks : Facebook.Unity.Tests.Mobile.AppLinks { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class AppRequest : Facebook.Unity.Tests.AppRequest { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class FeedShare : Facebook.Unity.Tests.FeedShare { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using Facebook.Unity.Mobile.IOS; using NUnit.Framework; [IOSTest] [TestFixture] public class Init : Facebook.Unity.Tests.Init { protected override void CallInit(InitDelegate callback) { ((IOSFacebook)this.Mock.Facebook).Init("123456789", false, null, null, callback); } } }
36
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using System; internal class IOSTestAttribute : Attribute { } }
29
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class Login : Facebook.Unity.Tests.Mobile.Login { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using System; using System.Collections.Generic; using System.Diagnostics; using Facebook.Unity.Mobile; using Facebook.Unity.Mobile.IOS; internal class MockIOS : MockWrapper, IIOSWrapper { public void Init( string appId, bool frictionlessRequests, string urlSuffix, string unityUserAgentSuffix) { this.LogMethodCall(); // Handle testing of init returning access token. It would be nice // to not have init return the access token but this could be // a breaking change for people who read the raw result ResultContainer resultContainer; IDictionary<string, object> resultExtras = this.ResultExtras; if (resultExtras != null) { var result = MockResults.GetGenericResult(0, resultExtras); resultContainer = new ResultContainer(result); } else { resultContainer = new ResultContainer(string.Empty); } Facebook.OnInitComplete(resultContainer); } public void EnableProfileUpdatesOnAccessTokenChange(bool enable) { this.LogMethodCall(); } public void LogInWithReadPermissions( int requestId, string scope) { this.LogMethodCall(); this.LoginCommon(requestId, scope); } public void LogInWithPublishPermissions( int requestId, string scope) { this.LogMethodCall(); this.LoginCommon(requestId, scope); } public void LoginWithTrackingPreference( int requestId, string scope, string tracking, string nonce) { this.LogMethodCall(); this.LoginCommon(requestId, scope); } public void LogOut() { this.LogMethodCall(); } public AuthenticationToken CurrentAuthenticationToken() { this.LogMethodCall(); return null; } public Profile CurrentProfile() { this.LogMethodCall(); return null; } public void SetPushNotificationsDeviceTokenString(string token) { this.LogMethodCall(); } public void SetShareDialogMode(int mode) { this.LogMethodCall(); } public void ShareLink( int requestId, string contentURL, string contentTitle, string contentDescription, string photoURL) { this.LogMethodCall(); var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.Facebook.OnShareLinkComplete(new ResultContainer(result)); } public void FeedShare( int requestId, string toId, string link, string linkName, string linkCaption, string linkDescription, string picture, string mediaSource) { this.LogMethodCall(); var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.Facebook.OnShareLinkComplete(new ResultContainer(result)); } public void AppRequest( int requestId, string message, string actionType, string objectId, string[] to = null, int toLength = 0, string filters = "", string[] excludeIds = null, int excludeIdsLength = 0, bool hasMaxRecipients = false, int maxRecipients = 0, string data = "", string title = "") { this.LogMethodCall(); var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.Facebook.OnAppRequestsComplete(new ResultContainer(result)); } public void FBAppEventsActivateApp() { this.LogMethodCall(); } public void LogAppEvent( string logEvent, double valueToSum, int numParams, string[] paramKeys, string[] paramVals) { this.LogMethodCall(); } public void LogPurchaseAppEvent( double logPurchase, string currency, int numParams, string[] paramKeys, string[] paramVals) { this.LogMethodCall(); } public void FBAppEventsSetLimitEventUsage(bool limitEventUsage) { this.LogMethodCall(); } public void FBAutoLogAppEventsEnabled(bool autoLogAppEventsEnabled) { this.LogMethodCall(); } public bool FBAdvertiserTrackingEnabled(bool advertiserTrackingEnabled) { this.LogMethodCall(); return true; } public void FBAdvertiserIDCollectionEnabled(bool advertiserIDCollectionEnabled) { this.LogMethodCall(); } public void GetAppLink(int requestId) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.Facebook.OnGetAppLinkComplete(new ResultContainer(result)); } public string FBSdkVersion() { return "1.0.0"; } public void FetchDeferredAppLink(int requestId) { this.LogMethodCall(); } public void OpenFriendFinderDialog(int requestId) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnFriendFinderComplete(new ResultContainer(result)); } public void RefreshCurrentAccessToken(int requestID) { var result = MockResults.GetLoginResult( requestID, string.Empty, this.ResultExtras); this.MobileFacebook.OnRefreshCurrentAccessTokenComplete(new ResultContainer(result)); } private void LoginCommon( int requestID, string scope) { var result = MockResults.GetLoginResult( requestID, scope, this.ResultExtras); this.Facebook.OnLoginComplete(new ResultContainer(result)); } public void FBSetUserID(string userID) { this.LogMethodCall(); } public string FBGetUserID() { this.LogMethodCall(); return "1234"; } public void SetDataProcessingOptions(string[] options, int country, int state) { this.LogMethodCall(); } public void UploadImageToMediaLibrary( int requestId, string caption, string mediaUri, bool shouldLaunchMediaDialog) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnUploadImageToMediaLibraryComplete(new ResultContainer(result)); } public void UploadVideoToMediaLibrary( int requestId, string caption, string mediaUri) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnUploadVideoToMediaLibraryComplete(new ResultContainer(result)); } public void GetTournaments(int requestId) { this.LogMethodCall(); } public void UpdateTournament(string tournamentId, int score, int requestId) { this.LogMethodCall(); } public void UpdateAndShareTournament( string tournamentId, int score, int requestId) { this.LogMethodCall(); } public void CreateAndShareTournament( int initialScore, string title, TournamentSortOrder sortOrder, TournamentScoreFormat scoreFormat, long endTime, string payload, int requestId) { this.LogMethodCall(); } public void CreateGamingContext(int requestId, string playerID) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnCreateGamingContextComplete(new ResultContainer(result)); } public void SwitchGamingContext(int requestId, string gamingContextID) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnSwitchGamingContextComplete(new ResultContainer(result)); } public void ChooseGamingContext( int requestId, string filter, int minSize, int maxSize) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnChooseGamingContextComplete(new ResultContainer(result)); } public void GetCurrentGamingContext(int requestId) { var result = MockResults.GetGenericResult(requestId, this.ResultExtras); this.MobileFacebook.OnGetCurrentGamingContextComplete(new ResultContainer(result)); } } }
343
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using NUnit.Framework; [IOSTest] [TestFixture] public class ShareLink : Facebook.Unity.Tests.ShareLink { } }
31
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Tests.Mobile.IOS { using System.Globalization; using NUnit.Framework; [IOSTest] [TestFixture] public class UserAgent : Facebook.Unity.Tests.UserAgent { [Test] public void VerifyUserAgent() { string expected = string.Format( CultureInfo.InvariantCulture, "FBiOSSDK/1.0.0 FBUnitySDK/{0}", FacebookSdkVersion.Build); this.VerifyUserAgent(expected); } } }
42
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.1")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; namespace Facebook.Unity.Windows { [Serializable] public class WindowsOptions { [Serializable] public class Browser { public int port = 0; public string scheme = "https"; public string url = "www.facebook.com"; } [Serializable] public class Curl { public uint backend = 1; public bool verify_peer = false; public uint verbose = 0; public string cainfo = ""; } [Serializable] public class Graph { public string scheme = "https"; public string url = "graph.fb.gg"; public string query = ""; } [Serializable] public class Logger { public string file = "fbg.log"; public string filter = "(\\w+)"; public int verbosity = 0; } [Serializable] public class Login { public string client_token = ""; public string redirect_uri = ""; public string permissions = "gaming_profile,user_friends"; } public Browser browser = new Browser(); public Curl curl = new Curl(); public Graph graph = new Graph(); public Logger logger = new Logger(); public Login login = new Login(); public WindowsOptions(string clientToken) { this.login.client_token = clientToken; } } }
76
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Windows { using System; using System.Collections.Generic; using UnityEngine; internal class WindowsWrapper : IWindowsWrapper { private fbg.InitResult result; private string userID; public WindowsWrapper() { } public bool Init(string appId, string clientToken) { WindowsOptions options = new WindowsOptions(clientToken); this.result = fbg.Globals.init(appId, JsonUtility.ToJson(options)); return result == fbg.InitResult.Success; } public void LogInWithScopes(IEnumerable<string> scope, string callbackId, CallbackManager callbackManager) { Dictionary<string, object> result = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId } }; try { List<fbg.LoginScope> loginScopes = this.ConvertToFbgLoginScope(scope); fbg.Globals.loginWithScopes(loginScopes.ToArray(), (accessToken) => { var perms = accessToken.Permissions.ConvertAll<string>(value => value.ToString()); var dataTime = Utilities.FromTimestamp((int)accessToken.Expiration); this.userID = accessToken.UserID.ToString(); result["WindowsCurrentAccessToken"] = new AccessToken(accessToken.Token, userID, dataTime, perms, null, "fb.gg"); callbackManager.OnFacebookResponse(new LoginResult((new ResultContainer(result)))); }, (error) => { string msg = "ERROR: " + error.Message + ","; msg += "InnerErrorCode: " + error.InnerErrorCode.ToString() + ","; msg += "InnerErrorMessage: " + error.InnerErrorMessage + ","; msg += "InnerErrorSubcode: " + error.InnerErrorSubcode.ToString() + ","; msg += "InnerErrorTraceId: " + error.InnerErrorTraceId; result[Constants.ErrorKey] = msg; callbackManager.OnFacebookResponse(new LoginResult((new ResultContainer(result)))); }); } catch (Exception e) { result[Constants.ErrorKey] = e.Message; callbackManager.OnFacebookResponse(new LoginResult((new ResultContainer(result)))); } } public bool IsLoggedIn() { return fbg.Globals.isLoggedIn(); } public void LogOut() { fbg.Globals.logout((success) => { Debug.Log("Logged out"); }, (error) => { Debug.LogError(error.Message); }); } public void Tick() { fbg.Globals.tick(); } public void Deinit() { this.result = fbg.Globals.deinit(); Debug.Log("Deinitialized Facebook SDK: " + this.result); } private List<fbg.LoginScope> ConvertToFbgLoginScope(IEnumerable<string> scope) { List<fbg.LoginScope> fbgLoginScope = new List<fbg.LoginScope>(); foreach (string str in scope) { string result = ""; string[] subs = str.Split('_'); foreach (string sub in subs) { if (sub.Length == 1) { result += char.ToUpper(sub[0]).ToString(); } else { result += (char.ToUpper(sub[0]) + sub.Substring(1)).ToString(); } } if (result != "") { fbgLoginScope.Add((fbg.LoginScope)Enum.Parse(typeof(fbg.LoginScope), result)); } } return fbgLoginScope; } public void GetCatalog(string callbackId, CallbackManager callbackManager) { fbg.Catalog.getCatalog(fbg.PagingType.None, "", 0, (catalogResult) => { CatalogResult result = new CatalogResult(WindowsCatalogParser.Parse(catalogResult, callbackId)); callbackManager.OnFacebookResponse(result); }, (error) => { PurchaseResult result = new PurchaseResult(WindowsCatalogParser.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void GetPurchases(string callbackId, CallbackManager callbackManager) { fbg.Purchases.getPurchases(fbg.PagingType.None, "", 0, (purchasesResult) => { PurchasesResult result = new PurchasesResult(WindowsPurchaseParser.Parse(purchasesResult, callbackId)); callbackManager.OnFacebookResponse(result); }, (error) => { PurchasesResult result = new PurchasesResult(WindowsPurchaseParser.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void Purchase(string newproductID, string newdeveloperPayload, string callbackId, CallbackManager callbackManager) { fbg.Purchases.purchase(newproductID, newdeveloperPayload, (purchaseResult) => { PurchaseResult result = new PurchaseResult(WindowsPurchaseParser.Parse(purchaseResult, callbackId, true)); callbackManager.OnFacebookResponse(result); }, (error) => { PurchaseResult result = new PurchaseResult(WindowsPurchaseParser.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void ConsumePurchase(string productToken, string callbackId, CallbackManager callbackManager) { fbg.Purchases.consume(productToken, (success) => { ConsumePurchaseResult result = new ConsumePurchaseResult(new ResultContainer(new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } } )); callbackManager.OnFacebookResponse(result); }, (error) => { ConsumePurchaseResult result = new ConsumePurchaseResult(WindowsPurchaseParser.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void CurrentProfile(string callbackId, CallbackManager callbackManager) { Dictionary<string, object> result = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId } }; if (IsLoggedIn()) { fbg.Profile.getProfile((windowsProfile) => { if (!String.IsNullOrEmpty(windowsProfile.Raw)) { try { Dictionary<string, object> profile = MiniJSON.Json.Deserialize(windowsProfile.Raw) as Dictionary<string, object>; profile.TryGetValue("first_name", out string firstName); profile.TryGetValue("name", out string name); profile.TryGetValue("email", out string email); profile.TryGetValue("picture", out Dictionary<string, object> picture); string imageURL = null; if (picture.TryGetValue("data", out Dictionary<string, object> pictureData)) { pictureData.TryGetValue("url", out imageURL); } profile.TryGetValue("link", out string link); result[ProfileResult.ProfileKey] = new Profile( userID, firstName, null, null, name, email, imageURL, link, null, null, null, null, null, null); } catch (Exception e) { result[Constants.ErrorKey] = "ERROR: " + e.Message; } } else { result[Constants.ErrorKey] = "ERROR: No profile data."; } callbackManager.OnFacebookResponse(new ProfileResult((new ResultContainer(result)))); }, (error) => { string msg = "ERROR: " + error.Message + ","; msg += "InnerErrorCode: " + error.InnerErrorCode.ToString() + ","; msg += "InnerErrorMessage: " + error.InnerErrorMessage + ","; msg += "InnerErrorSubcode: " + error.InnerErrorSubcode.ToString() + ","; msg += "InnerErrorTraceId: " + error.InnerErrorTraceId; result[Constants.ErrorKey] = msg; callbackManager.OnFacebookResponse(new ProfileResult((new ResultContainer(result)))); }); } else { result[Constants.ErrorKey] = "ERROR: user must by logged in."; callbackManager.OnFacebookResponse(new ProfileResult((new ResultContainer(result)))); } } public void LoadInterstitialAd(string placementID, string callbackId, CallbackManager callbackManager) { fbg.Inappad.loadInterstitialAd(placementID, (response) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } }; resultDict[Constants.ErrorKey] = response.Error; InterstitialAdResult result = new InterstitialAdResult(new ResultContainer(resultDict)); callbackManager.OnFacebookResponse(result); }, (error) => { InterstitialAdResult result = new InterstitialAdResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void ShowInterstitialAd(string placementID, string callbackId, CallbackManager callbackManager) { fbg.Inappad.showInterstitialAd(placementID, (response) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } }; resultDict[Constants.ErrorKey] = response.Error; InterstitialAdResult result = new InterstitialAdResult(new ResultContainer(resultDict)); callbackManager.OnFacebookResponse(result); }, (error) => { InterstitialAdResult result = new InterstitialAdResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void LoadRewardedVideo(string placementID, string callbackId, CallbackManager callbackManager) { fbg.Inappad.loadRewardedVideo(placementID, (response) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } }; resultDict[Constants.ErrorKey] = response.Error; RewardedVideoResult result = new RewardedVideoResult(new ResultContainer(resultDict)); callbackManager.OnFacebookResponse(result); }, (error) => { RewardedVideoResult result = new RewardedVideoResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void ShowRewardedVideo(string placementID, string callbackId, CallbackManager callbackManager) { fbg.Inappad.showRewardedVideo(placementID, (response) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } }; resultDict[Constants.ErrorKey] = response.Error; RewardedVideoResult result = new RewardedVideoResult(new ResultContainer(resultDict)); callbackManager.OnFacebookResponse(result); }, (error) => { RewardedVideoResult result = new RewardedVideoResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void OpenFriendFinderDialog(string callbackId, CallbackManager callbackManager) { fbg.Invite.gameInvite( (invitation) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId } }; callbackManager.OnFacebookResponse(new FriendFinderInvitationResult(new ResultContainer(resultDict))); }, (error) => { FriendFinderInvitationResult result = new FriendFinderInvitationResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); } ); } public void GetFriendFinderInvitations(string callbackId, CallbackManager callbackManager) { fbg.ReceivedInvitations.getReceivedInvitations(fbg.PagingType.None, "", 0, (fbg.ReceivedInvitations receivedInvitations) => { IList<FriendFinderInviation> invitationsList = new List<FriendFinderInviation>(); for (uint i = 0; i < receivedInvitations.Length; ++i) { var item = receivedInvitations[i]; invitationsList.Add(new FriendFinderInviation(item.Id, item.ApplicationId, item.ApplicationName, item.FromId, item.FromName, item.ToId, item.ToName, item.Message, item.CreatedTime)); } Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {FriendFinderInvitationResult.InvitationsKey,invitationsList } }; callbackManager.OnFacebookResponse(new FriendFinderInvitationResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { FriendFinderInvitationResult result = new FriendFinderInvitationResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void DeleteFriendFinderInvitation(string invitationId, string callbackId, CallbackManager callbackManager) { fbg.ReceivedInvitations.removeInvitation(invitationId, (fbg.DeleteInvitation success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, }; Dictionary<string, object> deletedInviation = MiniJSON.Json.Deserialize(success.Raw) as Dictionary<string, object>; if (!deletedInviation.TryGetValue(invitationId, out bool deletedOK)) { resultDict[Constants.ErrorKey] = "ERROR: wrong deleted inviationID: " + invitationId; } else if (!deletedOK) { resultDict[Constants.ErrorKey] = "ERROR: Fail deleting inviationID: " + invitationId; } callbackManager.OnFacebookResponse(new FriendFinderInvitationResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { FriendFinderInvitationResult result = new FriendFinderInvitationResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void ScheduleAppToUserNotification(string title, string body, Uri media, int timeInterval, string payload, string callbackId, CallbackManager callbackManager) { fbg.AppToUserNotifications.scheduleAppToUserNotification(title, body, media.ToString(), timeInterval, payload, (fbg.ScheduleAppToUserNotificationResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, }; callbackManager.OnFacebookResponse(new ScheduleAppToUserNotificationResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { ScheduleAppToUserNotificationResult result = new ScheduleAppToUserNotificationResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void PostSessionScore(int score, string callbackId, CallbackManager callbackManager) { fbg.Tournaments.postSessionScore(score, (fbg.PostSessionScoreResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {"Response", success.Raw }, }; callbackManager.OnFacebookResponse(new SessionScoreResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { SessionScoreResult result = new SessionScoreResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void PostTournamentScore(int score, string callbackId, CallbackManager callbackManager) { fbg.Tournaments.postTournamentScore(score, (fbg.PostTournamentScoreResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {"Response", success.Raw }, }; callbackManager.OnFacebookResponse(new TournamentScoreResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { TournamentScoreResult result = new TournamentScoreResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void GetTournament(string callbackId, CallbackManager callbackManager) { fbg.Tournaments.getTournament( (fbg.GetTournamentResult tournamentData) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, }; Dictionary<string, object> response = MiniJSON.Json.Deserialize(tournamentData.Raw) as Dictionary<string, object>; Dictionary<string, object> success = null; if (response.TryGetValue("success", out success)) { string tournamentId; if (success.TryGetValue("tournamentId", out tournamentId)) { resultDict["tournament_id"] = tournamentId; } string contextId; if (success.TryGetValue("contextId", out contextId)) { resultDict["context_id"] = contextId; } int endTime; if (success.TryGetValue("endTime", out endTime)) { resultDict["end_time"] = endTime; } string tournamentTitle; if (success.TryGetValue("tournamentTitle", out tournamentTitle)) { resultDict["tournament_title"] = tournamentTitle; } IDictionary<string, string> payload; if (success.TryGetValue("payload", out payload)) { resultDict["payload"] = payload; } } else { resultDict[Constants.ErrorKey] = "ERROR: Wrong Tournament Data"; } callbackManager.OnFacebookResponse(new TournamentResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { TournamentResult result = new TournamentResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void ShareTournament(int score, Dictionary<string, string> data, string callbackId, CallbackManager callbackManager) { fbg.Tournaments.shareTournament(score, MiniJSON.Json.Serialize(data), (fbg.ShareTournamentResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {"Response", success.Raw }, }; callbackManager.OnFacebookResponse(new TournamentScoreResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { TournamentScoreResult result = new TournamentScoreResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void CreateTournament(int initialScore, string title, string imageBase64DataUrl, string sortOrder, string scoreFormat, Dictionary<string, string> data, string callbackId, CallbackManager callbackManager) { fbg.Tournaments.createTournament( initialScore, title, imageBase64DataUrl, sortOrder, scoreFormat, MiniJSON.Json.Serialize(data), (fbg.CreateTournamentResult tournamentData) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, }; Dictionary<string, object> response = MiniJSON.Json.Deserialize(tournamentData.Raw) as Dictionary<string, object>; Dictionary<string, object> success = null; if (response.TryGetValue("success", out success)) { string tournamentId; if (success.TryGetValue("tournamentId", out tournamentId)) { resultDict["tournament_id"] = tournamentId; } string contextId; if (success.TryGetValue("contextId", out contextId)) { resultDict["context_id"] = contextId; } int endTime; if (success.TryGetValue("endTime", out endTime)) { resultDict["end_time"] = endTime; } string tournamentTitle; if (success.TryGetValue("tournamentTitle", out tournamentTitle)) { resultDict["tournament_title"] = tournamentTitle; } IDictionary<string, string> payload; if (success.TryGetValue("payload", out payload)) { resultDict["payload"] = payload; } } else { resultDict[Constants.ErrorKey] = "ERROR: Wrong Tournament Data"; } callbackManager.OnFacebookResponse(new TournamentResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { TournamentResult result = new TournamentResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void UploadImageToMediaLibrary(string caption, Uri imageUri, bool shouldLaunchMediaDialog, string travelId, string callbackId, CallbackManager callbackManager) { fbg.Share.uploadImageToMediaLibrary( caption, imageUri.LocalPath, shouldLaunchMediaDialog, travelId, (fbg.UploadImageToMediaLibraryResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {"id", success.Id }, }; callbackManager.OnFacebookResponse(new MediaUploadResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { MediaUploadResult result = new MediaUploadResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void UploadVideoToMediaLibrary(string caption, Uri videoUri, bool shouldLaunchMediaDialog, string travelId, string callbackId, CallbackManager callbackManager) { fbg.Share.uploadVideoToMediaLibrary( caption, videoUri.LocalPath, shouldLaunchMediaDialog, travelId, (fbg.UploadVideoToMediaLibraryResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId }, {"video_id", success.VideoId }, }; callbackManager.OnFacebookResponse(new MediaUploadResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { MediaUploadResult result = new MediaUploadResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void SetVirtualGamepadLayout(string layout, string callbackId, CallbackManager callbackManager) { fbg.Virtualgamepad.setVirtualGamepadLayout(layout, (fbg.VirtualGamepadLayoutResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId }, { "success", success }, }; callbackManager.OnFacebookResponse(new VirtualGamepadLayoutResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { VirtualGamepadLayoutResult result = new VirtualGamepadLayoutResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void GetUserLocale(string callbackId, CallbackManager callbackManager) { Dictionary<string, object> result = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId } }; if (IsLoggedIn()) { fbg.Profile.getProfile((windowsProfile) => { result.Add("locale", windowsProfile.Locale); callbackManager.OnFacebookResponse(new LocaleResult((new ResultContainer(result)))); }, (error) => { string msg = "ERROR: " + error.Message + ","; msg += "InnerErrorCode: " + error.InnerErrorCode.ToString() + ","; msg += "InnerErrorMessage: " + error.InnerErrorMessage + ","; msg += "InnerErrorSubcode: " + error.InnerErrorSubcode.ToString() + ","; msg += "InnerErrorTraceId: " + error.InnerErrorTraceId; result[Constants.ErrorKey] = msg; callbackManager.OnFacebookResponse(new LocaleResult(new ResultContainer(result))); }); } else { result[Constants.ErrorKey] = "ERROR: user must be logged in."; callbackManager.OnFacebookResponse(new LocaleResult(new ResultContainer(result))); } } public void SetSoftKeyboardOpen(bool open, string callbackId, CallbackManager callbackManager) { fbg.Softkeyboard.setSoftKeyboardOpen(open, (fbg.SoftkeyboardAction success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId }, { "success", success }, }; callbackManager.OnFacebookResponse(new SoftKeyboardOpenResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { SoftKeyboardOpenResult result = new SoftKeyboardOpenResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void CreateReferral(string payload, string callbackId, CallbackManager callbackManager) { fbg.Referrals.createReferral(payload, (fbg.CreateReferralResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId }, { "raw", success.Raw }, { "referral_link", success.ReferralLink }, }; callbackManager.OnFacebookResponse(new ReferralsCreateResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { ReferralsCreateResult result = new ReferralsCreateResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } public void GetDataReferral(string callbackId, CallbackManager callbackManager) { fbg.Referrals.getDataReferral( (fbg.GetDataReferralResult success) => { Dictionary<string, object> resultDict = new Dictionary<string, object>() { { Constants.CallbackIdKey, callbackId }, { "raw", success.Raw }, { "payload", success.Payload }, }; callbackManager.OnFacebookResponse(new ReferralsGetDataResult(new ResultContainer(resultDict))); }, (fbg.Error error) => { ReferralsGetDataResult result = new ReferralsGetDataResult(WindowsParserBase.SetError(error, callbackId)); callbackManager.OnFacebookResponse(result); }); } } }
722
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; namespace Facebook.Unity.Windows { class WindowsCatalogParser: WindowsParserBase { public static ResultContainer Parse(fbg.Catalog catalog, string callbackId) { IDictionary<string, object> deserializedCatalogData = Facebook.MiniJSON.Json.Deserialize(catalog.Raw) as Dictionary<string, object>; ResultContainer container; if (deserializedCatalogData.TryGetValue("data", out IList apiData)) { IList<Product> products = new List<Product>(); foreach (IDictionary<string, object> product in apiData) { products.Add(Utilities.ParseProductFromCatalogResult(product, true)); } container = new ResultContainer(new Dictionary<string, object>() { {Constants.CallbackIdKey, callbackId}, {"RawResult", catalog.Raw}, {"products", products} }); } else { container = new ResultContainer(new Dictionary<string, object>() { {Constants.CallbackIdKey, callbackId}, {"RawResult", catalog.Raw}, {Constants.ErrorKey, "ERROR: Parsing catalog. Wrong data format"} }); } return container; } } }
61
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; namespace Facebook.Unity.Windows { class WindowsParserBase { public static ResultContainer SetError(fbg.Error error, string callbackId) { string msg = "ERROR: " + error.Message + ","; msg += "InnerErrorCode: " + error.InnerErrorCode.ToString() + ","; msg += "InnerErrorMessage: " + error.InnerErrorMessage + ","; msg += "InnerErrorSubcode: " + error.InnerErrorSubcode.ToString() + ","; msg += "InnerErrorTraceId: " + error.InnerErrorTraceId; ResultContainer container = new ResultContainer(new Dictionary<string, object>() { {Constants.CallbackIdKey,callbackId}, {Constants.ErrorKey,msg } } ); return container; } } }
45
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; namespace Facebook.Unity.Windows { class WindowsPurchaseParser : WindowsParserBase { public static ResultContainer Parse(fbg.Purchases purchases, string callbackId, bool onlyFirst=false) { IDictionary<string, object> deserializedPurchaseData = Facebook.MiniJSON.Json.Deserialize(purchases.Raw) as Dictionary<string, object>; ResultContainer container; if (deserializedPurchaseData.TryGetValue("data", out IList apiData)) { IList<Purchase> purchasesList = new List<Purchase>(); foreach (IDictionary<string, object> purchase in apiData) { purchasesList.Add( Utilities.ParsePurchaseFromDictionary(purchase, true) ); } Dictionary<string, object> result = new Dictionary<string, object>() { {Constants.CallbackIdKey, callbackId}, {"RawResult", purchases.Raw} }; if (purchasesList.Count >= 1) { if (onlyFirst){ result["purchase"] = purchasesList[0]; }else{ result["purchases"] = purchasesList; } } else { result[Constants.ErrorKey] = "ERROR: Parsing purchases. No purchase data."; } container = new ResultContainer(result); } else { container = new ResultContainer(new Dictionary<string, object>() { {Constants.CallbackIdKey, callbackId}, {"RawResult", purchases.Raw}, {Constants.ErrorKey, "ERROR: Parsing purchases. Wrong data format"} }); } return container; } } }
75
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion("16.0.1")]
25
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.IO; using UnityEngine; using UnityEditor; #if UNITY_IOS using UnityEditor.Build.Reporting; using UnityEditor.iOS.Xcode; #endif using UnityEditor.Callbacks; namespace Facebook.Unity.PostProcess {     /// <summary>     /// Automatically disables Bitcode on iOS builds     /// </summary> public static class DisableBitcode { [PostProcessBuildAttribute(999)] public static void OnPostProcessBuild(BuildTarget buildTarget, string pathToBuildProject) { #if UNITY_IOS if (buildTarget != BuildTarget.iOS) return; string projectPath = pathToBuildProject + "/Unity-iPhone.xcodeproj/project.pbxproj"; PBXProject pbxProject = new PBXProject(); pbxProject.ReadFromFile(projectPath); //Disabling Bitcode on all targets //Main string target = pbxProject.GetUnityMainTargetGuid(); pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO"); //Unity Tests target = pbxProject.TargetGuidByName(PBXProject.GetUnityTestTargetName()); pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO"); //Unity Framework target = pbxProject.GetUnityFrameworkTargetGuid(); pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO"); pbxProject.WriteToFile(projectPath); #endif } } }
63
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; public class InputSystemWarning : MonoBehaviour { void Awake() { #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER Debug.LogWarning("You are using the new Input System, but this example uses Unity Engine OLD input system. Please, set your input configuration to Old or Both."); #endif } }
32
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class ProductRowPrefab : MonoBehaviour { [SerializeField] private RawImage _thumbImg; [SerializeField] private Text _titleText; [SerializeField] private Text _productIdText; [SerializeField] private GameObject _buyBtn; private Product _product; private LogScroller _logScroller; private PurchasePage _parentScript; private void Awake () { } public void OnLogBtnClick () { _logScroller.Log(_product.ToString()); } public void OnPurchaseBtnClick() { _parentScript.MakePurchase(_product); } public void Initialize (PurchasePage parentScript, LogScroller logScroller, Product product) { _parentScript = parentScript; _logScroller = logScroller; _product = product; _titleText.text = product.Title; _productIdText.text = product.ProductID; _buyBtn.transform.GetChild(0).GetComponent<Text>().text = product.Price; SetThumb(product.ProductID, product.ImageURI); } private void SetThumb (string productId, string url) { StartCoroutine(Utility.GetTexture(productId, url, (texture) => { _thumbImg.texture = texture; })); } private void LogText (string text) { _logScroller.Log(text); } }
75
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class PurchaseRowPrefab : MonoBehaviour { [SerializeField] private Text _purchaseTokenText; [SerializeField] private Text _productIdText; [SerializeField] private Text _purchaseTimeText; [SerializeField] private GameObject _consumeBtn; private string DATE_FORMAT = @"M/d/yyyy hh:mm:ss tt"; private Purchase _purchase; private LogScroller _logScroller; private PurchasePage _parentScript; public string GetPurchaseToken () { return _purchase.PurchaseToken; } public void OnLogBtnClick () { _logScroller.Log(_purchase.ToString()); } public void OnConsumeBtnClick () { _parentScript.ConsumePurchase(_purchase, delegate (bool success) { Destroy(gameObject); }); } public void Initialize (PurchasePage parentScript, LogScroller logScroller, Purchase purchase) { _parentScript = parentScript; _logScroller = logScroller; _purchase = purchase; _purchaseTokenText.text = purchase.PurchaseToken; _productIdText.text = purchase.ProductID; _purchaseTimeText.text = purchase.PurchaseTime.ToLocalTime().ToString(DATE_FORMAT); SetConsumeBtnData(purchase.IsConsumed); } private void SetConsumeBtnData (bool isConsumed) { _consumeBtn.GetComponent<Button>().interactable = !isConsumed; _consumeBtn.transform.GetChild(0).GetComponent<Text>().text = isConsumed ? "Consumed" : "Consume"; } }
72
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using Facebook.Unity; public class AdsPage : MonoBehaviour { private LogScroller _logScroller; // Replace the below INTERSTITIAL_ID and VIDEO_PLACEMENT_ID with your app placement IDs private string INTERSTITIAL_PLACEMENT_ID = "123456"; private string VIDEO_PLACEMENT_ID = "123456"; private void Awake () { _logScroller = transform.root.GetComponent<UIState>().logScroller; } public void OnLoadInterstitialBtnClick () { _LogText("Loading Interstitial Ad"); FBGamingServices.LoadInterstitialAd(INTERSTITIAL_PLACEMENT_ID, delegate(IInterstitialAdResult result) { if (result.Error == null && result.ResultDictionary != null) { _LogText("Interstitial Ad Loaded"); } else { _LogText("ERR: Failed to load Interstitial Ad\n" + result.Error.ToString()); } }); } public void OnLoadVideoBtnClick () { _LogText("Loading Video Ad"); FBGamingServices.LoadRewardedVideo(VIDEO_PLACEMENT_ID, delegate(IRewardedVideoResult result) { if (result.Error == null && result.ResultDictionary != null) { _LogText("Video Ad Loaded"); } else { _LogText("ERR: Failed to load Video Ad\n" + result.Error.ToString()); } }); } public void OnViewInterstitialBtnClick () { _LogText("View Interstitial Ad"); FBGamingServices.ShowInterstitialAd(INTERSTITIAL_PLACEMENT_ID, delegate(IInterstitialAdResult result) { if (result.Error == null && result.ResultDictionary != null) { _LogText("Interstitial Ad Viewed"); } else { _LogText("ERR: Failed to view Interstitial Ad\n" + result.Error.ToString()); } }); } public void OnViewVideoBtnClick () { _LogText("View Video Ad"); FBGamingServices.ShowRewardedVideo(VIDEO_PLACEMENT_ID, delegate(IRewardedVideoResult result) { if (result.Error == null && result.ResultDictionary != null) { _LogText("Video Ad Viewed"); } else { _LogText("ERR: Failed to watch Video Ad\n" + result.Error.ToString()); } }); } // private private void _LogText (string text) { _logScroller.Log(text); } }
83
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LogScroller : MonoBehaviour { [SerializeField] private GameObject _content; [HideInInspector] public List<String> texts = new List<String>(); private string DATE_FORMAT = @"M/d/yyyy hh:mm:ss tt"; private int index = 0; void Start() { } public void ClearLogs () { texts.Clear(); foreach (Transform child in _content.transform) { Destroy(child.gameObject); } } public void Log (string text) { GameObject nText = new GameObject("text-" + index++); nText.transform.parent = _content.transform; nText.transform.localPosition = new Vector3(0, 0, 0); nText.transform.localScale = new Vector3(1, 1, 1); nText.transform.SetAsFirstSibling(); string formattedText = string.Format("{0}\n{1}\n", DateTime.Now.ToString(DATE_FORMAT), text); texts.Insert(0, formattedText); Text textComp = nText.AddComponent<Text>(); textComp.text = formattedText; textComp.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); textComp.color = new Color(1, 1, 1, 1); } }
61
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class MainPage : MonoBehaviour { [SerializeField] private Menu _menu; private LogScroller _logScroller; private void Awake () { _logScroller = transform.root.GetComponent<UIState>().logScroller; _logScroller.Log(Application.identifier); if (!FB.IsInitialized) { _LogText("FB.Init called"); FB.Init(_OnInitComplete); } } public void OnLogAcessTokenBtnClick () { AccessToken currentToken = AccessToken.CurrentAccessToken; if (currentToken == null) { _LogText("CurrentAccessToken is empty"); } else { _LogText("CurrentAccessToken: " + currentToken.ToString()); } } public void OnLogPayloadBtnClick () { _LogText("Getting Payload"); FBGamingServices.GetPayload(delegate (IPayloadResult result) { _LogText("payload\n" + JsonUtility.ToJson(result.Payload)); }); } public void OnNavBtnClick (string pageName) { _menu.NavToPage(pageName); } // private private void _LogText (string text) { _logScroller.Log(text); } private void _OnInitComplete () { if (FB.IsInitialized) { _LogText("FB.Init Successful; FBGamingServices.InitCloudGame called"); FBGamingServices.InitCloudGame(_OnInitCloud); } else { _LogText("ERR: FB.Init failed"); } } private void _OnInitCloud (IInitCloudGameResult result) { if (result.Error == null && result.ResultDictionary != null) { _LogText("InitCloudGame Successful"); } else { _LogText("ERR: InitCloudGame failed\n" + result.Error.ToString()); } } }
81
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Menu : MonoBehaviour { [SerializeField] private Button _backBtn; [SerializeField] private Sprite _mutedSprite; [SerializeField] private Sprite _volumeSprite; [SerializeField] private Image _mutedBtnImg; [SerializeField] private AudioSource _bgMusic; [SerializeField] private GameObject _pages; private GameObject _currentPage; private LogScroller _logScroller; private bool _muted; private Stack<GameObject> _pagesStack = new Stack<GameObject>(); private void Awake () { _logScroller = transform.root.GetComponent<UIState>().logScroller; _muted = PlayerPrefs.GetInt("muted", 0) > 0 ? true : false; _SetMuteBtnIcon(); // deactivate all pages and set first page as active foreach(Transform child in _pages.transform) { child.gameObject.SetActive(false); } _currentPage = _pages.transform.GetChild(0).gameObject; _currentPage.SetActive(true); } public void NavToPage (string pageName) { GameObject target = _FindChild(_pages.transform, pageName); // _LogText(pageName + " " + !!target); if (target != null) { _currentPage.SetActive(false); _pagesStack.Push(_currentPage); _currentPage = target; target.SetActive(true); _backBtn.interactable = true; } else { _LogText("ERR: Missing page '" + pageName + "'"); } } public void OnBackBtnClick () { if (_pagesStack.Count > 0) { _currentPage.SetActive(false); GameObject target = _pagesStack.Pop(); _currentPage = target; target.SetActive(true); if (_pagesStack.Count == 0) { _backBtn.interactable = false; } } else { _LogText("ERR: On last page?"); } } public void OnToggleMuteBtnClick () { _muted = !_muted; PlayerPrefs.SetInt("muted", _muted ? 1 : 0); _SetMuteBtnIcon(); } // private private GameObject _FindChild (Transform target, string name) { foreach (Transform child in target) { if (child.gameObject.name == name) { return child.gameObject; } } return null; } private void _LogText (string text) { _logScroller.Log(text); } private void _SetMuteBtnIcon () { Sprite targetSprite = _muted ? _mutedSprite : _volumeSprite; _mutedBtnImg.sprite = targetSprite; _bgMusic.mute = _muted; } }
111