Database.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Mono.Data.Sqlite;
  5. using System.Data;
  6. using System;
  7. using UnityEngine.Networking;
  8. using System.IO;
  9. public class Database : MonoBehaviour {
  10. private const string onlineQuestionsUrl = "nordh.xyz/narKampen/dbFiles/Question.php";
  11. private const string serverUrl = "nordh.xyz/narKampen/dbFiles/";
  12. string connectionType;
  13. string databaseUrl;
  14. string gameMode;
  15. int winAmount = -1;
  16. int questionTimer = -1;
  17. public GameObject questionCardPrefab;
  18. private static Database instance;
  19. public static Database Instance { get { return instance; } }
  20. IDbConnection conn;
  21. private void Awake() {
  22. if (instance == null) {
  23. instance = this;
  24. }
  25. }
  26. internal List<CategoryPanel.Category> GetCategories() {
  27. List<CategoryPanel.Category> list = new List<CategoryPanel.Category>();
  28. string sql = "SELECT name, r, g, b, a, id FROM category";
  29. IDbCommand cmd = GetConnection();
  30. cmd.CommandText = sql;
  31. IDataReader reader = cmd.ExecuteReader();
  32. while (reader.Read()) {
  33. CategoryPanel.Category cat = new CategoryPanel.Category();
  34. byte r = (byte)reader.GetInt32(1);
  35. byte g = (byte)reader.GetInt32(2);
  36. byte b = (byte)reader.GetInt32(3);
  37. byte a = (byte)reader.GetInt32(4);
  38. cat.color = new Color32(r, g, b, a);
  39. cat.name = reader.GetString(0);
  40. cat.id = reader.GetInt32(5);
  41. list.Add(cat);
  42. }
  43. CloseConnection();
  44. return list;
  45. }
  46. internal void SetupNewOnlineGame(int limitPerQuestion, int limitPerPlayer, int toWin, List<InviteSearchResult> inviteUsers) {
  47. List<int> playerIds = new List<int>();
  48. inviteUsers.ForEach(i => playerIds.Add(i.GetId()));
  49. Debug.Log(playerIds);
  50. int currentUser = Database.Instance.GetSignedInUser();
  51. playerIds.Add(currentUser);
  52. Debug.Log(inviteUsers);
  53. var form = new WWWForm();
  54. form.AddField("currentUser", currentUser);
  55. form.AddField("winNumber", toWin);
  56. form.AddField("limitPerQuestion", limitPerQuestion);
  57. form.AddField("limitPerPlayer", limitPerPlayer);
  58. form.AddField("playerIds", String.Join(",", playerIds));
  59. Debug.Log(CallOnlineDatabaseWithResponse("NewOnlineGame.php", form));
  60. }
  61. [Serializable]
  62. public class Question {
  63. public string question;
  64. public string answer;
  65. public string id;
  66. public string category;
  67. }
  68. [Serializable]
  69. public class Questions {
  70. public List<Question> questionsList = new List<Question>();
  71. }
  72. [Serializable]
  73. public class PlayerInfo {
  74. public string username;
  75. public string status;
  76. }
  77. [Serializable]
  78. public class PlayerInfos {
  79. public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
  80. }
  81. [Serializable]
  82. public class OnlineGame {
  83. public string id;
  84. public string winNumber;
  85. public string answerTimer;
  86. public string roundTimeLimit;
  87. public string currentPlayer;
  88. public string round;
  89. public string startDate;
  90. public string LastPlayedDate;
  91. public string finishedDate;
  92. public string status;
  93. }
  94. [Serializable]
  95. public class OnlineGames {
  96. public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
  97. }
  98. [Serializable]
  99. public class UserName {
  100. public string id;
  101. public string username;
  102. }
  103. [Serializable]
  104. public class UserNames {
  105. public List<UserName> usernamesList = new List<UserName>();
  106. }
  107. private void CallDatabase(string filename, WWWForm formData) {
  108. string postUrl = serverUrl + filename;
  109. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  110. www.SendWebRequest();
  111. if (www.isNetworkError || www.isHttpError) {
  112. Debug.Log(www.error);
  113. } else {
  114. while (!www.isDone) {
  115. }
  116. }
  117. }
  118. private string CallOnlineDatabaseWithResponse(string filename, WWWForm formData) {
  119. string postUrl = serverUrl + filename;
  120. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  121. www.SendWebRequest();
  122. if (www.isNetworkError || www.isHttpError) {
  123. Debug.Log(www.error);
  124. } else {
  125. while (!www.isDone) {
  126. }
  127. }
  128. return www.downloadHandler.text;
  129. }
  130. internal void SetLastPlayedDate(int gameId) {
  131. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  132. IDbCommand cmd = GetConnection();
  133. cmd.CommandText = sql;
  134. cmd.ExecuteNonQuery();
  135. cmd.Dispose();
  136. CloseConnection();
  137. }
  138. private IDbCommand GetConnection() {
  139. if (databaseUrl == null) { // ej bra lösning för online
  140. SetLocalOrOnline("Local");
  141. }
  142. conn = new SqliteConnection(databaseUrl);
  143. conn.Open();
  144. IDbCommand cmd = conn.CreateCommand();
  145. return cmd;
  146. }
  147. private void CloseConnection() {
  148. conn.Close();
  149. }
  150. string questionString = "";
  151. string answerString = "";
  152. string idString = "";
  153. string categoryString = "";
  154. private int round = -1;
  155. private string SearchString;
  156. public string QuestionString { get => questionString; set => questionString = value; }
  157. private void Start() {
  158. if (instance == null) {
  159. instance = this;
  160. }
  161. if (databaseUrl == null || databaseUrl.Equals("")) {
  162. SetLocalOrOnline("Local"); // Temporary, should not be needed after local testing
  163. }
  164. }
  165. internal void KeepSignedIn(string username, int userId, bool keepSigendIn) {
  166. int ksi = 0;
  167. if (keepSigendIn) {
  168. ksi = 1;
  169. }
  170. string sql = "INSERT OR REPLACE INTO userSettings (username, userId, keepSignedIn) VALUES ('" + username + "', " + userId + "," + ksi + ")";
  171. IDbCommand cmd = GetConnection();
  172. cmd.CommandText = sql;
  173. cmd.ExecuteNonQuery();
  174. CloseConnection();
  175. }
  176. internal bool IsKeepSignedIn() {
  177. string sql = "SELECT keepSignedIn FROM userSettings";
  178. IDbCommand cmd = GetConnection();
  179. cmd.CommandText = sql;
  180. IDataReader reader = cmd.ExecuteReader();
  181. int res = 0;
  182. while (reader.Read()) {
  183. res = reader.GetInt32(0);
  184. }
  185. return res == 1;
  186. }
  187. internal int GetSignedInUser() {
  188. string sql = "SELECT userId FROM userSettings";
  189. IDbCommand cmd = GetConnection();
  190. cmd.CommandText = sql;
  191. int userId = -1;
  192. IDataReader reader = cmd.ExecuteReader();
  193. while (reader.Read()) {
  194. userId = reader.GetInt32(0);
  195. }
  196. CloseConnection();
  197. return userId;
  198. }
  199. internal void LogoutUser() {
  200. string sql = "UPDATE userSettings SET keepSignedIn = 0";
  201. IDbCommand cmd = GetConnection();
  202. cmd.CommandText = sql;
  203. cmd.ExecuteNonQuery();
  204. CloseConnection();
  205. }
  206. internal int GetQuestionTimer(int gameId) {
  207. if (questionTimer == -1) {
  208. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  209. if (databaseUrl == null) {
  210. SetLocalOrOnline("Local");
  211. }
  212. IDbCommand cmd = GetConnection();
  213. cmd.CommandText = sql;
  214. IDataReader reader = cmd.ExecuteReader();
  215. while (reader.Read()) {
  216. questionTimer = reader.GetInt32(0);
  217. }
  218. reader.Close();
  219. cmd.Dispose();
  220. }
  221. CloseConnection();
  222. return this.questionTimer;
  223. }
  224. internal List<OnlineGameScript> GetOnlineGames(int userId, GameObject prefab) {
  225. WWWForm formData = new WWWForm();
  226. formData.AddField("userId", userId);
  227. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
  228. response = "{\"onlineGamesList\" : " + response + " }";
  229. OnlineGames og = new OnlineGames();
  230. JsonUtility.FromJsonOverwrite(response, og);
  231. GameObject onlineGameObject;
  232. OnlineGameScript ogs = null;
  233. List<OnlineGameScript> games = new List<OnlineGameScript>();
  234. foreach (OnlineGame game in og.onlineGamesList) {
  235. onlineGameObject = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  236. ogs = onlineGameObject.GetComponent<OnlineGameScript>();
  237. ogs.SetGameStatus(game.status);
  238. if (game.status.Equals("PENDING")) {
  239. Int32.TryParse(game.id, out int gameId);
  240. List<KeyValuePair<string, string>> playerInfos = GetGameInfo(gameId);
  241. string extraInfo = "";
  242. foreach (KeyValuePair<string, string> s in playerInfos) {
  243. if (s.Value.Equals("WAITING")) {
  244. extraInfo += s.Key + ",";
  245. }
  246. }
  247. extraInfo = extraInfo.TrimEnd(',');
  248. ogs.SetGameStatusText(extraInfo);
  249. } else if (game.status.Equals("OTHERS_TURN")) {
  250. ogs.SetGameStatusText(game.currentPlayer);
  251. } else {
  252. ogs.SetGameStatusText();
  253. }
  254. games.Add(ogs);
  255. }
  256. return games;
  257. }
  258. internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
  259. List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
  260. WWWForm form = new WWWForm();
  261. form.AddField("gameId", gameId);
  262. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  263. response = "{\"playerInfoList\" : " + response + " }";
  264. PlayerInfos pi = new PlayerInfos();
  265. JsonUtility.FromJsonOverwrite(response, pi);
  266. foreach (PlayerInfo p in pi.playerInfoList) {
  267. KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
  268. returnList.Add(player);
  269. }
  270. return returnList;
  271. }
  272. internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
  273. List<LocalGameScript> games = new List<LocalGameScript>();
  274. string sql = "SELECT game.*, name, localUsers.id as userId FROM game INNER JOIN localGamePlayers on game.id = localGamePlayers.gameId INNER JOIN localUsers on playerId = localUsers.id order by game.id ASC, userId ASC";
  275. IDbConnection conn = new SqliteConnection(databaseUrl);
  276. conn.Open();
  277. IDbCommand cmd = conn.CreateCommand();
  278. cmd.CommandText = sql;
  279. IDataReader reader = cmd.ExecuteReader();
  280. int currentGame = -1;
  281. GameObject localGame;
  282. LocalGameScript lgs = null;
  283. string currentPlayerName = "";
  284. int currentPoints = 0;
  285. while (reader.Read()) {
  286. if (currentGame != reader.GetInt32(0)) {
  287. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  288. lgs = localGame.GetComponent<LocalGameScript>();
  289. lgs.GameId = reader.GetInt32(0);
  290. lgs.GameMode = reader.GetString(1);
  291. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  292. lgs.AnswerTimer = reader.GetInt32(3);
  293. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  294. lgs.CurrentPlayer = reader.GetString(5);
  295. lgs.Round = reader.GetInt32(6).ToString();
  296. lgs.StartDate = reader.GetString(7);
  297. lgs.LastPlayedDate = reader.GetString(8);
  298. lgs.FinishedDate = reader.IsDBNull(9) ? "" : reader.GetString(9);
  299. currentPlayerName = reader.GetString(10);
  300. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  301. lgs.AddPlayer(currentPlayerName, currentPoints);
  302. games.Add(lgs);
  303. } else if (currentGame == reader.GetInt32(0)) {
  304. currentPlayerName = reader.GetString(10);
  305. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  306. lgs.AddPlayer(currentPlayerName, currentPoints);
  307. }
  308. currentGame = reader.GetInt32(0);
  309. }
  310. reader.Close();
  311. cmd.Dispose();
  312. conn.Close();
  313. return games;
  314. }
  315. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  316. string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
  317. IDbConnection conn = new SqliteConnection(databaseUrl);
  318. conn.Open();
  319. IDbCommand cmd = conn.CreateCommand();
  320. cmd.CommandText = sql;
  321. cmd.ExecuteNonQuery();
  322. cmd.Dispose();
  323. conn.Close();
  324. }
  325. internal void RemoveGame(int gameId) {
  326. string sql = "DELETE FROM game WHERE id = " + gameId;
  327. List<LocalGameScript> games = new List<LocalGameScript>();
  328. IDbConnection conn = new SqliteConnection(databaseUrl);
  329. conn.Open();
  330. IDbCommand cmd = conn.CreateCommand();
  331. cmd.CommandText = sql;
  332. cmd.ExecuteNonQuery();
  333. string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
  334. cmd.CommandText = deleteLockedQuestionsSql;
  335. cmd.ExecuteNonQuery();
  336. cmd.Dispose();
  337. conn.Close();
  338. }
  339. public string GetCurrentPlayer(int gameId) {
  340. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  341. IDbConnection conn = new SqliteConnection(databaseUrl);
  342. conn.Open();
  343. IDbCommand cmd = conn.CreateCommand();
  344. cmd.CommandText = sql;
  345. IDataReader reader = cmd.ExecuteReader();
  346. string currentPlayer = "";
  347. while (reader.Read()) {
  348. currentPlayer = reader.GetString(0);
  349. }
  350. reader.Close();
  351. cmd.Dispose();
  352. conn.Close();
  353. return currentPlayer;
  354. }
  355. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  356. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  357. IDbConnection conn = new SqliteConnection(databaseUrl);
  358. conn.Open();
  359. IDbCommand cmd = conn.CreateCommand();
  360. cmd.CommandText = sql;
  361. cmd.ExecuteNonQuery();
  362. cmd.Dispose();
  363. conn.Close();
  364. }
  365. internal int GetPlayerPoints(int gameId, string playerName) {
  366. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerName + "'";
  367. IDbConnection conn = new SqliteConnection(databaseUrl);
  368. conn.Open();
  369. IDbCommand cmd = conn.CreateCommand();
  370. cmd.CommandText = sql;
  371. IDataReader reader = cmd.ExecuteReader();
  372. int points = 0;
  373. while (reader.Read()) {
  374. points = reader.GetInt32(0);
  375. }
  376. reader.Close();
  377. cmd.Dispose();
  378. conn.Close();
  379. return points;
  380. }
  381. internal void SetFinishedDate(int gameId, string finishedDate) {
  382. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  383. IDbConnection conn = new SqliteConnection(databaseUrl);
  384. conn.Open();
  385. IDbCommand cmd = conn.CreateCommand();
  386. cmd.CommandText = sql;
  387. cmd.ExecuteNonQuery();
  388. cmd.Dispose();
  389. conn.Close();
  390. }
  391. internal void SetRoundValue(int gameId, int round) {
  392. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  393. IDbConnection conn = new SqliteConnection(databaseUrl);
  394. conn.Open();
  395. IDbCommand cmd = conn.CreateCommand();
  396. cmd.CommandText = sql;
  397. cmd.ExecuteNonQuery();
  398. cmd.Dispose();
  399. conn.Close();
  400. }
  401. internal int GetRoundValue(int gameId) {
  402. if (this.round == -1) {
  403. string sql = "SELECT round FROM game WHERE id = " + gameId;
  404. IDbConnection conn = new SqliteConnection(databaseUrl);
  405. conn.Open();
  406. IDbCommand cmd = conn.CreateCommand();
  407. cmd.CommandText = sql;
  408. IDataReader reader = cmd.ExecuteReader();
  409. while (reader.Read()) {
  410. this.round = reader.GetInt32(0);
  411. }
  412. reader.Close();
  413. cmd.Dispose();
  414. conn.Close();
  415. }
  416. return this.round;
  417. }
  418. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  419. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  420. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  421. "WHERE gameId = " + gameId;
  422. IDbConnection conn = new SqliteConnection(databaseUrl);
  423. conn.Open();
  424. IDbCommand cmd = conn.CreateCommand();
  425. cmd.CommandText = sql;
  426. IDataReader reader = cmd.ExecuteReader();
  427. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  428. while (reader.Read()) {
  429. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  430. returnList.Add(player);
  431. }
  432. return returnList;
  433. }
  434. public string AnswerString { get => answerString; set => answerString = value; }
  435. public string IdString { get => idString; set => idString = value; }
  436. public string CategoryString { get => categoryString; set => categoryString = value; }
  437. public void SetLocalOrOnline(string type) {
  438. gameMode = type;
  439. if (type.Equals("Local")) {
  440. string databaseName = "narKampenLocal.db";
  441. if (Application.platform == RuntimePlatform.Android) {
  442. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  443. if (!File.Exists(databaseUrl)) {
  444. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  445. load.SendWebRequest();
  446. while (!load.isDone) { }
  447. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  448. }
  449. databaseUrl = "URI=file:" + databaseUrl;
  450. } else {
  451. databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
  452. }
  453. } else {
  454. databaseUrl = onlineQuestionsUrl;
  455. }
  456. connectionType = type;
  457. }
  458. internal int GetQuestionsLost(int gameId, string playerName) {
  459. string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
  460. IDbConnection conn = new SqliteConnection(databaseUrl);
  461. conn.Open();
  462. IDbCommand cmd = conn.CreateCommand();
  463. cmd.CommandText = sql;
  464. IDataReader reader = cmd.ExecuteReader();
  465. int returnValue = 0;
  466. while (reader.Read()) {
  467. returnValue = reader.GetInt32(0);
  468. }
  469. reader.Close();
  470. cmd.Dispose();
  471. conn.Close();
  472. return returnValue;
  473. }
  474. public string GetGameMode(int gameId) {
  475. if (this.gameMode == null) {
  476. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  477. IDbConnection conn = new SqliteConnection(databaseUrl);
  478. conn.Open();
  479. IDbCommand cmd = conn.CreateCommand();
  480. cmd.CommandText = sql;
  481. IDataReader reader = cmd.ExecuteReader();
  482. while (reader.Read()) {
  483. this.gameMode = reader.GetString(0);
  484. }
  485. reader.Close();
  486. cmd.Dispose();
  487. conn.Close();
  488. }
  489. return this.gameMode;
  490. }
  491. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
  492. IDbConnection conn = new SqliteConnection(databaseUrl);
  493. conn.Open();
  494. string questionSql = "SELECT id FROM questions order by random() limit 1";
  495. IDbCommand cmd = conn.CreateCommand();
  496. cmd.CommandText = questionSql;
  497. IDataReader reader = cmd.ExecuteReader();
  498. int questionId = -1;
  499. while (reader.Read()) {
  500. questionId = reader.GetInt32(0);
  501. }
  502. foreach (string player in playerNames) {
  503. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  504. int playerId;
  505. cmd = conn.CreateCommand();
  506. cmd.CommandText = sql;
  507. reader = cmd.ExecuteReader();
  508. if (reader.Read()) {
  509. playerId = reader.GetInt32(0);
  510. } else {
  511. reader.Close();
  512. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  513. cmd.CommandText = sql;
  514. cmd.ExecuteNonQuery();
  515. cmd.CommandText = "SELECT last_insert_rowid()";
  516. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  517. playerId = (int)lastInsert64;
  518. }
  519. cmd.Dispose();
  520. reader.Close();
  521. LinkPlayerToGame(playerId, gameId);
  522. SavePlayersQuestion(questionId.ToString(), player, gameId);
  523. }
  524. IDbCommand cmd2 = conn.CreateCommand();
  525. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  526. cmd2.ExecuteNonQuery();
  527. cmd2.Dispose();
  528. conn.Close();
  529. }
  530. private void LinkPlayerToGame(int playerId, int gameId) {
  531. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  532. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  533. conn2.Open();
  534. IDbCommand cmd = conn2.CreateCommand();
  535. cmd.CommandText = sql;
  536. cmd.ExecuteNonQuery();
  537. cmd.Dispose();
  538. conn2.Close();
  539. }
  540. internal int GetWinCondition(int gameId) {
  541. if (winAmount == -1) {
  542. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  543. IDbConnection conn = new SqliteConnection(databaseUrl);
  544. conn.Open();
  545. IDbCommand cmd = conn.CreateCommand();
  546. cmd.CommandText = sql;
  547. IDataReader reader = cmd.ExecuteReader();
  548. while (reader.Read()) {
  549. this.winAmount = reader.GetInt32(0);
  550. }
  551. reader.Close();
  552. cmd.Dispose();
  553. conn.Close();
  554. }
  555. return this.winAmount;
  556. }
  557. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
  558. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  559. IDbConnection conn = new SqliteConnection(databaseUrl);
  560. conn.Open();
  561. IDbCommand cmd = conn.CreateCommand();
  562. cmd.CommandText = sql;
  563. int status = cmd.ExecuteNonQuery();
  564. cmd.CommandText = "SELECT last_insert_rowid()";
  565. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  566. return (int)lastInsert64;
  567. }
  568. public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
  569. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  570. Color32 questionCategoryColor = new Color32(0, 0, 20, 20);
  571. if (connectionType == null) {
  572. SetLocalOrOnline(GetGameMode(gameId));
  573. }
  574. if (connectionType == "Local") {
  575. IDbConnection conn = new SqliteConnection(databaseUrl);
  576. conn.Open();
  577. IDbCommand cmd = conn.CreateCommand();
  578. string answeredIds = String.Join(",", userAnsweredQuestions);
  579. string sql = "SELECT questions.id, question, answer, categoryId as category, name, category.R, category.G, category.B, category.A FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId WHERE questions.id NOT IN (" + answeredIds + ") AND questions.id NOT IN (SELECT questionId FROM questionsInGame WHERE gameId = " + gameId + " AND userId = (SELECT id from localUsers WHERE name = '" + userName + "')) ORDER BY RANDOM() limit 1";
  580. cmd.CommandText = sql;
  581. IDataReader reader = cmd.ExecuteReader();
  582. int id = -1;
  583. while (reader.Read()) {
  584. id = reader.GetInt32(0);
  585. string question = reader.GetString(1);
  586. int answer = reader.GetInt32(2);
  587. int catergoryId = reader.GetInt32(3);
  588. string categoryName = reader.GetString(4);
  589. idString = id.ToString();
  590. questionString = question;
  591. categoryString = catergoryId.ToString();
  592. answerString = answer.ToString();
  593. byte r = (byte)reader.GetInt32(5);
  594. byte g = (byte)reader.GetInt32(6);
  595. byte b = (byte)reader.GetInt32(7);
  596. byte a = (byte)reader.GetInt32(8);
  597. questionCategoryColor = new Color32(r, g, b, a);
  598. }
  599. reader.Close();
  600. string saveSentQuestionSql = "INSERT INTO questionsInGame (gameId, questionId, userId) VALUES (" + gameId + ", " + id + ", (SELECT id FROM localUsers WHERE name = '" + userName + "'))";
  601. cmd.CommandText = saveSentQuestionSql;
  602. cmd.ExecuteNonQuery();
  603. cmd.Dispose();
  604. conn.Close();
  605. } else { // Connect Through db
  606. Debug.Log("Online Call");
  607. StartCoroutine(GetQuestionData(false));
  608. }
  609. NewQuestion q = NewQuestion.Instance();
  610. q.questionString = questionString;
  611. q.answerString = answerString;
  612. q.categoryString = categoryString;
  613. q.idString = idString;
  614. q.SetQuestionCategoryColor(questionCategoryColor);
  615. return q;
  616. }
  617. public void SavePlayersQuestion(string questionId, string playerNameValue, int gameId) {
  618. if (databaseUrl == null) {
  619. SetLocalOrOnline(GetGameMode(gameId));
  620. }
  621. Int32.TryParse(questionId, out int qId);
  622. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES ('" + playerNameValue + "'," + qId + "," + gameId + ")";
  623. IDbConnection conn = new SqliteConnection(databaseUrl);
  624. conn.Open();
  625. IDbCommand cmd = conn.CreateCommand();
  626. cmd.CommandText = sql;
  627. cmd.ExecuteReader();
  628. cmd.Dispose();
  629. conn.Close();
  630. }
  631. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue) {
  632. if (databaseUrl == null) {
  633. SetLocalOrOnline(GetGameMode(gameId));
  634. }
  635. List<QuestionCard> questions = new List<QuestionCard>();
  636. if (connectionType.Equals("Local")) {
  637. string sql = "SELECT * FROM questions inner join questionToCategory on questions.id = questionToCategory.questionId INNER JOIN category ON category.id = questionToCategory.categoryId WHERE questions.id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  638. IDbConnection conn = new SqliteConnection(databaseUrl);
  639. conn.Open();
  640. IDbCommand cmd = conn.CreateCommand();
  641. cmd.CommandText = sql;
  642. IDataReader reader = cmd.ExecuteReader();
  643. while (reader.Read()) {
  644. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  645. QuestionCard q = question.GetComponent<QuestionCard>();
  646. q.SetAnswerText(reader.GetInt32(2).ToString());
  647. q.SetQuestionText(reader.GetString(1));
  648. q.idString = reader.GetInt32(0).ToString();
  649. Color32 questionCategoryColor = new Color32((byte)reader.GetInt32(7), (byte)reader.GetInt32(8), (byte)reader.GetInt32(9), (byte)reader.GetInt32(10));
  650. q.SetQuestionCategoryColor(questionCategoryColor);
  651. questions.Add(q);
  652. }
  653. cmd.Dispose();
  654. conn.Close();
  655. }
  656. return questions;
  657. }
  658. private IEnumerator GetQuestionData(bool showAnswer) {
  659. UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/Question.php");
  660. yield return www.SendWebRequest();
  661. if (www.isNetworkError || www.isHttpError) {
  662. Debug.Log(www.error);
  663. } else {
  664. while (!www.isDone) {
  665. yield return null;
  666. }
  667. // Show result
  668. string jsonData = www.downloadHandler.text;
  669. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  670. Questions qe = new Questions();
  671. JsonUtility.FromJsonOverwrite(jsonData, qe);
  672. questionString = qe.questionsList[0].question;
  673. answerString = qe.questionsList[0].answer;
  674. idString = qe.questionsList[0].id;
  675. categoryString = qe.questionsList[0].category;
  676. }
  677. }
  678. public List<UserName> GetUsersToInvite(string searchString) {
  679. string postUrl = "nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
  680. postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
  681. UserNames uNames = new UserNames();
  682. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  683. www.SendWebRequest();
  684. if (www.isNetworkError || www.isHttpError) {
  685. Debug.Log(www.error);
  686. } else {
  687. while (!www.isDone) {
  688. }
  689. // Show result
  690. string jsonData = www.downloadHandler.text;
  691. jsonData = "{\"usernamesList\" : " + jsonData + " }";
  692. JsonUtility.FromJsonOverwrite(jsonData, uNames);
  693. }
  694. // TODO handle empty
  695. return uNames.usernamesList;
  696. }
  697. }