private void LockState(string guildId, string userId, bool isLocked)
        {
            var nstate = _uow.Db <NameState>()
                         .Where(p => p.DiscordServerId == guildId && p.FortniteUserId == userId)
                         .FirstOrDefault();

            if (nstate == null)
            {
                nstate = new NameState
                {
                    DiscordServerId = guildId,
                    FortniteUserId  = userId,
                    InQueue         = false,
                    LockName        = isLocked
                };
                _uow.Db <NameState>()
                .Add(nstate);
            }
            else
            {
                nstate.LockName = isLocked;
                _uow.Db <NameState>()
                .Update(nstate);
            }
            _uow.Commit();
        }
Example #2
0
        public void Set <T>(StylePropertyName styleName, T value, GUIState state = GUIState.Normal)
        {
            var nameState = new NameState {
                Name = styleName, State = state
            };
            var dict = this.GetDict <T>();

            dict[nameState] = value;
        }
Example #3
0
 private bool TrySetWritingNameWithMapping(string localName, string ns)
 {
     if (!localName.Equals("item") || !ns.Equals("item"))
     {
         return(false);
     }
     nameState = NameState.IsWritingNameWithMapping;
     return(true);
 }
        void PopNameState()
        {
            NameState ns = attic.Pop();

            instances        = ns.instances;
            protoDefinitions = ns.protoDefinitions;
            nodes            = ns.nodes;
            inPROTO          = ns.inPROTO;
        }
Example #5
0
 private static bool CheckAdmin(ApplicationEngine engine, NameState state)
 {
     if (engine.CheckWitnessInternal(state.Owner))
     {
         return(true);
     }
     if (state.Admin is null)
     {
         return(false);
     }
     return(engine.CheckWitnessInternal(state.Admin));
 }
Example #6
0
        private void WriteServerTypeAttribute()
        {
            string       str          = serverTypeValue;
            JsonDataType jsonDataType = dataType;
            NameState    _nameState   = this.nameState;

            (this).WriteStartElement("__type");
            (this).WriteValue(str);
            WriteEndElement();
            dataType                 = jsonDataType;
            this.nameState           = _nameState;
            wroteServerTypeAttribute = true;
        }
		void PushNameState()
		{
			NameState ns=new NameState();
			ns.instances=instances;
			ns.protoDefinitions=protoDefinitions;
			ns.nodes=nodes;
			ns.inPROTO=inPROTO;

			attic.Push(ns);

			protoDefinitions=new Dictionary<string, X3DPrototypeInstance>(ns.protoDefinitions);

			instances=new Dictionary<string, X3DNode>();

			nodes=new List<X3DNode>();
		}
Example #8
0
        public T Get <T>(GUIStyleName styleName, GUIState state = GUIState.Normal)
        {
            T   value;
            var nameState = new NameState {
                Name = styleName, State = state
            };
            var dict = GetDict <T>();

            //try get the style value of specified state
            if (dict.TryGetValue(nameState, out value))
            {
                return(value);
            }

            if (state != GUIState.Normal)
            {
                //try to get the style value of Normal state
                if (dict.TryGetValue(new NameState {
                    Name = styleName, State = GUIState.Normal
                }, out value))
                {
                    return(value);
                }
            }

            var defalutDict = Default.GetDict <T>();

            //try to get a default value of  specified state
            if (defalutDict.TryGetValue(nameState, out value))
            {
                return(value);
            }

            if (state != GUIState.Normal)
            {
                // try to get a default value of Normal state
                if (defalutDict.TryGetValue(new NameState {
                    Name = styleName, State = GUIState.Normal
                }, out value))
                {
                    return(value);
                }
            }

            Log.Warning("Cannot find the style<{0},{1}>", styleName.ToString(), state.ToString());
            return(default(T));//still not found, get defalut value of that types //FIXME may we should throw an exception instead?
        }
        void PushNameState()
        {
            NameState ns = new NameState();

            ns.instances        = instances;
            ns.protoDefinitions = protoDefinitions;
            ns.nodes            = nodes;
            ns.inPROTO          = inPROTO;

            attic.Push(ns);

            protoDefinitions = new Dictionary <string, X3DPrototypeInstance>(ns.protoDefinitions);

            instances = new Dictionary <string, X3DNode>();

            nodes = new List <X3DNode>();
        }
Example #10
0
        public T Get <T>(GUIStyleName styleName, GUIState state = GUIState.Normal)
        {
            T   value;
            var nameState = new NameState {
                Name = styleName, State = state
            };
            var dict = this.GetDict <T>();

            //try get the style value of specified state
            if (dict.TryGetValue(nameState, out value))
            {
                return(value);
            }

            if (state != GUIState.Normal)
            {
                //try to get the style value of Normal state
                if (dict.TryGetValue(new NameState {
                    Name = styleName, State = GUIState.Normal
                }, out value))
                {
                    return(value);
                }
            }

            var defalutDict = Default.GetDict <T>();

            //try to get a default value of  specified state
            if (defalutDict.TryGetValue(nameState, out value))
            {
                return(value);
            }

            if (state != GUIState.Normal)
            {
                // try to get a default value of Normal state
                if (defalutDict.TryGetValue(new NameState {
                    Name = styleName, State = GUIState.Normal
                }, out value))
                {
                    return(value);
                }
            }

            throw new InvalidOperationException($"Cannot find the style<{styleName},{state}>");
        }
Example #11
0
 public Task <NameState> AddOrGetNameStateAsync(FortniteUser user, string guildId)
 {
     return(Task.Run(() =>
     {
         var ns = _uow.Db <NameState>().Where(f => f.FortniteUserId == user.Id && f.DiscordServerId == guildId).FirstOrDefault();
         if (ns == null)
         {
             ns = new NameState()
             {
                 DiscordServerId = guildId,
                 FortniteUserId = user.Id
             };
             _uow.Db <NameState>().Add(ns);
             _uow.Commit();
         }
         return ns;
     }));
 }
Example #12
0
 public Task UnLinkEpicName()
 {
     return(Task.Run(async() =>
     {
         if (Context.DiscordUser.IsValidName)
         {
             NameState ns = Context.Repo.Db <NameState>().Where(p => p.DiscordServerId == Context.Guild.Id.ToString() && p.FortniteUserId == Context.DiscordUser.Id).FirstOrDefault();
             if (ns != null)
             {
                 ns.LockName = false;
                 Context.Repo.Db <NameState>().Update(ns);
                 Context.Repo.Commit();
             }
             Context.DiscordUser.EpicId = null;
             Context.DiscordUser.IsValidName = false;
             Context.DiscordUser.VerifiedProfile = false;
             Context.Repo.Db <FortniteUser>().Update(Context.DiscordUser);
             Context.Repo.Commit();
             try
             {
                 var user = (SocketGuildUser)Context.Message.Author;
                 List <Task> tlist = new List <Task>();
                 tlist.Add(user.ModifyAsync((o) =>
                 {
                     o.Nickname = null;
                 }));
                 var roles = await user.GetUserRolesAsync(GetLanguage());
                 foreach (var role in roles)
                 {
                     tlist.Add(user.RemoveRoleAsync(role.Value));
                 }
                 Task.WaitAll(tlist.ToArray());
             }
             catch (Exception)
             {
             }
             await ReplyEmbedAsync(Translate.GetBotTranslation(BotTranslationString.NameUnlinked, GetLanguage(), Context.PlayerName));
         }
         else
         {
             await ReplyEmbedAsync(Translate.GetBotTranslation(BotTranslationString.NameisNotLinked, GetLanguage()));
         }
     }));
 }
Example #13
0
        private Token Step(int character, NameState newState, NameTokenType newNameTokenType, bool create = false)
        {
            Token res = null;

            if (create)
            {
                res = new Token((int)_nameTokenType, Text.ToString());
                Text.Clear();
            }

            if (character != IgnoreChar)
            {
                Text.Append((char)character);
            }

            CurrentState   = newState;
            _nameTokenType = newNameTokenType;

            return(res);
        }
Example #14
0
        private uint Renew(ApplicationEngine engine, string name)
        {
            if (!nameRegex.IsMatch(name))
            {
                throw new ArgumentException(null, nameof(name));
            }
            string[] names = name.Split('.');
            if (names.Length != 2)
            {
                throw new ArgumentException(null, nameof(name));
            }
            engine.AddGas(GetPrice(engine.Snapshot));
            byte[]    hash  = GetKey(Utility.StrictUTF8.GetBytes(name));
            NameState state = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Token).Add(hash)).GetInteroperable <NameState>();

            engine.Snapshot.Delete(CreateStorageKey(Prefix_Expiration).AddBigEndian(state.Expiration).Add(hash));
            state.Expiration += OneYear;
            engine.Snapshot.Add(CreateStorageKey(Prefix_Expiration).AddBigEndian(state.Expiration).Add(hash), new StorageItem(new byte[] { 0 }));
            return(state.Expiration);
        }
Example #15
0
        private bool Register(ApplicationEngine engine, string name, UInt160 owner)
        {
            if (!nameRegex.IsMatch(name))
            {
                throw new ArgumentException(null, nameof(name));
            }
            string[] names = name.Split('.');
            if (names.Length != 2)
            {
                throw new ArgumentException(null, nameof(name));
            }
            if (!engine.CheckWitnessInternal(owner))
            {
                throw new InvalidOperationException();
            }
            byte[] hash = GetKey(Utility.StrictUTF8.GetBytes(name));
            if (engine.Snapshot.TryGet(CreateStorageKey(Prefix_Token).Add(hash)) is not null)
            {
                return(false);
            }
            StringList roots = engine.Snapshot[CreateStorageKey(Prefix_Roots)].GetInteroperable <StringList>();

            if (roots.BinarySearch(names[1]) < 0)
            {
                throw new InvalidOperationException();
            }
            engine.AddGas(GetPrice(engine.Snapshot));
            NameState state = new NameState
            {
                Owner       = owner,
                Name        = name,
                Description = "",
                Expiration  = (uint)(engine.PersistingBlock.Timestamp / 1000) + OneYear
            };

            Mint(engine, state);
            engine.Snapshot.Add(CreateStorageKey(Prefix_Expiration).AddBigEndian(state.Expiration).Add(hash), new StorageItem(new byte[] { 0 }));
            return(true);
        }
Example #16
0
        private void SetAdmin(ApplicationEngine engine, string name, UInt160 admin)
        {
            if (!nameRegex.IsMatch(name))
            {
                throw new ArgumentException(null, nameof(name));
            }
            string[] names = name.Split('.');
            if (names.Length != 2)
            {
                throw new ArgumentException(null, nameof(name));
            }
            if (admin != null && !engine.CheckWitnessInternal(admin))
            {
                throw new InvalidOperationException();
            }
            NameState state = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Token).Add(GetKey(Utility.StrictUTF8.GetBytes(name)))).GetInteroperable <NameState>();

            if (!engine.CheckWitnessInternal(state.Owner))
            {
                throw new InvalidOperationException();
            }
            state.Admin = admin;
        }
Example #17
0
        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            if (IsClosed)
            {
                ThrowClosed();
            }
            if (!string.IsNullOrEmpty(prefix))
            {
                if (IsWritingNameWithMapping && prefix == "xmlns")
                {
                    if (ns != null && ns != "http://www.w3.org/2000/xmlns/")
                    {
                        throw new ArgumentException("XmlPrefixBoundToNamespace");
                    }
                }
                else
                {
                    throw new ArgumentException("prefix", "JsonPrefixMustBeNullOrEmpty");
                }
            }
            else if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/" && localName != "xmlns")
            {
                prefix = "xmlns";
            }
            if (!string.IsNullOrEmpty(ns))
            {
                if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/")
                {
                    prefix = "xmlns";
                }
                else
                {
                    throw new ArgumentException("ns", "JsonNamespaceMustBeEmpty");
                }
            }
            if (localName == null)
            {
                throw new ArgumentException("localName");
            }
            if (localName.Length == 0)
            {
                throw new ArgumentException("localName", "JsonInvalidLocalNameEmpty");
            }
            if (nodeType != JsonNodeType.Element && !wroteServerTypeAttribute)
            {
                throw new XmlException("JsonAttributeMustHaveElement");
            }
            if (HasOpenAttribute)
            {
                throw new XmlException("JsonOpenAttributeMustBeClosedFirst");
            }

            if (prefix == "xmlns")
            {
                isWritingXmlnsAttribute = true;
            }
            else
            {
                switch (localName)
                {
                case "type":
                    if (dataType != JsonDataType.None)
                    {
                        throw new XmlException("JsonAttributeAlreadyWritten");
                    }

                    isWritingDataTypeAttribute = true;

                    break;

                case "__type":
                    if (serverTypeValue != null)
                    {
                        throw new XmlException("JsonAttributeAlreadyWritten");
                    }

                    if (dataType != JsonDataType.None && dataType != JsonDataType.Object)
                    {
                        throw new XmlException("JsonServerTypeSpecifiedForInvalidDataType");
                    }
                    isWritingServerTypeAttribute = true;
                    break;

                case "item":
                    if (WrittenNameWithMapping)
                    {
                        throw new XmlException("JsonAttributeAlreadyWritten");
                    }

                    if (!IsWritingNameWithMapping)
                    {
                        throw new XmlException("JsonEndElementNoOpenNodes");
                    }

                    nameState |= NameState.IsWritingNameAttribute;
                    break;

                default:
                    throw new ArgumentException("localName", "JsonUnexpectedAttributeLocalName");
                }
            }
        }
 private void WriteServerTypeAttribute()
 {
     string serverTypeValue = this.serverTypeValue;
     JsonDataType dataType = this.dataType;
     NameState nameState = this.nameState;
     base.WriteStartElement("__type");
     this.WriteValue(serverTypeValue);
     this.WriteEndElement();
     this.dataType = dataType;
     this.nameState = nameState;
     this.wroteServerTypeAttribute = true;
 }
        public override void WriteEndElement()
        {
            if (this.IsClosed)
            {
                ThrowClosed();
            }
            if (this.depth == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonEndElementNoOpenNodes")));
            }
            if (this.HasOpenAttribute)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonOpenAttributeMustBeClosedFirst", new object[] { "WriteEndElement" })));
            }
            this.endElementBuffer = false;
            JsonNodeType type = this.ExitScope();
            if (type == JsonNodeType.Collection)
            {
                this.nodeWriter.WriteText(0x5d);
                type = this.ExitScope();
            }
            else if (this.nodeType == JsonNodeType.QuotedText)
            {
                this.WriteJsonQuote();
            }
            else if (this.nodeType == JsonNodeType.Element)
            {
                if ((this.dataType == JsonDataType.None) && (this.serverTypeValue != null))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonMustSpecifyDataType", new object[] { "type", "object", "__type" })));
                }
                if (this.IsWritingNameWithMapping && !this.WrittenNameWithMapping)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonMustSpecifyDataType", new object[] { "item", string.Empty, "item" })));
                }
                if ((this.dataType == JsonDataType.None) || (this.dataType == JsonDataType.String))
                {
                    this.nodeWriter.WriteText(0x22);
                    this.nodeWriter.WriteText(0x22);
                }
            }
            if (this.depth != 0)
            {
                switch (type)
                {
                    case JsonNodeType.Element:
                        this.endElementBuffer = true;
                        break;

                    case JsonNodeType.Object:
                        this.nodeWriter.WriteText(0x7d);
                        if ((this.depth > 0) && (this.scopes[this.depth] == JsonNodeType.Element))
                        {
                            this.ExitScope();
                            this.endElementBuffer = true;
                        }
                        break;
                }
            }
            this.dataType = JsonDataType.None;
            this.nodeType = JsonNodeType.EndElement;
            this.nameState = NameState.None;
            this.wroteServerTypeAttribute = false;
        }
        /*
         * public async Task _HelpCmd()
         * {
         *  var cmds1 = "";
         *  var cmds2 = "";
         *  var cuser = this.Context.Guild.GetUser(this.Context.User.Id);
         *
         *  if (cuser.IsServerOwner() || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"__**Server Owner**__\n" +
         *              $"**f.lang <TR/EN/RU/ES/DE/PT/FR/NL>** :changes the native bot response language\n" +
         *              $"**f.pve.maproles.add** :manually adds none/Stonewood/Plankerton/CannyValley/TwinePeaks map roles\n" +
         *              $"**f.restrict.role <ROLE NAME>** :specific access to **f.pve...** commands for usage\n" +
         *              $"**f.restrict.role.remove <ROLE NAME>** :removes specific role from access list\n" +
         *              $"**f.restrict.role.clear** :everyone in discord can use **f.pve....** commands\n\n";
         *  }
         *
         *  if (cuser.GuildPermissions.Administrator || cuser.IsServerOwner() || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"  __**Administrator**__\n" +
         *              $"**f.state.decimals <ON/OFF>** :(default:on)controls the state of displaying decimal point of power level at current discord\n" +
         *              $"**f.state.autoremove <ON/OFF>** :(default:off)remove user request after FTN Power responds\n" +
         *              $"**f.stat** :how many user are there in discord server\n" +
         *              $"**f.helpme <MSG>** :sends private help message to FTN Power Developer\n" +
         *              $"**f.check.webhook** :checks webhook configurations for Mission Alert and Daily Llama\n" +
         *              $"**f.discord.info** :shows current discord's bot information\n\n";
         *  }
         *
         *  if (cuser.GuildPermissions.ManageNicknames || cuser.GuildPermissions.ManageRoles || cuser.Username == "Kesintisiz")
         *  {
         *      cmds1 += $"  __*needs ManageRoles + ManageNicknames Permisions to use(can be moderator)*__\n" +
         *              $"**f.user.mode @MENTION <PVE/PVP>** :changes mentioned user's game mode(like f.mode)\n" +
         *              $"**f.user.info @MENTION** :CHANGES mentioned user's information\n" +
         *              $"**f.user.name @MENTION <EPIC NAME>** :sets a name to mentioned user (like f.name)\n" +
         *              $"**f.user.update @MENTION** :adds user to queue for account power check (like f.update/f.up)\n\n";
         *  }
         *
         *  cmds2 += $"  __**PVE User**__\n" +
         *           $"**f.verify** :profile verification via FTN Power\n" +
         *           $"**f.mode <PVE/PVP>** :changes your game mode\n" +
         *           $"**f.pve** :current user's stats\n" +
         *           $"**f.pve <EPIC NAME>** :specified user stats\n" +
         *           $"**f.pve.survivors** :calculation of current squads resources\n" +
         *          $"**f.pr <EPIC NAME>** OR **f.pve.resources <EPIC NAME>** :specified user's resources\n" +
         *          $"**f.pr** OR **f.pve.resources** :list of current user's resources\n" +
         *          //  $"**f.pa** OR **f.pve.alerts** :list of current user's Alerts\n" +
         *          //    $"**f.pa <EPIC NAME>** OR **f.pve.alerts <EPIC NAME>** :specific user's Alerts\n" +
         *          $"**f.ps** OR **f.pve.missions** :pve mission alerts\n" +
         *          $"**f.pm** OR **f.pve.missions <vbuck/legendary/epic/legend survivor/legend perk/epic perk>** :filtered mission alerts\n" +
         *          $"**f.patch** :Fortnite Patch Notes\n" +
         *          $"**f.lock** :locks name changes in typed discord by FTN Power\n" +
         *          $"**f.unlock** :un-locks name changes in typed discord by FTN Power\n" +
         *          $"**f.link <EPIC NAME>** OR **f.name <EPIC NAME>** :sets/links a fortnite username(default:PVE)\n" +
         *          $"**f.unlink** :removes your Epic Name from bot\n" +
         *          $"**f.up** OR **f.update** :updates user's current GameMode status (according to discord nickname)\n" +
         *          $"**f.name.tag <LEFT/RIGHT>** :(default:LEFT)shows user power at the end of name or beginning of the name\n" +
         *          $"**f.donate** OR **f.info** :donation and help links\n" +
         *          $"**f.top** :shows current discord's Fortnite pve top list\n" +
         *          $"**f.top.global** :shows global Fortnite pve top list (which discord uses FTN Power)\n\n";
         *
         *  cmds2 += $"  __**PVP User**__\n" +
         *           $"**f.pvp.name <EPIC NAME>** :sets/links a fortnite username(PVP) (and adds to queue)\n" +
         *           $"**f.pvp.up** OR **f.up** :updates user's current GameMode status (according to discord nickname)\n" +
         *           $"**f.pvp** :current user's battle royale match stats\n" +
         *           $"**f.pvp <EPIC NAME>** :specified user's battle royale match stats\n\n";
         *
         *  if (cmds1 != "")
         *  {
         *      await this.ReplyEmbedAsync(cmds1, "FTN Power Commands");
         *  }
         *  if (cmds2 != "")
         *  {
         *      await this.ReplyEmbedAsync(cmds2, "FTN Power Commands");
         *  }
         *
         *  return;
         * }
         */
        public Task _NameChange(string mention, [Remainder] string newName)
        {
            return(Task.Run(async() =>
            {
                if (string.IsNullOrWhiteSpace(newName))
                {
                    return;
                }

                SocketGuildUser cuser = null;
                bool anotherUser = false;
                if (Context.Message.MentionedUsers.Count == 1 && !string.IsNullOrWhiteSpace(mention))
                {
                    anotherUser = true;
                    var u = Context.Message.MentionedUsers.First();

                    cuser = Context.Guild.GetUser(u.Id);
                }
                else
                {
                    cuser = Context.Guild.GetUser(Context.User.Id);
                }
                if (cuser.IsBot)
                {
                    return;
                }
                newName = newName.TrimStart('<').TrimEnd('>');
                if (!newName.ValidName())
                {
                    await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.ContainsNotAllowed, GetLanguage(), cuser.Mention));
                    Log.Write(Serilog.Events.LogEventLevel.Error, "user {UserName}({UserId}) in guild {GuildId} has no valid n-length, current is {UserNameLength} Text:'{WrongText}'", cuser.Username, cuser.Id, cuser.Guild.Id, newName.Length, newName);
                    return;
                }

                var uid = cuser.Id.ToString();
                var guid = cuser.Guild.Id.ToString();
                var usr = Context.DiscordUser;
                if (anotherUser)
                {
                    usr = Context.Repo.Db <FortniteUser>()
                          .GetById(uid);
                }
                if (usr == null)
                {
                    usr = await Context.Repo.User.AddOrGetUserAsync(uid, guid, GameUserMode.PVE);
                }
                NameState ns = usr.NameStates.FirstOrDefault(p => p.FortniteUserId == uid && p.DiscordServerId == guid);
                if (ns == null)
                {
                    ns = await Context.Repo.User.AddOrGetNameStateAsync(usr, guid);
                }
                else if (ns.LockName)
                {
                    await ReplyEmbedErrorAsync(ToTranslate(BotTranslationString.YourNameIsLocked, GetLanguage(), cuser.Mention));
                    return;
                }
                var pstate = await CheckUserPriority(new TimeSpan(0, 0, 10, 0), usr, cuser, ns);
                if (pstate.Value == null)
                {
                    return;
                }

                IUserMessage msg = null;
                var checkVerificationOfNewName = Api.GetUserIdByName(newName);
                if (checkVerificationOfNewName.Value == null)
                {
                    msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                    await msg?.SetErrorAsync();
                    return;
                }

                if (Context.Repo.Db <FortniteUser>().All().Any(f => f.VerifiedProfile && f.IsValidName && f.EpicId == checkVerificationOfNewName.Value.id && f.Id != uid))
                {
                    await ReplyEmbedErrorAsync($"you can not take {checkVerificationOfNewName.Value.displayName} Username, it is __already verified__ by account owner.");
                    return;
                }
                bool profileNotFoundButNameExists = false;
                if (Context.GuildConfig.Owner.DefaultGameMode == GameUserMode.PVE && Context.DiscordUser.GameUserMode == GameUserMode.NULL ||
                    Context.DiscordUser.GameUserMode == GameUserMode.PVE)
                {
                    Context.DiscordUser.VerifiedProfile = false;
                    Context.Repo.Db <FortniteUser>().Update(Context.DiscordUser);
                    Context.Repo.Commit();
                    msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                    var mapUser = await Api.GetPVEProfileByName(checkVerificationOfNewName.Value.displayName);
                    if (mapUser.Value != null)
                    {
                        await Context.Repo.UpdateDatabasePVEProfileAsync(mapUser, cuser, msg, Context.DiscordUser.NameTag, ns.LockName, Context.GuildConfig.Owner.PVEDecimalState);
                        return;
                    }
                    else
                    {
                        profileNotFoundButNameExists = checkVerificationOfNewName.Value != null;
                    }
                }
                else if (Context.GuildConfig.Owner.DefaultGameMode == GameUserMode.PVP_WIN_ALL && Context.DiscordUser.GameUserMode == GameUserMode.NULL ||
                         Context.DiscordUser.GameUserMode == GameUserMode.PVP_WIN_ALL)
                {
                    var mapUserPVP = await Api.GetPVPProfileByName(checkVerificationOfNewName.Value.displayName);
                    if (mapUserPVP.Value != null)
                    {
                        if (mapUserPVP.Value.IsPrivate)
                        {
                            msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.PvpProfilIsNotPublic, GetLanguage(), cuser.Mention), pstate);
                        }
                        else
                        {
                            Context.DiscordUser.VerifiedProfile = false;
                            Context.Repo.Db <FortniteUser>().Update(Context.DiscordUser);
                            Context.Repo.Commit();
                            msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.NameWillBeUpdated, GetLanguage(), cuser.Mention, newName), pstate);
                            await Context.Repo.UpdateDatabasePVPProfileAsync(mapUserPVP, cuser, msg, Context.DiscordUser.NameTag, ns.LockName);
                            return;
                        }
                    }
                    else
                    {
                        profileNotFoundButNameExists = checkVerificationOfNewName.Value != null;
                    }
                }
                if (profileNotFoundButNameExists)
                {
                    await msg?.SetConsolePlayerAsync();
                }
                else
                {
                    await msg?.SetErrorAsync();
                }
            }));
        }
 public override void WriteStartAttribute(string prefix, string localName, string ns)
 {
     if (this.IsClosed)
     {
         ThrowClosed();
     }
     if (!string.IsNullOrEmpty(prefix))
     {
         if (!this.IsWritingNameWithMapping || (prefix != "xmlns"))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("prefix", System.Runtime.Serialization.SR.GetString("JsonPrefixMustBeNullOrEmpty", new object[] { prefix }));
         }
         if ((ns != null) && (ns != "http://www.w3.org/2000/xmlns/"))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("XmlPrefixBoundToNamespace", new object[] { "xmlns", "http://www.w3.org/2000/xmlns/", ns }), "ns"));
         }
     }
     else if ((this.IsWritingNameWithMapping && (ns == "http://www.w3.org/2000/xmlns/")) && (localName != "xmlns"))
     {
         prefix = "xmlns";
     }
     if (!string.IsNullOrEmpty(ns))
     {
         if (!this.IsWritingNameWithMapping || (ns != "http://www.w3.org/2000/xmlns/"))
         {
             if ((!string.IsNullOrEmpty(prefix) || (localName != "xmlns")) || (ns != "http://www.w3.org/2000/xmlns/"))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", System.Runtime.Serialization.SR.GetString("JsonNamespaceMustBeEmpty", new object[] { ns }));
             }
             prefix = "xmlns";
             this.isWritingXmlnsAttributeDefaultNs = true;
         }
         else
         {
             prefix = "xmlns";
         }
     }
     if (localName == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
     }
     if (localName.Length == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", System.Runtime.Serialization.SR.GetString("JsonInvalidLocalNameEmpty"));
     }
     if ((this.nodeType != JsonNodeType.Element) && !this.wroteServerTypeAttribute)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonAttributeMustHaveElement")));
     }
     if (this.HasOpenAttribute)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonOpenAttributeMustBeClosedFirst", new object[] { "WriteStartAttribute" })));
     }
     if (prefix == "xmlns")
     {
         this.isWritingXmlnsAttribute = true;
     }
     else if (localName == "type")
     {
         if (this.dataType != JsonDataType.None)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonAttributeAlreadyWritten", new object[] { "type" })));
         }
         this.isWritingDataTypeAttribute = true;
     }
     else if (localName == "__type")
     {
         if (this.serverTypeValue != null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonAttributeAlreadyWritten", new object[] { "__type" })));
         }
         if ((this.dataType != JsonDataType.None) && (this.dataType != JsonDataType.Object))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonServerTypeSpecifiedForInvalidDataType", new object[] { "__type", "type", this.dataType.ToString().ToLowerInvariant(), "object" })));
         }
         this.isWritingServerTypeAttribute = true;
     }
     else
     {
         if (localName != "item")
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", System.Runtime.Serialization.SR.GetString("JsonUnexpectedAttributeLocalName", new object[] { localName }));
         }
         if (this.WrittenNameWithMapping)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonAttributeAlreadyWritten", new object[] { "item" })));
         }
         if (!this.IsWritingNameWithMapping)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonEndElementNoOpenNodes")));
         }
         this.nameState |= NameState.IsWritingNameAttribute;
     }
 }
        public async Task <KeyValuePair <bool, PriorityTable> > CheckUserPriority(TimeSpan?requestSecondLimit, FortniteUser usr, IGuildUser cuser, NameState ns = null, DateTimeOffset?lastMassUpdate = null)
        {
            if (!requestSecondLimit.HasValue)
            {
                requestSecondLimit = new TimeSpan(0, 0, 10, 0);
            }
            TimeSpan reminder = DateTimeOffset.UtcNow - usr.LastUpDateTime;

            if (lastMassUpdate.HasValue)
            {
                reminder = DateTimeOffset.UtcNow - lastMassUpdate.Value;
            }
            var pStateResult = Context.Repo.Priority.IsPartnerGuild(cuser.Guild.Id);

            if (pStateResult.Key == false)
            {
                pStateResult = Context.Repo.Priority.IsPartnerUser(cuser.Id);
            }
            if (pStateResult.Key && pStateResult.Value.GetPriorityState() != PriorityState.Normal)
            {
                if (!lastMassUpdate.HasValue)
                {
                    requestSecondLimit = new TimeSpan(0, 0, 0, 1);
                }
            }
            if (reminder.TotalSeconds > requestSecondLimit.Value.TotalSeconds)
            {
                return(pStateResult);
            }
            else
            {
                var ts = requestSecondLimit.Value.Add(new TimeSpan(0, 0, 0, 1)) - reminder;
                await ReplyEmbedErrorAsync(ToTranslate(BotTranslationString.YouHaveToWaitTime1, GetLanguage(), cuser.Mention,
                                                       ts.Hours, ts.Minutes, ts.Seconds));

                return(new KeyValuePair <bool, PriorityTable>(false, null));
            }
        }
        public Task _UpdateName(string mention)
        {
            return(Task.Run(async() =>
            {
                Regex r = new Regex("<@!?(\\d+)>", RegexOptions.Singleline);
                var m = r.Match(mention);
                if (m.Success)
                {
                    RestGuildUser cuser = Context.DiscordRestApi.GetGuildUserAsync(Context.Guild.Id, m.Groups[1].Value.ToUlong()).Result;
                    if (cuser == null)
                    {
                        return;
                    }
                    if (cuser.IsServerOwner())
                    {
                        await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.CanNotUpdateDiscordOwner, GetLanguage(), cuser.Mention));
                        return;
                    }

                    var uid = cuser.Id.ToString();
                    {
                        var usr = Context.Repo.Db <FortniteUser>()
                                  .GetById(uid);
                        NameState ns = usr.NameStates.FirstOrDefault(p => p.FortniteUserId == uid && p.DiscordServerId == Context.Guild.Id.ToString());
                        if (usr == null)
                        {
                            await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.FirstlyUseAnotherCmd1, GetLanguage(), cuser.Mention));
                            return;
                        }
                        else if (ns == null)
                        {
                            ns = await Context.Repo.User.AddOrGetNameStateAsync(usr, Context.Guild.Id.ToString());
                        }

                        if (!usr.IsValidName)
                        {
                            await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.FirstlyUseAnotherCmd2, GetLanguage(), cuser.Mention));

                            return;
                        }
                        var pstate = await CheckUserPriority(new TimeSpan(0, 0, 10, 0), usr, cuser, ns);
                        if (pstate.Value == null)
                        {
                            return;
                        }
                        var msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.UpdateRequestReceived, GetLanguage(), mention), pstate);
                        if (!string.IsNullOrWhiteSpace(usr.EpicId))
                        {
                            if (usr.GameUserMode == GameUserMode.PVE)
                            {
                                FortnitePVEProfile fortniteProfile = Context.Repo.Db <FortnitePVEProfile>()
                                                                     .All()
                                                                     .FirstOrDefault(f => f.EpicId == usr.EpicId);
                                await SetNewNameViaMode <FortnitePVEProfile>(cuser, usr, msg, fortniteProfile);
                            }
                            else
                            {
                                FortnitePVPProfile fortniteProfile = Context.Repo.Db <FortnitePVPProfile>()
                                                                     .All()
                                                                     .FirstOrDefault(f => f.EpicId == usr.EpicId);
                                await SetNewNameViaMode <FortnitePVPProfile>(cuser, usr, msg, fortniteProfile);
                            }
                        }
                        else
                        {
                            await msg.SetErrorAsync();
                        }
                    }
                }
                else
                {
                    ReplyEmbedErrorAsync($"invalid user mention.").Wait();
                }
            }));
        }
Example #24
0
 private void WriteServerTypeAttribute()
 {
     string str = serverTypeValue;
     JsonDataType jsonDataType = dataType;
     NameState _nameState = this.nameState;
     (this).WriteStartElement("__type");
     (this).WriteValue(str);
     WriteEndElement();
     dataType = jsonDataType;
     this.nameState = _nameState;
     wroteServerTypeAttribute = true;
 }
Example #25
0
        public override void WriteEndAttribute()
        {
            if (IsClosed)
            {
                ThrowClosed();
            }

            if (!HasOpenAttribute)
            {
                throw new XmlException("JsonNoMatchingStartAttribute");
            }

            if (isWritingDataTypeAttribute)
            {
                switch (attributeText)
                {
                case "number":
                    ThrowIfServerTypeWritten("number");
                    dataType = JsonDataType.Number;
                    break;

                case "string":
                    ThrowIfServerTypeWritten("string");
                    dataType = JsonDataType.String;
                    break;

                case "array":
                    ThrowIfServerTypeWritten("array");
                    dataType = JsonDataType.Array;
                    break;

                case "object":
                    dataType = JsonDataType.Object;
                    break;

                case "null":
                    ThrowIfServerTypeWritten("null");
                    dataType = JsonDataType.Null;
                    break;

                case "boolean":
                    ThrowIfServerTypeWritten("boolean");
                    dataType = JsonDataType.Boolean;
                    break;

                default:
                    throw new XmlException("JsonUnexpectedAttributeValue");
                }
                attributeText = null;

                isWritingDataTypeAttribute = false;

                if (IsWritingNameWithMapping && !WrittenNameWithMapping)
                {
                    return;
                }

                WriteDataTypeServerType();
            }
            else if (isWritingServerTypeAttribute)
            {
                serverTypeValue = attributeText;

                attributeText = null;

                isWritingServerTypeAttribute = false;

                if (IsWritingNameWithMapping && !WrittenNameWithMapping || dataType != JsonDataType.Object)
                {
                    return;
                }

                WriteServerTypeAttribute();
            }
            else if (IsWritingNameAttribute)
            {
                WriteJsonElementName(attributeText);
                attributeText = null;
                nameState     = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
                WriteDataTypeServerType();
            }
            else
            {
                if (!isWritingXmlnsAttribute)
                {
                    return;
                }
                attributeText           = null;
                isWritingXmlnsAttribute = false;
            }
        }
        public override void WriteEndAttribute()
        {
            if (this.IsClosed)
            {
                ThrowClosed();
            }
            if (!this.HasOpenAttribute)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonNoMatchingStartAttribute")));
            }
            if (!this.isWritingDataTypeAttribute)
            {
                if (this.isWritingServerTypeAttribute)
                {
                    this.serverTypeValue = this.attributeText;
                    this.attributeText = null;
                    this.isWritingServerTypeAttribute = false;
                    if ((!this.IsWritingNameWithMapping || this.WrittenNameWithMapping) && (this.dataType == JsonDataType.Object))
                    {
                        this.WriteServerTypeAttribute();
                    }
                }
                else if (this.IsWritingNameAttribute)
                {
                    this.WriteJsonElementName(this.attributeText);
                    this.attributeText = null;
                    this.nameState = NameState.WrittenNameWithMapping | NameState.IsWritingNameWithMapping;
                    this.WriteDataTypeServerType();
                }
                else if (this.isWritingXmlnsAttribute)
                {
                    if (!string.IsNullOrEmpty(this.attributeText) && this.isWritingXmlnsAttributeDefaultNs)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", System.Runtime.Serialization.SR.GetString("JsonNamespaceMustBeEmpty", new object[] { this.attributeText }));
                    }
                    this.attributeText = null;
                    this.isWritingXmlnsAttribute = false;
                    this.isWritingXmlnsAttributeDefaultNs = false;
                }
            }
            else
            {
                switch (this.attributeText)
                {
                    case "number":
                        this.ThrowIfServerTypeWritten("number");
                        this.dataType = JsonDataType.Number;
                        break;

                    case "string":
                        this.ThrowIfServerTypeWritten("string");
                        this.dataType = JsonDataType.String;
                        break;

                    case "array":
                        this.ThrowIfServerTypeWritten("array");
                        this.dataType = JsonDataType.Array;
                        break;

                    case "object":
                        this.dataType = JsonDataType.Object;
                        break;

                    case "null":
                        this.ThrowIfServerTypeWritten("null");
                        this.dataType = JsonDataType.Null;
                        break;

                    case "boolean":
                        this.ThrowIfServerTypeWritten("boolean");
                        this.dataType = JsonDataType.Boolean;
                        break;

                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonUnexpectedAttributeValue", new object[] { this.attributeText })));
                }
                this.attributeText = null;
                this.isWritingDataTypeAttribute = false;
                if (!this.IsWritingNameWithMapping || this.WrittenNameWithMapping)
                {
                    this.WriteDataTypeServerType();
                }
            }
        }
Example #27
0
        public override void WriteEndElement()
        {
            if (IsClosed)
            {
                ThrowClosed();
            }
            if (depth == 0)
            {
                throw new XmlException("JsonEndElementNoOpenNodes");
            }
            if (HasOpenAttribute)
            {
                throw new XmlException("JsonOpenAttributeMustBeClosedFirst");
            }

            endElementBuffer = false;

            JsonNodeType jsonNodeType = ExitScope();

            if (jsonNodeType == JsonNodeType.Collection)
            {
                //nodeWriter.WriteEndArray();
                nodeWriter.Write("]");
                jsonNodeType = ExitScope();
            }
            else if (nodeType == JsonNodeType.QuotedText)
            {
                WriteJsonQuote();
            }
            else if (nodeType == JsonNodeType.Element)
            {
                if (dataType == JsonDataType.None && serverTypeValue != null)
                {
                    throw new XmlException("JsonMustSpecifyDataType");
                }
                if (IsWritingNameWithMapping && !WrittenNameWithMapping)
                {
                    throw new XmlException("JsonMustSpecifyDataType");
                }
                if (dataType == JsonDataType.None || dataType == JsonDataType.String)
                {
                    nodeWriter.Write(@"""");
                    nodeWriter.Write(@"""");
                }
            }
            if (depth != 0)
            {
                if (jsonNodeType == JsonNodeType.Element)
                {
                    endElementBuffer = true;
                }
                else if (jsonNodeType == JsonNodeType.Object)
                {
                    nodeWriter.Write("}");

                    if (depth > 0 && scopes[depth] == JsonNodeType.Element)
                    {
                        ExitScope();
                        endElementBuffer = true;
                    }
                }
            }
            dataType  = JsonDataType.None;
            nodeType  = JsonNodeType.EndElement;
            nameState = NameState.None;
            wroteServerTypeAttribute = false;
        }
Example #28
0
        public override void WriteEndElement()
        {
            if (IsClosed)
            {
                ThrowClosed();
            }

            if (_depth == 0)
            {
                throw new XmlException(SR.JsonEndElementNoOpenNodes);
            }
            if (HasOpenAttribute)
            {
                throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteEndElement"));
            }

            _endElementBuffer = false;

            JsonNodeType token = ExitScope();
            if (token == JsonNodeType.Collection)
            {
                _indentLevel--;
                if (_indent)
                {
                    if (_nodeType == JsonNodeType.Element)
                    {
                        _nodeWriter.WriteText(WHITESPACE);
                    }
                    else
                    {
                        WriteNewLine();
                        WriteIndent();
                    }
                }
                _nodeWriter.WriteText(JsonGlobals.EndCollectionChar);
                token = ExitScope();
            }
            else if (_nodeType == JsonNodeType.QuotedText)
            {
                // For writing "
                WriteJsonQuote();
            }
            else if (_nodeType == JsonNodeType.Element)
            {
                if ((_dataType == JsonDataType.None) && (_serverTypeValue != null))
                {
                    throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString));
                }

                if (IsWritingNameWithMapping && !WrittenNameWithMapping)
                {
                    // Ending </item> without writing item attribute
                    // Not providing a better error message because localization deadline has passed.
                    throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString));
                }

                // the element is empty, it does not have any content, 
                if ((_dataType == JsonDataType.None) ||
                    (_dataType == JsonDataType.String))
                {
                    _nodeWriter.WriteText(JsonGlobals.QuoteChar);
                    _nodeWriter.WriteText(JsonGlobals.QuoteChar);
                }
            }
            else
            {
                // Assert on only StandaloneText and EndElement because preceding if
                //    conditions take care of checking for QuotedText and Element.
                Fx.Assert((_nodeType == JsonNodeType.StandaloneText) || (_nodeType == JsonNodeType.EndElement),
                    "nodeType has invalid value " + _nodeType + ". Expected it to be QuotedText, Element, StandaloneText, or EndElement.");
            }
            if (_depth != 0)
            {
                if (token == JsonNodeType.Element)
                {
                    _endElementBuffer = true;
                }
                else if (token == JsonNodeType.Object)
                {
                    _indentLevel--;
                    if (_indent)
                    {
                        if (_nodeType == JsonNodeType.Element)
                        {
                            _nodeWriter.WriteText(WHITESPACE);
                        }
                        else
                        {
                            WriteNewLine();
                            WriteIndent();
                        }
                    }
                    _nodeWriter.WriteText(JsonGlobals.EndObjectChar);
                    if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element)
                    {
                        ExitScope();
                        _endElementBuffer = true;
                    }
                }
            }

            _dataType = JsonDataType.None;
            _nodeType = JsonNodeType.EndElement;
            _nameState = NameState.None;
            _wroteServerTypeAttribute = false;
        }
