Exemplo n.º 1
0
        public void ProcessMessage(MsgReply rply, IChatMessage[] chain)
        {
            StringBuilder str = new StringBuilder();
            List <string> pic = new List <string>();

            foreach (IChatMessage msg in chain)
            {
                switch (msg.Type)
                {
                case PlainMessage.MsgType:
                    PlainMessage pmsg = (PlainMessage)msg;
                    str.Append(pmsg.Message);
                    break;

                case ImageMessage.MsgType:
                    ImageMessage imsg = (ImageMessage)msg;
                    pic.Add(imsg.Url);
                    break;

                default:
                    break;
                }
            }
            PrivateMessage(rply, str.ToString(), pic.ToArray());
        }
Exemplo n.º 2
0
        public static void usersetCapeSelf(string[] cmd, MsgReply rep)
        {
            if (cmd.Length < 2)
            {
                rep.reply("用法:\n" + cmd[0] + " https://xxxx.xxxx.xxxx/xxxx.png");
                return;
            }
            if (!MCServer.SkinHandler.checkPick(cmd[1]))
            {
                rep.reply("图片格式有误。必须是有效PNG图片,且为64*32或64*64比例。");
                return;
            }
            string         uuid     = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
            string         pname    = DBHandler.me.getUserOwnedProfileName(rep.qq);
            string         oldtdata = DBHandler.me.getProfileUUIDTexture(uuid);
            List <Texture> l        = new List <Texture>();

            if (oldtdata != null)
            {
                JObject oldtexture = (JObject)JsonConvert.DeserializeObject(oldtdata);
                if (oldtexture["textures"]["SKIN"] != null)
                {
                    Dictionary <string, string> ddd = new Dictionary <string, string>();
                    Texture tt = new Texture(oldtexture["textures"]["SKIN"].Value <string>("url"), "SKIN", ddd);
                    l.Add(tt);
                }
            }
            Dictionary <string, string> d = new Dictionary <string, string>();

            d.Add("model", "slim");
            Texture t = new Texture(cmd[1], "SKIN", d);

            l.Add(t);
            SkinHandler sh = new SkinHandler(DBHandler.me.getUserOwnedProfileUUID(rep.qq), DBHandler.me.getUserOwnedProfileName(rep.qq), l);

            if (DBHandler.me.setProfileUUIDTexture(uuid, sh.ToString()))
            {
                rep.reply("操作成功,您的皮肤已设置。");
            }
            else
            {
                rep.reply("操作失败");
            }
        }
        public override async Task <IActionResult> Result()
        {
            var currentStep = Storage.GetCurrentStep(MsgId);

            //Switch to next step = currentStep + 1
            switch (currentStep + 1)
            {
                #region step 1
            case 1:
            {
                Storage.AddOrUpdateToStorage(MsgId, 1, null);
                using (var petTypeDAO = new PetTypeDAO())
                {
                    return(Receiver.Json(new
                        {
                            speech = "",
                            messages = new[]
                            {
                                new
                                {
                                    type = 2,
                                    platform = "facebook",
                                    title = "Bạn muốn sản phẩm cho thú cưng nào ạ?",
                                    replies = (await petTypeDAO.ReadAll(false))
                                              .Select(x => x.Name)
                                              .ToArray()
                                }
                            }
                        }));
                }
            }

                #endregion
                #region Step 2
            case 2:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var petTypeDAO = new PetTypeDAO())
                    {
                        if (await(await petTypeDAO.ReadAll(false))
                            .Select(x => x.Name)
                            .AllAsync(x => x != MsgReply))
                        {
                            _isSkipValidation = true;
                            goto case 1;
                        }
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 2, null);
                Storage.AddOrUpdateToStorage(MsgId, 1, MsgReply);
                return(Receiver.Json(new
                    {
                        speech = "",
                        messages = new[]
                        {
                            new
                            {
                                type = 2,
                                platform = "facebook",
                                title = "Bạn muốn mua gì cho bé ạ?",
                                replies = new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }
                            }
                        }
                    }));
            }

                #endregion
                #region Step 3
            case 3:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 2;
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 3, null);
                Storage.AddOrUpdateToStorage(MsgId, 2, MsgReply);
                return(Receiver.Json(new
                    {
                        speech = "",
                        messages = new[]
                        {
                            new
                            {
                                type = 2,
                                platform = "facebook",
                                title = "Bạn có thể cho mình biết mức giá bạn muốn tìm kiếm?",
                                replies = new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }
                            }
                        }
                    }));
            }
                #endregion
                #region Step 4

            case 4:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }.All(x =>
                                                                                                  x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 3;
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 4, null);
                Storage.AddOrUpdateToStorage(MsgId, 3, MsgReply);

                //Find minimum and maximum price from step 3
                int minimumPrice, maximumPrice;

                switch (Storage[MsgId, 3])
                {
                case "<100000":
                    minimumPrice = 0;
                    maximumPrice = 99999;
                    break;

                case "100000 - 300000":
                    minimumPrice = 100000;
                    maximumPrice = 300000;
                    break;

                case ">300000 - 500000":
                    minimumPrice = 300001;
                    maximumPrice = 500000;
                    break;

                default:
                    minimumPrice = 500001;
                    maximumPrice = int.MaxValue;
                    break;
                }

                //Find product in step 2, for pet in step 1
                return(await MessengerProductListResult(GetProductType(), minimumPrice, maximumPrice));
            }

                #endregion
                #region Step 5
            case 5:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var productDAO = new ProductDAO())
                    {
                        if (await productDAO.Read(MsgQuery, false) == null)
                        {
                            _isSkipValidation = true;
                            goto case 4;
                        }
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 5, null);
                Storage.AddOrUpdateToStorage(MsgId, 4, MsgQuery);
                return(Receiver.Json(new
                    {
                        speech = "Bạn có thể cho mình biết tên đăng nhập trên hệ thống Cutieshop được không ạ?\nNếu chưa có, bạn có thể gõ tên đăng nhập mới để chúng mình tạo tài khoản cho bạn"
                    }));
            }
                #endregion
                #region Step 6

            case 6:
            {
                //This step receive username first, then the email and address. So we need to keep the username to the storage for further uses, email will be used once in this step and can be queried by DAO easily in the future.
                //Checking null will prevent email from being overwritten to username in Storage
                if (Storage[MsgId, 5] == null)
                {
                    Storage.AddOrUpdateToStorage(MsgId, 5, MsgReply);
                }

                using (var userDAO = new UserDAO())
                {
                    var user = await userDAO.ReadChild(Storage[MsgId, 5], true);

                    //If user is null, create a user, then ask customer their email
                    if (user == null)
                    {
                        Storage.AddOrUpdateToStorage(MsgId, 6, "userPassword", new GuidHelper().CreateGuid());
                        await userDAO.Create(new Auth
                            {
                                Username = Storage[MsgId, 5],
                                Password = Storage[MsgId, 6, "userPassword"]
                            });

                        await userDAO.CreateChild(new User
                            {
                                Username = Storage[MsgId, 5],
                                Email    = string.Empty,
                                Address  = string.Empty
                            });

                        await userDAO.Context.SaveChangesAsync();
                    }

                    user = await userDAO.ReadChild(Storage[MsgId, 5], true);

                    //If email is empty, as for email
                    if (user.Email == string.Empty)
                    {
                        if (Storage[MsgId, 6, "isAskForEmail"] == null)
                        {
                            Storage.AddOrUpdateToStorage(MsgId, 6, "isAskForEmail", "1");
                            return(Receiver.Json(new
                                {
                                    speech = "Bạn hãy cho mình biết email nhé"
                                }));
                        }

                        //Validate email
                        var atInd = MsgReply.IndexOf("@", StringComparison.OrdinalIgnoreCase);
                        if (atInd < 1 || atInd == MsgReply.Length - 1)
                        {
                            return(Receiver.Json(new
                                {
                                    speech = "Email không hợp lệ\nVui lòng nhập lại email"
                                }));
                        }

                        user.Email = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //If address is empty but email is not, MsgReply must be address
                    if (user.Address == string.Empty)
                    {
                        if (Storage[MsgId, 6, "isAskForAddress"] == null)
                        {
                            Storage.AddOrUpdateToStorage(MsgId, 6, "isAskForAddress", "1");
                            return(Receiver.Json(new
                                {
                                    speech = "Bạn cho mình xin địa chỉ"
                                }));
                        }

                        user.Address = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //Ready to jump into step 7 after this
                    Storage.AddOrUpdateToStorage(MsgId, 6, null);

                    using (var onlineOrderProductDAO = new OnlineOrderProductDAO(userDAO.Context))
                    {
                        var orderId = new GuidHelper().CreateGuid();
                        await onlineOrderProductDAO.Create(new OnlineOrder
                            {
                                OnlineOrderId = orderId,
                                FirstName     = user.FirstName,
                                LastName      = user.LastName,
                                Address       = user.Address,
                                PostCode      = "10000",
                                City          = user.City,
                                PhoneNo       = "12345678",
                                Email         = user.Email,
                                Date          = DateTime.Now,
                                Username      = user.Username,
                                StatusId      = 0
                            });

                        await onlineOrderProductDAO.CreateChild(new OnlineOrderProduct
                            {
                                ProductId     = Storage[MsgId, 4],
                                OnlineOrderId = orderId,
                                Quantity      = 1
                            });

                        Product buyProduct;
                        using (var productDAO = new ProductDAO())
                        {
                            buyProduct = await productDAO.Read(Storage[MsgId, 4], false);
                        }
                        var mailProductTable = _mailContent.BuyReq.TableRow.
                                               Replace("{0}", buyProduct.Name)
                                               .Replace("{1}", buyProduct.Description)
                                               .Replace("{2}", "1");

                        var mailBody = _mailContent.BuyReq.Body
                                       .Replace("{0}", user.Username)
                                       .Replace("{1}", mailProductTable)
                                       .Replace("{2}", "http://cutieshopapi.azurewebsites.net/verify?id=" + orderId);

                        MailUtils.Send(user.Email, _mailContent.BuyReq.Subject, mailBody);

                        var reply =
                            $"Mail xác nhận đã được gửi đến {user.Email}. Hãy xác nhận qua mail để hoàn tất đặt hàng nhé!";

                        //Send temporary password if customer create new account
                        if (Storage[MsgId, 6, "userPassword"] != null)
                        {
                            reply = $"Password tạm thời của bạn là {Storage[MsgId, 6, "userPassword"]}. Bạn nên vào trang chủ để thay đổi mật khẩu mặc định\n" + reply;
                        }

                        //Remove data in storage
                        Storage.RemoveId(MsgId);

                        return(Receiver.Json(new
                            {
                                speech = reply
                            }));
                    }
                }
            }

                #endregion
            }

            Storage.RemoveId(MsgId);
            throw new UnhandledChatException();
        }
