Exemplo n.º 1
0
        /// <summary>
        /// Первичная аутентификация пользователя
        /// </summary>
        /// <returns>Статус аутентификации</returns>
        public bool Authenticate(string body)
        {
            string login_message = Encoding.UTF8.GetString(Convert.FromBase64String(body));
            int    login_length = login_message[0]; string msg = login_message.Substring(1);
            // Формат сообщения логина:
            // Первый символ интерпретируется (не парсится!!!) как число - длина логина в символах
            // Логин + пароль - строка в UTF-8, кодированная в Base64
            string login = msg.Substring(0, login_length), password = msg.Substring(login_length);

            Console.WriteLine("Login = {0}, password = {1}", login, password);

            // TODO: Replace with 1C authorization
            if (!(Constant.UserList.ContainsKey(login) && Constant.UserList[login] == password))
            {
                return(false);
            }

            using (var db = new ReaGameContext())
            {
                var user = db.Users.FirstOrDefault(x => x.UserName == login);

                if (user == null)
                {
                    // TODO: Update db with new user info
                    Console.WriteLine("[{0}]: new user {1}", ID, login);
                }
                else // TODO: <- TEMP!
                {
                    UserID = user.UserId;
                }
            }
            return(true);
        }
Exemplo n.º 2
0
 private void MsgGetQuizInfo(string body)
 {
     clientStream.ReadByte();
     clientStream.ReadByte();
     using (var db = new ReaGameContext())
     {
         var obj = JObject.FromObject(db.Quizzes.Select(x => x.QuizId == int.Parse(body)));
         obj.Add(new JProperty("categories", new JArray(
                                   from cat in db.QuestionCategories
                                   select new JObject(
                                       new JProperty("name", cat.Name),
                                       // TODO: только список ценовых категорий, в которых есть вопросы - конкретные вопросы будут выбираться случайным образом во время игры!
                                       new JProperty("questions", new JArray(
                                                         from quest in cat.Questions
                                                         orderby quest.Score
                                                         select new JObject(
                                                             new JProperty("id", quest.QuestionId),
                                                             new JProperty("text", quest.Text),
                                                             new JProperty("score", quest.Score)
                                                             )
                                                         )
                                                     )
                                       )
                                   )));
         SendMessage(MsgType.Json, obj.ToString());
     }
 }
Exemplo n.º 3
0
 private void MsgTest(string body)
 {
     using (var db = new ReaGameContext())
     {
         SendMessage(MsgType.Test, DateTime.Now.ToBinary().ToString());
     }
 }
Exemplo n.º 4
0
 private void MsgGetQuizList(string body)
 {
     // TODO: append hi-score
     using (var db = new ReaGameContext())
     {
         /*var obj = new JObject(
          *  new JProperty("quiz_list",
          *  new JArray(
          *      from quiz in db.Quizzes
          *      select JObject.FromObject(quiz)
          *      )
          *  )
          * );*/
         // aaaeeeee 🐱‍🚀
         var obj = JObject.FromObject(db.Quizzes.Select(q => new { q.QuizId, q.Name }).ToDictionary(q => q.QuizId, q => q.Name));
         SendMessage(MsgType.Json, obj.ToString());
     }
 }
Exemplo n.º 5
0
 static void QuizInfo(Quiz quiz, ReaGameContext db)
 {
     if (quiz == null)
     {
         return;
     }
     Console.WriteLine("\n[{0}] {1}\nTime: {2}\n[{3}|{4}|{5}]", quiz.QuizId, quiz.Name, quiz.TimeToSolve, quiz.ScoreGreat, quiz.ScoreGood, quiz.ScoreMediocre);
     foreach (var cat in quiz.QuestionCategories)
     {
         Console.WriteLine("\t{0}: {1}", cat.CategoryId, cat.Name);
         foreach (var quest in db.Questions.Where(x => x.CategoryId == cat.CategoryId))
         {
             Console.WriteLine("\t\t{0}: [{1}][{2} pts.] {3}", quest.QuestionId, quest.Type, quest.Score, quest.Text);
             foreach (var answ in quest.QuestionAnswers)
             {
                 Console.WriteLine("\t\t\t{0} {1}", answ.IsCorrect ? "+" : "-", answ.AnswerId, answ.Text);
             }
         }
     }
     Console.WriteLine();
 }
