Advertisement
Guest User

Untitled

a guest
May 31st, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.81 KB | None | 0 0
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="PmAppworks.cs" company="ProjectMakers"> </copyright>
  3. // <summary>
  4. // AppWorks Data
  5. // Created by ProjectMakers
  6. // Version: 1.0.0.0
  7. // http://projectmakers.de
  8. // </summary>
  9. // --------------------------------------------------------------------------------------------------------------------
  10.  
  11. using Newtonsoft.Json;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Net;
  16. using System.Net.Security;
  17. using System.Security.Cryptography.X509Certificates;
  18.  
  19. namespace Appworks
  20. {
  21. public class Data
  22. {
  23. private static string _publisherToken;
  24. private static string _gameId;
  25. private const int MaxErrorCount = 10;
  26.  
  27. public static bool LoggedIn { get; protected set; }
  28. public static bool CurrentSave { get; protected set; }
  29. public static bool SaveError { get; protected set; }
  30.  
  31. private const string ServerAddress = "pm-appworks.de";
  32. private const string UlrPort = "8081";
  33. private const string Ulr = "https://" + ServerAddress + ":" + UlrPort + "/";
  34. private const string UrlGetUid = Ulr + "GetUid";
  35. private const string UrlLogin = Ulr + "UserLogin";
  36. private const string UrlPublisher = Ulr + "PublisherLogin";
  37. private const string UrlRegister = Ulr + "UserRegister";
  38. private const string UrlSetGameInfo = Ulr + "SetGameInfo";
  39. private const string UrlUserToken = Ulr + "GetToken";
  40. private const string UrlHasKey = Ulr + "HasKey";
  41. private const string UrlGetKey = Ulr + "GetGameInfo";
  42. private const string EmptyString = "empty";
  43.  
  44. public static string UserId;
  45. private static int _sendErrorCount;
  46.  
  47. private static string _userToken;
  48. private static string _userName;
  49.  
  50. private static Dictionary<string, object> _saveDic = new Dictionary<string, object>();
  51. private static List<string> _saveList = new List<string>();
  52.  
  53. private static bool _checkToken;
  54.  
  55. public static string Instantiate(string token, string id)
  56. {
  57. _publisherToken = token;
  58. _gameId = id;
  59.  
  60. return Publisher();
  61. }
  62.  
  63. private static string Publisher()
  64. {
  65. Dictionary<string, string> headerDic = new Dictionary<string, string>
  66. {
  67. {"publisherToken", _publisherToken},
  68. {"publisherGameId", _gameId}
  69. };
  70.  
  71. string result = Request(UrlPublisher, EmptyString, headerDic);
  72.  
  73. if (result.Contains("true"))
  74. {
  75. _checkToken = true;
  76. return "Publisher PublisherToken check successful!";
  77. }
  78. return "Publisher PublisherToken check issues! " + result;
  79. }
  80.  
  81. /// <summary>
  82. /// Login user in AppWorks.
  83. /// Is required: name and password in text fields!
  84. /// </summary>
  85. public static string Login(string name, string password)
  86. {
  87. _userName = name;
  88.  
  89. if (_checkToken)
  90. {
  91. Dictionary<string, string> headerDic = new Dictionary<string, string>
  92. {
  93. {"userName", name},
  94. {"userPassword", password}
  95. };
  96.  
  97. string result = Request(UrlLogin, EmptyString, headerDic);
  98.  
  99. if (result != "false" && result != null)
  100. {
  101. LoggedIn = true;
  102. return GetUserId();
  103. }
  104. LoggedIn = false;
  105. return result;
  106. }
  107. return "false";
  108. }
  109.  
  110. private static string GetUserId()
  111. {
  112. if (_checkToken)
  113. {
  114. Dictionary<string, string> headerDic = new Dictionary<string, string>
  115. {
  116. { "userName", _userName }
  117. };
  118.  
  119. string result = Request(UrlGetUid, EmptyString, headerDic);
  120.  
  121. if (result != "false" && result != null)
  122. {
  123. UserId = result;
  124. return GetToken();
  125. }
  126. return result;
  127. }
  128. return "false";
  129. }
  130.  
  131. private static string GetToken()
  132. {
  133. if (_checkToken)
  134. {
  135. Dictionary<string, string> headerDic = new Dictionary<string, string>
  136. {
  137. {"userID", UserId}
  138. };
  139.  
  140. string result = Request(UrlUserToken, EmptyString, headerDic);
  141.  
  142. if (result != "false" && result != null)
  143. {
  144. _userToken = result;
  145. return result;
  146. }
  147. return "You have a problem with your login!";
  148. }
  149. return "You are not registered as a developer!";
  150. }
  151.  
  152. /// <summary>
  153. /// Register user in AppWorks.
  154. /// Is required: name, password and e-mail in text fields!
  155. /// </summary>
  156. public static string Register(string name, string password, string password2, string email)
  157. {
  158. if (name != null && password != null && password2 != null && email != null)
  159. {
  160. if (password == password2)
  161. {
  162. if (email.Contains("@") && email.Contains("."))
  163. {
  164. return RegisterIt(name, password, email);
  165. }
  166. return "This is not an e-mail!";
  167. }
  168. return "Passwords do not match!";
  169. }
  170. return "Please fill out the form!";
  171. }
  172.  
  173. private static string RegisterIt(string username, string password, string email)
  174. {
  175. if (_checkToken)
  176. {
  177. Dictionary<string, string> headerDic = new Dictionary<string, string>
  178. {
  179. {"userName", username},
  180. {"userPassword", password},
  181. {"userMail", email}
  182. };
  183.  
  184. string result = Request(UrlRegister, EmptyString, headerDic);
  185.  
  186. if (result == "true")
  187. {
  188. GetUserId();
  189. return "You have registered and can log in now!";
  190. }
  191. return "You could not sign up!";
  192. }
  193. return "You are not registered as a user!";
  194. }
  195.  
  196. /// <summary> Save variable. </summary>
  197. /// <param name="key"> Name of the variable to be save.</param>
  198. /// <param name="value"> Value to be save.</param>
  199. public static string Save(string key, object value)
  200. {
  201. if (!_checkToken) return "UserToken is false!";
  202.  
  203. string json = JsonConvert.SerializeObject(value,
  204. new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  205.  
  206. _saveDic.Add(key, json);
  207. _saveList.Add(key);
  208.  
  209. if (!CurrentSave)
  210. {
  211. CurrentSave = true;
  212. return SetValue();
  213. }
  214. return "Saving already in progress...";
  215. }
  216.  
  217. private static string SetValue()
  218. {
  219. if (_saveList.Count > 0)
  220. {
  221. string tempListKey = _saveList[0];
  222. return DicWork(tempListKey, _saveDic[tempListKey].ToString());
  223. }
  224. _saveDic.Clear();
  225. CurrentSave = false;
  226. return "Saved complete!";
  227. }
  228.  
  229. private static string DicWork(string key, string value)
  230. {
  231. Dictionary<string, string> headerDic = new Dictionary<string, string>
  232. {
  233. {"key", key},
  234. {"publisherGameId", _gameId.ToString()},
  235. {"publisherToken", _publisherToken},
  236. {"userID", UserId},
  237. {"userToken", _userToken}
  238. };
  239.  
  240. string result = Request(UrlSetGameInfo, value, headerDic);
  241.  
  242. switch (result)
  243. {
  244. case "true":
  245. SaveError = false;
  246. _saveList.RemoveAt(0);
  247. SetValue();
  248. return "Save data successful";
  249. case "false":
  250. SetValue();
  251. return "Save send error count: " + _sendErrorCount;
  252. default:
  253. return SaveConnectError();
  254. }
  255. }
  256.  
  257. private static string SaveConnectError()
  258. {
  259. string jsonDic = JsonConvert.SerializeObject(_saveDic, new JsonSerializerSettings()
  260. { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  261. string jsonList = JsonConvert.SerializeObject(_saveList, new JsonSerializerSettings()
  262. { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  263. // TODO Was tun bei connect Error?!
  264. SaveError = true;
  265.  
  266. return "Save send error (no return from server) | " + MaxErrorCount + " errors!";
  267. }
  268.  
  269. /// <summary> Load variable. </summary>
  270. /// <param name="key"> Name of the variable to be load.</param>
  271. public static T Load<T>(string key)
  272. {
  273. T value = default(T);
  274. // BUG print the TryGetData Log!
  275. TryGetData(key, out value);
  276. return value;
  277. }
  278.  
  279. private static string TryGetData<T>(string key, out T value)
  280. {
  281. string result = GetData(key);
  282. value = default(T);
  283.  
  284. if (!string.IsNullOrEmpty(result))
  285. {
  286. value = JsonConvert.DeserializeObject<T>(result);
  287. return "Get data successful!";
  288. }
  289. return "Get data error - it was not a " + typeof(T).FullName + "!";
  290. }
  291.  
  292. private static string GetData(string key)
  293. {
  294. Dictionary<string, string> headerDic = new Dictionary<string, string>
  295. {
  296. {"publisherGameId", _gameId},
  297. {"publisherToken", _publisherToken},
  298. {"userID", UserId},
  299. {"userToken", _userToken},
  300. { "key", key}
  301. };
  302. string result = Request(UrlGetKey, EmptyString, headerDic);
  303. if (result != "false") { return result; }
  304. if (_sendErrorCount > MaxErrorCount)
  305. { return "Get data error (no return from server)"; }
  306. return "Get data error: " + _sendErrorCount;
  307. }
  308.  
  309. /// <summary> Checks if the variable exists. </summary>
  310. /// <param name="key"> Name of the variable to be checked.</param>
  311. public static bool HasKey(string key)
  312. {
  313. Dictionary<string, string> headerDic = new Dictionary<string, string>
  314. {
  315. {"curUserId", UserId},
  316. {"publisherGameId", _gameId},
  317. {"publisherToken", _publisherToken},
  318. {"userToken", _userToken}
  319. };
  320. string result = Request(UrlHasKey, key, headerDic);
  321. if (result == "true") { return true; }
  322. return false;
  323. }
  324.  
  325. public static bool SslValidation(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  326. {
  327. if (errors == SslPolicyErrors.None) return true;
  328. foreach (X509ChainStatus t in chain.ChainStatus)
  329. {
  330. if (t.Status == X509ChainStatusFlags.RevocationStatusUnknown) continue;
  331. chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
  332. chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
  333. chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
  334. chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
  335. if (!chain.Build((X509Certificate2)certificate)) { return false; }
  336. }
  337. return true;
  338. }
  339.  
  340. private static string Request(string url, string value, Dictionary<string, string> dictionary)
  341. {
  342. ServicePointManager.ServerCertificateValidationCallback = SslValidation;
  343.  
  344. var request = (HttpWebRequest)HttpWebRequest.Create(url);
  345. request.ContentType = "application/json";
  346. request.Method = "POST";
  347.  
  348. foreach (var o in dictionary)
  349. { request.Headers.Add(o.Key + ":" + o.Value); }
  350. try
  351. {
  352. using (var writer = new StreamWriter(request.GetRequestStream()))
  353. {
  354. writer.Write(value);
  355. writer.Flush();
  356. writer.Close();
  357. }
  358. }
  359. catch (Exception e)
  360. {
  361. _sendErrorCount++;
  362. if (_sendErrorCount >= MaxErrorCount) { return "fatalError"; }
  363. return "false request" + e;
  364. }
  365. var response = (HttpWebResponse)request.GetResponse();
  366. try
  367. {
  368. using (var stream = new StreamReader(response.GetResponseStream()))
  369. {
  370. var result = stream.ReadToEnd();
  371. stream.Close();
  372. _sendErrorCount = 0;
  373. return result;
  374. }
  375. }
  376. catch (Exception)
  377. {
  378. _sendErrorCount++;
  379. if (_sendErrorCount >= MaxErrorCount)
  380. {
  381. return "fatalError";
  382. }
  383. return "false response";
  384. }
  385. }
  386. }
  387. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement