Database.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. string connectionType;
  11. string databaseUrl;
  12. string gameMode;
  13. int winAmount = -1;
  14. public GameObject questionCardPrefab;
  15. [Serializable]
  16. public class Question {
  17. public string question;
  18. public string answer;
  19. public string id;
  20. public string category;
  21. }
  22. [Serializable]
  23. public class Questions {
  24. public List<Question> questionsList = new List<Question>();
  25. }
  26. internal void SetLastPlayedDate(int gameId) {
  27. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  28. IDbConnection conn = new SqliteConnection(databaseUrl);
  29. conn.Open();
  30. IDbCommand cmd = conn.CreateCommand();
  31. cmd.CommandText = sql;
  32. cmd.ExecuteNonQuery();
  33. cmd.Dispose();
  34. conn.Close();
  35. }
  36. string questionString = "";
  37. string answerString = "";
  38. string idString = "";
  39. string categoryString = "";
  40. private int round = -1;
  41. public string QuestionString { get => questionString; set => questionString = value; }
  42. private void Start() {
  43. if (databaseUrl == null || databaseUrl.Equals("")) {
  44. SetLocalOrOnline("Local"); // Temporary, shoild not be needed after local testing
  45. }
  46. }
  47. internal int GetQuestionTimer(int gameId) {
  48. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  49. if (databaseUrl == null) {
  50. SetLocalOrOnline("Local");
  51. }
  52. IDbConnection conn = new SqliteConnection(databaseUrl);
  53. conn.Open();
  54. IDbCommand cmd = conn.CreateCommand();
  55. cmd.CommandText = sql;
  56. IDataReader reader = cmd.ExecuteReader();
  57. int answerTime = 15;
  58. while (reader.Read()) {
  59. answerTime = reader.GetInt32(0);
  60. }
  61. reader.Close();
  62. cmd.Dispose();
  63. conn.Close();
  64. return answerTime;
  65. }
  66. internal void GetOnlineGames(int userId) {
  67. string sql = "SELECT * FROM games WHERE userId = " + userId;
  68. }
  69. internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
  70. List<LocalGameScript> games = new List<LocalGameScript>();
  71. 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";
  72. IDbConnection conn = new SqliteConnection(databaseUrl);
  73. conn.Open();
  74. IDbCommand cmd = conn.CreateCommand();
  75. cmd.CommandText = sql;
  76. IDataReader reader = cmd.ExecuteReader();
  77. int currentGame = -1;
  78. GameObject localGame;// = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  79. LocalGameScript lgs = null;//= localGame.GetComponent<LocalGameScript>();
  80. string currentPlayerName = "";
  81. int currentPoints = 0;
  82. while (reader.Read()) {
  83. if (currentGame != reader.GetInt32(0)) {
  84. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  85. lgs = localGame.GetComponent<LocalGameScript>();
  86. lgs.GameId = reader.GetInt32(0);
  87. lgs.GameMode = reader.GetString(1);
  88. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  89. lgs.AnswerTimer = reader.GetInt32(3);
  90. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  91. lgs.CurrentPlayer = reader.GetString(5);
  92. lgs.Round = reader.GetInt32(6).ToString();
  93. lgs.StartDate = reader.GetValue(7) != DBNull.Value ? reader.GetString(7) : "";
  94. lgs.LastPlayedDate = reader.GetValue(8) != DBNull.Value ? reader.GetString(8) : "";
  95. lgs.FinishedDate = reader.GetValue(9) != DBNull.Value ? reader.GetString(9) : "";
  96. currentPlayerName = reader.GetString(10);
  97. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  98. lgs.AddPlayer(currentPlayerName, currentPoints);
  99. games.Add(lgs);
  100. } else if (currentGame == reader.GetInt32(0)) {
  101. currentPlayerName = reader.GetString(10);
  102. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  103. lgs.AddPlayer(currentPlayerName, currentPoints);
  104. }
  105. currentGame = reader.GetInt32(0);
  106. }
  107. reader.Close();
  108. cmd.Dispose();
  109. conn.Close();
  110. return games;
  111. }
  112. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  113. string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
  114. IDbConnection conn = new SqliteConnection(databaseUrl);
  115. conn.Open();
  116. IDbCommand cmd = conn.CreateCommand();
  117. cmd.CommandText = sql;
  118. cmd.ExecuteNonQuery();
  119. cmd.Dispose();
  120. conn.Close();
  121. }
  122. internal void RemoveGame(int gameId) {
  123. string sql = "DELETE FROM game WHERE id = " + gameId;
  124. List<LocalGameScript> games = new List<LocalGameScript>();
  125. IDbConnection conn = new SqliteConnection(databaseUrl);
  126. conn.Open();
  127. IDbCommand cmd = conn.CreateCommand();
  128. cmd.CommandText = sql;
  129. cmd.ExecuteNonQuery();
  130. string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
  131. cmd.CommandText = deleteLockedQuestionsSql;
  132. cmd.ExecuteNonQuery();
  133. cmd.Dispose();
  134. conn.Close();
  135. }
  136. public string GetCurrentPlayer(int gameId) {
  137. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  138. IDbConnection conn = new SqliteConnection(databaseUrl);
  139. conn.Open();
  140. IDbCommand cmd = conn.CreateCommand();
  141. cmd.CommandText = sql;
  142. IDataReader reader = cmd.ExecuteReader();
  143. string currentPlayer = "";
  144. while (reader.Read()) {
  145. currentPlayer = reader.GetString(0);
  146. }
  147. reader.Close();
  148. cmd.Dispose();
  149. conn.Close();
  150. return currentPlayer;
  151. }
  152. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  153. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  154. IDbConnection conn = new SqliteConnection(databaseUrl);
  155. conn.Open();
  156. IDbCommand cmd = conn.CreateCommand();
  157. cmd.CommandText = sql;
  158. cmd.ExecuteNonQuery();
  159. cmd.Dispose();
  160. conn.Close();
  161. }
  162. internal int GetPlayerPoints(int gameId, string playerName) {
  163. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" +playerName + "'";
  164. IDbConnection conn = new SqliteConnection(databaseUrl);
  165. conn.Open();
  166. IDbCommand cmd = conn.CreateCommand();
  167. cmd.CommandText = sql;
  168. IDataReader reader = cmd.ExecuteReader();
  169. int points = 0;
  170. while (reader.Read()) {
  171. points = reader.GetInt32(0);
  172. }
  173. reader.Close();
  174. cmd.Dispose();
  175. conn.Close();
  176. return points;
  177. }
  178. internal void SetFinishedDate(int gameId, string finishedDate) {
  179. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  180. IDbConnection conn = new SqliteConnection(databaseUrl);
  181. conn.Open();
  182. IDbCommand cmd = conn.CreateCommand();
  183. cmd.CommandText = sql;
  184. cmd.ExecuteNonQuery();
  185. cmd.Dispose();
  186. conn.Close();
  187. }
  188. internal void SetRoundValue(int gameId, int round) {
  189. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  190. IDbConnection conn = new SqliteConnection(databaseUrl);
  191. conn.Open();
  192. IDbCommand cmd = conn.CreateCommand();
  193. cmd.CommandText = sql;
  194. cmd.ExecuteNonQuery();
  195. cmd.Dispose();
  196. conn.Close();
  197. }
  198. internal int GetRoundValue(int gameId) {
  199. if (this.round == -1) {
  200. string sql = "SELECT round FROM game WHERE id = " + gameId;
  201. IDbConnection conn = new SqliteConnection(databaseUrl);
  202. conn.Open();
  203. IDbCommand cmd = conn.CreateCommand();
  204. cmd.CommandText = sql;
  205. IDataReader reader = cmd.ExecuteReader();
  206. while (reader.Read()) {
  207. this.round = reader.GetInt32(0);
  208. }
  209. reader.Close();
  210. cmd.Dispose();
  211. conn.Close();
  212. }
  213. return this.round;
  214. }
  215. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  216. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  217. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  218. "WHERE gameId = " + gameId;
  219. IDbConnection conn = new SqliteConnection(databaseUrl);
  220. conn.Open();
  221. IDbCommand cmd = conn.CreateCommand();
  222. cmd.CommandText = sql;
  223. IDataReader reader = cmd.ExecuteReader();
  224. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  225. while (reader.Read()) {
  226. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  227. returnList.Add(player);
  228. }
  229. return returnList;
  230. }
  231. public string AnswerString { get => answerString; set => answerString = value; }
  232. public string IdString { get => idString; set => idString = value; }
  233. public string CategoryString { get => categoryString; set => categoryString = value; }
  234. public void SetLocalOrOnline(string type) {
  235. gameMode = type;
  236. if (type.Equals("Local")) {
  237. string databaseName = "narKampenLocal.db";
  238. if (Application.platform == RuntimePlatform.Android) {
  239. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  240. if (!File.Exists(databaseUrl)) {
  241. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  242. load.SendWebRequest();
  243. while (!load.isDone) { }
  244. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  245. }
  246. databaseUrl = "URI=file:" + databaseUrl;
  247. } else {
  248. databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
  249. }
  250. } else {
  251. databaseUrl = "nordh.xyz/narKampen/dbFiles/dbAccess.php";
  252. }
  253. connectionType = type;
  254. }
  255. internal int GetQuestionsLost(int gameId, string playerName) {
  256. string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
  257. IDbConnection conn = new SqliteConnection(databaseUrl);
  258. conn.Open();
  259. IDbCommand cmd = conn.CreateCommand();
  260. cmd.CommandText = sql;
  261. IDataReader reader = cmd.ExecuteReader();
  262. int returnValue = 0;
  263. while (reader.Read()) {
  264. returnValue = reader.GetInt32(0);
  265. }
  266. reader.Close();
  267. cmd.Dispose();
  268. conn.Close();
  269. return returnValue;
  270. }
  271. public string GetGameMode(int gameId) {
  272. if (this.gameMode == null) {
  273. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  274. IDbConnection conn = new SqliteConnection(databaseUrl);
  275. conn.Open();
  276. IDbCommand cmd = conn.CreateCommand();
  277. cmd.CommandText = sql;
  278. IDataReader reader = cmd.ExecuteReader();
  279. while (reader.Read()) {
  280. this.gameMode = reader.GetString(0);
  281. }
  282. reader.Close();
  283. cmd.Dispose();
  284. conn.Close();
  285. }
  286. return this.gameMode;
  287. }
  288. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
  289. IDbConnection conn = new SqliteConnection(databaseUrl);
  290. conn.Open();
  291. string questionSql = "SELECT id FROM questions order by random() limit 1";
  292. IDbCommand cmd = conn.CreateCommand();
  293. cmd.CommandText = questionSql;
  294. IDataReader reader = cmd.ExecuteReader();
  295. int questionId = -1;
  296. while (reader.Read()) {
  297. questionId = reader.GetInt32(0);
  298. }
  299. foreach (string player in playerNames) {
  300. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  301. int playerId;
  302. cmd = conn.CreateCommand();
  303. cmd.CommandText = sql;
  304. reader = cmd.ExecuteReader();
  305. if (reader.Read()) {
  306. playerId = reader.GetInt32(0);
  307. } else {
  308. reader.Close();
  309. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  310. cmd.CommandText = sql;
  311. cmd.ExecuteNonQuery();
  312. cmd.CommandText = "SELECT last_insert_rowid()";
  313. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  314. playerId = (int)lastInsert64;
  315. }
  316. cmd.Dispose();
  317. reader.Close();
  318. LinkPlayerToGame(playerId, gameId);
  319. SavePlayersQuestion(questionId.ToString(), player, gameId);
  320. }
  321. IDbCommand cmd2 = conn.CreateCommand();
  322. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  323. cmd2.ExecuteNonQuery();
  324. cmd2.Dispose();
  325. conn.Close();
  326. }
  327. private void LinkPlayerToGame(int playerId, int gameId) {
  328. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  329. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  330. conn2.Open();
  331. IDbCommand cmd = conn2.CreateCommand();
  332. cmd.CommandText = sql;
  333. cmd.ExecuteNonQuery();
  334. cmd.Dispose();
  335. conn2.Close();
  336. }
  337. internal int GetWinCondition(int gameId) {
  338. if (winAmount == -1) {
  339. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  340. IDbConnection conn = new SqliteConnection(databaseUrl);
  341. conn.Open();
  342. IDbCommand cmd = conn.CreateCommand();
  343. cmd.CommandText = sql;
  344. IDataReader reader = cmd.ExecuteReader();
  345. while (reader.Read()) {
  346. this.winAmount = reader.GetInt32(0);
  347. }
  348. reader.Close();
  349. cmd.Dispose();
  350. conn.Close();
  351. }
  352. return this.winAmount;
  353. }
  354. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
  355. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  356. IDbConnection conn = new SqliteConnection(databaseUrl);
  357. conn.Open();
  358. IDbCommand cmd = conn.CreateCommand();
  359. cmd.CommandText = sql;
  360. int status = cmd.ExecuteNonQuery();
  361. cmd.CommandText = "SELECT last_insert_rowid()";
  362. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  363. return (int)lastInsert64;
  364. }
  365. public NewQuestion GetNewQuestion() {
  366. if (connectionType == null) {
  367. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  368. SetLocalOrOnline(GetGameMode(gameId));
  369. }
  370. if (connectionType == "Local") {
  371. IDbConnection conn = new SqliteConnection(databaseUrl);
  372. conn.Open();
  373. IDbCommand cmd = conn.CreateCommand();
  374. string sql = "SELECT questions.id, question, answer, categoryId as category, name FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId ORDER BY RANDOM() limit 1";
  375. cmd.CommandText = sql;
  376. IDataReader reader = cmd.ExecuteReader();
  377. while (reader.Read()) {
  378. int id = reader.GetInt32(0);
  379. string question = reader.GetString(1);
  380. int answer = reader.GetInt32(2);
  381. int catergoryId = reader.GetInt32(3);
  382. string categoryName = reader.GetString(4);
  383. idString = id.ToString();
  384. questionString = question;
  385. categoryString = catergoryId.ToString();
  386. answerString = answer.ToString();
  387. }
  388. reader.Close();
  389. cmd.Dispose();
  390. conn.Close();
  391. } else { // Connect Through db
  392. Debug.Log("Online Call");
  393. StartCoroutine(GetQuestionData(false));
  394. }
  395. NewQuestion q = NewQuestion.Instance();
  396. q.questionString = questionString;
  397. q.answerString = answerString;
  398. q.categoryString = categoryString;
  399. q.idString = idString;
  400. return q;
  401. }
  402. public void SavePlayersQuestion(string questionId, string playerNameValue, int gameId) {
  403. if (databaseUrl == null) {
  404. SetLocalOrOnline(GetGameMode(gameId));
  405. }
  406. Int32.TryParse(questionId, out int qId);
  407. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES ('" + playerNameValue + "'," + qId + "," + gameId + ")";
  408. IDbConnection conn = new SqliteConnection(databaseUrl);
  409. conn.Open();
  410. IDbCommand cmd = conn.CreateCommand();
  411. cmd.CommandText = sql;
  412. cmd.ExecuteReader();
  413. cmd.Dispose();
  414. conn.Close();
  415. }
  416. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue) {
  417. if (databaseUrl == null) {
  418. SetLocalOrOnline(GetGameMode(gameId));
  419. }
  420. List<QuestionCard> questions = new List<QuestionCard>();
  421. if (connectionType.Equals("Local")) {
  422. string sql = "SELECT * FROM questions WHERE id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  423. IDbConnection conn = new SqliteConnection(databaseUrl);
  424. conn.Open();
  425. IDbCommand cmd = conn.CreateCommand();
  426. cmd.CommandText = sql;
  427. IDataReader reader = cmd.ExecuteReader();
  428. while (reader.Read()) {
  429. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  430. QuestionCard q = question.GetComponent<QuestionCard>();
  431. q.SetAnswerText(reader.GetInt32(2).ToString());
  432. q.SetQuestionText(reader.GetString(1));
  433. q.idString = reader.GetInt32(0).ToString();
  434. questions.Add(q);
  435. }
  436. cmd.Dispose();
  437. conn.Close();
  438. }
  439. return questions;
  440. }
  441. private IEnumerator GetQuestionData(bool showAnswer) {
  442. UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/dbAccess.php");
  443. yield return www.SendWebRequest();
  444. if (www.isNetworkError || www.isHttpError) {
  445. Debug.Log(www.error);
  446. } else {
  447. while (!www.isDone) {
  448. yield return null;
  449. }
  450. // Show result
  451. string jsonData = www.downloadHandler.text;
  452. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  453. Questions qe = new Questions();
  454. JsonUtility.FromJsonOverwrite(jsonData, qe);
  455. /* if (qe.questionsList.Count > 0 && questionText != null) {
  456. if (showAnswer && answerText != null) {
  457. answerText.text = qe.questionsList[0].answer;
  458. }
  459. questionText.text = qe.questionsList[0].question;
  460. } */
  461. questionString = qe.questionsList[0].question;
  462. answerString = qe.questionsList[0].answer;
  463. idString = qe.questionsList[0].id;
  464. categoryString = qe.questionsList[0].category;
  465. }
  466. }
  467. }