Compare commits

..

10 Commits

Author SHA1 Message Date
dfbc7fffb3 bugfixed 2024-08-13 10:17:10 +08:00
096459b2a1 触发webhook重构 2024-08-13 10:00:02 +08:00
30ce6a3233 增加结案推送 2024-08-13 09:44:22 +08:00
52706352c0 增加案件编号和地址参数 2024-08-12 23:47:55 +08:00
66b61e0ac4 增加微信分发机制 2024-08-12 23:45:18 +08:00
ac96a27072 开发暂存 2024-08-10 23:43:46 +08:00
25467c85aa drone更新 2024-03-24 13:40:02 +08:00
f6b7f1eb5e 过期时间转换成秒 2023-12-22 21:25:01 +08:00
2b2530dfbb token过期自动删除 2023-12-20 21:21:27 +08:00
01c1542f61 把数据库文件映射出来 2023-11-19 18:35:09 +08:00
26 changed files with 1392 additions and 125 deletions

View File

@ -40,7 +40,7 @@ steps:
script:
- docker stop autodispatch
- docker rm autodispatch
- docker rmi 121.4.75.240:5000/autodispatch/web
- docker pull 121.4.75.240:5000/autodispatch/web
- docker run -d --name autodispatch -p 88:8080 121.4.75.240:5000/autodispatch/web
- docker rmi 24.233.2.182:5000/autodispatch/web
- docker pull 24.233.2.182:5000/autodispatch/web
- docker run -d --name autodispatch -p 88:8080 -v /root/Dispathing/Dispathing.db:/app/Dispathing.db 24.233.2.182:5000/autodispatch/web

View File

@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore;
using WorkerService1.Domains;
using WorkerService1.Dto.Configuration;
namespace WorkerService1;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
private static readonly ILoggerFactory _loggerFactory = new LoggerFactory();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var clientEntry = modelBuilder.Entity<ClientOptions>();
clientEntry.HasKey(x => x.Id);
var logEntry = modelBuilder.Entity<LogInfo>();
logEntry.HasKey(x => x.Id);
logEntry.HasIndex(x => x.CreateTime);
var polygonEntry = modelBuilder.Entity<Polygon>();
polygonEntry.HasKey(x => x.PolygonId);
polygonEntry.Property(x => x.Points).HasColumnType("jsonb");
polygonEntry.Property(x => x.RangeCameras).HasColumnType("jsonb");
var smsSendRecordEntry = modelBuilder.Entity<SmsSendRecord>();
smsSendRecordEntry.HasKey(x => x.Id);
smsSendRecordEntry.HasIndex(x => x.SendTime);
}
public DbSet<SmsSendRecord> SmsSendRecords { get; set; }
public DbSet<ClientOptions> ClientOptions { get; set; }
public DbSet<LogInfo> LogInfos { get; set; }
public DbSet<Polygon> Polygons { get; set; }
}

View File

@ -10,11 +10,19 @@
<ItemGroup>
<PackageReference Include="LiteDB.Async" Version="0.1.7" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.7.23375.6"/>
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4" />
<PackageReference Include="SharpMap" Version="1.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="TencentCloudSDK" Version="3.0.1065" />
</ItemGroup>
<ItemGroup>

View File

