Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // --------------------------------------------------------------------------------------------------------------------
- // <copyright file="PmAppworks.cs" company="ProjectMakers"> </copyright>
- // <summary>
- // AppWorks Data
- // Created by ProjectMakers
- // Version: 1.0.0.0
- // http://projectmakers.de
- // </summary>
- // --------------------------------------------------------------------------------------------------------------------
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Security;
- using System.Security.Cryptography.X509Certificates;
- namespace Appworks
- {
- public class Data
- {
- private static string _publisherToken;
- private static string _gameId;
- private const int MaxErrorCount = 10;
- public static bool LoggedIn { get; protected set; }
- public static bool CurrentSave { get; protected set; }
- public static bool SaveError { get; protected set; }
- private const string ServerAddress = "pm-appworks.de";
- private const string UlrPort = "8081";
- private const string Ulr = "https://" + ServerAddress + ":" + UlrPort + "/";
- private const string UrlGetUid = Ulr + "GetUid";
- private const string UrlLogin = Ulr + "UserLogin";
- private const string UrlPublisher = Ulr + "PublisherLogin";
- private const string UrlRegister = Ulr + "UserRegister";
- private const string UrlSetGameInfo = Ulr + "SetGameInfo";
- private const string UrlUserToken = Ulr + "GetToken";
- private const string UrlHasKey = Ulr + "HasKey";
- private const string UrlGetKey = Ulr + "GetGameInfo";
- private const string EmptyString = "empty";
- public static string UserId;
- private static int _sendErrorCount;
- private static string _userToken;
- private static string _userName;
- private static Dictionary<string, object> _saveDic = new Dictionary<string, object>();
- private static List<string> _saveList = new List<string>();
- private static bool _checkToken;
- public static string Instantiate(string token, string id)
- {
- _publisherToken = token;
- _gameId = id;
- return Publisher();
- }
- private static string Publisher()
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"publisherToken", _publisherToken},
- {"publisherGameId", _gameId}
- };
- string result = Request(UrlPublisher, EmptyString, headerDic);
- if (result.Contains("true"))
- {
- _checkToken = true;
- return "Publisher PublisherToken check successful!";
- }
- return "Publisher PublisherToken check issues! " + result;
- }
- /// <summary>
- /// Login user in AppWorks.
- /// Is required: name and password in text fields!
- /// </summary>
- public static string Login(string name, string password)
- {
- _userName = name;
- if (_checkToken)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"userName", name},
- {"userPassword", password}
- };
- string result = Request(UrlLogin, EmptyString, headerDic);
- if (result != "false" && result != null)
- {
- LoggedIn = true;
- return GetUserId();
- }
- LoggedIn = false;
- return result;
- }
- return "false";
- }
- private static string GetUserId()
- {
- if (_checkToken)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- { "userName", _userName }
- };
- string result = Request(UrlGetUid, EmptyString, headerDic);
- if (result != "false" && result != null)
- {
- UserId = result;
- return GetToken();
- }
- return result;
- }
- return "false";
- }
- private static string GetToken()
- {
- if (_checkToken)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"userID", UserId}
- };
- string result = Request(UrlUserToken, EmptyString, headerDic);
- if (result != "false" && result != null)
- {
- _userToken = result;
- return result;
- }
- return "You have a problem with your login!";
- }
- return "You are not registered as a developer!";
- }
- /// <summary>
- /// Register user in AppWorks.
- /// Is required: name, password and e-mail in text fields!
- /// </summary>
- public static string Register(string name, string password, string password2, string email)
- {
- if (name != null && password != null && password2 != null && email != null)
- {
- if (password == password2)
- {
- if (email.Contains("@") && email.Contains("."))
- {
- return RegisterIt(name, password, email);
- }
- return "This is not an e-mail!";
- }
- return "Passwords do not match!";
- }
- return "Please fill out the form!";
- }
- private static string RegisterIt(string username, string password, string email)
- {
- if (_checkToken)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"userName", username},
- {"userPassword", password},
- {"userMail", email}
- };
- string result = Request(UrlRegister, EmptyString, headerDic);
- if (result == "true")
- {
- GetUserId();
- return "You have registered and can log in now!";
- }
- return "You could not sign up!";
- }
- return "You are not registered as a user!";
- }
- /// <summary> Save variable. </summary>
- /// <param name="key"> Name of the variable to be save.</param>
- /// <param name="value"> Value to be save.</param>
- public static string Save(string key, object value)
- {
- if (!_checkToken) return "UserToken is false!";
- string json = JsonConvert.SerializeObject(value,
- new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
- _saveDic.Add(key, json);
- _saveList.Add(key);
- if (!CurrentSave)
- {
- CurrentSave = true;
- return SetValue();
- }
- return "Saving already in progress...";
- }
- private static string SetValue()
- {
- if (_saveList.Count > 0)
- {
- string tempListKey = _saveList[0];
- return DicWork(tempListKey, _saveDic[tempListKey].ToString());
- }
- _saveDic.Clear();
- CurrentSave = false;
- return "Saved complete!";
- }
- private static string DicWork(string key, string value)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"key", key},
- {"publisherGameId", _gameId.ToString()},
- {"publisherToken", _publisherToken},
- {"userID", UserId},
- {"userToken", _userToken}
- };
- string result = Request(UrlSetGameInfo, value, headerDic);
- switch (result)
- {
- case "true":
- SaveError = false;
- _saveList.RemoveAt(0);
- SetValue();
- return "Save data successful";
- case "false":
- SetValue();
- return "Save send error count: " + _sendErrorCount;
- default:
- return SaveConnectError();
- }
- }
- private static string SaveConnectError()
- {
- string jsonDic = JsonConvert.SerializeObject(_saveDic, new JsonSerializerSettings()
- { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
- string jsonList = JsonConvert.SerializeObject(_saveList, new JsonSerializerSettings()
- { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
- // TODO Was tun bei connect Error?!
- SaveError = true;
- return "Save send error (no return from server) | " + MaxErrorCount + " errors!";
- }
- /// <summary> Load variable. </summary>
- /// <param name="key"> Name of the variable to be load.</param>
- public static T Load<T>(string key)
- {
- T value = default(T);
- // BUG print the TryGetData Log!
- TryGetData(key, out value);
- return value;
- }
- private static string TryGetData<T>(string key, out T value)
- {
- string result = GetData(key);
- value = default(T);
- if (!string.IsNullOrEmpty(result))
- {
- value = JsonConvert.DeserializeObject<T>(result);
- return "Get data successful!";
- }
- return "Get data error - it was not a " + typeof(T).FullName + "!";
- }
- private static string GetData(string key)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"publisherGameId", _gameId},
- {"publisherToken", _publisherToken},
- {"userID", UserId},
- {"userToken", _userToken},
- { "key", key}
- };
- string result = Request(UrlGetKey, EmptyString, headerDic);
- if (result != "false") { return result; }
- if (_sendErrorCount > MaxErrorCount)
- { return "Get data error (no return from server)"; }
- return "Get data error: " + _sendErrorCount;
- }
- /// <summary> Checks if the variable exists. </summary>
- /// <param name="key"> Name of the variable to be checked.</param>
- public static bool HasKey(string key)
- {
- Dictionary<string, string> headerDic = new Dictionary<string, string>
- {
- {"curUserId", UserId},
- {"publisherGameId", _gameId},
- {"publisherToken", _publisherToken},
- {"userToken", _userToken}
- };
- string result = Request(UrlHasKey, key, headerDic);
- if (result == "true") { return true; }
- return false;
- }
- public static bool SslValidation(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- if (errors == SslPolicyErrors.None) return true;
- foreach (X509ChainStatus t in chain.ChainStatus)
- {
- if (t.Status == X509ChainStatusFlags.RevocationStatusUnknown) continue;
- chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
- chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
- chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
- chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
- if (!chain.Build((X509Certificate2)certificate)) { return false; }
- }
- return true;
- }
- private static string Request(string url, string value, Dictionary<string, string> dictionary)
- {
- ServicePointManager.ServerCertificateValidationCallback = SslValidation;
- var request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.ContentType = "application/json";
- request.Method = "POST";
- foreach (var o in dictionary)
- { request.Headers.Add(o.Key + ":" + o.Value); }
- try
- {
- using (var writer = new StreamWriter(request.GetRequestStream()))
- {
- writer.Write(value);
- writer.Flush();
- writer.Close();
- }
- }
- catch (Exception e)
- {
- _sendErrorCount++;
- if (_sendErrorCount >= MaxErrorCount) { return "fatalError"; }
- return "false request" + e;
- }
- var response = (HttpWebResponse)request.GetResponse();
- try
- {
- using (var stream = new StreamReader(response.GetResponseStream()))
- {
- var result = stream.ReadToEnd();
- stream.Close();
- _sendErrorCount = 0;
- return result;
- }
- }
- catch (Exception)
- {
- _sendErrorCount++;
- if (_sendErrorCount >= MaxErrorCount)
- {
- return "fatalError";
- }
- return "false response";
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement