static CallbackResult OnSpeechRequest(byte[] data, CallbackResult prevResult) { if (prevResult == CallbackResult.Normal && Config.Profile.OverrideSpeechColor) { byte[] newData = (byte[])data.Clone(); ByteConverter.BigEndian.ToBytes(Config.Profile.Colors.FontColor.Value, newData, 4); Core.SendToServer(newData); return CallbackResult.Sent; } else { return CallbackResult.Normal; } }
private static CallbackResult OnUnicodeSpeechRequest(byte[] data, CallbackResult prevResult) { UnicodeSpeechRequest packet = new UnicodeSpeechRequest(data); if (!Core.LoggedIn || packet.Text.Length == 0) return CallbackResult.Eat; if (packet.Text[0] == ',') { ProcessCommand(packet.Text); return CallbackResult.Eat; } else { return CallbackResult.Normal; } }
/// <summary> /// If <paramref name="callHandlers"/> is true, OnServerMessage handlers are called and /// if result is <see cref="CallbackResult.Normal"/> data are sent to the client. /// </summary> /// <param name="data">Buffer to send.</param> /// <param name="callHandlers">True if OnServerMessage handlers should be called; otherwise false.</param> public static void SendToClient(byte[] data, bool callHandlers) { UltimaSocket socket = CommunicationManager.Socket; if (socket != null) { CallbackResult result = CallbackResult.Normal; if (callHandlers) { result = OnServerMessage(data, CallbackResult.Normal); } if (result == CallbackResult.Normal) { socket.SendToClient(data); } } }
public CallbackResult RemoveEntriesForFiles(List <string> virtualPaths) { foreach (string virtualPath in virtualPaths) { string entry = virtualPath.Replace(GVFSConstants.PathSeparator, GVFSConstants.GitPathSeparator); entry = "!" + GVFSConstants.GitPathSeparatorString + entry; this.entriesToRemove.Add(entry); // We must add the folder path to this file so that git clean removes the folders if they are empty. CallbackResult result = this.AddFolderEntriesForFile(entry); if (result != CallbackResult.Success) { return(result); } } return(CallbackResult.Success); }
public CallbackResult OnWalkRequestSucceeded(byte[] data, CallbackResult prevResult) { if (World.Player.Hidden) { if (prevResult < CallbackResult.Sent) { if (x % 5 == 0) { UO.Print(0x011C, "Stealth : {0}", x); } x++; } } else { x = 1; } return(CallbackResult.Normal); }
public CallbackResult OnAsciiSpeech(byte[] data, CallbackResult prevState) { AsciiSpeech packet = new AsciiSpeech(data); if (AsciiSpeechBeforeOverride != null) { AsciiSpeechBeforeOverride(packet, new EventArgs()); } ConsoleOverrideItem item = GetOverrideItem(packet); if (item != null) { item.Print(); return(item.CallbackResult); } return(CallbackResult.Normal); }
public async Task SubtractRemainingWaitingTimeAsync_WithValueLargerThanCurrent_ResultShouldBeZero() { // Arrange. await this.CreateDefaultCallback(); var transaction = uint256.Parse("008b3395991c7893bb8a82d8389a48ded863af914d9cc31711554bc97e4723c0"); var successResult = new CallbackResult(CallbackResult.StatusSuccess, "success"); var timeoutResult = new CallbackResult(CallbackResult.StatusError, "timeout"); var waitingTime = TimeSpan.FromMinutes(5); var watch = await this.subject.AddAsync(transaction, 10, waitingTime, successResult, timeoutResult, this.defaultCallback, CancellationToken.None); // Act. await this.subject.SubtractRemainingWaitingTimeAsync(watch.Id, TimeSpan.FromMinutes(6), CancellationToken.None); // Assert. Assert.Equal(TimeSpan.Zero, await this.subject.GetRemainingWaitingTimeAsync(watch.Id, CancellationToken.None)); }
static CallbackResult OnWalkRequestFailed(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x21) { throw new Exception("Invalid packet passed to OnWalkRequestFailed."); } World.RealPlayer.X = ByteConverter.BigEndian.ToUInt16(data, 2); World.RealPlayer.Y = ByteConverter.BigEndian.ToUInt16(data, 4); World.RealPlayer.Direction = data[6]; World.RealPlayer.Z = (sbyte)data[7]; ClearStack(); WorldPacketHandler.objectCallbacks.InvokeAsync(new ObjectChangedEventArgs(World.PlayerSerial, ObjectChangeType.CharUpdated)); return(CallbackResult.Normal); } }
public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, StripeCheckoutOneTimeSettings settings) { // The ProcessCallback method is only intendid to be called via a Stripe Webhook and so // it's job is to process the webhook event and finalize / update the order accordingly try { var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey; var webhookSigningSecret = settings.TestMode ? settings.TestWebhookSigningSecret : settings.LiveWebhookSigningSecret; ConfigureStripe(secretKey); var stripeEvent = GetWebhookStripeEvent(request, webhookSigningSecret); if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted) { if (stripeEvent.Data?.Object?.Instance is Session stripeSession) { var paymentIntentService = new PaymentIntentService(); var paymentIntent = paymentIntentService.Get(stripeSession.PaymentIntentId); return(CallbackResult.Ok(new TransactionInfo { TransactionId = GetTransactionId(paymentIntent), AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount), PaymentStatus = GetPaymentStatus(paymentIntent) }, new Dictionary <string, string> { { "stripeSessionId", stripeSession.Id }, { "stripePaymentIntentId", stripeSession.PaymentIntentId }, { "stripeChargeId", GetTransactionId(paymentIntent) }, { "stripeCardCountry", paymentIntent.Charges?.Data?.FirstOrDefault()?.PaymentMethodDetails?.Card?.Country } })); } } } catch (Exception ex) { Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - ProcessCallback"); } return(CallbackResult.BadRequest()); }
public async Task GetStatusAsync_WithExistRule_ShouldSuccess() { // Arrange. await this.CreateDefaultCallback(); var transaction = uint256.Parse("008b3395991c7893bb8a82d8389a48ded863af914d9cc31711554bc97e4723c0"); var successResult = new CallbackResult(CallbackResult.StatusSuccess, "success"); var timeoutResult = new CallbackResult(CallbackResult.StatusError, "timeout"); var timeout = TimeSpan.FromMinutes(5); var rule = await this.subject.AddAsync(transaction, 10, timeout, successResult, timeoutResult, this.defaultCallback, CancellationToken.None); // Act. var status = await this.subject.GetStatusAsync(rule.Id, CancellationToken.None); // Assert. Assert.Equal(RuleStatus.Pending, status); }
private static CallbackResult OnUnicodeSpeechRequest(byte[] data, CallbackResult prevResult) { UnicodeSpeechRequest packet = new UnicodeSpeechRequest(data); if (!Core.LoggedIn || packet.Text.Length == 0) { return(CallbackResult.Eat); } if (packet.Text[0] == ',') { ProcessCommand(packet.Text); return(CallbackResult.Eat); } else { return(CallbackResult.Normal); } }
private static CallbackResult OnCharacterStatus(byte[] data, CallbackResult prevResult) { if (data[0] != 0x11) { throw new ArgumentException("Invalid packet passed to OnCharacterStatus."); } if (ByteConverter.BigEndian.ToUInt32(data, 3) == playerId) { player = ByteConverter.BigEndian.ToAsciiString(data, 7, 30); if (player.Contains("\0")) { player = player.Remove(player.IndexOf('\0')); } } OnChanged(EventArgs.Empty); return(CallbackResult.Normal); }
static CallbackResult OnSkillsUpdate(byte[] data, CallbackResult prevResult) { lock (syncRoot) { PacketReader reader = new PacketReader(data); byte id = reader.ReadByte(); if (id != 0x3A) { throw new Exception("Invalid packet passed to OnSkillsUpdate."); } ushort packetLenght = reader.ReadUInt16(); byte type = reader.ReadByte(); bool skillcup = (type == 0x02) || (type == 0x03) || (type == 0xDF); bool loop = (type != 0xDF && type != 0xFF); int @base = (loop ? 1 : 0); // For some strange reason, list has base 1 for skillid, and update 0. ushort lastID; // Loop only one time if Type is 0xFF, otherwise loop until SkillID is zero. while (reader.Offset < reader.Length && (lastID = reader.ReadUInt16()) > 0) { SkillValue value = new SkillValue(); value.ID = (ushort)(lastID - @base); value.Value = reader.ReadUInt16(); value.RealValue = reader.ReadUInt16(); value.Lock = (SkillLock)reader.ReadByte(); value.MaxValue = skillcup ? reader.ReadUInt16() : (ushort)0xFFFF; // TODO Trace.WriteLine(String.Format("Received skill {0} update to {1}", value.ID, value.RealValue), "World"); OnSkillChanged(value); // Stop iteration if (!loop) { break; } } return(CallbackResult.Normal); } }
private static CallbackResult OnLoginCompletePacket(byte[] data, CallbackResult prevResult) { if (data[0] != 0x55) { throw new ArgumentException("Invalid packet passed to OnLoginCompletePacket."); } if (!loggedIn) { loggedIn = true; OnLoginComplete(EventArgs.Empty); return(CallbackResult.Normal); } else { Debug.WriteLine("Unexpected LoginComplete packet dropped.", "Communication"); return(CallbackResult.Eat); } }
private static CallbackResult OnLoginConfirmedPacket(byte[] data, CallbackResult prevResult) { if (data[0] != 0x1B) { throw new ArgumentException("Invalid packet passed to OnLoginConfirmed."); } uint playerSerial = ByteConverter.BigEndian.ToUInt32(data, 1); if (!Config.InternalSettings.ElementExists("Characters", new ElementInfo("Character", new AttributeInfo("serial", playerSerial.ToString("X8"))))) { SelectProfile("NewProfileName", false); } else { Config.Profile.ChangeProfile(Config.PlayerProfile); } return(CallbackResult.Normal); }
public async Task UpdateCurrentWatchAsync_WithNonExist_ShouldThrow() { // Arrange. await this.CreateDefaultCallback(); var transaction = uint256.Parse("008b3395991c7893bb8a82d8389a48ded863af914d9cc31711554bc97e4723c0"); var successResult = new CallbackResult(CallbackResult.StatusSuccess, "success"); var timeoutResult = new CallbackResult(CallbackResult.StatusError, "timeout"); var waitingTime = TimeSpan.FromMinutes(5); var rule = await this.subject.AddAsync(transaction, 10, waitingTime, successResult, timeoutResult, this.defaultCallback, CancellationToken.None); var watch = await this.CreateWatch(rule, uint256.One, uint256.One); // Act && Assert. await Assert.ThrowsAsync <KeyNotFoundException>( () => this.subject.UpdateCurrentWatchAsync(Guid.NewGuid(), watch.Id, CancellationToken.None) ); }
public CallbackResult OnOpenStatus(byte[] data, CallbackResult prevState) { if (prevState == CallbackResult.Normal) { if (data[5] == 4) { Serial s = ByteConverter.BigEndian.ToUInt32(data, 6); //if (!Targeting.IsLastSelectedNPC(s)) //{ UOCharacter ch = new UOCharacter(s); if (/*ch.Notoriety == Notoriety.Guild || ch.Notoriety == Notoriety.Innocent || */ Game.CurrentGame.IsAlie(s)) { Aliases.SetObject("laststatus", s); Aliases.SetObject("LastAlieManual", s); Aliases.SetObject("LastStatusManual", s); Aliases.SetObject("LastStatusManualMobs", s); } else { Aliases.SetObject("laststatus", s); Aliases.SetObject("LastStatusManual", s); Aliases.SetObject("LastStatusManualMobs", s); } if ((Game.IsMob(s) && Game.IsMobActive(s)) || ch.Renamable) { Aliases.SetObject("SelectedMob", s); } if (EnableShowStatusBar && !Game.Rename(s)) { new StatusBar().Show(s); } } return(CallbackResult.Normal); // } } return(CallbackResult.Normal); }
private static CallbackResult OnServerSelect(byte[] data, CallbackResult prevResult) { if (data[0] != 0xA0) { throw new ArgumentException("Invalid packet passed to OnServerSelect."); } if (serverList == null) { throw new InvalidOperationException("ServerList not received yet."); } ushort shardIndex = ByteConverter.BigEndian.ToUInt16(data, 1); shard = ""; serverList.TryGetValue(shardIndex, out shard); serverList = null; OnChanged(EventArgs.Empty); return(CallbackResult.Normal); }
public async Task ExecuteAsync_WithValidArgumentsAndNetworkFail_ShouldThrow() { // Arrange. var result = new CallbackResult("", null); var id = Guid.NewGuid(); var url = new Uri("https://zcoin.io/callback"); var cancellationToken = new CancellationToken(false); var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.BadRequest; this.client .SendAsync(Arg.Any <HttpRequestMessage>(), Arg.Is <CancellationToken>(c => c == cancellationToken)) .Returns(Task.FromResult(response)); // Act && Assert. await Assert.ThrowsAsync <HttpRequestException>( () => this.subject.ExecuteAsync(id, url, result, cancellationToken) ); }
CallbackResult onStoodUp(byte[] data, CallbackResult prev) { PacketReader p = new PacketReader(data); p.Skip(1); uint serial = p.ReadUInt32(); ushort action = p.ReadUInt16(); if (StoodUp != null && (action == 26 || action == 11 || action == 29)) { foreach (EventHandler <StoodUpEventHandlerArgs> ev in StoodUp.GetInvocationList()) { ev.BeginInvoke(this, new StoodUpEventHandlerArgs() { action = action, serial = serial }, null, null); } } return(CallbackResult.Normal); }
CallbackResult OnBuildWall(byte[] data, CallbackResult prev) // 0x1A { PacketReader pr = new PacketReader(data); pr.Skip(3); uint serial = pr.ReadUInt32(); ushort graphic = pr.ReadUInt16(); ushort X = pr.ReadUInt16(); ushort Y = pr.ReadUInt16(); if (graphic == 0x3947 || graphic == 0x3956) // Energy { TmpCounter++; if (DateTime.Now - WallCall < TimeSpan.FromSeconds(10) && TmpCounter % 7 == 0) { Collection.Add(new Wall() { CreateTime = DateTime.Now, Serial = serial, Type = WallTime.EnergyLast, X = X, Y = Y }); } return(CallbackResult.Normal); } else if (graphic == 0x0080) // Stone { TmpCounter++; if (DateTime.Now - WallCall < TimeSpan.FromSeconds(10) && TmpCounter % 5 == 0) { Collection.Add(new Wall() { CreateTime = DateTime.Now, Serial = serial, Type = WallTime.StoneLast, X = X, Y = Y }); } return(CallbackResult.Normal); } return(CallbackResult.Normal); }
CallbackResult onMenu(byte[] data, CallbackResult prevResult) { if (first) { first = false; return(CallbackResult.Normal); } PacketReader pr = new PacketReader(data); pr.Skip(3); dialogID = pr.ReadUInt32(); menuid = pr.ReadUInt16(); int length = pr.ReadByte(); pr.Skip(length); int responses = pr.ReadByte(); for (int i = 0; i < responses; i++) { pr.Skip(4); length = pr.ReadByte(); Tracked.Add(pr.ReadAnsiString(length)); } printTrackList(); Core.UnregisterServerMessageCallback(0x7C, onMenu); PacketWriter pw = new PacketWriter(0x7D); pw.Write(dialogID); pw.Write(menuid); pw.Write(fake); pw.Write(fake); pw.Write(fake); Core.SendToServer(pw.GetBytes()); Core.SendToClient(pw.GetBytes()); dialogID = 0; menuid = 0; Core.UnregisterServerMessageCallback(0x7C, onMenu); return(CallbackResult.Sent); //TODO Track hlasky pri .. }
static CallbackResult OnContainerContents(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { Trace.WriteLine(String.Format("Populating container.."), "World"); PacketReader reader = new PacketReader(data); byte id = reader.ReadByte(); if (id != 0x3C) { throw new Exception("Invalid packet passed to OnContainerContents."); } ushort blockSize = reader.ReadUInt16(); if (blockSize != reader.Length) { Trace.WriteLine(String.Format("BlockSize ({0}) for dynamic packet 0x3C doesn't meet data lenght ({1}).", blockSize, data.Length), "World"); } ushort items = reader.ReadUInt16(); while (items > 0) { bool isNew; uint serial = AddToContainerData(reader, out isNew); if (isNew) { itemAdded.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.NewItem)); } itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.ItemUpdated)); ObjectChanged(serial, ObjectChangeType.ItemUpdated); items--; } return(CallbackResult.Normal); } }
public CallbackResult CallBack_JsonTag_82729_11() { /*orderby=时间&desc=false&pagesize=3&fields=title,时间,time,desc,img,id*/ string jsonname = this.CallValue("jsonname"); if (jsonname != "JsonTag_82729_11") { return(null); } var list = from a in Db_Context.Article.Where(x => x.IsLock != true) select new { a.Title, a.Time, a.Desc, a.Img, a.ID }; int __page = 0; int.TryParse(this.CallValue("page"), out __page); __page = __page < 1 ? 1 : __page; int totalsize = list.Count(); list = list.OrderBy(c => c.Time).Skip((__page - 1) * 3).Take(3); dynamic json = new ExpandoObject(); json.jsonname = "JsonTag_82729_11"; json.tagstr = "orderby=时间&desc=false&pagesize=3&fields=title,时间,time,desc,img,id"; json.skip = (__page - 1) * 3; json.pagesize = 3; json.listsize = totalsize; json.page = __page; json.over = list.Count() < 3; json.data = list; CallbackResult call = new CallbackResult(json); call.type = "jsoncall"; return(call); }
static CallbackResult OnPlayerSync(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x20) { throw new Exception("Invalid packet passed to OnPlayerSync."); } uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); if (World.RealPlayer == null) { Trace.WriteLine(String.Format("LoginConfirm packet not received yet."), "World"); return(CallbackResult.Normal); } if (World.PlayerSerial != serial) { throw new InvalidOperationException("Invalid serial in 0x20 packet."); } World.RealPlayer.Graphic = ByteConverter.BigEndian.ToUInt16(data, 5); World.RealPlayer.Status = data[7]; World.RealPlayer.Color = ByteConverter.BigEndian.ToUInt16(data, 8); World.RealPlayer.Flags = ByteConverter.BigEndian.ToByte(data, 10); World.RealPlayer.X = ByteConverter.BigEndian.ToUInt16(data, 11); World.RealPlayer.Y = ByteConverter.BigEndian.ToUInt16(data, 13); World.RealPlayer.Z = ByteConverter.BigEndian.ToSByte(data, 18); World.RealPlayer.Direction = ByteConverter.BigEndian.ToByte(data, 17); WalkHandling.ClearStack(); Trace.WriteLine(String.Format("Player updated ({0}).", World.RealPlayer), "World"); ObjectChanged(serial, ObjectChangeType.CharUpdated); return(CallbackResult.Normal); } }
CallbackResult ForceWalk(byte[] data, CallbackResult prev)//0x02 clientReq { PacketReader pr = new PacketReader(data); PacketWriter pw = new PacketWriter(); byte cmd = pr.ReadByte(); byte dir = pr.ReadByte(); byte seq = pr.ReadByte(); uint fwalkPrev = pr.ReadUInt32(); if (Convert.ToUInt16(dir) > 7) { dir = Convert.ToByte(Convert.ToUInt16(dir) - 128); pw.Write(cmd); pw.Write(dir); pw.Write(seq); pw.Write(fwalkPrev); Core.SendToServer(pw.GetBytes()); return(CallbackResult.Eat); } return(CallbackResult.Normal); }
public CallbackResult ProcessMessage(byte[] data, CallbackResult prevResult) { CallbackObject[] cl; lock (syncRoot) { if (data == null || data.Length == 0) { return(CallbackResult.Eat); } byte id = data[0]; cl = list[id] != null ? list[id].ToArray() : null; } // Mimo synchronizacni kontext if (cl != null) { byte[] local = new byte[data.Length]; Array.Copy(data, local, data.Length); for (int i = 0; i < cl.Length; i++) { try { CallbackResult r = cl[i].Callback(data, prevResult); if (r > prevResult) { prevResult = r; } } catch (Exception e) { Trace.WriteLine(String.Format("Unhandled error in {0}. Exception:\r\n{1}", callbacksName, e), "Phoenix"); } } } return(prevResult); }
/// <summary> /// Creates a new <see cref="CallbackData"/> from a list of headers /// </summary> /// <param name="headers">The <see cref="HeaderCollection"/> used to populate the object</param> /// <returns><see cref="CallbackData"/></returns> public new static CallbackData FromHeaders(HeaderCollection headers) { try { CallbackDataBase baseObj = CallbackDataBase.FromHeaders(headers); CallbackResult result = CallbackResult.TIMEDOUT; string resultString = headers.GetHeaderStringValue(Header.NOTIFICATION_CALLBACK_RESULT, true); if(!String.IsNullOrEmpty(resultString)) result = (CallbackResult)Enum.Parse(typeof(CallbackResult), resultString, true); string notificationID = headers.GetHeaderStringValue(Header.NOTIFICATION_ID, false); CallbackData context = new CallbackData(baseObj.Data, baseObj.Type, result, notificationID); return context; } catch { return null; } }
static CallbackResult OnAddToContainer(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { PacketReader reader = new PacketReader(data); if (reader.ReadByte() != 0x25) { throw new Exception("Invalid packet passed to OnAddToContainer."); } bool isNew; uint serial = AddToContainerData(reader, out isNew); if (isNew) { itemAdded.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.NewItem)); } itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.ItemUpdated)); ObjectChanged(serial, ObjectChangeType.ItemUpdated); return(CallbackResult.Normal); } }
public async Task ListActiveAsync_NonPendingRule_ShouldBeFilterOut() { // Arrange. await this.CreateDefaultCallback(); var transaction = uint256.Parse("008b3395991c7893bb8a82d8389a48ded863af914d9cc31711554bc97e4723c0"); var successResult = new CallbackResult(CallbackResult.StatusSuccess, "success"); var timeoutResult = new CallbackResult(CallbackResult.StatusError, "timeout"); var watches = new List <Rule>(); watches.Add(await this.subject.AddAsync(transaction, 10, TimeSpan.FromMinutes(5), successResult, timeoutResult, this.defaultCallback, CancellationToken.None)); await this.subject.UpdateStatusAsync(watches.Last().Id, RuleStatus.Success, CancellationToken.None); // Act. var retrieved = (await this.subject.ListWaitingAsync(CancellationToken.None)).ToList(); // Assert. Assert.Empty(retrieved); }
/** <inheritdoc /> */ public void Start(IPluginContext <TestIgnitePluginConfiguration> context) { context.RegisterExceptionMapping("org.apache.ignite.platform.plugin.PlatformTestPluginException", (className, message, inner, ignite) => new TestIgnitePluginException(className, message, ignite, inner)); context.RegisterCallback(1, (input, output) => { CallbackResult = input.ReadString(); output.WriteString(CallbackResult.ToUpper()); return(CallbackResult.Length); }); var ex = Assert.Throws <IgniteException>(() => context.RegisterCallback(1, (input, output) => 0)); Assert.AreEqual("Plugin callback with id 1 is already registered", ex.Message); Context = context; EnsureIgniteWorks(false); }
private CallbackResult OnAutoUpdateCharacter(byte[] data, CallbackResult prevResult) { PacketReader reader = new PacketReader(data); reader.Skip(5); ushort model = reader.ReadUInt16(); if ((model == 0x0005) || (model == 0x0006)) { model = 0x0004; // na gargoyla } if ((model == 0x00CD) || (model == 0x00EE)) { model = 0x002C; // na ratmana } if (model == 0x0034) { model = 0x0021; // na lizardmana } ByteConverter.BigEndian.ToBytes((ushort)model, data, 5); return(CallbackResult.Normal); }
private static CallbackResult OnClientTarget(byte[] data, CallbackResult prevResult) { lock (syncRoot) { switch (CurrentState) { case State.ServerTarget: clientTarget = null; FinishWork(); return(CallbackResult.Normal); case State.Target: TargetData target = TargetData.FromData(data); if (target.TargetId == clientTarget.TargetId && target.Type <= clientTarget.Type) { clientTarget.Serial = target.Serial; clientTarget.X = target.X; clientTarget.Y = target.Y; clientTarget.Z = target.Z; clientTarget.Graphic = target.Graphic; } else { Trace.WriteLine("Incorrect target received from client.", "UIManager"); } operationResult.Event.Set(); operationResult = null; clientTarget = null; FinishWork(); return(CallbackResult.Eat); default: Trace.WriteLine("Dropped unexpected client target.", "UIManager"); return(CallbackResult.Eat); } } }
static CallbackResult OnContainerContents(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { Trace.WriteLine(String.Format("Populating container.."), "World"); PacketReader reader = new PacketReader(data); byte id = reader.ReadByte(); if (id != 0x3C) throw new Exception("Invalid packet passed to OnContainerContents."); ushort blockSize = reader.ReadUInt16(); if (blockSize != reader.Length) Trace.WriteLine(String.Format("BlockSize ({0}) for dynamic packet 0x3C doesn't meet data lenght ({1}).", blockSize, data.Length), "World"); ushort items = reader.ReadUInt16(); while (items > 0) { bool isNew; uint serial = AddToContainerData(reader, out isNew); if (isNew) itemAdded.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.NewItem)); itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.ItemUpdated)); ObjectChanged(serial, ObjectChangeType.ItemUpdated); items--; } return CallbackResult.Normal; } }
static CallbackResult OnWarMode(byte[] data, CallbackResult prevResult) { World.RealPlayer.WarMode = data[1] > 0; ObjectChanged(World.RealPlayer.Serial, ObjectChangeType.CharUpdated); return CallbackResult.Normal; }
static CallbackResult OnOpenContainer(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x24) throw new Exception("Invalid packet passed to OnOpenContainer."); uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); ushort gump = ByteConverter.BigEndian.ToUInt16(data, 5); RealItem container = World.FindRealItem(serial); if (container == null) { Trace.WriteLine("Cannot open non-existing container.", "World"); return CallbackResult.Normal; } // Items will be populated later. List<uint> removeList = new List<uint>(); World.GetContainerContents(container.Serial, removeList); for (int i = 0; i < removeList.Count; i++) { World.ItemList.Remove(removeList[i]); } container.Opened = true; Trace.WriteLine(String.Format("Opening container 0x{0}..", serial.ToString("X8")), "World"); ObjectChanged(serial, ObjectChangeType.ItemOpened); return CallbackResult.Normal; } }
static CallbackResult OnItemDetails(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { PacketReader reader = new PacketReader(data); byte id = reader.ReadByte(); if (id != 0x1A) throw new Exception("Invalid packet passed to OnItemDetails."); ushort blockSize = reader.ReadUInt16(); if (blockSize != reader.Length) return CallbackResult.Normal; uint serial = reader.ReadUInt32(); bool isNew = false; RealItem item = World.FindRealItem(serial); if (item == null) { item = new RealItem(serial); World.Add(item); isNew = true; } ushort dispId = reader.ReadUInt16(); if ((serial & 0x80000000) != 0) { item.Amount = reader.ReadUInt16(); } if ((dispId & 0x8000) != 0) { dispId += reader.ReadByte(); } item.Graphic = (ushort)(dispId & 0x7FFF); ushort x = reader.ReadUInt16(); item.X = (ushort)(x & 0x7FFF); ushort y = reader.ReadUInt16(); item.Y = (ushort)(y & 0x3FFF); if ((x & 0x8000) != 0) { byte direction = reader.ReadByte(); } item.Z = reader.ReadSByte(); if ((y & 0x8000) != 0) { item.Color = reader.ReadUInt16(); } if ((y & 0x4000) != 0) { item.Flags = reader.ReadByte(); } item.Detach(); #if WORLDDEBUG Trace.WriteLine(String.Format("Item updated ({0}).", item.Description), "World"); #endif if (isNew) itemAdded.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.NewItem)); ObjectChanged(serial, ObjectChangeType.ItemUpdated); itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(item.Serial, ObjectChangeType.ItemUpdated)); return CallbackResult.Normal; } }
static CallbackResult OnCharacterUpdate(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { PacketReader reader = new PacketReader(data); if (reader.ReadByte() != 0x77) throw new Exception("Invalid packet passed to OnCharacterUpdate."); bool newCharacter = false; uint serial = reader.ReadUInt32(); RealCharacter chr = World.FindRealCharacter(serial); if (chr == null) { chr = new RealCharacter(serial); World.Add(chr); newCharacter = true; } chr.Graphic = reader.ReadUInt16(); chr.X = reader.ReadUInt16(); chr.Y = reader.ReadUInt16(); chr.Z = reader.ReadSByte(); chr.Direction = reader.ReadByte(); chr.Color = reader.ReadUInt16(); chr.Flags = reader.ReadByte(); chr.Notoriety = reader.ReadByte(); #if WORLDDEBUG Debug.WriteLine(String.Format("Character updated ({0}).", chr.Description), "World"); #endif if (newCharacter) characterAppeared.InvokeAsync(null, new CharacterAppearedEventArgs(serial)); ObjectChanged(serial, ObjectChangeType.CharUpdated); return CallbackResult.Normal; } }
static CallbackResult OnPlayerSync(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x20) throw new Exception("Invalid packet passed to OnPlayerSync."); uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); if (World.RealPlayer == null) { Trace.WriteLine(String.Format("LoginConfirm packet not received yet."), "World"); return CallbackResult.Normal; } if (World.PlayerSerial != serial) throw new InvalidOperationException("Invalid serial in 0x20 packet."); World.RealPlayer.Graphic = ByteConverter.BigEndian.ToUInt16(data, 5); World.RealPlayer.Status = data[7]; World.RealPlayer.Color = ByteConverter.BigEndian.ToUInt16(data, 8); World.RealPlayer.Flags = ByteConverter.BigEndian.ToByte(data, 10); World.RealPlayer.X = ByteConverter.BigEndian.ToUInt16(data, 11); World.RealPlayer.Y = ByteConverter.BigEndian.ToUInt16(data, 13); World.RealPlayer.Z = ByteConverter.BigEndian.ToSByte(data, 18); World.RealPlayer.Direction = ByteConverter.BigEndian.ToByte(data, 17); WalkHandling.ClearStack(); Trace.WriteLine(String.Format("Player updated ({0}).", World.RealPlayer), "World"); ObjectChanged(serial, ObjectChangeType.CharUpdated); return CallbackResult.Normal; } }
private static CallbackResult OnCharacterList(byte[] data, CallbackResult prevResult) { if (data[0] != 0xA9) throw new ArgumentException("Invalid packet passed to OnCharacterList."); charListSent = true; return CallbackResult.Normal; }
private static CallbackResult OnLoginConfirmedPacket(byte[] data, CallbackResult prevResult) { if (data[0] != 0x1B) throw new ArgumentException("Invalid packet passed to OnLoginConfirmed."); uint playerSerial = ByteConverter.BigEndian.ToUInt32(data, 1); if (!Config.InternalSettings.ElementExists("Characters", new ElementInfo("Character", new AttributeInfo("serial", playerSerial.ToString("X8"))))) { SelectProfile("NewProfileName", false); } else { Config.Profile.ChangeProfile(Config.PlayerProfile); } return CallbackResult.Normal; }
internal static CallbackResult OnClientMessage(byte[] data, CallbackResult prevResult) { return clientMsgCallbacks.ProcessMessage(data, prevResult); }
static CallbackResult OnUpdateStats(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x2D) throw new Exception("Invalid packet passed to OnUpdateStats."); uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); RealCharacter chr = World.FindRealCharacter(serial); if (chr == null) { Trace.WriteLine(String.Format("Cannot update stats for unknown character (serial=0x{0}).", serial.ToString("X8")), "World"); return CallbackResult.Normal; } chr.MaxHits = ByteConverter.BigEndian.ToInt16(data, 5); chr.Hits = ByteConverter.BigEndian.ToInt16(data, 7); chr.MaxMana = ByteConverter.BigEndian.ToInt16(data, 9); chr.Mana = ByteConverter.BigEndian.ToInt16(data, 11); chr.MaxStamina = ByteConverter.BigEndian.ToInt16(data, 13); chr.Stamina = ByteConverter.BigEndian.ToInt16(data, 15); ObjectChanged(serial, ObjectChangeType.CharUpdated); return CallbackResult.Normal; } }
static CallbackResult OnUniSpeech(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { UnicodeSpeech packet = new UnicodeSpeech(data); RealObject obj = World.FindRealObject(packet.Serial); if (obj == null) { // System speech return CallbackResult.Normal; } if (obj.Name != packet.Name) { obj.Name = packet.Name; #if WORLDDEBUG Trace.WriteLine(String.Format("Object name updated: {0}", obj.Description), "World"); #endif if (obj is RealItem) { itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(obj.Serial, ObjectChangeType.ItemUpdated)); ObjectChanged(obj.Serial, ObjectChangeType.ItemUpdated); } else { ObjectChanged(obj.Serial, ObjectChangeType.CharUpdated); } } return CallbackResult.Normal; } }
static CallbackResult OnThingName(byte[] data, CallbackResult prevResult) { // This packet is probably sent for Characters only lock (World.SyncRoot) { if (data[0] != 0x98) throw new Exception("Invalid packet passed to OnThingName."); ushort blockSize = ByteConverter.BigEndian.ToUInt16(data, 1); if (data.Length != blockSize) Trace.WriteLine(String.Format("BlockSize ({0}) for dynamic packet 0x98 doesn't meet data lenght ({1}).", data.Length), "World"); if (blockSize != 37) { Trace.WriteLine(String.Format("Invalid 0x98 ThingName packet lenght. Maybe a client version of packet."), "World"); return CallbackResult.Normal; } uint serial = ByteConverter.BigEndian.ToUInt32(data, 3); RealObject obj = World.FindRealObject(serial); if (obj == null) { Trace.WriteLine(String.Format("Cannot set name for non-existing object (serial=0x{0}).", serial.ToString("X8")), "World"); return CallbackResult.Normal; } string name = ByteConverter.BigEndian.ToAsciiString(data, 7, 30); if (name != obj.Name) { obj.Name = name; Trace.WriteLine(String.Format("Object name upadted: {0}", obj), "World"); if (obj is RealItem) { itemUpdated.InvokeAsync(null, new ObjectChangedEventArgs(serial, ObjectChangeType.ItemUpdated)); ObjectChanged(serial, ObjectChangeType.ItemUpdated); } else { ObjectChanged(serial, ObjectChangeType.CharUpdated); } } return CallbackResult.Normal; } }
static CallbackResult OnSunLight(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { Trace.WriteLine("Light changed to " + data[1].ToString(), "Phoenix"); World.SunLight = data[1]; return CallbackResult.Normal; } }
internal static CallbackResult OnServerMessage(byte[] data, CallbackResult prevResult) { return serverMsgCallbacks.ProcessMessage(data, prevResult); }
static CallbackResult OnServerPing(byte[] data, CallbackResult lastResult) { if (pingQueue.Count > 0) { latencyList.Add((int)(NativeTimer.timeGetTime() - pingQueue.Dequeue())); UpdateLatency(); } return data[1] != 0x7F ? CallbackResult.Normal : CallbackResult.Eat; }
private static CallbackResult OnLoginCompletePacket(byte[] data, CallbackResult prevResult) { if (data[0] != 0x55) throw new ArgumentException("Invalid packet passed to OnLoginCompletePacket."); if (!loggedIn) { loggedIn = true; OnLoginComplete(EventArgs.Empty); return CallbackResult.Normal; } else { Debug.WriteLine("Unexpected LoginComplete packet dropped.", "Communication"); return CallbackResult.Eat; } }
static CallbackResult OnWalkRequest(byte[] data, CallbackResult prevResult) { walkQueue.Enqueue(NativeTimer.timeGetTime()); return CallbackResult.Normal; }
/// <summary> /// Sets the <see cref="CallbackData"/> for this response /// </summary> /// <param name="notificationID">The ID of the notification making the callback</param> /// <param name="callbackContext">The <see cref="CallbackContext"/> of the request</param> /// <param name="callbackResult">The <see cref="CallbackResult"/> (clicked, closed)</param> public void SetCallbackData(string notificationID, CallbackContext callbackContext, CallbackResult callbackResult) { if (callbackContext != null) { CallbackData cd = new CallbackData(callbackContext.Data, callbackContext.Type, callbackResult, notificationID); this.callbackData = cd; } }
static CallbackResult OnWalkRequestSucceed(byte[] data, CallbackResult prevResult) { if (walkQueue.Count > 0) { latencyList.Add((int)(NativeTimer.timeGetTime() - walkQueue.Dequeue())); UpdateLatency(); } return CallbackResult.Normal; }
static CallbackResult OnCharacterStatus(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { PacketReader reader = new PacketReader(data); if (reader.ReadByte() != 0x11) throw new Exception("Invalid packet passed to OnCharacterStatus."); ushort blockSize = reader.ReadUInt16(); if (data.Length != blockSize) Trace.WriteLine(String.Format("BlockSize ({0}) for dynamic packet 0x11 doesn't meet data lenght ({1}).", blockSize, data.Length), "World"); uint serial = reader.ReadUInt32(); RealCharacter chr = World.FindRealCharacter(serial); if (chr == null) { Trace.WriteLine(String.Format("Cannot update status for unknown character (serial=0x{0:X8}).", serial), "World"); return CallbackResult.Normal; } chr.Name = reader.ReadAnsiString(30); chr.Hits = reader.ReadInt16(); chr.MaxHits = reader.ReadInt16(); chr.Renamable = reader.ReadByte() > 0; byte more = reader.ReadByte(); if (more > 0) { byte gender = reader.ReadByte(); chr.Strenght = reader.ReadInt16(); chr.Dexterity = reader.ReadInt16(); chr.Intelligence = reader.ReadInt16(); chr.Stamina = reader.ReadInt16(); chr.MaxStamina = reader.ReadInt16(); chr.Mana = reader.ReadInt16(); chr.MaxMana = reader.ReadInt16(); chr.Gold = reader.ReadInt32(); chr.Armor = reader.ReadUInt16(); chr.Weight = reader.ReadUInt16(); } #if WORLDDEBUG Trace.WriteLine(String.Format("Character status updated ({0}).", chr.Description), "World"); #endif ObjectChanged(serial, ObjectChangeType.CharUpdated, true); return CallbackResult.Normal; } }
static CallbackResult OnClientPing(byte[] data, CallbackResult lastResult) { pingQueue.Enqueue(NativeTimer.timeGetTime()); System.Diagnostics.Debug.WriteLine("Ping sent by client", "Information"); return CallbackResult.Normal; }
static CallbackResult OnPlayerSync(byte[] data, CallbackResult prevResult) { uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); if (Phoenix.WorldData.World.RealPlayer != null && serial == Phoenix.WorldData.World.PlayerSerial) { walkQueue.Clear(); UpdateLatency(); } return CallbackResult.Normal; }
/// <summary> /// Creates a new instance of this class /// </summary> /// <param name="notificationUUID">The UUID of the notification making the callback</param> /// <param name="result">The callback result</param> public NotificationCallbackEventArgs(string notificationUUID, CallbackResult result) { this.notificationUUID = notificationUUID; this.result = result; }
static CallbackResult OnLoginConfirm(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x1B) throw new Exception("Invalid packet passed to OnLoginConfirm."); bool expected = (World.PlayerSerial == World.InvalidSerial); uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); if (!expected && World.PlayerSerial != serial) { Trace.WriteLine("Invalid serial in LoginConfirm! Packet ignored.", "World"); return CallbackResult.Normal; } World.PlayerSerial = serial; RealCharacter chr = World.FindRealCharacter(World.PlayerSerial); if (chr == null) { chr = new RealCharacter(World.PlayerSerial); World.Add(chr); } chr.Graphic = ByteConverter.BigEndian.ToUInt16(data, 9); chr.X = ByteConverter.BigEndian.ToUInt16(data, 11); chr.Y = ByteConverter.BigEndian.ToUInt16(data, 13); chr.Z = ByteConverter.BigEndian.ToSByte(data, 16); chr.Direction = ByteConverter.BigEndian.ToByte(data, 17); WalkHandling.ClearStack(); if (expected) Trace.WriteLine(String.Format("Player logged in. ({0}).", chr), "World"); else Trace.WriteLine("Unexpected LoginConfirm packet.", "World"); return CallbackResult.Normal; } }
private static void serializeCallbackResult(JsonWriter writer, CallbackResult result) { if (result == null) { writer.Write(null); } else { writer.WriteObjectStart(); writer.WritePropertyName("type"); if (result is FlowCallbackResult) writer.Write("flow"); else if (result is MessageCallbackResult) writer.Write("message"); else if (result is FormCallbackResult) writer.Write("form"); writer.WritePropertyName("value"); result.Write(writer, false); writer.WriteObjectEnd(); } }
private CallbackResult PacketHandler(byte[] data, CallbackResult prevResult) { lock (syncRoot) { IMacroCommand cmd = PacketTranslator.Translate(data); if (cmd != null) { AddCommand(cmd); } } return CallbackResult.Normal; }
static CallbackResult OnObjectRemove(byte[] data, CallbackResult prevResult) { lock (World.SyncRoot) { if (data[0] != 0x1D) throw new Exception("Invalid packet passed to OnObjectRemove."); uint serial = ByteConverter.BigEndian.ToUInt32(data, 1); if (serial != World.PlayerSerial) { // Get item before we remove it, so we know its parent // It will be null for chars, thats ok RealItem item = World.FindRealItem(serial); if (World.Remove(serial)) Trace.WriteLine(String.Format("Object 0x{0:X8} removed from world.", serial), "World"); else Trace.WriteLine(String.Format("Cannot remove 0x{0:X8}. Object doesn't exist.", serial), "World"); // Invoke all events manually objectCallbacks.InvokeAsync(new ObjectChangedEventArgs(serial, ObjectChangeType.Removed)); while (item != null) { RealObject obj = World.FindRealObject(item.Container); if (obj != null) objectCallbacks.InvokeAsync(new ObjectChangedEventArgs(obj.Serial, serial, ObjectChangeType.SubItemRemoved)); item = obj as RealItem; } return CallbackResult.Normal; } else { Trace.WriteLine("Cannot remove player. Packet dropped.", "World"); return CallbackResult.Eat; } } }