Database.cs 28 KB

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