Example #29
0
 private void WriteServerTypeAttribute()
 {
     string value = _serverTypeValue;
     JsonDataType oldDataType = _dataType;
     NameState oldNameState = _nameState;
     WriteStartElement(JsonGlobals.serverTypeString);
     WriteValue(value);
     WriteEndElement();
     _dataType = oldDataType;
     _nameState = oldNameState;
     _wroteServerTypeAttribute = true;
 }
Example #30
0
        public override void WriteEndAttribute()
        {
            if (IsClosed)
            {
                ThrowClosed();
            }
            if (!HasOpenAttribute)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new XmlException(SR.GetString(SR.JsonNoMatchingStartAttribute)));
            }

            Fx.Assert(!(isWritingDataTypeAttribute && isWritingServerTypeAttribute),
                "Can not write type attribute and __type attribute at the same time.");

            if (isWritingDataTypeAttribute)
            {
                switch (attributeText)
                {
                    case JsonGlobals.numberString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.numberString);
                            dataType = JsonDataType.Number;
                            break;
                        }
                    case JsonGlobals.stringString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.stringString);
                            dataType = JsonDataType.String;
                            break;
                        }
                    case JsonGlobals.arrayString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.arrayString);
                            dataType = JsonDataType.Array;
                            break;
                        }
                    case JsonGlobals.objectString:
                        {
                            dataType = JsonDataType.Object;
                            break;
                        }
                    case JsonGlobals.nullString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.nullString);
                            dataType = JsonDataType.Null;
                            break;
                        }
                    case JsonGlobals.booleanString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.booleanString);
                            dataType = JsonDataType.Boolean;
                            break;
                        }
                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new XmlException(SR.GetString(SR.JsonUnexpectedAttributeValue, attributeText)));
                }

                attributeText = null;
                isWritingDataTypeAttribute = false;

                if (!IsWritingNameWithMapping || WrittenNameWithMapping)
                {
                    WriteDataTypeServerType();
                }
            }
            else if (isWritingServerTypeAttribute)
            {
                serverTypeValue = attributeText;
                attributeText = null;
                isWritingServerTypeAttribute = false;

                // we are writing __type after type="object" (enforced by WSE)
                if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && dataType == JsonDataType.Object)
                {
                    WriteServerTypeAttribute();
                }
            }
            else if (IsWritingNameAttribute)
            {
                WriteJsonElementName(attributeText);
                attributeText = null;
                nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
                WriteDataTypeServerType();
            }
            else if (isWritingXmlnsAttribute)
            {
                if (!string.IsNullOrEmpty(attributeText) && isWritingXmlnsAttributeDefaultNs)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", SR.GetString(SR.JsonNamespaceMustBeEmpty, attributeText));
                }

                attributeText = null;
                isWritingXmlnsAttribute = false;
                isWritingXmlnsAttributeDefaultNs = false;
            }
        }