@ -1,3 +1,4 @@
using AutoDispathingWork.Utils;
using Microsoft.Extensions.Options;
using WorkerService1.Domains;
using WorkerService1.Dto.Configuration;
@ -8,24 +9,19 @@ namespace WorkerService1;
public class CloseWorker : BackgroundService
{
private readonly ILogger<CloseWorker> _logger;
private readonly SpiderServices _spiderServices;
private readonly IServiceProvider _serviceProvider;
public CloseWorker(ILogger<CloseWorker> logger, SpiderServices spiderServices, IServiceProvider serviceProvider)
public CloseWorker(ILogger<CloseWorker> logger)
{
_logger = logger;
_spiderServices = spiderServices;
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _serviceProvider.CreateScope();
var scope = StaticServiceProvider.Current.CreateScope();
var settingServices = scope.ServiceProvider.GetRequiredService<SettingServices>();
var options = settingServices.GetClientOptions();
var options = await settingServices.GetClientOptions();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
@ -43,12 +39,14 @@ public class CloseWorker : BackgroundService
finally
{
await Task.Delay(options.Delay, stoppingToken);
scope.Dispose();
}
}
}
private async Task Handle()
{
var _spiderServices = StaticServiceProvider.Current.GetRequiredService<SpiderServices>();
var listRes = await _spiderServices.GetTaskList(3);
if (listRes.IsSuccess)
{
@ -59,7 +57,7 @@ public class CloseWorker : BackgroundService
foreach (var item in needDispose)
{
//2.结案操作
var result = await _spiderServices.CloseFile(item.caseNumber, "");
var result = await _spiderServices.CloseFile(item.caseNumber, "",item.address);
if (result.IsSuccess)
{
var message = $"结案成功,任务编号:{item.caseNumber},任务地址:{item.address},任务类型:{item.typeCode}";

View File

@ -1,6 +1,7 @@
using AutoDispathingWork.Utils;
using LiteDB;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WorkerService1.Domains;
using WorkerService1.Dto;
using WorkerService1.Dto.Configuration;
@ -30,10 +31,10 @@ public class UserController : ControllerBase
[HttpGet("/api/Polygon/Pages")]
public async Task<SpiderResponse<List<Polygon>>> GetPolygon([FromQuery] PageRequest request,
[FromServices] LiteDatabase db, [FromServices] SpiderServices spiderServices)
[FromServices] ApplicationDbContext db, [FromServices] SpiderServices spiderServices)
{
var polygon = db.GetCollection<Polygon>();
var result = polygon.FindAll().ToList();
var polygon = db.Polygons;
var result = await polygon.ToListAsync();
var cameras = await spiderServices.GetCameras();
var cameraLocation = cameras.Result?.Records.Select(x => (x.name, Location: new Points(x.lon, x.lat)))
.ToList();
@ -56,37 +57,39 @@ public class UserController : ControllerBase
[HttpPost("/api/Polygon")]
public SpiderResponse<bool> CreateOrUpdatePolygon([FromBody] Polygon request, [FromServices] LiteDatabase db)
public async Task<SpiderResponse<bool>> CreateOrUpdatePolygon([FromBody] Polygon request,
[FromServices] ApplicationDbContext db)
{
var polygon = db.GetCollection<Polygon>();
var polygon = db.Polygons;
if (request.PolygonId == null)
{
request.PolygonId = Guid.NewGuid();
var result = polygon.Insert(request);
return new SpiderResponse<bool>()
var result = await polygon.AddAsync(request);
await db.SaveChangesAsync();
return new SpiderResponse<bool>
{
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "保存成功", Result = true
};
}
else
var old = await polygon.FirstOrDefaultAsync(x => x.PolygonId == request.PolygonId);
old.Points = request.Points;
old.Name = request.Name;
polygon.Update(old);
await db.SaveChangesAsync();
return new SpiderResponse<bool>
{
var old = polygon.FindOne(x => x.PolygonId == request.PolygonId);
old.Points = request.Points;
old.Name = request.Name;
polygon.Update(old);
return new SpiderResponse<bool>()
{
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "更新成功", Result = true
};
}
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "更新成功", Result = true
};
}
[HttpDelete("/api/Polygon/{polygonId}")]
public SpiderResponse<bool> DeletePolygon([FromRoute] Guid polygonId, [FromServices] LiteDatabase db)
public async Task<SpiderResponse<bool>> DeletePolygon([FromRoute] Guid polygonId,
[FromServices] ApplicationDbContext db)
{
var polygon = db.GetCollection<Polygon>();
var result = polygon.FindById(polygonId);
var polygon = db.Polygons;
var result = await polygon.FirstOrDefaultAsync(x => x.PolygonId == polygonId);
if (result == null)
{
return new SpiderResponse<bool>()
@ -95,7 +98,8 @@ public class UserController : ControllerBase
};
}
polygon.Delete(polygonId);
polygon.Remove(result);
await db.SaveChangesAsync();
return new SpiderResponse<bool>()
{
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "删除区域信息成功", Result = true
@ -103,10 +107,11 @@ public class UserController : ControllerBase
}
[HttpGet("/api/Polygon/{polygonId}")]
public SpiderResponse<Polygon> GetPolygon([FromRoute] Guid polygonId, [FromServices] LiteDatabase db)
public async Task<SpiderResponse<Polygon>> GetPolygon([FromRoute] Guid polygonId,
[FromServices] ApplicationDbContext db)
{
var polygon = db.GetCollection<Polygon>();
var result = polygon.FindById(polygonId);
var polygon = db.Polygons;
var result = await polygon.FirstOrDefaultAsync(x => x.PolygonId == polygonId);
if (result == null)
{
return new SpiderResponse<Polygon>()
@ -123,11 +128,11 @@ public class UserController : ControllerBase
[HttpPut("/api/Polygon/{polygonId}/UserId/{userId}")]
public async Task<SpiderResponse<bool>> BindPolygonUserId([FromRoute] Guid polygonId, [FromRoute] string userId,
[FromServices] LiteDatabase db, [FromServices] SpiderServices spiderServices)
public async Task<SpiderResponse<bool>> BindPolygonUserId([FromRoute] Guid polygonId, [FromRoute] string userId
, [FromServices] ApplicationDbContext db, [FromServices] SpiderServices spiderServices)
{
var polygon = db.GetCollection<Polygon>();
var result = polygon.FindOne(x => x.PolygonId == polygonId);
var polygon = db.Polygons;
var result = await polygon.FirstOrDefaultAsync(x => x.PolygonId == polygonId);
if (result == null)
{
@ -149,9 +154,11 @@ public class UserController : ControllerBase
if (currentUser != null)
{
result.UserName = currentUser.UserRealName;
result.PhoneNumber = currentUser.UserPhoneNumber;
}
polygon.Update(result);
await db.SaveChangesAsync();
return new SpiderResponse<bool>()
{
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "更新区域信息成功", Result = true
@ -159,13 +166,13 @@ public class UserController : ControllerBase
}
[HttpGet("/api/Polygon/others")]
public SpiderResponse<List<List<List<Points>>>> GetAllPoints([FromQuery] Guid? polygonId,
[FromServices] LiteDatabase db)
public async Task<SpiderResponse<List<List<List<Points>>>>> GetAllPoints([FromQuery] Guid? polygonId
, [FromServices] ApplicationDbContext db)
{
var polygon = db.GetCollection<Polygon>();
var polygon = db.Polygons;
if (polygonId.HasValue)
{
var result = polygon.Find(x => x.PolygonId != polygonId).ToList();
var result = await polygon.Where(x => x.PolygonId != polygonId).ToListAsync();
var points = result.Select(x => x.Points).ToList();
return new SpiderResponse<List<List<List<Points>>>>()
{
@ -174,7 +181,7 @@ public class UserController : ControllerBase
}
else
{
var result = polygon.FindAll().ToList();
var result = await polygon.ToListAsync();
var points = result.Select(x => x.Points).ToList();
return new SpiderResponse<List<List<List<Points>>>>()
{
@ -185,10 +192,10 @@ public class UserController : ControllerBase
[HttpGet("/api/Polygon/{polygonId}/InRangeCameras")]
public async IAsyncEnumerable<string> IsRangeInPolygon([FromRoute] Guid polygonId,
[FromServices] LiteDatabase db, [FromServices] SpiderServices spiderServices)
[FromServices] ApplicationDbContext db, [FromServices] SpiderServices spiderServices)
{
var polygon = db.GetCollection<Polygon>();
var result = polygon.FindOne(x => x.PolygonId == polygonId);
var polygon = db.Polygons;
var result = await polygon.FirstOrDefaultAsync(x => x.PolygonId == polygonId);
if (result != null)
{
var cameras = await spiderServices.GetCameras();
@ -210,20 +217,20 @@ public class UserController : ControllerBase
}
[HttpGet("/api/Setting")]
public SpiderResponse<ClientOptions> GetClientOptions([FromServices] SettingServices settingServices)
public async Task<SpiderResponse<ClientOptions>> GetClientOptions([FromServices] SettingServices settingServices)
{
return new SpiderResponse<ClientOptions>()
{
IsSuccess = true, Code = SpiderResponseCode.Success, Message = "获取配置成功",
Result = settingServices.GetClientOptions()
Result = await settingServices.GetClientOptions()
};
}
[HttpPost("/api/Setting")]
public SpiderResponse<ClientOptions> SettingClientOptions([FromBody] ClientOptionsReq options,
public async Task<SpiderResponse<ClientOptions>> SettingClientOptions([FromBody] ClientOptionsReq options,
[FromServices] SettingServices settingServices)
{
var setting = settingServices.GetClientOptions();
var setting = await settingServices.GetClientOptions();
setting.Delay = options.Delay;
setting.DispatchingRunning = options.DispatchingRunning;
setting.CloseFileRunning = options.CloseFileRunning;
@ -243,13 +250,14 @@ public class UserController : ControllerBase
}
[HttpGet("/api/Log")]
public SpiderResponse<PageResponse<LogInfo>> GetLog([FromQuery] PageRequest request, [FromServices] LiteDatabase db)
public SpiderResponse<PageResponse<LogInfo>> GetLog([FromQuery] PageRequest request,
[FromServices] ApplicationDbContext db)
{
var collection = db.GetCollection<LogInfo>();
var logs = collection.Query()
var collection = db.LogInfos;
var logs = collection
.OrderByDescending(x => x.CreateTime)
.Skip((request.Page - 1) * request.PageSize)
.Limit(request.PageSize)
.Take(request.PageSize)
.ToList();
var total = collection.Count();
return new SpiderResponse<PageResponse<LogInfo>>()

Binary file not shown.

View File

@ -13,7 +13,7 @@ public class LogInfo
public LogInfo(string level, string message, [CallerMemberName] string from = "")
{
Id = Guid.NewGuid();
CreateTime = DateTime.Now;
CreateTime = DateTime.UtcNow;
Message = message;
Level = level;
From = from;
@ -32,9 +32,9 @@ public static class LogInfoExtensions
{
var logger = StaticServiceProvider.GetLogger(from);
logger.LogInformation(message);
var db = StaticServiceProvider.GetLogDb();
var log = new LogInfo("Info", message, from);
db.Insert(log);
StaticServiceProvider.AddLog(log);
return log;
}
@ -42,9 +42,8 @@ public static class LogInfoExtensions
{
var logger = StaticServiceProvider.GetLogger(from);
logger.LogError(message);
var db = StaticServiceProvider.GetLogDb();
var log = new LogInfo("Error", message, from);
db.Insert(log);
StaticServiceProvider.AddLog(log);
return log;
}
@ -52,9 +51,8 @@ public static class LogInfoExtensions
{
var logger = StaticServiceProvider.GetLogger(from);
logger.LogWarning(message);
var db = StaticServiceProvider.GetLogDb();
var log = new LogInfo("Warning", message, from);
db.Insert(log);
StaticServiceProvider.AddLog(log);
return log;
}
@ -62,9 +60,8 @@ public static class LogInfoExtensions
{
var logger = StaticServiceProvider.GetLogger(from);
logger.LogDebug(message);
var db = StaticServiceProvider.GetLogDb();
var log = new LogInfo("Debug", message, from);
db.Insert(log);
StaticServiceProvider.AddLog(log);
return log;
}
}

View File

@ -6,6 +6,7 @@ public class Polygon
public string Name { get; set; }
public string? UserId { get; set; }
public string? UserName { get; set; }
public string? PhoneNumber { get; set; }
public List<List<Points>>? Points { get; set; }
public List<string>? RangeCameras { get; set; } = new List<string>();

View File

@ -0,0 +1,38 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WorkerService1.Domains;
public class SmsSendRecord
{
/// <summary>
/// 自增主键
/// </summary>
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/// <summary>
/// 业务id
/// </summary>
public string RefrenceId { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// 短信内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 发送时间
/// </summary>
public DateTime SendTime { get; set; }
/// <summary>
/// 是否成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMessage { get; set; }
}

View File

@ -4,7 +4,8 @@ namespace WorkerService1.Dto.Configuration;
public class ClientOptions
{
public string ApiGateway { get; set; } = "http://121.4.75.240/";
public Guid Id { get; set; } = Guid.NewGuid();
public string ApiGateway { get; set; } = "http://101.35.48.186/";
[JsonPropertyName("username")]
public string UserName { get; set; } = "ganquanjiedao";
[JsonPropertyName("password")]

View File

@ -27,4 +27,5 @@ public class UserRecord
[JsonPropertyName("id")] public string Id { get; set; }
[JsonPropertyName("userName")] public string UserName { get; set; }
[JsonPropertyName("userRealName")] public string UserRealName { get; set; }
[JsonPropertyName("phoneNo")] public string UserPhoneNumber { get; set; }
}

View File

@ -0,0 +1,145 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WorkerService1;
using WorkerService1.Domains;
#nullable disable
namespace AutoDispathingWork.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240810135019_initDb")]
partial class initDb
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkerService1.Domains.LogInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("From")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Level")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreateTime");
b.ToTable("LogInfos");
});
modelBuilder.Entity("WorkerService1.Domains.Polygon", b =>
{
b.Property<Guid?>("PolygonId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<List<List<Points>>>("Points")
.HasColumnType("jsonb");
b.Property<List<string>>("RangeCameras")
.HasColumnType("jsonb");
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("UserName")
.HasColumnType("text");
b.HasKey("PolygonId");
b.ToTable("Polygons");
});
modelBuilder.Entity("WorkerService1.Dto.Configuration.ClientOptions", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ApiGateway")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseFileApi")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("CloseFileRunning")
.HasColumnType("boolean");
b.Property<int>("Delay")
.HasColumnType("integer");
b.Property<string>("DiposeOrder")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("DispatchingRunning")
.HasColumnType("boolean");
b.Property<string>("GetCamerasApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetTaskApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetUserApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("LoginApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "password");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "username");
b.HasKey("Id");
b.ToTable("ClientOptions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using WorkerService1.Domains;
#nullable disable
namespace AutoDispathingWork.Migrations
{
/// <inheritdoc />
public partial class initDb : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ClientOptions",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ApiGateway = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Delay = table.Column<int>(type: "integer", nullable: false),
DispatchingRunning = table.Column<bool>(type: "boolean", nullable: false),
CloseFileRunning = table.Column<bool>(type: "boolean", nullable: false),
LoginApi = table.Column<string>(type: "text", nullable: false),
GetTaskApi = table.Column<string>(type: "text", nullable: false),
GetUserApi = table.Column<string>(type: "text", nullable: false),
DiposeOrder = table.Column<string>(type: "text", nullable: false),
CloseFileApi = table.Column<string>(type: "text", nullable: false),
GetCamerasApi = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ClientOptions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LogInfos",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Message = table.Column<string>(type: "text", nullable: false),
From = table.Column<string>(type: "text", nullable: false),
Level = table.Column<string>(type: "text", nullable: false),
CreateTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LogInfos", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Polygons",
columns: table => new
{
PolygonId = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
UserId = table.Column<string>(type: "text", nullable: true),
UserName = table.Column<string>(type: "text", nullable: true),
Points = table.Column<List<List<Points>>>(type: "jsonb", nullable: true),
RangeCameras = table.Column<List<string>>(type: "jsonb", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Polygons", x => x.PolygonId);
});
migrationBuilder.CreateIndex(
name: "IX_LogInfos_CreateTime",
table: "LogInfos",
column: "CreateTime");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ClientOptions");
migrationBuilder.DropTable(
name: "LogInfos");
migrationBuilder.DropTable(
name: "Polygons");
}
}
}

View File

@ -0,0 +1,182 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WorkerService1;
using WorkerService1.Domains;
#nullable disable
namespace AutoDispathingWork.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240810152436_dbv2")]
partial class dbv2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkerService1.Domains.LogInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("From")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Level")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreateTime");
b.ToTable("LogInfos");
});
modelBuilder.Entity("WorkerService1.Domains.Polygon", b =>
{
b.Property<Guid?>("PolygonId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<List<List<Points>>>("Points")
.HasColumnType("jsonb");
b.Property<List<string>>("RangeCameras")
.HasColumnType("jsonb");
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("UserName")
.HasColumnType("text");
b.HasKey("PolygonId");
b.ToTable("Polygons");
});
modelBuilder.Entity("WorkerService1.Domains.SmsSendRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ErrorMessage")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsSuccess")
.HasColumnType("boolean");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RefrenceId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("SendTime")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SendTime");
b.ToTable("SmsSendRecords");
});
modelBuilder.Entity("WorkerService1.Dto.Configuration.ClientOptions", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ApiGateway")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseFileApi")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("CloseFileRunning")
.HasColumnType("boolean");
b.Property<int>("Delay")
.HasColumnType("integer");
b.Property<string>("DiposeOrder")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("DispatchingRunning")
.HasColumnType("boolean");
b.Property<string>("GetCamerasApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetTaskApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetUserApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("LoginApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "password");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "username");
b.HasKey("Id");
b.ToTable("ClientOptions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AutoDispathingWork.Migrations
{
/// <inheritdoc />
public partial class dbv2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SmsSendRecords",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RefrenceId = table.Column<string>(type: "text", nullable: false),
PhoneNumber = table.Column<string>(type: "text", nullable: false),
Content = table.Column<string>(type: "text", nullable: false),
SendTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
IsSuccess = table.Column<bool>(type: "boolean", nullable: false),
ErrorMessage = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SmsSendRecords", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_SmsSendRecords_SendTime",
table: "SmsSendRecords",
column: "SendTime");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SmsSendRecords");
}
}
}

View File

@ -0,0 +1,185 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WorkerService1;
using WorkerService1.Domains;
#nullable disable
namespace AutoDispathingWork.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240812130932_dbv3")]
partial class dbv3
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkerService1.Domains.LogInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("From")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Level")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreateTime");
b.ToTable("LogInfos");
});
modelBuilder.Entity("WorkerService1.Domains.Polygon", b =>
{
b.Property<Guid?>("PolygonId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<List<List<Points>>>("Points")
.HasColumnType("jsonb");
b.Property<List<string>>("RangeCameras")
.HasColumnType("jsonb");
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("UserName")
.HasColumnType("text");
b.HasKey("PolygonId");
b.ToTable("Polygons");
});
modelBuilder.Entity("WorkerService1.Domains.SmsSendRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ErrorMessage")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsSuccess")
.HasColumnType("boolean");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RefrenceId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("SendTime")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SendTime");
b.ToTable("SmsSendRecords");
});
modelBuilder.Entity("WorkerService1.Dto.Configuration.ClientOptions", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ApiGateway")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseFileApi")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("CloseFileRunning")
.HasColumnType("boolean");
b.Property<int>("Delay")
.HasColumnType("integer");
b.Property<string>("DiposeOrder")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("DispatchingRunning")
.HasColumnType("boolean");
b.Property<string>("GetCamerasApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetTaskApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetUserApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("LoginApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "password");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "username");
b.HasKey("Id");
b.ToTable("ClientOptions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AutoDispathingWork.Migrations
{
/// <inheritdoc />
public partial class dbv3 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "PhoneNumber",
table: "Polygons",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PhoneNumber",
table: "Polygons");
}
}
}

