public void UserJoined(IVoltronSession session) { using (var da = DAFactory.Get()) { var myLotID = da.Roommates.GetAvatarsLots(session.AvatarId).FirstOrDefault(); var myLot = (myLotID == null) ? null : da.Lots.Get(myLotID.lot_id); if (myLot != null) { var free = da.Elections.GetFreeVote(session.AvatarId); var nhoodID = (int)(myLot?.neighborhood_id ?? 0); if (free != null) { nhoodID = free.neighborhood_id; //enrolled to a free vote. receive vote mail for that neighborhood } var myNeigh = da.Neighborhoods.Get((uint)nhoodID); if (myNeigh != null && myNeigh.election_cycle_id != null) { var curCycle = da.Elections.GetCycle(myNeigh.election_cycle_id.Value); if (curCycle != null) { var date = Epoch.Now; if (StateHasEmail(curCycle.current_state) && date < curCycle.end_date + 3 * 24 * 60 * 60) { var mail = Kernel.Get <MailHandler>(); SendStateEmail(da, mail, myNeigh, curCycle, session.AvatarId); } } } } } }
public void TickEvents() { var time = DateTime.UtcNow; if (time > Next) //check events every hour { Next = NextHour(time); //activate the new event using (var da = DA.Get()) { var active = da.Events.GetActive(time); List <DbEvent> newEvts, oldEvts; lock (ActiveEvents) { newEvts = active.Where(x => !ActiveEvents.Any(y => y.event_id == x.event_id)).ToList(); oldEvts = ActiveEvents.Where(x => !active.Any(y => y.event_id == x.event_id)).ToList(); ActiveEvents.Clear(); ActiveEvents.AddRange(active); } //TODO: deactivation event ActivateEvents(newEvts); } } }
public void RunMissedTasks() { using (var db = DAFactory.Get()) { foreach (var task in _Schedule) { if (!task.Run_If_Missed) { continue; } DbTaskType type; if (!Enum.TryParse(task.Task, out type)) { continue; } var rangeEnd = task.CronSchedule.GetLastValidTime(); var rangeStart = task.CronSchedule.GetStartOfRange(rangeEnd); var lastRun = db.Tasks.CompletedAfter(type, rangeStart); if (lastRun == null) { Run(task); } } } }
public async void Handle(IGluonSession session, NotifyLotRoommateChange packet) { //recieved from a lot server to notify of another lot's roommate change. using (var da = DAFactory.Get()) { var lot = da.Lots.Get(packet.LotId); if (lot == null) { return; //lot missing } DataService.Invalidate <FSO.Common.DataService.Model.Lot>(lot.location); //if online, notify the lot var lotOwned = da.LotClaims.GetByLotID(lot.lot_id); if (lotOwned != null) { var lotServer = LotServers.GetLotServerSession(lotOwned.owner); if (lotServer != null) { //immediately notify lot of new roommate lotServer.Write(packet); } } else { //try force the lot open //we don't need to send any packets in this case - the lot fully restores object ownership from db. var result = await Lots.TryFindOrOpen(lot.location, 0, NullSecurityContext.INSTANCE); } } }
public void UserJoined(IVoltronSession session) { //common info used by most requests using (var da = DAFactory.Get()) { var myLotID = da.Roommates.GetAvatarsLots(session.AvatarId).FirstOrDefault(); var myLot = (myLotID == null) ? null : da.Lots.Get(myLotID.lot_id); if (myLot != null) { var myNeigh = da.Neighborhoods.Get(myLot.neighborhood_id); if (myNeigh != null && myNeigh.election_cycle_id != null) { var curCycle = da.Elections.GetCycle(myNeigh.election_cycle_id.Value); if (curCycle != null) { var date = Epoch.Now; if (StateHasEmail(curCycle.current_state) && date < curCycle.end_date + 3 * 24 * 60 * 60) { var mail = Kernel.Get <MailHandler>(); SendStateEmail(da, mail, myNeigh, curCycle, session.AvatarId); } } } } } }
protected override void PreLoad(Callback <uint, Neighborhood> appender) { using (var db = DAFactory.Get()) { var nhoods = db.Neighborhoods.All(ShardId); var midnight = LotVisitUtils.Midnight(); //gets this morning's midnight (basically current date, with day reset) var activityBeginning = midnight - new TimeSpan(7, 0, 0, 0); var visits = db.LotVisits.StreamBetweenPlusNhood(ShardId, activityBeginning, midnight).ToList(); var enumerator = visits.GetEnumerator(); var nhoodHours = new Dictionary <uint, double>(); while (enumerator.MoveNext()) { var visit = enumerator.Current; var span = LotVisitUtils.CalculateDateOverlap(activityBeginning, midnight, visit.time_created, visit.time_closed.Value); if (nhoodHours.ContainsKey(visit.neighborhood_id)) { nhoodHours[visit.neighborhood_id] += span.TotalMinutes; } else { nhoodHours.Add(visit.neighborhood_id, span.TotalMinutes); } } var order = nhoodHours.OrderByDescending(x => x.Value).ToList(); WorstRating = nhoods.Count; foreach (var item in nhoods) { var lots = db.Lots.GetLocationsInNhood((uint)item.neighborhood_id); var avatars = db.Avatars.GetLivingInNhood((uint)item.neighborhood_id); var townHall = db.Lots.Get(item.town_hall_id ?? 0)?.location ?? 0; var cycle = (item.election_cycle_id == null) ? null : db.Elections.GetCycle(item.election_cycle_id.Value); var converted = HydrateOne(item, avatars, lots, townHall, cycle, visits, order); var intId = (uint)item.neighborhood_id; appender(intId, converted); } // var neighObj = nhoods.Select(x => { var loc = MapCoordinates.Unpack(x.location); var result = new CityNeighbourhood() { Name = x.name, Color = new Color(x.color), Description = x.description, GUID = x.guid, Location = new Point(loc.X, loc.Y), ID = x.neighborhood_id }; return(result); }).ToList(); Lots.CityRepresentation.City_NeighJSON = JsonConvert.SerializeObject(neighObj); } }
public void Free() { //Release the claim if (ClaimId == null) { return; } using (var da = DAFactory.Get()) { da.LotClaims.Delete(ClaimId.Value, Context.Config.Call_Sign); } }
/// <summary> /// Changes a user's password. /// </summary> /// <param name="user_id"></param> /// <param name="new_password"></param> public void ChangePassword(uint user_id, string new_password) { using (var da = DAFactory.Get()) { var passhash = PasswordHasher.Hash(new_password); var authSettings = new Database.DA.Users.UserAuthenticate(); authSettings.scheme_class = passhash.scheme; authSettings.data = passhash.data; authSettings.user_id = user_id; da.Users.UpdateAuth(authSettings); } }
public bool TryJoin(IVoltronSession session) { if (Container.IsAvatarOnLot(session.AvatarId)) { return(false); //already on the lot. } lock (_Visitors) { if (ShuttingDown || (_Visitors.Count >= ((Context.HighMax)?128:24))) { if (ShuttingDown) { return(false); //cannot join } //check if this user has special permissions. should only happen when a lot is full //let them in anyways if they do var avatar = DAFactory.Get().Avatars.Get(session.AvatarId); if (avatar.moderation_level == 0 && !Context.JobLot) { if (DAFactory.Get().Roommates.Get(session.AvatarId, Context.DbId) == null) { return(false); //not a roommate } } } session.SetAttribute("currentLot", ((Context.Id & 0x40000000) > 0)?(int)Context.Id:Context.DbId); _Visitors.Add(session.AvatarId, session); SyncNumVisitors(); InBackground(() => Container.AvatarJoin(session)); return(true); } }
/* * TODO: city data service access for desired shards. * Need to maintain connections to shards and request from their data services... * Either that or online status has to at least writeback to DB. */ public CityInfoController(IDAFactory daFactory, IServerNFSProvider nfs) : base("/userapi/city") { this.DAFactory = daFactory; this.NFS = nfs; this.After.AddItemToEndOfPipeline(x => { x.Response.WithHeader("Access-Control-Allow-Origin", "*"); }); this.Get["/{shardid}/{id}.png"] = parameters => { using (var da = daFactory.Get()) { var lot = da.Lots.GetByLocation((int)parameters.shardid, (uint)parameters.id); if (lot == null) { return(HttpStatusCode.NotFound); } return(Response.AsImage(Path.Combine(NFS.GetBaseDirectory(), "Lots/" + lot.lot_id.ToString("x8") + "/thumb.png"))); } }; this.Get["/{shardid}/city.json"] = parameters => { var now = Epoch.Now; if (LastModelUpdate < now - 15) { LastModelUpdate = now; lock (ModelLock) { LastModel = new CityInfoModel(); using (var da = daFactory.Get()) { var lots = da.Lots.AllLocations((int)parameters.shardid); var lotstatus = da.LotClaims.AllLocations((int)parameters.shardid); LastModel.reservedLots = lots.ConvertAll(x => x.location).ToArray(); LastModel.names = lots.ConvertAll(x => x.name).ToArray(); LastModel.activeLots = lotstatus.ConvertAll(x => x.location).ToArray(); LastModel.onlineCount = lotstatus.ConvertAll(x => x.active).ToArray(); } } } lock (ModelLock) { return(Response.AsJson(LastModel)); } }; }
private object HandleLoadAvatarById(IVoltronSession session, cTSONetMessageStandard msg) { var request = msg.ComplexParameter as LoadAvatarByIDRequest; if (request == null) { return(null); } if (request.AvatarId != session.AvatarId) { throw new Exception("Permission denied, you cannot load an avatar you do not own"); } using (var da = DAFactory.Get()) { var avatar = da.Avatars.Get(session.AvatarId); if (avatar == null) { return(null); } var bonus = da.Bonus.GetByAvatarId(avatar.avatar_id); return(new cTSONetMessageStandard() { MessageID = 0x8ADF865D, DatabaseType = DBResponseType.LoadAvatarByID.GetResponseID(), Parameter = msg.Parameter, ComplexParameter = new LoadAvatarByIDResponse() { AvatarId = session.AvatarId, Cash = (uint)avatar.budget, Bonus = bonus.Select(x => { return new LoadAvatarBonus() { PropertyBonus = x.bonus_property == null ? (uint)0 : (uint)x.bonus_property.Value, SimBonus = x.bonus_sim == null ? (uint)0 : (uint)x.bonus_sim.Value, VisitorBonus = x.bonus_visitor == null ? (uint)0 : (uint)x.bonus_visitor, Date = x.period.ToShortDateString() }; }).ToList() } }); }; }
public void Handle(IVoltronSession session, FindAvatarRequest packet) { if (session.IsAnonymous) { return; } using (var da = DAFactory.Get()) { var privacy = da.Avatars.GetPrivacyMode(packet.AvatarId); if (privacy > 0) { session.Write(new FindAvatarResponse { AvatarId = packet.AvatarId, LotId = 0, Status = FindAvatarResponseStatus.PRIVACY_ENABLED }); return; } //TODO: get ignore status var claim = da.AvatarClaims.GetByAvatarID(packet.AvatarId); //maybe check shard id against avatar in future. The client should do this anyways, and the server providing this functionality to everyone isnt a disaster. var location = claim?.location ?? 0; session.Write(new FindAvatarResponse { AvatarId = packet.AvatarId, LotId = location, Status = (location == 0)?FindAvatarResponseStatus.NOT_ON_LOT:FindAvatarResponseStatus.FOUND }); } }
public void UpdateTuningCache() { lock (this) { using (var da = DAFactory.Get()) { TuningCache = new DynamicTuning(da.Tuning.All()); } var upgrades = Content.Content.Get().Upgrades.ActiveFile; if (upgrades == null) { ObjectUpgradeData = new byte[0]; } else { using (var mem = new MemoryStream()) { using (var writer = new BinaryWriter(mem)) { upgrades.Save(writer); } ObjectUpgradeData = mem.ToArray(); } } } }
protected override void Bootstrap() { base.Bootstrap(); IDAFactory da = Kernel.Get <IDAFactory>(); using (var db = da.Get()) { var oldClaims = db.LotClaims.GetAllByOwner(Config.Call_Sign).ToList(); if (oldClaims.Count > 0) { LOG.Warn("Detected " + oldClaims.Count + " previously allocated lot claims, perhaps the server did not shut down cleanly. Lot consistency may be affected."); db.LotClaims.RemoveAllByOwner(Config.Call_Sign); } var oldAvatarClaims = db.AvatarClaims.GetAllByOwner(Config.Call_Sign).ToList(); if (oldAvatarClaims.Count > 0) { LOG.Warn("Detected " + oldAvatarClaims.Count + " avatar claims, perhaps the server did not shut down cleanly. Avatar consistency may be affected."); db.AvatarClaims.DeleteAll(Config.Call_Sign); } } Connections = Kernel.Get <CityConnections>(); Connections.OnCityDisconnected += Connections_OnCityDisconnected; Connections.Start(); }
public void Handle(IGluonSession session, TransferClaim request) { if (request.Type != Protocol.Gluon.Model.ClaimType.LOT) { //what? session.Write(new TransferClaimResponse { Status = TransferClaimResponseStatus.REJECTED, Type = request.Type, ClaimId = request.ClaimId, EntityId = request.EntityId }); return; } Lots.TryClose(request.EntityId, request.ClaimId); try { using (var db = DAFactory.Get()) { db.LotClaims.Delete(request.ClaimId, request.FromOwner); } } catch (Exception e) { //probably already unclaimed. do nothing. } }
public async void Handle(IVoltronSession session, AvatarRetireRequest packet) { if (session.IsAnonymous) //CAS users can't do this. { return; } try { using (var da = DA.Get()) { var avatar = da.Avatars.Get(session.AvatarId); if (avatar == null) { return; } if (avatar.date > Epoch.Now - (60 * 60 * 24 * 7) && !da.Users.GetById(session.UserId).is_admin) { session.Write(new Protocol.Voltron.Packets.AnnouncementMsgPDU() { SenderID = "??" + "System", Message = "\r\n" + "You cannot delete a sim younger than a week old!", Subject = "Error" }); LOG.Info("Avatar " + avatar.name + " under account " + avatar.user_id + " attempted to delete a less than week old account."); session.Close(); return; } LOG.Info("Deleting avatar " + avatar.name + " under account " + avatar.user_id + "."); var lots = da.Roommates.GetAvatarsLots(session.AvatarId); foreach (var roomie in lots) { var lot = da.Lots.Get(roomie.lot_id); if (lot == null) { continue; } var kickResult = await Kernel.Get <ChangeRoommateHandler>().TryKick(lot.location, session.AvatarId, session.AvatarId); //if something goes wrong here, just return. if (kickResult != Protocol.Electron.Model.ChangeRoommateResponseStatus.SELFKICK_SUCCESS) { return; } } da.Avatars.Delete(session.AvatarId); } //now all our objects have null owner. objects with null owner will be cleaned out by the purge task (this needs to hit nfs & db). session.Close(); } catch { } }
public override void Start() { Bootstrap(); using (var db = DAFactory.Get()) { db.Hosts.CreateHost(CreateHost()); } Acceptor = new AsyncSocketAcceptor(); try { if (Config.Certificate != null) { var ssl = new SslFilter(new System.Security.Cryptography.X509Certificates.X509Certificate2(Config.Certificate)); ssl.SslProtocol = SslProtocols.Tls; Acceptor.FilterChain.AddLast("ssl", ssl); if (Debugger != null) { Acceptor.FilterChain.AddLast("packetLogger", new AriesProtocolLogger(Debugger.GetPacketLogger(), Kernel.Get <ISerializationContext>())); Debugger.AddSocketServer(this); } Acceptor.FilterChain.AddLast("protocol", new ProtocolCodecFilter(Kernel.Get <AriesProtocol>())); Acceptor.Handler = this; Acceptor.Bind(IPEndPointUtils.CreateIPEndPoint(Config.Binding)); LOG.Info("Listening on " + Acceptor.LocalEndPoint + " with TLS"); } //Bind in the plain too as a workaround until we can get Mina.NET to work nice for TLS in the AriesClient PlainAcceptor = new AsyncSocketAcceptor(); if (Debugger != null) { PlainAcceptor.FilterChain.AddLast("packetLogger", new AriesProtocolLogger(Debugger.GetPacketLogger(), Kernel.Get <ISerializationContext>())); } PlainAcceptor.FilterChain.AddLast("protocol", new ProtocolCodecFilter(Kernel.Get <AriesProtocol>())); PlainAcceptor.Handler = this; PlainAcceptor.Bind(IPEndPointUtils.CreateIPEndPoint(Config.Binding.Replace("100", "101"))); LOG.Info("Listening on " + PlainAcceptor.LocalEndPoint + " in the plain"); } catch (Exception ex) { LOG.Error("Unknown error bootstrapping server: " + ex.ToString(), ex); } }
public void UpdateTuning(bool immediately) { LOG.Info("Updating tuning on lot server " + Config.Call_Sign + "..."); using (var da = DAFactory.Get()) { var tuning = da.Tuning.All().ToList(); List <LotHostEntry> lots; lock (Lots) lots = Lots.Values.ToList(); foreach (var lot in lots) { var container = lot.Container; lot.InBackground(() => { container?.UpdateTuning(tuning); }); } } }
public override void PersistMutation(object entity, MutationType type, string path, object value) { var avatar = entity as Avatar; using (var db = DAFactory.Get()) { switch (path) { case "Avatar_Description": db.Avatars.UpdateDescription(avatar.Avatar_Id, avatar.Avatar_Description); break; case "Avatar_PrivacyMode": db.Avatars.UpdatePrivacyMode(avatar.Avatar_Id, avatar.Avatar_PrivacyMode); break; } } }
public AdminTasksController(IDAFactory daFactory, JWTFactory jwt, IGluonHostPool hostPool) : base("/admin") { JWTTokenAuthentication.Enable(this, jwt); this.Get["/tasks"] = _ => { this.DemandAdmin(); using (var da = daFactory.Get()) { var offset = this.Request.Query["offset"]; var limit = this.Request.Query["limit"]; if (offset == null) { offset = 0; } if (limit == null) { limit = 20; } if (limit > 100) { limit = 100; } var result = da.Tasks.All((int)offset, (int)limit); return(Response.AsPagedList <DbTask>(result)); } }; this.Post["/tasks/request"] = x => { var task = this.Bind <TaskRequest>(); var taskServer = hostPool.GetByRole(Database.DA.Hosts.DbHostRole.task).FirstOrDefault(); if (taskServer == null) { return(Response.AsJson(-1)); } else { try { var id = taskServer.Call(new RequestTask() { TaskType = task.task_type.ToString(), ParameterJson = JsonConvert.SerializeObject(task.parameter), ShardId = (task.shard_id == null || !task.shard_id.HasValue) ? -1 : task.shard_id.Value }).Result; return(Response.AsJson(id)); }catch (Exception ex) { return(Response.AsJson(-1)); } } }; }
public bool AttemptLoadRing() { //first let's try load our adjacent lots. int attempts = 0; var lotStr = LotPersist.lot_id.ToString("x8"); while (++attempts < Config.RingBufferSize) { LOG.Info("Checking ring " + attempts + " for lot with dbid = " + Context.DbId); try { var path = Path.Combine(Config.SimNFS, "Lots/" + lotStr + "/state_" + LotPersist.ring_backup_num.ToString() + ".fsov"); using (var file = new BinaryReader(File.OpenRead(path))) { var marshal = new VMMarshal(); marshal.Deserialize(file); if (LotPersist.move_flags > 0) { //must rotate lot to face its new road direction! var oldDir = ((VMTSOLotState)marshal.PlatformState).Size >> 16; var newDir = VMLotTerrainRestoreTools.PickRoadDir(Terrain.Roads[1, 1]); var rotate = new VMLotRotate(marshal); rotate.Rotate(((newDir - oldDir) + 4) % 4); } Lot.Load(marshal); CleanLot(); Lot.Reset(); } using (var db = DAFactory.Get()) db.Lots.UpdateRingBackup(LotPersist.lot_id, LotPersist.ring_backup_num); return(true); } catch (Exception e) { LOG.Info("Ring load failed with exception: " + e.ToString() + " for lot with dbid = " + Context.DbId); LotPersist.ring_backup_num--; if (LotPersist.ring_backup_num < 0) { LotPersist.ring_backup_num += (sbyte)Config.RingBufferSize; } } } LOG.Error("FAILED to load all backups for lot with dbid = " + Context.DbId + "! Forcing lot close"); var backupPath = Path.Combine(Config.SimNFS, "Lots/" + lotStr + "/failedRestore" + (DateTime.Now.ToBinary().ToString()) + "/"); Directory.CreateDirectory(backupPath); foreach (var file in Directory.EnumerateFiles(Path.Combine(Config.SimNFS, "Lots/" + lotStr + "/"))) { File.Copy(file, backupPath + Path.GetFileName(file)); } throw new Exception("failed to load lot!"); return(false); }
protected override void PreLoad(Callback <uint, Lot> appender) { using (var db = DAFactory.Get()) { var all = db.Lots.All(ShardId); foreach (var item in all) { var roommates = db.Roommates.GetLotRoommates(item.lot_id); var admit = db.LotAdmit.GetLotInfo(item.lot_id); var converted = HydrateOne(item, roommates, admit); var intId = MapCoordinates.Pack(converted.Lot_Location.Location_X, converted.Lot_Location.Location_Y); appender(intId, converted); } } }
public async void SessionClosed(IAriesSession session) { if (!(session is IVoltronSession)) { return; } IVoltronSession voltronSession = (IVoltronSession)session; VoltronSessions.UnEnroll(session); if (voltronSession.IsAnonymous) { return; } Liveness.EnqueueChange(() => { //unenroll in voltron group, mark as offline in data service. //since this can happen async make sure our session hasnt been reopened before trying to delete its claim if (Sessions.GetByAvatarId(voltronSession.AvatarId)?.Connected == true) { return; } var avatar = DataService.Get <Avatar>(voltronSession.AvatarId).Result; if (avatar != null) { avatar.Avatar_IsOnline = false; } using (var db = DAFactory.Get()) { // if we don't own the claim for the avatar, we need to tell the server that does to release the avatar. // right now it's just lot servers. var claim = db.AvatarClaims.Get(voltronSession.AvatarClaimId); if (claim != null && claim.owner != Context.Config.Call_Sign) { var lotServer = LotServers.GetLotServerSession(claim.owner); if (lotServer != null) { var lot = db.Lots.GetByLocation(Context.ShardId, claim.location); lotServer.Write(new RequestLotClientTermination() { AvatarId = voltronSession.AvatarId, LotId = (lot != null) ? lot.lot_id : ((int)claim.location), FromOwner = Context.Config.Call_Sign }); } } //nuke the claim anyways to be sure. db.AvatarClaims.Delete(voltronSession.AvatarClaimId, Context.Config.Call_Sign); } }); }
public void OnTransferClaimResponse(TransferClaimResponse response) { if (response.Type != Protocol.Gluon.Model.ClaimType.LOT) { return; } uint?location; if (response.ClaimId != 0) { using (var da = DAFactory.Get()) { location = da.Lots.Get(response.EntityId)?.location; } } else { location = (uint)response.EntityId; } if (location == null) { return; } var allocation = Get(location.Value); lock (allocation) { allocation.OnTransferClaimResponse(response); if (allocation.State == LotAllocationState.FAILED) { //Failed, remove LotAllocation removedAllocation = Remove(location.Value); } } //Touches the db so do this outside of the lock if (allocation.State == LotAllocationState.FAILED) { allocation.Free(); } }
public void UpdateTuningCache() { lock (this) { using (var da = DAFactory.Get()) { TuningCache = new DynamicTuning(da.Tuning.All()); } } }
protected override void Bootstrap() { var shards = Kernel.Get <IShardsDomain>(); var shard = shards.GetById(Config.ID); if (shard == null) { throw new Exception("Unable to find a shard with id " + Config.ID + ", check it exists in the database"); } LOG.Info("City identified as " + shard.Name); var context = new CityServerContext(); context.ShardId = shard.Id; context.Config = Config; Kernel.Bind <EventSystem>().ToSelf().InSingletonScope(); Kernel.Bind <CityLivenessEngine>().ToSelf().InSingletonScope(); Kernel.Bind <CityServerContext>().ToConstant(context); Kernel.Bind <int>().ToConstant(shard.Id).Named("ShardId"); Kernel.Bind <CityServerConfiguration>().ToConstant(Config); Kernel.Bind <JobMatchmaker>().ToSelf().InSingletonScope(); Kernel.Bind <LotServerPicker>().To <LotServerPicker>().InSingletonScope(); Kernel.Bind <LotAllocations>().To <LotAllocations>().InSingletonScope(); Kernel.Bind <Neighborhoods>().ToSelf().InSingletonScope(); Kernel.Bind <Tuning>().ToSelf().InSingletonScope(); Liveness = Kernel.Get <CityLivenessEngine>(); IDAFactory da = Kernel.Get <IDAFactory>(); using (var db = da.Get()){ var version = ServerVersion.Get(); db.Shards.UpdateVersion(shard.Id, version.Name, version.Number, version.UpdateID); ((Shards)shards).Update(); var oldClaims = db.LotClaims.GetAllByOwner(context.Config.Call_Sign).ToList(); if (oldClaims.Count > 0) { LOG.Warn("Detected " + oldClaims.Count + " previously allocated lot claims, perhaps the server did not shut down cleanly. Lot consistency may be affected."); db.LotClaims.RemoveAllByOwner(context.Config.Call_Sign); } var oldAvatarClaims = db.AvatarClaims.GetAllByOwner(context.Config.Call_Sign).ToList(); if (oldAvatarClaims.Count > 0) { LOG.Warn("Detected " + oldAvatarClaims.Count + " avatar claims, perhaps the server did not shut down cleanly. Avatar consistency may be affected."); db.AvatarClaims.DeleteAll(context.Config.Call_Sign); } } base.Bootstrap(); Kernel.Get <EventSystem>().Init(); }
public void Handle(IVoltronSession session, ModerationRequest packet) { if (session.IsAnonymous) { return; } using (var da = DAFactory.Get()) { var user = da.Users.GetById(session.UserId); var mod = user.is_moderator; var admin = user.is_admin; if (!(mod || admin)) { return; } switch (packet.Type) { case ModerationRequestType.IPBAN_USER: case ModerationRequestType.BAN_USER: case ModerationRequestType.KICK_USER: var targetAvatar = packet.EntityId; if (packet.Type == ModerationRequestType.BAN_USER || packet.Type == ModerationRequestType.IPBAN_USER) { var ava = da.Avatars.Get(packet.EntityId); if (ava != null) { var theiruser = da.Users.GetById(ava.user_id); if (theiruser != null && !(theiruser.is_admin || theiruser.is_moderator)) { FSO.Server.Api.Api.INSTANCE?.SendBanMail(theiruser.username, theiruser.email, 0); // Need to handle end_date in the future da.Users.UpdateBanned(theiruser.user_id, true); if (packet.Type == ModerationRequestType.IPBAN_USER && theiruser.last_ip != "127.0.0.1" && theiruser.last_ip != "::1") { da.Bans.Add(theiruser.last_ip, theiruser.user_id, "Banned from ingame", 0, theiruser.client_id); } } else { return; } } } Sessions.GetByAvatarId(targetAvatar)?.Close(); break; } } }
public async void SessionClosed(IAriesSession session) { if (!(session is IVoltronSession)) { return; } IVoltronSession voltronSession = (IVoltronSession)session; VoltronSessions.UnEnroll(session); if (voltronSession.IsAnonymous) { return; } //unenroll in voltron group, mark as offline in data service. var avatar = await DataService.Get <Avatar>(voltronSession.AvatarId); if (avatar != null) { avatar.Avatar_IsOnline = false; } using (var db = DAFactory.Get()) { // if we don't own the claim for the avatar, we need to tell the server that does to release the avatar. // right now it's just lot servers. var claim = db.AvatarClaims.GetByAvatarID((uint)voltronSession.AvatarClaimId); if (claim != null && claim.owner != Context.Config.Call_Sign) { var lotServer = LotServers.GetLotServerSession(claim.owner); if (lotServer != null) { var lot = db.Lots.GetByLocation(Context.ShardId, claim.location); lotServer.Write(new RequestLotClientTermination() { AvatarId = voltronSession.AvatarId, LotId = (lot != null)?lot.lot_id:((int)claim.location), FromOwner = Context.Config.Call_Sign }); } } //nuke the claim anyways to be sure. db.AvatarClaims.Delete(voltronSession.AvatarClaimId, Context.Config.Call_Sign); } }
public AdminShardsController(IDAFactory daFactory, JWTFactory jwt) : base("/admin") { JWTTokenAuthentication.Enable(this, jwt); this.Get["/shards"] = _ => { this.DemandAdmin(); using (var db = daFactory.Get()) { var shards = db.Shards.All(); return(Response.AsJson(shards)); } }; }
public LotContainer(IDAFactory da, LotContext context, ILotHost host, IKernel kernel, LotServerConfiguration config, IRealestateDomain realestate) { VM.UseWorld = false; DAFactory = da; Host = host; Context = context; Kernel = kernel; Config = config; JobLot = (context.Id & 0x40000000) > 0; if (JobLot) { var jobPacked = Context.DbId - 0x200; var jobLevel = (short)((jobPacked - 1) & 0xF); var jobType = (short)((jobPacked - 1) / 0xF); LotPersist = new DbLot { lot_id = Context.DbId, location = Context.Id, category = LotCategory.money, name = "{job:" + jobType + ":" + jobLevel + "}", admit_mode = 4 }; LotAdj = new List <DbLot>(); LotRoommates = new List <DbRoommate>(); Terrain = new VMTSOSurroundingTerrain(); for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { Terrain.Roads[x, y] = 0xF; //crossroads everywhere } } } else { using (var db = DAFactory.Get()) { LotPersist = db.Lots.Get(context.DbId); LotAdj = db.Lots.GetAdjToLocation(context.ShardId, LotPersist.location); LotRoommates = db.Roommates.GetLotRoommates(context.DbId); } Realestate = realestate.GetByShard(LotPersist.shard_id); GenerateTerrain(); } }