Example #31
0
 protected override void OnTransferred(ApplicationEngine engine, UInt160 from, NameState token)
 {
     token.Admin = null;
 }
Example #32
0
        public override void WriteEndAttribute()
        {
            if (IsClosed)
                ThrowClosed();

            if (!HasOpenAttribute)
                throw new XmlException("JsonNoMatchingStartAttribute");

            if (isWritingDataTypeAttribute)
            {
                switch (attributeText)
                {
                    case "number":
                        ThrowIfServerTypeWritten("number");
                        dataType = JsonDataType.Number;
                        break;
                    case "string":
                        ThrowIfServerTypeWritten("string");
                        dataType = JsonDataType.String;
                        break;
                    case "array":
                        ThrowIfServerTypeWritten("array");
                        dataType = JsonDataType.Array;
                        break;
                    case "object":
                        dataType = JsonDataType.Object;
                        break;
                    case "null":
                        ThrowIfServerTypeWritten("null");
                        dataType = JsonDataType.Null;
                        break;
                    case "boolean":
                        ThrowIfServerTypeWritten("boolean");
                        dataType = JsonDataType.Boolean;
                        break;
                    default:
                        throw new XmlException("JsonUnexpectedAttributeValue");
                }
                attributeText = null;

                isWritingDataTypeAttribute = false;

                if (IsWritingNameWithMapping && !WrittenNameWithMapping)
                    return;

                WriteDataTypeServerType();
            }
            else if (isWritingServerTypeAttribute)
            {
                serverTypeValue = attributeText;

                attributeText = null;

                isWritingServerTypeAttribute = false;

                if (IsWritingNameWithMapping && !WrittenNameWithMapping || dataType != JsonDataType.Object)
                    return;

                WriteServerTypeAttribute();
            }
            else if (IsWritingNameAttribute)
            {
                WriteJsonElementName(attributeText);
                attributeText = null;
                nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
                WriteDataTypeServerType();
            }
            else
            {
                if (!isWritingXmlnsAttribute)
                    return;
                attributeText = null;
                isWritingXmlnsAttribute = false;
            }
        }
Example #33
0
 private bool TrySetWritingNameWithMapping(string localName, string ns)
 {
     if (localName.Equals(JsonGlobals.itemString) && ns.Equals(JsonGlobals.itemString))
     {
         _nameState = NameState.IsWritingNameWithMapping;
         return true;
     }
     return false;
 }
Example #34
0
        public override void WriteEndElement()
        {
            if (IsClosed)
                ThrowClosed();
            if (depth == 0)
                throw new XmlException("JsonEndElementNoOpenNodes");
            if (HasOpenAttribute)
                throw new XmlException("JsonOpenAttributeMustBeClosedFirst");

            endElementBuffer = false;

            JsonNodeType jsonNodeType = ExitScope();

            if (jsonNodeType == JsonNodeType.Collection)
            {
                //nodeWriter.WriteEndArray();
                nodeWriter.Write("]");
                jsonNodeType = ExitScope();
            }
            else if (nodeType == JsonNodeType.QuotedText)
                WriteJsonQuote();
            else if (nodeType == JsonNodeType.Element)
            {
                if (dataType == JsonDataType.None && serverTypeValue != null)
                    throw new XmlException("JsonMustSpecifyDataType");
                if (IsWritingNameWithMapping && !WrittenNameWithMapping)
                    throw new XmlException("JsonMustSpecifyDataType");
                if (dataType == JsonDataType.None || dataType == JsonDataType.String)
                {
                    nodeWriter.Write(@"""");
                    nodeWriter.Write(@"""");
                }
            }
            if (depth != 0)
            {
                if (jsonNodeType == JsonNodeType.Element)
                    endElementBuffer = true;
                else if (jsonNodeType == JsonNodeType.Object)
                {
                    nodeWriter.Write("}");

                    if (depth > 0 && scopes[depth] == JsonNodeType.Element)
                    {
                        ExitScope();
                        endElementBuffer = true;
                    }
                }
            }
            dataType = JsonDataType.None;
            nodeType = JsonNodeType.EndElement;
            nameState = NameState.None;
            wroteServerTypeAttribute = false;
        }
Example #35
0
        public override void WriteEndAttribute()
        {
            if (IsClosed)
            {
                ThrowClosed();
            }
            if (!HasOpenAttribute)
            {
                throw new XmlException(SR.JsonNoMatchingStartAttribute);
            }

            Fx.Assert(!(_isWritingDataTypeAttribute && _isWritingServerTypeAttribute),
                "Can not write type attribute and __type attribute at the same time.");

            if (_isWritingDataTypeAttribute)
            {
                switch (_attributeText)
                {
                    case JsonGlobals.numberString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.numberString);
                            _dataType = JsonDataType.Number;
                            break;
                        }
                    case JsonGlobals.stringString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.stringString);
                            _dataType = JsonDataType.String;
                            break;
                        }
                    case JsonGlobals.arrayString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.arrayString);
                            _dataType = JsonDataType.Array;
                            break;
                        }
                    case JsonGlobals.objectString:
                        {
                            _dataType = JsonDataType.Object;
                            break;
                        }
                    case JsonGlobals.nullString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.nullString);
                            _dataType = JsonDataType.Null;
                            break;
                        }
                    case JsonGlobals.booleanString:
                        {
                            ThrowIfServerTypeWritten(JsonGlobals.booleanString);
                            _dataType = JsonDataType.Boolean;
                            break;
                        }
                    default:
                        throw new XmlException(SR.Format(SR.JsonUnexpectedAttributeValue, _attributeText));
                }

                _attributeText = null;
                _isWritingDataTypeAttribute = false;

                if (!IsWritingNameWithMapping || WrittenNameWithMapping)
                {
                    WriteDataTypeServerType();
                }
            }
            else if (_isWritingServerTypeAttribute)
            {
                _serverTypeValue = _attributeText;
                _attributeText = null;
                _isWritingServerTypeAttribute = false;

                // we are writing __type after type="object" (enforced by WSE)
                if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && _dataType == JsonDataType.Object)
                {
                    WriteServerTypeAttribute();
                }
            }
            else if (IsWritingNameAttribute)
            {
                WriteJsonElementName(_attributeText);
                _attributeText = null;
                _nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
                WriteDataTypeServerType();
            }
            else if (_isWritingXmlnsAttribute)
            {
                if (!string.IsNullOrEmpty(_attributeText) && _isWritingXmlnsAttributeDefaultNs)
                {
                    throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, _attributeText));
                }

                _attributeText = null;
                _isWritingXmlnsAttribute = false;
                _isWritingXmlnsAttributeDefaultNs = false;
            }
        }