View File

@ -0,0 +1,182 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WorkerService1;
using WorkerService1.Domains;
#nullable disable
namespace AutoDispathingWork.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkerService1.Domains.LogInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("From")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Level")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreateTime");
b.ToTable("LogInfos");
});
modelBuilder.Entity("WorkerService1.Domains.Polygon", b =>
{
b.Property<Guid?>("PolygonId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<List<List<Points>>>("Points")
.HasColumnType("jsonb");
b.Property<List<string>>("RangeCameras")
.HasColumnType("jsonb");
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("UserName")
.HasColumnType("text");
b.HasKey("PolygonId");
b.ToTable("Polygons");
});
modelBuilder.Entity("WorkerService1.Domains.SmsSendRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ErrorMessage")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsSuccess")
.HasColumnType("boolean");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RefrenceId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("SendTime")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SendTime");
b.ToTable("SmsSendRecords");
});
modelBuilder.Entity("WorkerService1.Dto.Configuration.ClientOptions", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ApiGateway")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseFileApi")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("CloseFileRunning")
.HasColumnType("boolean");
b.Property<int>("Delay")
.HasColumnType("integer");
b.Property<string>("DiposeOrder")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("DispatchingRunning")
.HasColumnType("boolean");
b.Property<string>("GetCamerasApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetTaskApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GetUserApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("LoginApi")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "password");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text")
.HasAnnotation("Relational:JsonPropertyName", "username");
b.HasKey("Id");
b.ToTable("ClientOptions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,6 +1,10 @@
using AutoDispathingWork.Utils;
using LiteDB;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.FileProviders;
using Microsoft.OpenApi.Models;
using Npgsql;
using WorkerService1;
using WorkerService1.Dto.Configuration;
using WorkerService1.Services;
@ -25,6 +29,19 @@ builder.Services.AddCors(x =>
.AllowAnyHeader();
});
});
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContextPool<ApplicationDbContext>(x =>
{
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
// 启用动态 JSON 序列化
dataSourceBuilder.EnableDynamicJson();
var dataSource = dataSourceBuilder.Build();
x.UseNpgsql(dataSource)
.UseLoggerFactory(new LoggerFactory())
.LogTo(Console.WriteLine, LogLevel.Information);
x.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning));
}
);
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<LiteDatabase>(x => new LiteDatabase(builder.Configuration["Database:ConnectionString"]));
@ -35,7 +52,8 @@ builder.Services.AddMemoryCache();
builder.Services.AddLogging();
// builder.Services.AddMvcCore();
builder.Services.AddSingleton<SpiderServices>();
builder.Services.AddScoped<SettingServices>();
builder.Services.AddSingleton<SettingServices>();
builder.Services.AddSingleton<WechatRobot>();
// #if !DEBUG
builder.Services.AddHostedService<Worker>();
builder.Services.AddHostedService<CloseWorker>();
@ -43,11 +61,16 @@ builder.Services.AddHostedService<CloseWorker>();
var app = builder.Build();
StaticServiceProvider.SetServiceProvider(app.Services);
app.UseCors("AllowAllOrigin");
#if DEBUG
app.UseSwagger();
app.UseSwaggerUI();
app.Services.GetService<WechatRobot>();
#endif
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();