Exemplo n.º 6
0
        /// <summary>
        /// Редактор содержимого базы данных
        /// </summary>
        /// <param name="args">Аргументы программы</param>
        /// <returns>True для продолжения работы сервера в обычном режиме; False для закрытия</returns>
        static bool DbEditor(string[] args)
        {
            Console.WriteLine("Server started in Database Editor mode");
            using (ReaGameContext db = new ReaGameContext())
            {
                Quiz             quiz = null;
                QuestionCategory cat  = null;
                Question         que  = null;
                QuestionAnswer   ans  = null;
                foreach (var q in db.Quizzes)
                {
                    Console.WriteLine(" [{0}]: {1}", q.QuizId, q.Name);
                }
                while (true)
                {
                    if (quiz != null)
                    {
                        Console.Write("[{0}]", quiz.Name);
                    }
                    Console.Write(":> ");
                    var cargs = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);
                    if (cargs.Length == 0)
                    {
                        continue;
                    }
                    try
                    {
                        switch (cargs[0])
                        {
                        case "quit": return(false);

                        case "start": return(true);

                        case "list":
                            if (cargs.Length < 2)
                            {
                                foreach (var q in db.Quizzes)
                                {
                                    Console.WriteLine(" [{0}]: {1}", q.QuizId, q.Name);
                                }
                            }
                            else
                            {
                                foreach (var q in db.Quizzes.Where(x => x.Name.Contains(cargs[1])))
                                {
                                    Console.WriteLine(" [{0}]: {1}", q.QuizId, q.Name);
                                }
                            }
                            break;

                        case "info":
                            if (cargs.Length > 1)
                            {
                                var a = db.Quizzes.FirstOrDefault(x => x.QuizId == int.Parse(cargs[1]));
                                if (a != null)
                                {
                                    QuizInfo(a, db);
                                }
                            }
                            else if (quiz != null)
                            {
                                QuizInfo(quiz, db);
                            }
                            break;

                        case "new":
                            if ((cargs.Length < 2) || (quiz != null))
                            {
                                continue;
                            }
                            quiz = new Quiz()
                            {
                                Name = cargs[1]
                            };
                            db.Quizzes.Add(quiz);
                            //db.Entry(quiz).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                            break;

                        case "edit":
                            if ((cargs.Length < 2))
                            {
                                continue;
                            }
                            quiz = db.Quizzes.FirstOrDefault(x => x.Name == cargs[1]);
                            if (quiz == null)
                            {
                                Console.WriteLine("Invalid quiz: {0}", cargs[1]);
                            }
                            break;

                        case "time":
                            if ((cargs.Length < 2) || (quiz == null))
                            {
                                continue;
                            }
                            quiz.TimeToSolve = int.Parse(cargs[1]);
                            break;

                        case "score":
                            if ((cargs.Length < 4) || (quiz == null))
                            {
                                continue;
                            }
                            quiz.ScoreGreat    = int.Parse(cargs[1]);
                            quiz.ScoreGood     = int.Parse(cargs[2]);
                            quiz.ScoreMediocre = int.Parse(cargs[3]);
                            break;

                        case "save":
                            db.SaveChanges();
                            break;

                        // Редактирование категорий
                        case "catadd":
                            if ((cargs.Length < 2) || (quiz == null))
                            {
                                continue;
                            }
                            if (db.QuestionCategories.Where(x => x.QuizId == quiz.QuizId && x.Name == cargs[1]).Count() > 0)
                            {
                                Console.WriteLine("Unoriginal category name!"); break;
                            }
                            cat = new QuestionCategory()
                            {
                                Name = cargs[1], QuizId = quiz.QuizId
                            };
                            db.QuestionCategories.Add(cat);
                            break;

                        case "catedit":
                            if ((cargs.Length < 2) || (quiz == null))
                            {
                                continue;
                            }
                            cat = db.QuestionCategories.FirstOrDefault(x => x.Name == cargs[1]);
                            if (cat == null)
                            {
                                Console.WriteLine("Invalid category: {0}", cargs[1]);
                            }
                            break;

                            // Добавление
                        }
                    }
                    catch (FormatException) { Console.WriteLine("Invalid input!"); }
                }
            }
        }