-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegionManager.cs
678 lines (620 loc) · 18.2 KB
/
RegionManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/*
TShock, a server mod for Terraria
Copyright (C) 2011-2012 The TShock Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml;
using MySql.Data.MySqlClient;
using TShockAPI;
using TShockAPI.DB;
using Terraria;
namespace Regions
{
public class RegionManager
{
public List<Region> Regions = new List<Region>();
private IDbConnection database;
public RegionManager(IDbConnection db)
{
database = db;
var table = new SqlTable("Regions",
new SqlColumn("X1", MySqlDbType.Int32),
new SqlColumn("Y1", MySqlDbType.Int32),
new SqlColumn("width", MySqlDbType.Int32),
new SqlColumn("height", MySqlDbType.Int32),
new SqlColumn("RegionName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("WorldID", MySqlDbType.Text),
new SqlColumn("UserIds", MySqlDbType.Text),
new SqlColumn("Protected", MySqlDbType.Int32),
new SqlColumn("Groups", MySqlDbType.Text),
new SqlColumn("Owner", MySqlDbType.VarChar, 50),
new SqlColumn("Z", MySqlDbType.Int32){ DefaultValue = "0" }
);
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
ReloadAllRegions();
}
public void ReloadAllRegions()
{
try
{
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", Main.worldID.ToString()))
{
Regions.Clear();
while (reader.Read())
{
int X1 = reader.Get<int>("X1");
int Y1 = reader.Get<int>("Y1");
int height = reader.Get<int>("height");
int width = reader.Get<int>("width");
int Protected = reader.Get<int>("Protected");
string mergedids = reader.Get<string>("UserIds");
string name = reader.Get<string>("RegionName");
string owner = reader.Get<string>("Owner");
string groups = reader.Get<string>("Groups");
int z = reader.Get<int>("Z");
string[] splitids = mergedids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString(), z);
r.SetAllowedGroups(groups);
try
{
for (int i = 0; i < splitids.Length; i++)
{
int id;
if (Int32.TryParse(splitids[i], out id)) // if unparsable, it's not an int, so silently skip
r.AllowedIDs.Add(id);
else
Log.Warn("One of your UserIDs is not a usable integer: " + splitids[i]);
}
}
catch (Exception e)
{
Log.Error("Your database contains invalid UserIDs (they should be ints).");
Log.Error("A lot of things will fail because of this. You must manually delete and re-create the allowed field.");
Log.Error(e.ToString());
Log.Error(e.StackTrace);
}
Regions.Add(r);
}
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
public void ReloadForUnitTest(String n)
{
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", n))
{
Regions.Clear();
while (reader.Read())
{
int X1 = reader.Get<int>("X1");
int Y1 = reader.Get<int>("Y1");
int height = reader.Get<int>("height");
int width = reader.Get<int>("width");
int Protected = reader.Get<int>("Protected");
string MergedIDs = reader.Get<string>("UserIds");
string name = reader.Get<string>("RegionName");
string[] SplitIDs = MergedIDs.Split(',');
string owner = reader.Get<string>("Owner");
string groups = reader.Get<string>("Groups");
int z = reader.Get<int>("Z");
Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString(), z);
r.SetAllowedGroups(groups);
try
{
for (int i = 0; i < SplitIDs.Length; i++)
{
int id;
if (Int32.TryParse(SplitIDs[i], out id)) // if unparsable, it's not an int, so silently skip
r.AllowedIDs.Add(id);
else if (SplitIDs[i] == "") // Split gotcha, can return an empty string with certain conditions
// but we only want to let the user know if it's really a nonparsable integer.
Log.Warn("UnitTest: One of your UserIDs is not a usable integer: " + SplitIDs[i]);
}
}
catch (Exception e)
{
Log.Error("Your database contains invalid UserIDs (they should be ints).");
Log.Error("A lot of things will fail because of this. You must manually delete and re-create the allowed field.");
Log.Error(e.Message);
Log.Error(e.StackTrace);
}
Regions.Add(r);
}
}
}
public bool AddRegion(int tx, int ty, int width, int height, string regionname, string owner, string worldid, int z = 0)
{
if (GetRegionByName(regionname) != null)
{
return false;
}
try
{
database.Query(
"INSERT INTO Regions (X1, Y1, width, height, RegionName, WorldID, UserIds, Protected, Groups, Owner, Z) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10);",
tx, ty, width, height, regionname, worldid, "", 1, "", owner, z);
Regions.Add(new Region(new Rectangle(tx, ty, width, height), regionname, owner, true, worldid, z));
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return false;
}
public bool DeleteRegion(string name)
{
try
{
database.Query("DELETE FROM Regions WHERE RegionName=@0 AND WorldID=@1", name, Main.worldID.ToString());
var worldid = Main.worldID.ToString();
Regions.RemoveAll(r => r.Name == name && r.WorldID == worldid);
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return false;
}
public bool SetRegionState(string name, bool state)
{
try
{
database.Query("UPDATE Regions SET Protected=@0 WHERE RegionName=@1 AND WorldID=@2", state ? 1 : 0, name,
Main.worldID.ToString());
var region = GetRegionByName(name);
if (region != null)
region.DisableBuild = state;
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return false;
}
}
public bool SetRegionStateTest(string name, string world, bool state)
{
try
{
database.Query("UPDATE Regions SET Protected=@0 WHERE RegionName=@1 AND WorldID=@2", state ? 1 : 0, name, world);
var region = GetRegionByName(name);
if (region != null)
region.DisableBuild = state;
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return false;
}
}
public bool CanBuild(int x, int y, TSPlayer ply)
{
if (!ply.Group.HasPermission(Permissions.canbuild))
{
return false;
}
Region top = null;
for (int i = 0; i < Regions.Count; i++)
{
if (Regions[i].InArea(x,y) )
{
if (top == null)
top = Regions[i];
else
{
if (Regions[i].Z > top.Z)
top = Regions[i];
}
}
}
return top == null || top.HasPermissionToBuildInRegion(ply);
}
public bool InArea(int x, int y)
{
foreach (Region region in Regions)
{
if (x >= region.Area.Left && x <= region.Area.Right &&
y >= region.Area.Top && y <= region.Area.Bottom &&
region.DisableBuild)
{
return true;
}
}
return false;
}
public List<string> InAreaRegionName(int x, int y)
{
List<string> regions = new List<string>() { };
foreach (Region region in Regions)
{
if (x >= region.Area.Left && x <= region.Area.Right &&
y >= region.Area.Top && y <= region.Area.Bottom &&
region.DisableBuild)
{
regions.Add(region.Name);
}
}
return regions;
}
public List<Region> InAreaRegion(int x, int y)
{
List<Region> regions = new List<Region>() { };
foreach (Region region in Regions)
{
if (x >= region.Area.Left && x <= region.Area.Right &&
y >= region.Area.Top && y <= region.Area.Bottom &&
region.DisableBuild)
{
regions.Add(region);
}
}
return regions;
}
public static List<string> ListIDs(string MergedIDs)
{
return MergedIDs.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public bool resizeRegion(string regionName, int addAmount, int direction)
{
//0 = up
//1 = right
//2 = down
//3 = left
int X = 0;
int Y = 0;
int height = 0;
int width = 0;
try
{
using (
var reader = database.QueryReader("SELECT X1, Y1, height, width FROM Regions WHERE RegionName=@0 AND WorldID=@1",
regionName, Main.worldID.ToString()))
{
if (reader.Read())
X = reader.Get<int>("X1");
width = reader.Get<int>("width");
Y = reader.Get<int>("Y1");
height = reader.Get<int>("height");
}
if (!(direction == 0))
{
if (!(direction == 1))
{
if (!(direction == 2))
{
if (!(direction == 3))
{
return false;
}
else
{
X -= addAmount;
width += addAmount;
}
}
else
{
height += addAmount;
}
}
else
{
width += addAmount;
}
}
else
{
Y -= addAmount;
height += addAmount;
}
int q =
database.Query(
"UPDATE Regions SET X1 = @0, Y1 = @1, width = @2, height = @3 WHERE RegionName = @4 AND WorldID=@5", X, Y, width,
height, regionName, Main.worldID.ToString());
if (q > 0)
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return false;
}
public bool RemoveUser(string regionName, string userName)
{
Region r = GetRegionByName(regionName);
if (r != null)
{
r.RemoveID(TShock.Users.GetUserID(userName));
string ids = string.Join(",", r.AllowedIDs);
int q = database.Query("UPDATE Regions SET UserIds=@0 WHERE RegionName=@1 AND WorldID=@2", ids,
regionName, Main.worldID.ToString());
if (q > 0)
return true;
}
return false;
}
public bool AddNewUser(string regionName, String userName)
{
try
{
string MergedIDs = string.Empty;
using (
var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName,
Main.worldID.ToString()))
{
if (reader.Read())
MergedIDs = reader.Get<string>("UserIds");
}
if (string.IsNullOrEmpty(MergedIDs))
MergedIDs = Convert.ToString(TShock.Users.GetUserID(userName));
else
MergedIDs = MergedIDs + "," + Convert.ToString(TShock.Users.GetUserID(userName));
int q = database.Query("UPDATE Regions SET UserIds=@0 WHERE RegionName=@1 AND WorldID=@2", MergedIDs,
regionName, Main.worldID.ToString());
foreach (var r in Regions)
{
if (r.Name == regionName && r.WorldID == Main.worldID.ToString())
r.setAllowedIDs(MergedIDs);
}
return q != 0;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return false;
}
/// <summary>
/// Gets all the regions names from world
/// </summary>
/// <param name="worldid">World name to get regions from</param>
/// <returns>List of regions with only their names</returns>
public List<Region> ListAllRegions(string worldid)
{
var regions = new List<Region>();
try
{
using (var reader = database.QueryReader("SELECT RegionName FROM Regions WHERE WorldID=@0", worldid))
{
while (reader.Read())
regions.Add(new Region {Name = reader.Get<string>("RegionName")});
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return regions;
}
public Region GetRegionByName(String name)
{
return Regions.FirstOrDefault(r => r.Name.Equals(name) && r.WorldID == Main.worldID.ToString());
}
public Region ZacksGetRegionByName(String name)
{
foreach (Region r in Regions)
{
if (r.Name.Equals(name))
return r;
}
return null;
}
public bool ChangeOwner(string regionName, string newOwner)
{
var region = GetRegionByName(regionName);
if (region != null)
{
region.Owner = newOwner;
int q = database.Query("UPDATE Regions SET Owner=@0 WHERE RegionName=@1 AND WorldID=@2", newOwner,
regionName, Main.worldID.ToString());
if (q > 0)
return true;
}
return false;
}
public bool AllowGroup(string regionName, string groups)
{
string groupsNew = "";
using (
var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName,
Main.worldID.ToString()))
{
if (reader.Read())
groupsNew = reader.Get<string>("Groups");
}
if (groupsNew != "")
groupsNew += ",";
groupsNew += groups;
int q = database.Query("UPDATE Regions SET Groups=@0 WHERE RegionName=@1 AND WorldID=@2", groupsNew,
regionName, Main.worldID.ToString());
Region r = GetRegionByName(regionName);
if (r != null)
{
r.SetAllowedGroups(groupsNew);
}
else
{
return false;
}
return q > 0;
}
public bool RemoveGroup(string regionName, string group)
{
Region r = GetRegionByName(regionName);
if (r != null)
{
r.RemoveGroup(group);
string groups = string.Join(",", r.AllowedGroups);
int q = database.Query("UPDATE Regions SET Groups=@0 WHERE RegionName=@1 AND WorldID=@2", groups,
regionName, Main.worldID.ToString());
if (q > 0)
return true;
}
return false;
}
public Region GetTopRegion( List<Region> regions )
{
Region ret = null;
foreach( Region r in regions)
{
if (ret == null)
ret = r;
else
{
if (r.Z > ret.Z)
ret = r;
}
}
return ret;
}
public bool SetZ( string name, int z )
{
try
{
database.Query("UPDATE Regions SET Z=@0 WHERE RegionName=@1 AND WorldID=@2", z, name,
Main.worldID.ToString());
var region = GetRegionByName(name);
if (region != null)
region.Z = z;
return true;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return false;
}
}
}
public class Region
{
public Rectangle Area { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool DisableBuild { get; set; }
public string WorldID { get; set; }
public List<int> AllowedIDs { get; set; }
public List<string> AllowedGroups { get; set; }
public int Z { get; set; }
public Region(Rectangle region, string name, string owner, bool disablebuild, string RegionWorldIDz, int z)
: this()
{
Area = region;
Name = name;
Owner = owner;
DisableBuild = disablebuild;
WorldID = RegionWorldIDz;
Z = z;
}
public Region()
{
Area = Rectangle.Empty;
Name = string.Empty;
DisableBuild = true;
WorldID = string.Empty;
AllowedIDs = new List<int>();
AllowedGroups = new List<string>();
Z = 0;
}
public bool InArea(Rectangle point)
{
if (Area.Contains(point.X, point.Y))
{
return true;
}
return false;
}
public bool InArea(int x, int y) //overloaded with x,y
{
if (x >= Area.Left && x <= Area.Right && y >= Area.Top && y <= Area.Bottom)
{
return true;
}
return false;
}
public bool HasPermissionToBuildInRegion(TSPlayer ply)
{
if (!ply.IsLoggedIn)
{
if (!ply.HasBeenNaggedAboutLoggingIn)
{
ply.SendMessage("You must be logged in to take advantage of protected regions.", Color.Red);
ply.HasBeenNaggedAboutLoggingIn = true;
}
return false;
}
if (!DisableBuild)
{
return true;
}
return AllowedIDs.Contains(ply.UserID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.UserAccountName ||
ply.Group.HasPermission("manageregion");
}
public void setAllowedIDs(String ids)
{
String[] id_arr = ids.Split(',');
List<int> id_list = new List<int>();
foreach (String id in id_arr)
{
int i = 0;
int.TryParse(id, out i);
if (i != 0)
id_list.Add(i);
}
AllowedIDs = id_list;
}
public void SetAllowedGroups(String groups)
{
// prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups))
{
List<String> groupArr = groups.Split(',').ToList();
for (int i = 0; i < groupArr.Count; i++)
groupArr[i] = groupArr[i].Trim();
AllowedGroups = groupArr;
}
}
public void RemoveID(int id)
{
var index = -1;
for (int i = 0; i < AllowedIDs.Count; i++)
{
if (AllowedIDs[i] == id)
{
index = i;
break;
}
}
AllowedIDs.RemoveAt(index);
}
public bool RemoveGroup(string groupName)
{
return AllowedGroups.Remove(groupName);
}
}
}