View File

@ -1,4 +1,6 @@
using LiteDB;
using AutoDispathingWork.Utils;
using LiteDB;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using WorkerService1.Dto.Configuration;
@ -7,12 +9,11 @@ namespace WorkerService1.Services;
public class SettingServices
{
private readonly IOptionsMonitor<ClientOptions> _optionsMonitor;
private readonly LiteDatabase _db;
public SettingServices(IOptionsMonitor<ClientOptions> optionsMonitor, LiteDatabase db)
public SettingServices(IOptionsMonitor<ClientOptions> optionsMonitor)
{
_optionsMonitor = optionsMonitor;
_db = db;
}
public void Reset()
@ -20,23 +21,41 @@ public class SettingServices
SettingClientOptions(_optionsMonitor.CurrentValue);
}
public ClientOptions GetClientOptions()
public async Task<ClientOptions> GetClientOptions()
{
var clientOptions = _db.GetCollection<ClientOptions>();
var dbOptions = clientOptions.FindAll().FirstOrDefault();
var scope = StaticServiceProvider.Current.CreateScope();
var _db = scope.ServiceProvider.GetService<ApplicationDbContext>();
var clientOptions = _db.ClientOptions;
var dbOptions = await clientOptions.FirstOrDefaultAsync();
if (dbOptions != null)
{
await _db.DisposeAsync();
scope.Dispose();
return dbOptions;
}
await _db.DisposeAsync();
scope.Dispose();
return _optionsMonitor.CurrentValue;
}
public ClientOptions SettingClientOptions(ClientOptions options)
{
var clientOptions = _db.GetCollection<ClientOptions>();
clientOptions.DeleteAll();
clientOptions.Insert(options);
var scope = StaticServiceProvider.Current.CreateScope();
var _db = scope.ServiceProvider.GetService<ApplicationDbContext>();
var clientOptions = _db.ClientOptions;
var dbOptions = clientOptions.FirstOrDefault();
if (dbOptions != null)
{
clientOptions.Remove(dbOptions);
_db.SaveChanges();
}
clientOptions.Add(options);
_db.SaveChanges();
_db.Dispose();
scope.Dispose();
return options;
}
}

