public ChatroomServerProtocolFactory(ChatroomSettings settings, params IChatroomServerPlugin[] plugins) { _settings = settings; LoadDefaultPlugins(); _plugins.AddRange(plugins); _clients = new ClientCache(); }
/// <summary> /// 绑定下拉控件数据集 /// </summary> public void BindList(int schoolId = 0, int trainPlaceId = 0, bool getFromCache = true) { _schoolID = schoolId; _trainPlaceID = trainPlaceId; var cacheName = "Group"; if (schoolId > 0) { cacheName += "#Sch_" + schoolId; } if (trainPlaceId > 0) { cacheName += "#Tp_" + trainPlaceId; } ClientCache.GetDataMethod method; if (schoolId > 0 && trainPlaceId > 0) { method = () => new GroupDao().GetListByPlaceSchool(trainPlaceId, schoolId); } else if (schoolId > 0) { method = () => new GroupDao().GetListByTrainPlace(trainPlaceId); } else if (trainPlaceId > 0) { method = () => new GroupDao().GetListBySchool(schoolId); } else { method = () => new GroupDao().GetList(); } ListIsValid = (List <Group>)(getFromCache ? ClientCache.GetAuto(cacheName, method) : ClientCache.GetUpdate(cacheName, method)); Properties.DataSource = ListIsValid; Properties.DisplayMember = "GroupName"; Properties.ValueMember = "GroupID"; Properties.BestFitMode = BestFitMode.BestFitResizePopup; Properties.SearchMode = SearchMode.AutoFilter; Properties.CaseSensitiveSearch = true; Properties.AutoSearchColumnIndex = 2; }
/// <summary> /// Gets the physical media related to the content record and writes it to /// the given http response. /// </summary> /// <param name="response">The http response</param> public void GetMedia(HttpContext context, int?width = null, int?height = null) { if (!ClientCache.HandleClientCache(context, Id.ToString(), Updated)) { byte[] data = null; var compress = false; bool draft = (this is Content ? ((Content)(object)this).IsDraft : false); if (width.HasValue) { // Try to get cached media from the provider if (draft) { data = Application.Current.MediaCacheProvider.GetDraft(Id, width.Value, height, Piranha.IO.MediaType.Media); } else { data = Application.Current.MediaCacheProvider.Get(Id, width.Value, height, (this is Upload ? Piranha.IO.MediaType.Upload : Piranha.IO.MediaType.Media)); } if (data == null) { // No cached media exists. Let's get it if (draft) { data = Application.Current.MediaProvider.GetDraft(Id, Piranha.IO.MediaType.Media); if (data == null) { draft = false; } } if (!draft) { data = Application.Current.MediaProvider.Get(Id, (this is Upload ? Piranha.IO.MediaType.Upload : Piranha.IO.MediaType.Media)); } if (data != null) { Image img = null; try { // We're requesting different dimensions, try to get the image using (var mem = new MemoryStream(data)) { img = Image.FromStream(mem); } if (img != null) { var newWidth = width.HasValue && width.Value < img.Width ? width : img.Width; var newHeight = height; if (!newHeight.HasValue) { newHeight = Convert.ToInt32(((double)width / img.Width) * img.Height); } int orgWidth = img.Width, orgHeight = img.Height; var cropV = ((Content)(object)this).VerticalCropping; var cropH = ((Content)(object)this).HorizontalCropping; using (var resized = Drawing.ImageUtils.Resize(img, newWidth.Value, newHeight.Value, cropH, cropV)) { if (resized.Width != orgWidth || resized.Height != orgHeight) { // Check for optional compression var param = SysParam.GetByName("COMPRESS_IMAGES"); if (param != null && param.Value == "1") { compress = true; } using (var mem = new MemoryStream()) { resized.Save(mem, compress ? ImageFormat.Jpeg : img.RawFormat); data = mem.ToArray(); } if (draft) { Application.Current.MediaCacheProvider.PutDraft(Id, data, width.Value, height, Piranha.IO.MediaType.Media); } else { Application.Current.MediaCacheProvider.Put(Id, data, width.Value, height, (this is Upload ? Piranha.IO.MediaType.Upload : Piranha.IO.MediaType.Media)); } } } img.Dispose(); } } catch { } } } } else { // Get the original media from the current provider if (draft) { data = Application.Current.MediaProvider.GetDraft(Id, Piranha.IO.MediaType.Media); if (data == null) { draft = false; } } if (!draft) { data = Application.Current.MediaProvider.Get(Id, (this is Upload ? Piranha.IO.MediaType.Upload : Piranha.IO.MediaType.Media)); } } if (data != null) { WriteFile(context, data, compress); } } }
public void RequestActivitySummaryLeaderboardDataMessageHandler(RequestActivitySummaryLeaderboardDataMessage message, Player player) { using var ctx = new UchuContext(); // Get current year and week number according to ISO 8601 var yearAndWeek = ISOWeek.GetYear(DateTime.Now) * 100 + ISOWeek.GetWeekOfYear(DateTime.Now); // Find leaderboard entries for this activity // If weekly leaderboard is requested, only return results from current week var leaderboardQueryable = ctx.ActivityScores .Where(score => score.Activity == message.GameId && (message.Weekly ? score.Week == yearAndWeek : score.Week == 0)); // Find leaderboard type var activity = ClientCache.Find <Activities>(message.GameId); var leaderboardType = (LeaderboardType)(activity?.LeaderboardType ?? -1); // For some reason, whoever made this in 2011 gave the the NS and NT footraces the // same activity ID. So for footraces, we filter by zone ID to ensure we don't mix // the leaderboards. But this check shouldn't be done for other leaderboards, as // Survival minigames have their leaderboards accessible from multiple zones. if (leaderboardType == LeaderboardType.Footrace) { leaderboardQueryable = leaderboardQueryable.Where(score => score.Zone == (int)player.Zone.ZoneId); } // Order either by time ascending or time descending depending on which kind of activity it is if (leaderboardType == LeaderboardType.Footrace || leaderboardType == LeaderboardType.AvantGardensSurvival || leaderboardType == LeaderboardType.BattleOfNimbusStation) { leaderboardQueryable = leaderboardQueryable.OrderByDescending(score => score.Time); } else { leaderboardQueryable = leaderboardQueryable.OrderBy(score => score.Time); } var leaderboard = leaderboardQueryable.ToList(); // Dictionary <rank, score> // Rank is what the client will show as position on the leaderboard var toSend = new Dictionary <int, ActivityScore>(); switch (message.QueryType) { case QueryType.TopSocial: // TODO: Friends. break; case QueryType.TopAll: // Top 10. for (var i = message.ResultsStart; i < message.ResultsEnd && i < leaderboard.Count; i++) { toSend.Add(i + 1, leaderboard[i]); } break; case QueryType.TopCharacter: // Leaderboard around this player's rank. var playerIndex = leaderboard.FindIndex(score => score.CharacterId == player.Id); // If player is not in leaderboard, return (client will show a friendly message telling the player // to first complete the activity) if (playerIndex == -1) { break; } var availableBefore = playerIndex; var availableAfter = leaderboard.Count - playerIndex; // By default we show 5 scores before this player's, and 4 after (last index isn't included). var includeBefore = 5; var includeAfter = 5; // For every step we can't go before, add one to after includeAfter += Math.Max(0, 5 - availableBefore); // For every step we can't go after, add one to before includeBefore += Math.Max(0, 5 - availableAfter); // Ensure we don't go outside the leaderboard limits var startIndex = Math.Max(0, playerIndex - includeBefore); var stopIndex = Math.Min(leaderboard.Count, playerIndex + includeAfter); for (var i = startIndex; i < stopIndex; i++) { toSend.Add(i + 1, leaderboard[i]); } break; } // "Properly" implementing this odd nested-dictionaries-and-arrays-inside-LDF didn't seem // particularly fun and/or useful; this implementation just does everything needed for leaderboards. var data = new LegoDataDictionary { { "ADO.Result", true }, { "Result.Count", 1 }, { "Result[0].Index", "RowNumber" }, { "Result[0].RowCount", toSend.Count }, }; var index = 0; foreach (var(rank, activityScore) in toSend) { var characterName = ctx.Characters.FirstOrDefault(c => c.Id == activityScore.CharacterId)?.Name ?? "Deleted Character"; data.Add($"Result[0].Row[{index}].CharacterID", activityScore.CharacterId); data.Add($"Result[0].Row[{index}].LastPlayed", activityScore.LastPlayed); data.Add($"Result[0].Row[{index}].NumPlayed", activityScore.NumPlayed); data.Add($"Result[0].Row[{index}].RowNumber", rank); data.Add($"Result[0].Row[{index}].Time", activityScore.Time); data.Add($"Result[0].Row[{index}].Points", activityScore.Points); data.Add($"Result[0].Row[{index}].name", characterName); // TODO: ".Relationship" variable (int). // (AGS client script: if not 0, FoundFriendGuild set to true. Teams?) // data.Add($"Result[0].Row[{index}].Relationship", 0); index++; } player.Message(new SendActivitySummaryLeaderboardDataMessage { Associate = player, GameId = message.GameId, InfoType = (int)message.QueryType, LeaderboardData = data, Throttled = false, Weekly = message.Weekly, }); }
protected EntityRepository() { this.DataPortalLocation = DataPortalLocation.Dynamic; _clientCache = new ClientCache(this); _serverCache = new ServerCache(this); }
/// <summary> /// Gets the thumbnail for the embedded resource with the given id. The thumbnail /// resources are specified in Piranha.Drawing.Thumbnails. /// </summary> /// <param name="context">The current http context</param> /// <param name="id">The resource id</param> /// <param name="size">The desired size</param> public static bool GetResourceThumbnail(HttpContext context, Guid id, int size = 60) { var content = new Content() { Id = id }; if (Drawing.Thumbnails.ContainsKey(id)) { if (!ClientCache.HandleClientCache(context, content.Id.ToString(), new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime)) { var data = Application.Current.MediaCacheProvider.Get(id, size, size); if (data == null) { var resource = Drawing.Thumbnails.GetById(id); if (size <= 32 && resource.Contains("ico-folder")) { resource = Drawing.Thumbnails.GetByType("folder-small"); } Stream strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); var img = Image.FromStream(strm); strm.Close(); // Generate thumbnail from image using (Bitmap bmp = new Bitmap(size, size)) { Graphics grp = Graphics.FromImage(bmp); grp.SmoothingMode = SmoothingMode.HighQuality; grp.CompositingQuality = CompositingQuality.HighQuality; grp.InterpolationMode = InterpolationMode.High; // Resize and crop image Rectangle dst = new Rectangle(0, 0, bmp.Width, bmp.Height); grp.DrawImage(img, dst, img.Width > img.Height ? (img.Width - img.Height) / 2 : 0, img.Height > img.Width ? (img.Height - img.Width) / 2 : 0, Math.Min(img.Width, img.Height), Math.Min(img.Height, img.Width), GraphicsUnit.Pixel); using (var mem = new MemoryStream()) { bmp.Save(mem, img.RawFormat); data = mem.ToArray(); } bmp.Dispose(); grp.Dispose(); } Application.Current.MediaCacheProvider.Put(id, data, size, size); content.WriteFile(context, data); img.Dispose(); } if (data != null) { context.Response.StatusCode = 200; context.Response.ContentType = "image/png"; context.Response.BinaryWrite(data); context.Response.EndClean(); } } return(true); } return(false); }
/// <summary> /// Gets a thumbnail representing the current content file. /// </summary> /// <param name="response">The http response</param> /// <param name="size">The desired size</param> public void GetThumbnail(HttpContext context, int size = 60) { if (!ClientCache.HandleClientCache(context, Id.ToString(), Updated)) { if (File.Exists(CachedThumbnailPath(size))) { // Return generated & cached thumbnail WriteFile(context.Response, CachedThumbnailPath(size)); } else if (File.Exists(PhysicalPath) || IsFolder) { Image img = null; if (IsImage) { img = Image.FromFile(PhysicalPath); } else if (IsFolder) { Stream strm = null; if (size > 32) { strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(folderThumb); } else { strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(folderThumbSmall); } img = Image.FromStream(strm); strm.Close(); } else { if (thumbs.ContainsKey(Type)) { Stream strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(thumbs[Type]); img = Image.FromStream(strm); strm.Close(); } else { Stream strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(defaultThumb); img = Image.FromStream(strm); strm.Close(); } } if (img != null) { // Generate thumbnail from image using (Bitmap bmp = new Bitmap(size, size)) { Graphics grp = Graphics.FromImage(bmp); grp.SmoothingMode = SmoothingMode.HighQuality; grp.CompositingQuality = CompositingQuality.HighQuality; grp.InterpolationMode = InterpolationMode.High; // Resize and crop image Rectangle dst = new Rectangle(0, 0, bmp.Width, bmp.Height); grp.DrawImage(img, dst, img.Width > img.Height ? (img.Width - img.Height) / 2 : 0, img.Height > img.Width ? (img.Height - img.Width) / 2 : 0, Math.Min(img.Width, img.Height), Math.Min(img.Height, img.Width), GraphicsUnit.Pixel); bmp.Save(CachedThumbnailPath(size), img.RawFormat); } WriteFile(context.Response, CachedThumbnailPath(size)); } } } }
static void Construct() { LrpClient = CreateLocalClient(Signature.Value, "SoftFX.LlApi."); LrpLlCommonClient = CreateLocalClient(Financial.Generated.Signature.Value, "SoftFX.LlCommon."); Serializer = new Financial.Generated.Serializer(LrpLlCommonClient); Handle = new Handle(LrpClient); Params = new Params(LrpClient); Client = new ClientServer(LrpClient); ClientCache = new ClientCache(LrpClient); FeedServer = new FeedServer(LrpClient); FeedCache = new FeedCache(LrpClient); TradeServer = new TradeServer(LrpClient); TradeCache = new TradeCache(LrpClient); Converter = new Converter(LrpClient); Iterator = new Iterator(LrpClient); Library = new Library(LrpClient); }
public async Task OnInteract(Player player) { if (PetWild) { XmlDocument doc = new XmlDocument(); //var currentPath = Zone.Server.Config.ResourcesConfiguration.GameResourceFolder; var currentPath = Zone.Server.Resources.RootPath; var partsToFind = ClientCache.Find <TamingBuildPuzzles>(GameObject.Lot) .ValidPiecesLXF.ToLower().Split('\\'); foreach (var part in partsToFind) { var allFound = Directory.GetFileSystemEntries(currentPath); var matching = allFound.FirstOrDefault(path => String.Equals(path, Path.Combine(currentPath, part), StringComparison.CurrentCultureIgnoreCase)); currentPath = matching ?? throw new FileNotFoundException("Could not find " + currentPath); } doc.Load(currentPath); foreach (XmlNode node in doc.DocumentElement.ChildNodes) { if (node.Name == "Bricks") { foreach (XmlNode BrickNode in node.ChildNodes) { if (BrickNode.Name == "Brick") { Brick current = new Brick(); current.DesignID = UInt32.Parse(BrickNode.Attributes["designID"].Value); foreach (XmlNode PartNode in BrickNode.ChildNodes) { if (PartNode.Name == "Part") { Part CurrentPart = new Part(); CurrentPart.Material = Int32.Parse(PartNode.Attributes["materials"].Value.Split(',') .ElementAt(0)); current.DesignPart = CurrentPart; } } Bricks.Add(current); } } break; } } Vector3 petPos = GameObject.Transform.Position; Vector3 pos = player.Transform.Position; double deg = Math.Atan2(petPos.Z - pos.Z, petPos.X - pos.X) * 180 / Math.PI; var interaction_distance = GameObject.Settings.ContainsKey("interaction_distance") ? GameObject.Settings["interaction_distance"] : 0.0f; pos = new Vector3( petPos.X + (float)interaction_distance * (float)Math.Cos(-deg), petPos.Y, petPos.Z + (float)interaction_distance * (float)Math.Sin(-deg) ); Zone.BroadcastMessage(new NotifyPetTamingMinigameMessage { Associate = player, ForceTeleport = true, PlayerTaming = player, PetId = GameObject.Id, NotifyType = PetTamingNotifyType.Begin, PetDestinationPosition = petPos, TeleportPosition = pos, TeleportRotation = pos.QuaternionLookRotation(petPos) }); player.Message(new NotifyPetTamingPuzzleSelectedMessage { Associate = player, Bricks = Bricks.ToArray() }); player.Message(new NotifyPetTamingMinigameMessage { Associate = GameObject, ForceTeleport = false, NotifyType = PetTamingNotifyType.Begin, PetId = (ObjectId)(ulong)0, PetDestinationPosition = Vector3.Zero, PlayerTaming = player, TeleportPosition = Vector3.Zero, TeleportRotation = Quaternion.Identity }); // Create all the pet listeners for other events Listen(player.OnPetTamingTryBuild, OnPetTamingTryBuild); Listen(player.OnNotifyTamingBuildSuccessMessage, OnNotifyTamingBuildSuccessMessage); } }
/// <summary> /// Loads generic CdClient information about the mission. /// </summary> private async Task LoadTemplateAsync() { var mission = await ClientCache.FindAsync <Core.Client.Missions>(MissionId); PrerequisiteMissions = mission.PrereqMissionID; IsMission = mission.IsMission ?? true; IsChoiceReward = (mission.IsChoiceReward ?? false) && IsMission; DefinedType = mission.Definedtype; DefinedSubType = mission.Definedsubtype; // Possible stat rewards RewardMaxHealth = mission.Rewardmaxhealth ?? 0; RewardMaxImagination = mission.Rewardmaximagination ?? 0; RewardMaxInventory = mission.Rewardmaxinventory ?? 0; RewardCurrency = mission.Rewardcurrency ?? 0; RewardCurrencyRepeatable = mission.Rewardcurrencyrepeatable ?? 0; RewardScore = mission.LegoScore ?? 0; Repeatable = mission.Repeatable ?? false; CooldownTime = mission.CooldownTime ?? 0; // Emotes RewardEmote1 = mission.Rewardemote ?? -1; RewardEmote2 = mission.Rewardemote2 ?? -1; RewardEmote3 = mission.Rewardemote3 ?? -1; RewardEmote4 = mission.Rewardemote4 ?? -1; // First optional reward item RewardItem1 = mission.Rewarditem1 ?? 0; RewardItem1Count = mission.Rewarditem1count ?? 1; RewardItem1Repeatable = mission.Rewarditem1repeatable ?? 0; RewardItem1RepeatableCount = mission.Rewarditem1repeatcount ?? 1; // Second optional reward item RewardItem2 = mission.Rewarditem2 ?? 0; RewardItem2Count = mission.Rewarditem2count ?? 1; RewardItem2Repeatable = mission.Rewarditem2repeatable ?? 0; RewardItem2RepeatableCount = mission.Rewarditem2repeatcount ?? 1; // Third optional reward item RewardItem3 = mission.Rewarditem3 ?? 0; RewardItem3Count = mission.Rewarditem3count ?? 1; RewardItem3Repeatable = mission.Rewarditem3repeatable ?? 0; RewardItem3RepeatableCount = mission.Rewarditem3repeatcount ?? 1; // Fourth optional reward item RewardItem4 = mission.Rewarditem4 ?? 0; RewardItem4Count = mission.Rewarditem4count ?? 1; RewardItem4Repeatable = mission.Rewarditem4repeatable ?? 0; RewardItem4RepeatableCount = mission.Rewarditem4repeatcount ?? 1; // Optional increment for vault inventory size RewardBankInventory = mission.Rewardbankinventory ?? 0; // Load all the tasks for this mission var tasks = await ClientCache.MissionTasksWithMissionIdCacheTable.FindAllAsync <MissionTasks>(MissionId); Tasks = new List <MissionTaskInstance>(); var index = 0; foreach (var task in tasks) { var taskType = (MissionTaskType)(task.TaskType ?? 0); if (!TaskTypes.TryGetValue(taskType, out var type)) { Logger.Debug($"No {nameof(MissionTaskInstance)} for {taskType} found."); continue; } if (task.Uid != null) { var instance = (MissionTaskInstance)Activator.CreateInstance(type, this, task.Uid.Value, index); if (instance == default || task.Uid == default) { Logger.Error($"Invalid task: {type} [{task.Uid}]"); continue; } instance.LoadTemplate(task); Tasks.Add(instance); } index++; } }
public void BindList(int SchoolID = 0, int TrainPlaceID = 0, bool getFromCache = true) { if (getFromCache) { if (SchoolID > 0 && TrainPlaceID > 0) { ListIsValid = (List <Group>)ClientCache.GetAuto("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListByPlaceSchool(TrainPlaceID, SchoolID)); } else { if (TrainPlaceID > 0) { ListIsValid = (List <Group>) ClientCache.GetAuto("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListByTrainPlace(TrainPlaceID)); } else { if (SchoolID > 0) { ListIsValid = (List <Group>)ClientCache.GetAuto("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListBySchool(SchoolID)); } else { ListIsValid = (List <Group>)ClientCache.GetAuto("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetList()); } } } } else { if (SchoolID > 0 && TrainPlaceID > 0) { ListIsValid = (List <Group>)ClientCache.GetUpdate("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListByPlaceSchool(TrainPlaceID, SchoolID)); } else { if (TrainPlaceID > 0) { ListIsValid = (List <Group>) ClientCache.GetUpdate("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListByTrainPlace(TrainPlaceID)); } else { if (SchoolID > 0) { ListIsValid = (List <Group>)ClientCache.GetUpdate("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetListBySchool(SchoolID)); } else { ListIsValid = (List <Group>)ClientCache.GetUpdate("Group" + SchoolID + TrainPlaceID, () => new GroupDao().GetList()); } } } } Properties.DataSource = ListIsValid; Properties.DisplayMember = "GroupName"; Properties.ValueMember = "GroupID"; Properties.BestFitMode = BestFitMode.BestFitResizePopup; Properties.SearchMode = SearchMode.AutoFilter; Properties.CaseSensitiveSearch = true; Properties.AutoSearchColumnIndex = 2; }