Example #36
0
        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            if (IsClosed)
                ThrowClosed();
            if (!string.IsNullOrEmpty(prefix))
            {
                if (IsWritingNameWithMapping && prefix == "xmlns")
                {
                    if (ns != null && ns != "http://www.w3.org/2000/xmlns/")
                        throw new ArgumentException("XmlPrefixBoundToNamespace");
                }
                else
                    throw new ArgumentException("prefix", "JsonPrefixMustBeNullOrEmpty");
            }
            else if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/" && localName != "xmlns")
                prefix = "xmlns";
            if (!string.IsNullOrEmpty(ns))
            {
                if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/")
                    prefix = "xmlns";
                else
                    throw new ArgumentException("ns", "JsonNamespaceMustBeEmpty");
            }
            if (localName == null)
                throw new ArgumentException("localName");
            if (localName.Length == 0)
                throw new ArgumentException("localName", "JsonInvalidLocalNameEmpty");
            if (nodeType != JsonNodeType.Element && !wroteServerTypeAttribute)
                throw new XmlException("JsonAttributeMustHaveElement");
            if (HasOpenAttribute)
                throw new XmlException("JsonOpenAttributeMustBeClosedFirst");

            if (prefix == "xmlns")
                isWritingXmlnsAttribute = true;
            else switch (localName)
                {
                    case "type":
                        if (dataType != JsonDataType.None)
                            throw new XmlException("JsonAttributeAlreadyWritten");

                        isWritingDataTypeAttribute = true;

                        break;
                    case "__type":
                        if (serverTypeValue != null)
                            throw new XmlException("JsonAttributeAlreadyWritten");

                        if (dataType != JsonDataType.None && dataType != JsonDataType.Object)
                            throw new XmlException("JsonServerTypeSpecifiedForInvalidDataType");
                        isWritingServerTypeAttribute = true;
                        break;
                    case "item":
                        if (WrittenNameWithMapping)
                            throw new XmlException("JsonAttributeAlreadyWritten");

                        if (!IsWritingNameWithMapping)
                            throw new XmlException("JsonEndElementNoOpenNodes");

                        nameState |= NameState.IsWritingNameAttribute;
                        break;
                    default:
                        throw new ArgumentException("localName", "JsonUnexpectedAttributeLocalName");
                }
        }
Example #37
0
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message
        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            if (IsClosed)
            {
                ThrowClosed();
            }
            if (!string.IsNullOrEmpty(prefix))
            {
                if (IsWritingNameWithMapping && prefix == JsonGlobals.xmlnsPrefix)
                {
                    if (ns != null && ns != xmlnsNamespace)
                    {
                        throw new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), nameof(ns));
                    }
                }
                else
                {
                    throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), nameof(prefix));
                }
            }
            else
            {
                if (IsWritingNameWithMapping && ns == xmlnsNamespace && localName != JsonGlobals.xmlnsPrefix)
                {
                    prefix = JsonGlobals.xmlnsPrefix;
                }
            }
            if (!string.IsNullOrEmpty(ns))
            {
                if (IsWritingNameWithMapping && ns == xmlnsNamespace)
                {
                    prefix = JsonGlobals.xmlnsPrefix;
                }
                else if (string.IsNullOrEmpty(prefix) && localName == JsonGlobals.xmlnsPrefix && ns == xmlnsNamespace)
                {
                    prefix = JsonGlobals.xmlnsPrefix;
                    _isWritingXmlnsAttributeDefaultNs = true;
                }
                else
                {
                    throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns));
                }
            }
            if (localName == null)
            {
                throw new ArgumentNullException(nameof(localName));
            }
            if (localName.Length == 0)
            {
                throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName));
            }
            if ((_nodeType != JsonNodeType.Element) && !_wroteServerTypeAttribute)
            {
                throw new XmlException(SR.JsonAttributeMustHaveElement);
            }
            if (HasOpenAttribute)
            {
                throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartAttribute"));
            }
            if (prefix == JsonGlobals.xmlnsPrefix)
            {
                _isWritingXmlnsAttribute = true;
            }
            else if (localName == JsonGlobals.typeString)
            {
                if (_dataType != JsonDataType.None)
                {
                    throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.typeString));
                }

                _isWritingDataTypeAttribute = true;
            }
            else if (localName == JsonGlobals.serverTypeString)
            {
                if (_serverTypeValue != null)
                {
                    throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.serverTypeString));
                }

                if ((_dataType != JsonDataType.None) && (_dataType != JsonDataType.Object))
                {
                    throw new XmlException(SR.Format(SR.JsonServerTypeSpecifiedForInvalidDataType,
                        JsonGlobals.serverTypeString, JsonGlobals.typeString, _dataType.ToString().ToLowerInvariant(), JsonGlobals.objectString));
                }

                _isWritingServerTypeAttribute = true;
            }
            else if (localName == JsonGlobals.itemString)
            {
                if (WrittenNameWithMapping)
                {
                    throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.itemString));
                }

                if (!IsWritingNameWithMapping)
                {
                    // Don't write attribute with local name "item" if <item> element is not open.
                    // Not providing a better error message because localization deadline has passed.
                    throw new XmlException(SR.JsonEndElementNoOpenNodes);
                }

                _nameState |= NameState.IsWritingNameAttribute;
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.JsonUnexpectedAttributeLocalName, localName), nameof(localName));
            }
        }
Example #38
0
 private bool TrySetWritingNameWithMapping(string localName, string ns)
 {
     if (!localName.Equals("item") || !ns.Equals("item"))
         return false;
     nameState = NameState.IsWritingNameWithMapping;
     return true;
 }
Example #39
0
 public bool Equals(NameState nameState)
 {
     return(nameState.Name == this.Name && nameState.State == this.State);
 }
 private bool TrySetWritingNameWithMapping(string localName, string ns)
 {
     if (localName.Equals("item") && ns.Equals("item"))
     {
         this.nameState = NameState.IsWritingNameWithMapping;
         return true;
     }
     return false;
 }