View File

@ -0,0 +1,117 @@
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Cvm.V20170312;
using TencentCloud.Cvm.V20170312.Models;
using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;
namespace WorkerService1.Services;
public class SmsService
{
public Task SendSmsAsync(string phoneNumber, string message, string refrenceId)
{
try
{
// 必要步骤:
// 实例化一个认证对象,入参需要传入腾讯云账户密钥对 SecretIdSecretKey。
// 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中。
// 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
// 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
// SecretId、SecretKey 查询https://console.cloud.tencent.com/cam/capi
Credential cred = new Credential
{
SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
};
/* :
* */
ClientProfile clientProfile = new ClientProfile
{
/* SDK默认用TC3-HMAC-SHA256进行签名
* */
SignMethod = ClientProfile.SIGN_TC3SHA256
};
/*
* */
var httpProfile = new HttpProfile
{
/* SDK默认使用POST方法
* 使GET方法GET方法无法处理一些较大的请求 */
ReqMethod = "GET",
Timeout = 10, // 请求连接超时时间,单位为秒(默认60秒)
/* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
Endpoint = "sms.tencentcloudapi.com"
};
// 代理服务器,当您的环境下有代理服务器时设定(无需要直接忽略)
// httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");
clientProfile.HttpProfile = httpProfile;
/* (sms为例)client对象
* ap-guangzhou https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
var client = new SmsClient(cred, "ap-guangzhou", clientProfile);
/*
* SDK源码确定SendSmsRequest有哪些属性可以设置
*
* 使IDE进行开发便 */
var req = new SendSmsRequest
{
/* :
* SDK采用的是指针风格指定参数使
* SDK提供对基本类型的指针引用封装函数
*
* : https://console.cloud.tencent.com/smsv2
* : https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId示例如1400006666 */
// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
SmsSdkAppId = "1400787878",
/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
// 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
SignName = "腾讯云",
/* 模板 ID: 必须填写已审核通过的模板 ID */
// 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
TemplateId = "449739",
/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
TemplateParamSet = new String[] { "1234" },
/* E.164 +[][]
* +8613711112222 + 8613711112222200*/
PhoneNumberSet = new String[] { "+86" + phoneNumber },
/* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息server 会原样返回 */
SessionContext = "",
/* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
ExtendCode = "",
/* 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId无需填写该字段。注月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 */
SenderId = ""
};
SendSmsResponse resp = client.SendSmsSync(req);
// 输出json格式的字符串回包
Console.WriteLine(AbstractModel.ToJsonString(resp));
/*
* [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
* [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
* [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
* [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
* [](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
*/
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.Read();
return Task.CompletedTask;
}
}

View File

@ -2,6 +2,7 @@
using System.Text;
using AutoDispathingWork.Utils;
using LiteDB;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using WorkerService1.Domains;
@ -33,26 +34,25 @@ public class SpiderServices
_serviceProvider = serviceProvider;
}
private IOptionsMonitor<ClientOptions> OptionsMonitor => _serviceProvider.CreateScope().ServiceProvider
.GetRequiredService<IOptionsMonitor<ClientOptions>>();
private ClientOptions GetClientOptions => _serviceProvider.CreateScope().ServiceProvider
.GetRequiredService<SettingServices>()
.GetClientOptions();
// private ClientOptions GetClientOptions => _serviceProvider.CreateScope().ServiceProvider
// .GetRequiredService<SettingServices>()
// .GetClientOptions();
private LiteDatabase GetLiteDatabase => _serviceProvider
.GetRequiredService<LiteDatabase>();
public async Task<SpiderResponse<LoginResultData>> Login()
{
using var scope = _serviceProvider.CreateScope();
using var client = _httpClientFactory.CreateClient();
var loginApi = GetClientOptions.LoginUrl;
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var loginApi = getClientOptions.LoginUrl;
var json = $@"
{{""userName"":""{GetClientOptions.UserName}"",""userPwd"":""{GetClientOptions.Password}"",""type"":""account"",""clientAppId"":""megcity-web""}}
{{""userName"":""{getClientOptions.UserName}"",""userPwd"":""{getClientOptions.Password}"",""type"":""account"",""clientAppId"":""megcity-web""}}
";
client.DefaultRequestHeaders.Add("Module-Alias", "pending-forward");
client.DefaultRequestHeaders.Add("Module-Source", "megcity-web");
client.DefaultRequestHeaders.Add("Origin", "http://121.4.75.240");
client.DefaultRequestHeaders.Add("Origin", _optionsMonitor.CurrentValue.ApiGateway);
var response = await client.PostAsync(loginApi, new StringContent(json, Encoding.UTF8, "application/json"));
var respJsonStr = await response.Content.ReadAsStringAsync();
_logger.LogInformation("登录返回: {tokenRes}", respJsonStr);
@ -83,13 +83,20 @@ public class SpiderServices
public async Task<string?> GetToken()
{
return await _memoryCache.GetOrCreateAsync(nameof(GetToken), async entry =>
var token = await _memoryCache.GetOrCreateAsync(nameof(GetToken), async entry =>
{
var loginRes = await Login();
if (!loginRes.IsSuccess) return null;
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(loginRes.Result?.ExpireTime ?? 0);
if (!loginRes.IsSuccess)
{
entry.AbsoluteExpiration = DateTimeOffset.Now;
return null;
}
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(loginRes.Result?.ExpireTime / 1000 ?? 0);
return loginRes.Result?.Token;
});
if (string.IsNullOrWhiteSpace(token)) _memoryCache.Remove(nameof(GetToken));
return token;
}
@ -129,7 +136,10 @@ public class SpiderServices
// {"state":[3],"pageNo":1,"pageSize":50,"sortType":[40,10],"handleStartTime":1697293650750,"handleEndTime":1699885650750}
// {"state":[1],"pageNo":1,"pageSize":50,"sortType":[20,10],"createStartTime":1697290618034,"createEndTime":1699882618034}
// {\"state\":[1],\"pageNo\":1,\"pageSize\":50,\"sortType\":[20,10],\"createStartTime\":1697204639551,\"createEndTime\":1697204639551}
var taskPath = GetClientOptions.GetTaskUrl;
using var scope = _serviceProvider.CreateScope();
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var taskPath = getClientOptions.GetTaskUrl;
var response = await client.PostAsync(taskPath,
new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"));
var respJsonStr = await response.Content.ReadAsStringAsync();
@ -172,7 +182,10 @@ public class SpiderServices
client.DefaultRequestHeaders.Add("module-alias", "pending-forward");
client.DefaultRequestHeaders.Add("module-source", "megcity-web");
var request = query ?? new UserQuery();
var userPath = GetClientOptions.GetUserUrl;
using var scope = _serviceProvider.CreateScope();
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var userPath = getClientOptions.GetUserUrl;
var response = await client.PostAsync(userPath,
new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"));
var respJsonStr = await response.Content.ReadAsStringAsync();
@ -215,7 +228,7 @@ public class SpiderServices
client.DefaultRequestHeaders.Add("module-alias", "pending-forward");
client.DefaultRequestHeaders.Add("module-source", "megcity-web");
var (handlerId, userRealName) = await GetUserIdByCamera(cameraName);
var (handlerId, phone, userRealName) = await GetUserIdByCamera(cameraName);
if (string.IsNullOrWhiteSpace(handlerId))
{
return new SpiderResponse<object>()
@ -234,7 +247,10 @@ public class SpiderServices
HandlerId = handlerId,
TypeCode = typeCode
};
var dispatchPath = string.Format(GetClientOptions.DiposeOrderUrl, caseNumber);
using var scope = _serviceProvider.CreateScope();
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var dispatchPath = string.Format(getClientOptions.DiposeOrderUrl, caseNumber);
var response = await client.PostAsync(dispatchPath,
new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"));
@ -247,6 +263,9 @@ public class SpiderServices
if (spiderRes?.code == 0)
{
var msg = $"成功分发任务,任务编号:{caseNumber},任务地址:{cameraName},任务类型:{typeCode},处理人:{userRealName}";
var smsService = scope.ServiceProvider.GetRequiredService<WechatRobot>();
await smsService.SendText($"{userRealName},您好,您有一条新案件,案件编号{caseNumber},案件地址{cameraName},请及时处置,谢谢。",
false);
_logger.LogInformation(msg);
return new SpiderResponse<object>()
@ -270,7 +289,7 @@ public class SpiderServices
// api/megcity/v1/events/pass
public async Task<SpiderResponse<object>> CloseFile(string caseNumber, string suggestion)
public async Task<SpiderResponse<object>> CloseFile(string caseNumber, string suggestion, string address)
{
var token = await GetToken();
using var client = _httpClientFactory.CreateClient();
@ -284,7 +303,10 @@ public class SpiderServices
//Region为请求文件接口需要的参数根据调用接口参数而定
form.Add(new StringContent(caseNumber), "caseNumber");
form.Add(new StringContent(suggestion), "suggestion");
var closeFile = GetClientOptions.CloseFileUrl;
using var scope = _serviceProvider.CreateScope();
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var closeFile = getClientOptions.CloseFileUrl;
var response = await client.PostAsync(closeFile, form);
var respJsonStr = await response.Content.ReadAsStringAsync();
@ -296,6 +318,10 @@ public class SpiderServices
if (spiderRes?.code == 0)
{
_logger.LogInformation("成功结案");
_serviceProvider.GetService<WechatRobot>()?
.SendText(
$"案件{caseNumber}已经结案,所在位置{address},处理意见{(string.IsNullOrWhiteSpace(suggestion) ? "" : suggestion)}",
false);
return new SpiderResponse<object>()
{
@ -329,7 +355,10 @@ public class SpiderServices
var request = $@"
{{""managementIds"":[""6e9232ef-7b84-11e8-86b1-6c92bf4e6960""],""name"":""{name}"" ,""action"":""all"",""pageNo"":1,""pageSize"":200}}
";
var getCamersPath = GetClientOptions.GetCamerasUrl;
using var scope = _serviceProvider.CreateScope();
var getClientOptions = await scope.ServiceProvider.GetService<SettingServices>()?
.GetClientOptions();
var getCamersPath = getClientOptions.GetCamerasUrl;
var response = await client.PostAsync(getCamersPath,
new StringContent(request, Encoding.UTF8, "application/json"));
var respJsonStr = await response.Content.ReadAsStringAsync();
@ -367,23 +396,25 @@ public class SpiderServices
};
}
public async Task<(string userId, string userRealName )> GetUserIdByCamera(string cameraAddress)
public async Task<(string userId, string phone, string userRealName )> GetUserIdByCamera(string cameraAddress)
{
using var scope = _serviceProvider.CreateScope();
var camerasResp = await GetCameras(cameraAddress);
var camera = camerasResp.Result?.Records.FirstOrDefault();
if (camera == null) return (string.Empty, string.Empty);
if (camera == null) return (string.Empty, string.Empty, string.Empty);
var location = new Points(camera.lon, camera.lat);
var db = _serviceProvider.GetRequiredService<LiteDatabase>();
var polygonDb = db.GetCollection<Polygon>();
var polygons = polygonDb.FindAll();
var db = scope.ServiceProvider.GetService<ApplicationDbContext>()
.Polygons;
var polygonDb = db;
var polygons = await polygonDb.ToListAsync();
foreach (var polygon in polygons)
{
if (location.IsPointInsidePolygon(polygon))
{
return (polygon.UserId, polygon.UserName);
return (polygon.UserId, polygon.PhoneNumber, polygon.UserName);
}
}
return (string.Empty, string.Empty);
return (string.Empty, string.Empty, string.Empty);
}
}

View File

@ -1,4 +1,6 @@
using LiteDB;
using Microsoft.EntityFrameworkCore;
using WorkerService1;
using WorkerService1.Domains;
namespace AutoDispathingWork.Utils;
@ -10,7 +12,7 @@ public class StaticServiceProvider
Current = serviceProvider;
}
private static IServiceProvider Current { get; set; }
public static IServiceProvider Current { get; set; }
public static T GetRequiredService<T>()
{
@ -22,9 +24,12 @@ public class StaticServiceProvider
return Current.GetService<T>();
}
public static ILiteCollection<LogInfo> GetLogDb()
public static void AddLog(LogInfo log)
{
return Current.GetRequiredService<LiteDatabase>().GetCollection<LogInfo>();
using var scope = Current.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.LogInfos.Add(log);
dbContext.SaveChanges();
}
public static ILogger GetLogger(string methodName)

View File

@ -0,0 +1,113 @@
using System.Text;
using Microsoft.Net.Http.Headers;
namespace WorkerService1;
public class WechatRobot
{
private const string ApiUrl = "https://qyapi.weixin.qq.com";
private const int TextUtf8MaxLength = 2000;
private const int MarkdownUtf8MaxLength = 4000;
private string _key;
private static readonly MediaTypeHeaderValue ApplicationJson =
new MediaTypeHeaderValue("application/json")
{
Charset = "utf-8"
};
private readonly HttpClient _client;
private readonly ILogger<WechatRobot> _logger;
public WechatRobot(ILogger<WechatRobot> logger, HttpClient client)
{
client.BaseAddress = new Uri(ApiUrl);
this._logger = logger;
_client = client;
_key = "e68b3791-e040-4c9b-9ac0-6f424e662185";
}
public async Task SendText(string content, bool isAtAll)
{
await this.Post($"/cgi-bin/webhook/send?key={_key}", BuildTextBody(content, isAtAll));
}
public async Task SendMarkdown(string content)
{
await this.Post($"/cgi-bin/webhook/send?key={_key}", BuildMarkdownBody(content));
}
private string BuildTextBody(string content, bool isAtAll)
{
var result = new StringBuilder("{\"msgtype\": \"text\",");
result.Append("\"text\": {");
result.Append($"\"content\": \"{Substring(content, TextUtf8MaxLength)}\",");
if (isAtAll)
{
result.Append($"\"mentioned_list\":[\"@all\"]");
}
result.Append("}}");
return result.ToString();
}
private string BuildMarkdownBody(string content)
{
var result = new StringBuilder("{\"msgtype\": \"markdown\",");
result.Append("\"markdown\": {");
result.Append($"\"content\": \"{Substring(FilterSpecialChar(content), MarkdownUtf8MaxLength)}\"");
result.Append("}}");
return result.ToString();
}
/// <summary>
/// 截取字符串
/// </summary>
/// <param name="content">字符串内容</param>
/// <param name="maxLength">字符串最大长度</param>
/// <returns>如果长度超出则按照 maxLength 截取返回,若没超出则原样返回 </returns>
private string Substring(string content, int maxLength)
{
var bytes = Encoding.UTF8.GetBytes(content);
if (bytes.Length > maxLength)
{
var temporaryBytes = bytes.Take(maxLength).ToArray();
return $"{Encoding.UTF8.GetString(temporaryBytes)}";
}
return content;
}
/// <summary>
/// 过滤 markdown 特殊字符
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
private string FilterSpecialChar(string content) => content?.Replace("\"", "''").Replace("`", "'");
private async Task Post(string url, string parameters)
{
try
{
HttpContent content = null;
if (!String.IsNullOrEmpty(parameters))
{
content = new StringContent(parameters, Encoding.UTF8);
if (content.Headers.ContentType != null)
{
content.Headers.ContentType.MediaType = "application/json";
content.Headers.ContentType.CharSet = "utf-8";
}
}
var resp = await _client.PostAsync(url, content);
await resp.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
this._logger.LogError(ex, $"WechatRobot Post fail,Url:{url},Parameters:{parameters}");
}
}
}

View File

@ -1,6 +1,6 @@
using Microsoft.Extensions.Options;
using AutoDispathingWork.Utils;
using WorkerService1.Domains;
using WorkerService1.Dto.Configuration;
using WorkerService1.Dto;
using WorkerService1.Services;
namespace WorkerService1;
@ -8,23 +8,19 @@ namespace WorkerService1;
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly SpiderServices _spiderServices;
private readonly IServiceProvider _serviceProvider;
public Worker(ILogger<Worker> logger, IServiceProvider serviceProvider, SpiderServices spiderServices)
public Worker(ILogger<Worker> logger)
{
_logger = logger;
_serviceProvider = serviceProvider;
_spiderServices = spiderServices;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _serviceProvider.CreateScope();
var scope = StaticServiceProvider.Current.CreateScope();
var settingServices = scope.ServiceProvider.GetRequiredService<SettingServices>();
var options = settingServices.GetClientOptions();
var options = await settingServices.GetClientOptions();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now.LocalDateTime);
@ -42,16 +38,19 @@ public class Worker : BackgroundService
finally
{
await Task.Delay(options.Delay, stoppingToken);
scope.Dispose();
}
}
}
private async Task Handle()
private static async Task Handle()
{
var _spiderServices = StaticServiceProvider.Current.GetRequiredService<SpiderServices>();
var logger= StaticServiceProvider.Current.GetRequiredService<ILogger<Worker>>();
var listRes = await _spiderServices.GetTaskList(1);
if (listRes.IsSuccess)
{
var needDispose = listRes.Result?.records.Where(x => x.disposalStatus == 1);
var needDispose = listRes.Result?.records.Where(x => x.disposalStatus == 1).ToList();
//轮询列表,看有没有符合状态的进行处理
if (needDispose?.Any() ?? false)
{
@ -73,6 +72,11 @@ public class Worker : BackgroundService
}
else
{
if (result.Code == SpiderResponseCode.Fail)
{
logger.LogError($"派发任务失败,错误信息:{result.Message}");
continue;
}
var message = $"派发任务失败,错误信息:{result.Message}";
message.Error();
}

View File

@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Host=101.35.48.186;Port=15432;Database=AutoDispathingWork;Username=postgres;Password=sl52788542;"
},
"Logging": {
"LogLevel": {
"Default": "Information",