Exemplo n.º 4
0
        public void PrivateMessage(MsgReply rep, string msgtext, string[] pictures)
        {
            try
            {
                /*
                 * if (msgtext.IndexOf("#") != 0)
                 * {
                 *  try
                 *  {
                 *      var ticket = BroadTicketUtility.TicketCoder.Decode(msgtext);
                 *      long qq = DataBase.me.getUserBoundedQQ(ticket.Data.Uid);
                 *      if (qq <= 0)
                 *      {
                 *          DataBase.me.boundBiliWithQQ(ticket.Data.Uid, rep.qq);
                 *          rep.reply("已将您的QQ与Bilibili账号绑定。");
                 *          qq = rep.qq;
                 *      }
                 *      if (qq != rep.qq)
                 *      {
                 *          rep.reply("我无法为您兑换船票,因为您Bilibili账号绑定的QQ与当前QQ不符。\n绑定的QQ:******" + qq.ToString()[6..] + "\n如果您确信这是一个误会,请联系运维@鸡蛋(1250542735)");
                 *          MainHolder.broadcaster.BroadcastToAdminGroup("船票兑换失败\nQQ<" + rep.qq + ">试图兑换船票{Serial=" + ticket.Data.SerialNumber + "}\n该船票颁发给BiliUID#" + ticket.Data.Uid + "@QQ<" + qq + ">\n拒绝兑换。");
                 *          return;
                 *      }
                 *      try
                 *      {
                 *          rep.reply(BroadTicketUtility.TicketCoder.Encode(ticket, false));
                 *          MainHolder.broadcaster.BroadcastToAdminGroup("船票兑换成功\nQQ<" + rep.qq + ">试图兑换船票{Serial=" + ticket.Data.SerialNumber + "}\n该船票颁发给BiliUID#" + ticket.Data.Uid + "\n已兑换。");
                 *          rep.reply("兑换成功,感谢您对鹿野的支持!");
                 *      }
                 *      catch (Exception err)
                 *      {
                 *          MainHolder.broadcaster.BroadcastToAdminGroup("[Exception]\n兑换船票时发生了一个错误:\n" + err.Message + "\nStack:\n" + err.StackTrace);
                 *          rep.reply("出现了一个错误,无法为您生成船票。请复制本消息并联系运维@鸡蛋(1250542735)\n" + err.Message + "\nStack:\n" + err.StackTrace);
                 *      }
                 *      return;
                 *  }
                 *  catch { }
                 *  MainHolder.broadcaster.SendToAnEgg(msgtext);
                 * }
                 * else*/
                {//是一条指令
                    try
                    {
                        string[] cmd = msgtext.Split(' ');
                        switch (cmd[0])
                        {
                        case "#reg":
                        case "#注册":
                        {
                            if (cmd.Length < 3)
                            {
                                rep.reply("用法:\n" + cmd[0] + " 角色名 密码");
                                break;
                            }
                            if (DBHandler.me.isRegistered(rep.qq))
                            {
                                rep.reply("您的QQ已经被绑定到一个MC账号,我们不允许重复注册。如果需要销号,请联系管理员。");
                                break;
                            }
                            else if (DBHandler.me.isNameTaken(cmd[1]))
                            {
                                rep.reply("这个用户名已经有人用了,换一个试试吧!");
                                break;
                            }
                            else if (cmd[2].Length < 5)
                            {
                                rep.reply("密码长度必须大于等于5位");
                                break;
                            }
                            else if (CheckEncode(cmd[1]))
                            {
                                rep.reply("用户名仅允许(A-Z,a-z,0-9,_),不允许特殊符号和中文。");
                                break;
                            }
                            bool succeed = true;
                            bool mojang  = false;
                            succeed = succeed && MCServer.DBHandler.me.addUser(rep.qq, cmd[2]);
                            succeed = succeed && MCServer.DBHandler.me.addProfile(cmd[1], rep.qq, out mojang);
                            if (succeed)
                            {
                                {
                                    string         uuid             = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
                                    string         pname            = DBHandler.me.getUserOwnedProfileName(rep.qq);
                                    List <Texture> l                = new List <Texture>();
                                    Dictionary <string, string> ddd = new Dictionary <string, string>();
                                    ddd.Add("model", "slim");
                                    Texture tt = new Texture("https://storage.microstorm.tech/skins/default.png", "SKIN", ddd);
                                    l.Add(tt);
                                    SkinHandler sh = new SkinHandler(DBHandler.me.getUserOwnedProfileUUID(rep.qq), DBHandler.me.getUserOwnedProfileName(rep.qq), l);
                                    if (DBHandler.me.setProfileUUIDTexture(uuid, sh.ToString()))
                                    {
                                        rep.reply("注册成功。使用以下信息登录:\n" +
                                                  "用户名:" + rep.qq + "@qq.com\n" +
                                                  "密码:" + cmd[2] + (mojang ? "\n[正版UUID]" : ""));
                                        MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + cmd[1] + ">在认证服务器中注册" + (mojang ? "\n[正版UUID]" : ""));
                                    }
                                    else
                                    {
                                        rep.reply("注册成功,[但设置默认皮肤时发生了一些问题]。\n联系管理解决后,使用以下信息登录:\n" +
                                                  "用户名:" + rep.qq + "@qq.com\n" +
                                                  "密码:" + cmd[2] + (mojang ? "\n[正版UUID]" : ""));
                                        MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + cmd[1] + ">在认证服务器中注册,但默认皮肤未能写入。【须进一步操作】" + (mojang ? "\n[正版UUID]" : ""));
                                    }
                                }
                            }
                            else
                            {
                                rep.reply("无法与中央数据库通讯。请稍后重试。\n如果该问题持续出现,请联系@鸡蛋<1250542735>");
                                MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + cmd[1] + ">在认证服务器中注册时发生错误。数据库连接不稳定。");
                            }
                        }
                        break;

                        case "#skin":
                        case "#皮肤":
                        {
                            if (cmd.Length < 2)
                            {
                                rep.reply("用法:\n" + cmd[0] + " https://xxxxx.xxxxx.xxxxx/xxx.png");
                                break;
                            }
                            if (!MCServer.SkinHandler.CheckSkinSourceTrusted(cmd[1]))
                            {
                                rep.reply("使用的图像URL无效。URL必须格式正确且来自可信的图像服务器。");
                                return;
                            }
                            if (!MCServer.SkinHandler.checkPick(cmd[1]))
                            {
                                rep.reply("图片格式有误。必须是有效PNG图片,且为64*32或64*64比例。");
                                return;
                            }
                            string         uuid     = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
                            string         pname    = DBHandler.me.getUserOwnedProfileName(rep.qq);
                            string         oldtdata = DBHandler.me.getProfileUUIDTexture(uuid);
                            List <Texture> l        = new List <Texture>();
                            if (oldtdata != null)
                            {
                                JObject oldtexture = (JObject)JsonConvert.DeserializeObject(oldtdata);
                                if (oldtexture["textures"]["CAPE"] != null)
                                {
                                    Dictionary <string, string> ddd = new Dictionary <string, string>();
                                    Texture tt = new Texture(oldtexture["textures"]["CAPE"].Value <string>("url"), "CAPE", ddd);
                                    l.Add(tt);
                                }
                            }
                            Dictionary <string, string> d = new Dictionary <string, string>();
                            d.Add("model", "slim");
                            Texture t = new Texture(cmd[1], "SKIN", d);
                            l.Add(t);
                            SkinHandler sh = new SkinHandler(DBHandler.me.getUserOwnedProfileUUID(rep.qq), DBHandler.me.getUserOwnedProfileName(rep.qq), l);
                            if (DBHandler.me.setProfileUUIDTexture(uuid, sh.ToString()))
                            {
                                rep.reply("操作成功,您的皮肤已设置。");
                            }
                            else
                            {
                                rep.reply("操作失败");
                            }
                        }
                        break;

                        case "#UUID_RESET":
                        case "#离线化UUID":
                        {
                            string __uuid  = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
                            string __pname = DBHandler.me.getUserOwnedProfileName(rep.qq);
                            bool   mmojang;
                            string nsu = DBHandler.genNoSlashUUID(__pname, out mmojang);
                            string su  = DBHandler.genSlashUUID(__pname);
                            if (DBHandler.me.changeProfileUUID(__uuid, nsu, su) && mmojang)
                            {
                                rep.reply("您(" + __pname + ")的UUID已更新:\n旧UUID:" + __uuid + "\n新UUID:" + nsu);
                                MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n" + __pname + "发起了UUID更新\n旧UUID:" + __uuid + "\n新UUID:" + nsu + "\n√ 通过");
                            }
                            else
                            {
                                rep.reply("您(" + __pname + ")的UUID无法更新。数据库出错或非Mojang账号\n旧UUID:" + __uuid);
                                MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n" + __pname + "发起了UUID更新\n旧UUID:" + __uuid + "\n新UUID:" + nsu + "\n× 失败");
                            }
                        }
                        break;

                        case "#cloneuuid":
                        {
                            string __uuid;
                            if (cmd.Length == 3)
                            {
                                __uuid = DBHandler.me.getUserOwnedProfileUUID(long.Parse(cmd[2]));
                            }
                            else
                            {
                                __uuid = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
                            }
                            string __pname = cmd[1];
                            bool   mmojang;
                            string nsu = DBHandler.genNoSlashUUID(__pname, out mmojang);
                            string su  = DBHandler.genSlashUUID(__pname);
                            if (!mmojang)
                            {
                                rep.reply("无法获取" + __pname + "的UUID,因此无法克隆。");
                            }
                            else
                            {
                                rep.reply("您申请克隆" + __pname + "的UUID,请等待管理员操作。");
                                MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n" + __pname + "发起了UUID更新\n旧UUID:" + __uuid + "\n新UUID:" + nsu + "\n#cloneuuid " + __pname + " " + rep.qq + "");
                            }
                        }
                        break;

                        case "#cape":
                        case "#披风":
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception err)
                    {
                        rep.reply("执行指令出错。请检查指令及其参数是否正确。如果确认操作无误,请将下面的信息转发给@鸡蛋");
                        rep.reply("未处理的异常:" + err.Message + "\n堆栈追踪:" + err.StackTrace);
                    }

                    if (DataBase.me.isUserOperator(rep.qq))//管理才能用的指令
                    {
                        try
                        {
                            string[] cmd = msgtext.Split(' ');
                            switch (cmd[0])
                            {
                            case "#dreg":
                            {
                                if (cmd.Length < 3)
                                {
                                    rep.reply("用法:\n" + cmd[0] + " QQ 角色名 密码");
                                    break;
                                }

                                long   qq     = long.Parse(cmd[1]);
                                string name   = cmd[2];
                                string passwd = cmd[3];
                                if (DBHandler.me.isRegistered(qq))
                                {
                                    rep.reply("QQ已经被绑定到一个MC账号,我们不允许重复注册。如果需要销号,请联系管理员。");
                                    break;
                                }
                                else if (DBHandler.me.isNameTaken(name))
                                {
                                    rep.reply("这个用户名已经有人用了,换一个试试吧!");
                                    break;
                                }
                                else if (passwd.Length < 5)
                                {
                                    rep.reply("密码长度必须大于等于5位");
                                    break;
                                }
                                else if (CheckEncode(name))
                                {
                                    rep.reply("用户名仅允许(A-Z,a-z,0-9,_),不允许特殊符号和中文。");
                                    break;
                                }
                                bool succeed = true;
                                bool mojang  = false;
                                succeed = succeed && MCServer.DBHandler.me.addUser(qq, passwd);
                                succeed = succeed && MCServer.DBHandler.me.addProfile(name, qq, out mojang);
                                if (succeed)
                                {
                                    {
                                        string         uuid             = DBHandler.me.getUserOwnedProfileUUID(qq);
                                        string         pname            = DBHandler.me.getUserOwnedProfileName(qq);
                                        List <Texture> l                = new List <Texture>();
                                        Dictionary <string, string> ddd = new Dictionary <string, string>();
                                        ddd.Add("model", "slim");
                                        Texture tt = new Texture("https://storage.microstorm.tech/skins/default.png", "SKIN", ddd);
                                        l.Add(tt);
                                        SkinHandler sh = new SkinHandler(DBHandler.me.getUserOwnedProfileUUID(qq), DBHandler.me.getUserOwnedProfileName(qq), l);
                                        if (DBHandler.me.setProfileUUIDTexture(uuid, sh.ToString()))
                                        {
                                            rep.reply("注册成功。使用以下信息登录:\n" +
                                                      "用户名:" + qq + "@qq.com\n" +
                                                      "密码:" + passwd + (mojang ? "\n[正版UUID]" : ""));
                                            MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + name + ">在认证服务器中注册" + (mojang ? "\n[正版UUID]" : ""));
                                        }
                                        else
                                        {
                                            rep.reply("注册成功,[但设置默认皮肤时发生了一些问题]。\n联系管理解决后,使用以下信息登录:\n" +
                                                      "用户名:" + qq + "@qq.com\n" +
                                                      "密码:" + passwd + (mojang ? "\n[正版UUID]" : ""));
                                            MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + name + ">在认证服务器中注册,但默认皮肤未能写入。【须进一步操作】" + (mojang ? "\n[正版UUID]" : ""));
                                        }
                                    }
                                }
                                else
                                {
                                    rep.reply("无法与中央数据库通讯。请稍后重试。\n如果该问题持续出现,请联系@鸡蛋<1250542735>");
                                    MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n玩家<" + name + ">在认证服务器中注册时发生错误。数据库连接不稳定。");
                                }
                            }
                            break;

                            case "#cloneuuid":
                            {
                                string __uuid;
                                if (cmd.Length == 3)
                                {
                                    __uuid = DBHandler.me.getUserOwnedProfileUUID(long.Parse(cmd[2]));
                                }
                                else
                                {
                                    __uuid = DBHandler.me.getUserOwnedProfileUUID(rep.qq);
                                }
                                string __pname = cmd[1];
                                bool   mmojang;
                                string nsu = DBHandler.genNoSlashUUID(__pname, out mmojang);
                                string su  = DBHandler.genSlashUUID(__pname);
                                if (DBHandler.me.changeProfileUUID(__uuid, nsu, su) && mmojang)
                                {
                                    rep.reply("您(" + __pname + ")的UUID已更新:\n旧UUID:" + __uuid + "\n新UUID:" + nsu);
                                    MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n" + __pname + "发起了UUID更新\n旧UUID:" + __uuid + "\n新UUID:" + nsu + "\n√ 通过");
                                }
                                else
                                {
                                    rep.reply("您(" + __pname + ")的UUID无法更新。数据库出错或非Mojang账号\n旧UUID:" + __uuid);
                                    MainHolder.broadcaster.BroadcastToAdminGroup("[MC AUTH SERVER]\n" + __pname + "发起了UUID更新\n旧UUID:" + __uuid + "\n新UUID:" + nsu + "\n× 失败");
                                }
                            }
                            break;

                            case "#查重":
                            {
                                rep.reply("====查重开始====\n" +
                                          "该操作需要大量数据库操作,请耐心等待\n" +
                                          "!如果发现结果不正确,请在对应群发送\n" +
                                          "#REFETCH_MEMBERS\n" +
                                          "!来重新同步数据");
                                Dictionary <long, List <long> > li;

                                if (!(cmd.Length > 1 && ((cmd[1] == "从缓存") || (cmd[1] == "cache"))))
                                {
                                    li = DataBase.me.findMeUser();
                                }
                                else
                                {
                                    li = me_user_tmp;
                                }

                                foreach (KeyValuePair <long, List <long> > groups in li)
                                {
                                    if (DataBase.me.isUserOperator(groups.Key))
                                    {
                                        continue;
                                    }
                                    string gps = "";
                                    foreach (long group in groups.Value)
                                    {
                                        gps += DataBase.me.getGroupName(group) + "(" + group + ")\n";
                                    }
                                    if (!(cmd.Length > 1 && ((cmd[1] == "计数") || (cmd[1] == "count"))))
                                    {
                                        rep.reply(new UserData(groups.Key).name + "(" + groups.Key + ")\n" + "该用户同时在这些群:\n" + gps);
                                    }
                                }
                                me_user_tmp = li;
                                rep.reply("共发现" + li.Count + "个重复加群用户\n" +
                                          "====查重结束====\n");
                            }
                            break;

                            case "#更新群":
                            case "#refetch":
                            {
                                rep.reply("!该操作涉及大量数据库操作,需要一定时间");
                                DataBase.me.update_groupmembers(long.Parse(cmd[1]));
                                rep.reply("已更新群成员数据");
                            }
                            break;

                            case "#初始化群":
                            case "#init_group":
                            {
                                rep.reply("!该操作涉及大量数据库操作,需要一定时间");
                                DataBase.me.init_groupdata(long.Parse(cmd[1]));
                                rep.reply("已完成群初始化");
                            }
                            break;

                            case "#手动拉黑":
                            case "#ban":
                            {
                                if (DataBase.me.addUserBlklist(long.Parse(cmd[1]), (
                                                                   (cmd.Length > 2 ? (cmd[2]) : ("管理员手动拉黑"))
                                                                   ), rep.qq))
                                {
                                    string name = "";
                                    try
                                    {
                                        name = "<" + new UserData(long.Parse(cmd[1])).name + ">";
                                    }
                                    catch
                                    {
                                        name = "* <UNKNOWN>";
                                    }
                                    rep.reply("已将" + name + "加入黑名单");
                                }
                                else
                                {
                                    rep.reply("无法执行该操作,中央数据库可能暂时不可用");
                                }
                            }
                            break;

                            case "#清缓存":
                            case "#clearcache":
                            {
                                me_user_tmp.Clear();
                                MainHolder.clearcache();
                                DataBase.me.clearCache();
                                rep.reply("√ 缓存已清空");
                            }
                            break;

                            case "#验证":
                            case "#check":
                                int uid, len, level, tstamp;
                                if (CrewKeyProcessor.checkToken(cmd[1], out uid, out len, out level, out tstamp))
                                {
                                    string dpword = "??未知??";
                                    switch (level)
                                    {
                                    case 1:
                                        dpword = "总督";
                                        break;

                                    case 2:
                                        dpword = "提督";
                                        break;

                                    case 3:
                                        dpword = "舰长";
                                        break;
                                    }
                                    rep.reply("签名有效√\n" +
                                              "颁发给UID:" + uid + "\n" +
                                              "用以证明购买 " + dpword + "*" + len + " 月\n" +
                                              "颁发时间:" + BiliApi.TimestampHandler.GetDateTime(tstamp) + "\n" +
                                              "\n" +
                                              "⚠该凭据仅表明以上购买信息真实有效,不做其它用途");
                                }
                                else
                                {
                                    rep.reply("该凭据签名无效×\n" +
                                              "⚠该凭据无法被正确解码或签名失效。这可能意味着它包含的信息遭到篡改。不要信任该凭据指示的任何信息。");
                                }
                                break;

                            case "#cape":
                            case "#披风":
                            {
                                long   qq  = -1;
                                string url = "";
                                if (cmd.Length < 3)
                                {
                                    if (!long.TryParse(cmd[1], out qq))
                                    {
                                        rep.reply("!正在操作您自己的账号");
                                        qq  = rep.qq;
                                        url = cmd[1];
                                    }
                                    else
                                    {
                                        if (cmd.Length < 2)
                                        {
                                            rep.reply("用法:\n" + cmd[0] + " (玩家QQ) 图片URL");
                                            break;
                                        }
                                        url = cmd[2];
                                    }
                                }
                                if (qq < 0)
                                {
                                    qq = long.Parse(cmd[1]);
                                }
                                if (!MCServer.SkinHandler.checkPick(url))
                                {
                                    rep.reply("图片格式有误。必须是有效PNG图片,且为64*32或64*64比例。");
                                    break;
                                }
                                string         uuid     = DBHandler.me.getUserOwnedProfileUUID(qq);
                                string         pname    = DBHandler.me.getUserOwnedProfileName(qq);
                                string         oldtdata = DBHandler.me.getProfileUUIDTexture(uuid);
                                List <Texture> l        = new List <Texture>();
                                if (oldtdata != null)
                                {
                                    JObject oldtexture = (JObject)JsonConvert.DeserializeObject(oldtdata);
                                    if (oldtexture["textures"]["SKIN"] != null)
                                    {
                                        Dictionary <string, string> ddd = new Dictionary <string, string>();
                                        ddd.Add("model", "slim");
                                        Texture tt = new Texture(oldtexture["textures"]["SKIN"].Value <string>("url"), "SKIN", ddd);
                                        l.Add(tt);
                                    }
                                }
                                Dictionary <string, string> d = new Dictionary <string, string>();
                                Texture t = new Texture(url, "CAPE", d);
                                l.Add(t);
                                SkinHandler sh = new SkinHandler(DBHandler.me.getUserOwnedProfileUUID(rep.qq), DBHandler.me.getUserOwnedProfileName(rep.qq), l);
                                if (DBHandler.me.setProfileUUIDTexture(uuid, sh.ToString()))
                                {
                                    rep.reply("操作成功,已为玩家" + pname + "设置披风。\n" + url);
                                }
                                else
                                {
                                    rep.reply("操作失败");
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        catch (Exception err)
                        {
                            rep.reply("执行指令出错。请检查指令及其参数是否正确。如果确认操作无误,请将下面的信息转发给@鸡蛋");
                            rep.reply("未处理的异常:" + err.Message + "\n堆栈追踪:" + err.StackTrace);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MainHolder.broadcaster.BroadcastToAdminGroup("[Exception]\n这条消息可能意味着机器人发生了错误。它仍在继续运行,但可能不是很稳定。下面的信息用来帮助鸡蛋定位错误,管理不必在意。\n[私聊信息处理]" + err.Message + "\n\n堆栈跟踪:\n" + err.StackTrace);
            }
        }
Exemplo n.º 5
0
        public override async Task <IActionResult> Result()
        {
            var currentStep = Storage.GetCurrentStep(MsgId);

            //Switch to next step = currentStep + 1
            switch (currentStep + 1)
            {
                #region step 1
            case 1:
                Storage.AddOrUpdate(MsgId, 1, null);
                using (var petTypeDAO = new PetTypeDAO())
                {
                    var allPetTypes = (await petTypeDAO
                                       .ReadAll(false))
                                      .Select(x => x.Name)
                                      .ToArray();

                    return(Recv.Json(RespObj(RespType.QuickReplies,
                                             "Bạn muốn sản phẩm cho thú cưng nào ạ?", allPetTypes)));
                }

                #endregion
                #region Step 2
            case 2:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var petTypeDAO = new PetTypeDAO())
                    {
                        if (await(await petTypeDAO.ReadAll(false))
                            .Select(x => x.Name)
                            .AllAsync(x => x != MsgReply))
                        {
                            _isSkipValidation = true;
                            goto case 1;
                        }
                    }
                }

                Storage.AddOrUpdate(MsgId, 2, null);
                Storage.AddOrUpdate(MsgId, 1, MsgReply);
                return(Recv.Json(RespObj(RespType.QuickReplies, "Bạn muốn mua gì cho bé ạ?",
                                         new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" })));

                #endregion
                #region Step 3
            case 3:
                //Check if answer is valid
                // ReSharper disable once InvertIf
                if (!_isSkipValidation)
                {
                    if (new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 2;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                return(Recv.Json(RespObj(RespType.QuickReplies,
                                         "Bạn có thể cho mình biết mức giá bạn muốn tìm kiếm?",
                                         new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" })));

                #endregion
                #region Step 4
            case 4:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 3;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                //Find minimum and maximum price from step 3
                int minimumPrice, maximumPrice;

                switch (Storage[MsgId, 3])
                {
                case "<100000":
                    minimumPrice = 0;
                    maximumPrice = 99999;
                    break;

                case "100000 - 300000":
                    minimumPrice = 100000;
                    maximumPrice = 300000;
                    break;

                case ">300000 - 500000":
                    minimumPrice = 300001;
                    maximumPrice = 500000;
                    break;

                default:
                    minimumPrice = 500001;
                    maximumPrice = int.MaxValue;
                    break;
                }

                //Find product in step 2, for pet in step 1
                return(await MessengerProductListResult(GetProductType(), minimumPrice, maximumPrice));

                #endregion
                #region Step 5
            case 5:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var productDAO = new ProductDAO())
                        if (await productDAO.Read(MsgQuery, false) == null)
                        {
                            _isSkipValidation = true;
                            goto case 4;
                        }
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));

                #endregion
                #region Step 6
            case 6:
                if (!int.TryParse(MsgReply, out var res) || res < 1)
                {
                    return(Recv.Json(RespObj(RespType.Text,
                                             "Số lượng nhập vào không hợp lệ. Vui lòng nhập lại")));
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(MultiResp(RespObj(RespType.Text,
                                                   "Bạn có thể cho mình biết tên đăng nhập trên hệ thống Cutieshop được không ạ?\nNếu chưa có, bạn có thể gõ tên đăng nhập mới để chúng mình tạo tài khoản cho bạn"),
                                           RespUndo())));

                #endregion
                #region Step 7
            case 7:
                if (_isUndoRequested && Storage[MsgId, 6] == null)
                {
                    Storage.StepBack(MsgId);
                    return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));
                }

                //This step receive username first, then the email and address. So we need to keep the username to the storage for further uses, email will be used once in this step and can be queried by DAO easily in the future.
                //Checking null will prevent email from being overwritten to username in Storage

                if (Storage[MsgId, 6] == null)
                {
                    if (!MsgReply.IsPureAscii() || MsgReply.Contains(' '))
                    {
                        return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập tên đăng nhập hợp lệ (không dấu, khoảng cách)")));
                    }
                    Storage.AddOrUpdate(MsgId, 6, MsgReply);
                }

                using (var userDAO = new UserDAO())
                {
                    var user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    //If user is null, create a user, then ask customer their email
                    if (user == null)
                    {
                        Storage.AddOrUpdate(MsgId, 7, "userPassword", NewGuid().ToString().Substring(0, 6));
                        await userDAO.Create(new Auth
                        {
                            Username = Storage[MsgId, 6],
                            Password = Storage[MsgId, 7, "userPassword"]
                        });

                        await userDAO.CreateChild(new User
                        {
                            Username = Storage[MsgId, 6],
                            Email    = string.Empty,
                            Address  = string.Empty
                        });

                        await userDAO.Context.SaveChangesAsync();
                    }

                    user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    if (Storage[MsgId, 7, "fullName"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskFullName"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskFullName", "1");
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (MsgReply.Trim().Count(x => x == ' ') == 0)
                        {
                            return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập đầy đủ họ tên")));
                        }

                        Storage.AddOrUpdate(MsgId, 7, "fullName", MsgReply);
                    }

                    //If email is empty, ask for email
                    if (user.Email == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForEmail"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                        }

                        //Undo handling
                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        //Validate email
                        if (!MsgReply.IsEmail())
                        {
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Email không hợp lệ\nVui lòng nhập lại email"), RespUndo())));
                        }

                        user.Email = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    if (Storage[MsgId, 7, "phoneNo"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                        }

                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", null);

                            if (Storage[MsgId, 7, "isAskForEmail"] != null)
                            {
                                user.Email = "";
                                await userDAO.Context.SaveChangesAsync();

                                return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                            }

                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == "1")
                        {
                            Storage.AddOrUpdate(MsgId, 7, "phoneNo", MsgReply);
                        }
                    }

                    if (_isUndoRequested)
                    {
                        user.Address = "";
                        await userDAO.Context.SaveChangesAsync();

                        Storage.AddOrUpdate(MsgId, 7, "phoneNo", null);
                        Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", null);
                        return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                    }

                    if (user.Address == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForAddress"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", "1");
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin địa chỉ"), RespUndo())));
                        }

                        user.Address = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //Ready to jump into step 8 (if exists) after this
                    Storage.AddOrUpdate(MsgId, 7, null);

                    using (var orderDAO = new OnlineOrderProductDAO(userDAO.Context))
                    {
                        var orderId = NewGuid().ToString();
                        await orderDAO.Create(orderId, Storage[MsgId, 7, "fullName"], user.Address, "10000", user.City, Storage[MsgId, 7, "phoneNo"], user.Email, user.Username, 0);

                        await orderDAO.CreateChild(Storage[MsgId, 4], orderId, int.Parse(Storage[MsgId, 5]));

                        Product buyProd;
                        using (var prdctDAO = new ProductDAO())
                            buyProd = await prdctDAO.Read(Storage[MsgId, 4], false);

                        var mailPrdctTbl = _mailContent.BuyReq.TableRow
                                           .MultiReplace(("{0}", buyProd.Name), ("{1}", buyProd.Description), ("{2}", Storage[MsgId, 5]));

                        var mailBody = _mailContent.BuyReq.Body
                                       .MultiReplace(
                            ("{0}", user.Username),
                            ("{1}", mailPrdctTbl),
                            ("{2}", orderId),
                            ("{3}", (buyProd.Price * int.Parse(Storage[MsgId, 5])).ToString()));

                        MailUtils.Send(user.Email, _mailContent.BuyReq.Subject, mailBody);

                        var reply = $"Mail xác nhận đã được gửi đến {user.Email}. Hãy xác nhận qua mail để hoàn tất đặt hàng nhé!";

                        //Send temporary password if customer create new account
                        if (Storage[MsgId, 7, "userPassword"] != null)
                        {
                            reply = $"Password tạm thời của bạn là {Storage[MsgId, 7, "userPassword"]}. Bạn nên vào trang chủ để thay đổi mật khẩu mặc định\n" + reply;
                        }

                        //Remove data in storage
                        Storage.RemoveId(MsgId);
                        return(Recv.Json(RespObj(RespType.Text, reply)));
                    }
                }
                #endregion
            }

            Storage.RemoveId(MsgId);
            throw new UnhandledChatException();
        }