Compare commits
No commits in common. "main" and "docs" have entirely different histories.
@ -1,24 +0,0 @@
|
|||||||
name: Publish JOBot on dev
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- dev
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build and deploy:
|
|
||||||
runs-on: host
|
|
||||||
name: Build and deploy
|
|
||||||
volumes:
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Update repo
|
|
||||||
run: |
|
|
||||||
pwd
|
|
||||||
cd /home/dockeruser/jobot-stack
|
|
||||||
git checkout dev
|
|
||||||
git pull
|
|
||||||
docker compose -f compose.dev.yml up -d postgres
|
|
||||||
|
|
||||||
cd /home/dockeruser/jobot-stack/JOBot.Backend
|
|
||||||
dotnet ef database update --connection "Host=localhost;Port=5432;Database=jobot;Username=postgres;Password=LocalDbPass"
|
|
||||||
docker compose up --build -d
|
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -404,7 +404,5 @@ FodyWeavers.xsd
|
|||||||
.docker
|
.docker
|
||||||
|
|
||||||
# Secrets
|
# Secrets
|
||||||
JOBot.Backend/appsettings.Development.json
|
|
||||||
JOBot.TClient/appsettings.json
|
JOBot.TClient/appsettings.json
|
||||||
/.idea/.idea.JOBot/Docker/compose.generated.override.yml
|
/.idea/.idea.JOBot/Docker/compose.generated.override.yml
|
||||||
/.idea/.idea.JOBot/Docker/compose.dev.generated.override.yml
|
|
||||||
|
@ -1,22 +0,0 @@
|
|||||||
using JOBot.Backend.Services;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace JOBot.Backend.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("auth")]
|
|
||||||
public class HeadHunterHookController(HeadHunterService hhService)
|
|
||||||
: ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
public async Task<IActionResult> Get(int userId, string? error, string code)
|
|
||||||
{
|
|
||||||
var res = await hhService.AuthUser(userId, code, error);
|
|
||||||
return res switch
|
|
||||||
{
|
|
||||||
HeadHunterService.Status.Success => Ok("Авторизация завершена успешно. Вернитесь в Telegram для продолжения."),
|
|
||||||
HeadHunterService.Status.UserNotFoundError => NotFound("Пользователь не найден."),
|
|
||||||
_ => BadRequest("Авторизация завершена с ошибкой. Вернитесь в Telegram для продолжения.") //TODO: Add resource
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,17 +1,19 @@
|
|||||||
|
namespace JOBot.Backend.DAL.Context;
|
||||||
|
|
||||||
using JOBot.Backend.DAL.Models;
|
using JOBot.Backend.DAL.Models;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace JOBot.Backend.DAL.Context;
|
public class AppDbContext : DbContext
|
||||||
|
|
||||||
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
|
||||||
{
|
{
|
||||||
public DbSet<User> Users { get; set; }
|
public DbSet<User> Users { get; set; }
|
||||||
|
|
||||||
|
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
base.OnModelCreating(modelBuilder);
|
base.OnModelCreating(modelBuilder);
|
||||||
|
|
||||||
modelBuilder.Entity<User>()
|
modelBuilder.Entity<User>()
|
||||||
.HasAlternateKey(b => b.UserId);
|
.HasAlternateKey(b => b.TelegramId);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,4 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using JOBot.Proto;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace JOBot.Backend.DAL.Models;
|
namespace JOBot.Backend.DAL.Models;
|
||||||
@ -9,31 +8,11 @@ public class User
|
|||||||
{
|
{
|
||||||
public Guid Id { get; set; }
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
[Key] public required long UserId { get; set; }
|
[Key]
|
||||||
|
public required long TelegramId { get; set; }
|
||||||
[MaxLength(255)] public string? Username { get; set; }
|
[MaxLength(50)]
|
||||||
|
public string? Username { get; set; }
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
|
||||||
[MaxLength(255)] public string? AccessToken { get; set; } = null;
|
public string? HeadHunterResumeUrl { get; set; }
|
||||||
[MaxLength(255)] public string? RefreshToken { get; set; } = null;
|
|
||||||
|
|
||||||
public bool Eula { get; set; } = false;
|
|
||||||
[MaxLength(255)] public string? CvUrl { get; set; } = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO: Негоже это маппинги в DAL ложить
|
|
||||||
public static class UserMap
|
|
||||||
{
|
|
||||||
public static GetUserResponse MapToResponse(this User user)
|
|
||||||
{
|
|
||||||
return new GetUserResponse
|
|
||||||
{
|
|
||||||
UserId = user.UserId,
|
|
||||||
Username = user.Username,
|
|
||||||
Eula = user.Eula,
|
|
||||||
IsLogged = user.RefreshToken != null,
|
|
||||||
CVUrl = user.CvUrl
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -1,14 +0,0 @@
|
|||||||
using System.Text.Json.Serialization;
|
|
||||||
|
|
||||||
namespace JOBot.Backend.DTOs.HeadHunterHook;
|
|
||||||
|
|
||||||
public record HeadHunterTokenResponseDto(
|
|
||||||
[property: JsonPropertyName("access_token")]
|
|
||||||
string AccessToken,
|
|
||||||
[property: JsonPropertyName("expires_in")]
|
|
||||||
int ExpiresIn,
|
|
||||||
[property: JsonPropertyName("refresh_token")]
|
|
||||||
string RefreshToken,
|
|
||||||
[property: JsonPropertyName("token_type")]
|
|
||||||
string TokenType
|
|
||||||
);
|
|
@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
|||||||
namespace JOBot.Backend.Data.Migrations
|
namespace JOBot.Backend.Data.Migrations
|
||||||
{
|
{
|
||||||
[DbContext(typeof(AppDbContext))]
|
[DbContext(typeof(AppDbContext))]
|
||||||
[Migration("20250710203327_Initial")]
|
[Migration("20250710125338_Initial")]
|
||||||
partial class Initial
|
partial class Initial
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@ -31,34 +31,22 @@ namespace JOBot.Backend.Data.Migrations
|
|||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<string>("AccessToken")
|
|
||||||
.HasMaxLength(255)
|
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<DateTime>("CreatedAt")
|
b.Property<DateTime>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("CvUrl")
|
b.Property<string>("HeadHunterResumeUrl")
|
||||||
.HasMaxLength(255)
|
.HasColumnType("text");
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<bool>("Eula")
|
b.Property<long>("TelegramId")
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<string>("RefreshToken")
|
|
||||||
.HasMaxLength(255)
|
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<long>("UserId")
|
|
||||||
.HasColumnType("bigint");
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
b.Property<string>("Username")
|
b.Property<string>("Username")
|
||||||
.HasMaxLength(255)
|
.HasMaxLength(50)
|
||||||
.HasColumnType("character varying(255)");
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
b.HasAlternateKey("UserId");
|
b.HasAlternateKey("TelegramId");
|
||||||
|
|
||||||
b.ToTable("Users");
|
b.ToTable("Users");
|
||||||
});
|
});
|
@ -16,18 +16,15 @@ namespace JOBot.Backend.Data.Migrations
|
|||||||
columns: table => new
|
columns: table => new
|
||||||
{
|
{
|
||||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
UserId = table.Column<long>(type: "bigint", nullable: false),
|
TelegramId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
Username = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true),
|
Username = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
|
||||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||||
AccessToken = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true),
|
HeadHunterResumeUrl = table.Column<string>(type: "text", nullable: true)
|
||||||
RefreshToken = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true),
|
|
||||||
Eula = table.Column<bool>(type: "boolean", nullable: false),
|
|
||||||
CvUrl = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true)
|
|
||||||
},
|
},
|
||||||
constraints: table =>
|
constraints: table =>
|
||||||
{
|
{
|
||||||
table.PrimaryKey("PK_Users", x => x.Id);
|
table.PrimaryKey("PK_Users", x => x.Id);
|
||||||
table.UniqueConstraint("AK_Users_UserId", x => x.UserId);
|
table.UniqueConstraint("AK_Users_TelegramId", x => x.TelegramId);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -28,34 +28,22 @@ namespace JOBot.Backend.Data.Migrations
|
|||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<string>("AccessToken")
|
|
||||||
.HasMaxLength(255)
|
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<DateTime>("CreatedAt")
|
b.Property<DateTime>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("CvUrl")
|
b.Property<string>("HeadHunterResumeUrl")
|
||||||
.HasMaxLength(255)
|
.HasColumnType("text");
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<bool>("Eula")
|
b.Property<long>("TelegramId")
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<string>("RefreshToken")
|
|
||||||
.HasMaxLength(255)
|
|
||||||
.HasColumnType("character varying(255)");
|
|
||||||
|
|
||||||
b.Property<long>("UserId")
|
|
||||||
.HasColumnType("bigint");
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
b.Property<string>("Username")
|
b.Property<string>("Username")
|
||||||
.HasMaxLength(255)
|
.HasMaxLength(50)
|
||||||
.HasColumnType("character varying(255)");
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
b.HasAlternateKey("UserId");
|
b.HasAlternateKey("TelegramId");
|
||||||
|
|
||||||
b.ToTable("Users");
|
b.ToTable("Users");
|
||||||
});
|
});
|
||||||
|
@ -1,18 +0,0 @@
|
|||||||
namespace JOBot.Backend.Infrastructure.Config;
|
|
||||||
|
|
||||||
public class HeadHunterConfig
|
|
||||||
{
|
|
||||||
public const string SectionName = "HeadHunter";
|
|
||||||
public required HeadHunterLinksConfig Links { get; init; }
|
|
||||||
public required string ClientId { get; init; }
|
|
||||||
public required string Secret { get; init; }
|
|
||||||
|
|
||||||
public class HeadHunterLinksConfig
|
|
||||||
{
|
|
||||||
public required string AuthLink { get; init; }
|
|
||||||
public required string HookDomain { get; init; }
|
|
||||||
public required string HookRoute { get; init; }
|
|
||||||
public required string HeadHunterApiDomain { get; init; }
|
|
||||||
public required string HeadHunterTokenRoute { get; init; }
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,38 +1,27 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Google.Protobuf" Version="3.30.2"/>
|
<PackageReference Include="Google.Protobuf" Version="3.30.2" />
|
||||||
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0"/>
|
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0" />
|
||||||
<PackageReference Include="Grpc.AspNetCore.Server.Reflection" Version="2.71.0"/>
|
<PackageReference Include="Grpc.Tools" Version="2.71.0">
|
||||||
<PackageReference Include="Grpc.Tools" Version="2.71.0">
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
</PackageReference>
|
||||||
</PackageReference>
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
|
||||||
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0"/>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
</PackageReference>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||||
</PackageReference>
|
</ItemGroup>
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4"/>
|
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.1.2"/>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Protobuf Include="..\Proto\*" GrpcServices="Server"></Protobuf>
|
<Protobuf Include="..\Proto\*" GrpcServices="Server"></Protobuf>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Folder Include="Data\Migrations\"/>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\JOBot.Infrastructure\JOBot.Infrastructure.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
@ -1,136 +0,0 @@
|
|||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
|
||||||
using JOBot.Backend.DAL.Context;
|
|
||||||
using JOBot.Backend.DTOs.HeadHunterHook;
|
|
||||||
using JOBot.Backend.Infrastructure.Config;
|
|
||||||
using JOBot.Infrastructure.Config;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace JOBot.Backend.Services;
|
|
||||||
|
|
||||||
public class HeadHunterService(
|
|
||||||
IChannel channel,
|
|
||||||
ILogger<HeadHunterService> logger,
|
|
||||||
IOptions<HeadHunterConfig> config,
|
|
||||||
IWebHostEnvironment env,
|
|
||||||
AppDbContext dbContext)
|
|
||||||
{
|
|
||||||
public enum Status
|
|
||||||
{
|
|
||||||
UserAuthRejectedError,
|
|
||||||
HeadHunterAuthRejectedError,
|
|
||||||
UserNotFoundError,
|
|
||||||
HeadHunterResponseDeserializationFailedError,
|
|
||||||
Success
|
|
||||||
}
|
|
||||||
|
|
||||||
private readonly HeadHunterConfig _config = config.Value;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Generate HeadHunter oauth authorization link
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="userId">Telegram UserId</param>
|
|
||||||
/// <returns>Link for auth</returns>
|
|
||||||
public string GenerateAuthLink(long userId)
|
|
||||||
{
|
|
||||||
return string.Format(_config.Links.AuthLink, [_config.ClientId, GetRedirectUrl(userId)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Status> AuthUser(int userId, string authorizationCode, string? error) //TODO: Разбить этот метод
|
|
||||||
{
|
|
||||||
logger.LogInformation($"Authorization for user {userId} in process...");
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(error))
|
|
||||||
{
|
|
||||||
logger.LogWarning($"User {userId} auth completed with error {error}");
|
|
||||||
return Status.UserAuthRejectedError;
|
|
||||||
}
|
|
||||||
|
|
||||||
HeadHunterTokenResponseDto? responseDto;
|
|
||||||
if (!env.IsDevelopment()) //Production server
|
|
||||||
{
|
|
||||||
using var client = new HttpClient();
|
|
||||||
var form = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
{ "client_id", _config.ClientId },
|
|
||||||
{ "client_secret", _config.Secret },
|
|
||||||
{ "code", authorizationCode },
|
|
||||||
{ "grant_type", "authorization_code" },
|
|
||||||
{ "redirect_uri", GetRedirectUrl(userId) }
|
|
||||||
};
|
|
||||||
client.BaseAddress = new UriBuilder(_config.Links.HeadHunterApiDomain)
|
|
||||||
{
|
|
||||||
Port = -1,
|
|
||||||
Scheme = "https"
|
|
||||||
}.Uri;
|
|
||||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("Jobot BackEnd Service");
|
|
||||||
|
|
||||||
using var res = await client.SendAsync(
|
|
||||||
new HttpRequestMessage(
|
|
||||||
HttpMethod.Post,
|
|
||||||
_config.Links.HeadHunterTokenRoute)
|
|
||||||
{
|
|
||||||
Content = new FormUrlEncodedContent(form)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.IsSuccessStatusCode)
|
|
||||||
{
|
|
||||||
logger.LogWarning($"Response of HttpRequest {_config.Links.HeadHunterApiDomain}" +
|
|
||||||
$"{_config.Links.HeadHunterTokenRoute} has unsuccessful status code {res.StatusCode}");
|
|
||||||
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
|
|
||||||
return Status.HeadHunterAuthRejectedError;
|
|
||||||
}
|
|
||||||
|
|
||||||
responseDto =
|
|
||||||
JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
|
|
||||||
|
|
||||||
if (responseDto == null)
|
|
||||||
{
|
|
||||||
logger.LogWarning($"User {userId} auth completed with error " +
|
|
||||||
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
|
|
||||||
return Status.HeadHunterResponseDeserializationFailedError;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
responseDto = new HeadHunterTokenResponseDto("testtoken", 0, "testtoken", "--");
|
|
||||||
}
|
|
||||||
|
|
||||||
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId);
|
|
||||||
|
|
||||||
if (user == null)
|
|
||||||
{
|
|
||||||
logger.LogWarning($"User {userId} search completed with error {nameof(Status.UserNotFoundError)}");
|
|
||||||
return Status.UserNotFoundError;
|
|
||||||
}
|
|
||||||
|
|
||||||
user.AccessToken = responseDto.AccessToken;
|
|
||||||
user.RefreshToken = responseDto.RefreshToken;
|
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync();
|
|
||||||
|
|
||||||
logger.LogInformation($"User {userId} auth completed!");
|
|
||||||
|
|
||||||
await channel.BasicPublishAsync(
|
|
||||||
string.Empty,
|
|
||||||
RabbitQueues.AuthQueue,
|
|
||||||
Encoding.UTF8.GetBytes(userId.ToString()));
|
|
||||||
|
|
||||||
logger.LogInformation("RabbitMQ event was created");
|
|
||||||
|
|
||||||
return Status.Success;
|
|
||||||
}
|
|
||||||
|
|
||||||
private string GetRedirectUrl(long userId)
|
|
||||||
{
|
|
||||||
return new UriBuilder(_config.Links.HookDomain)
|
|
||||||
{
|
|
||||||
Port = -1,
|
|
||||||
Scheme = "https",
|
|
||||||
Path = _config.Links.HookRoute,
|
|
||||||
Query = $"?userId={userId}"
|
|
||||||
}.ToString();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,85 +1,43 @@
|
|||||||
using Grpc.Core;
|
using Grpc.Core;
|
||||||
using JOBot.Backend.DAL.Context;
|
|
||||||
using JOBot.Backend.DAL.Models;
|
|
||||||
using JOBot.Proto;
|
using JOBot.Proto;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using JOBot.Backend.DAL.Context;
|
||||||
using User = JOBot.Backend.DAL.Models.User;
|
|
||||||
|
using Models = JOBot.Backend.DAL.Models;
|
||||||
|
|
||||||
namespace JOBot.Backend.Services.gRPC;
|
namespace JOBot.Backend.Services.gRPC;
|
||||||
|
public class UserService(AppDbContext dbContext) : User.UserBase
|
||||||
public class UserService(AppDbContext dbContext, HeadHunterService hhService) : Proto.User.UserBase
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// Create user
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="_"></param>
|
|
||||||
/// <returns>Status of operation (fail if user exists)</returns>
|
|
||||||
public override async Task<RegisterResponse> Register(RegisterRequest request, ServerCallContext _)
|
|
||||||
{
|
|
||||||
if (await dbContext.Users.AnyAsync(x => x.UserId == request.UserId))
|
|
||||||
return new RegisterResponse { Success = false };
|
|
||||||
|
|
||||||
dbContext.Users.Add(new User
|
public override Task<RegisterResponse> Register(
|
||||||
{
|
RegisterRequest request,
|
||||||
UserId = request.UserId,
|
|
||||||
Username = !string.IsNullOrEmpty(request.Username) ? request.Username : null
|
|
||||||
});
|
|
||||||
await dbContext.SaveChangesAsync();
|
|
||||||
|
|
||||||
return new RegisterResponse { Success = true };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Get user for client
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="_"></param>
|
|
||||||
/// <returns>User, or throws RPC exception if not found</returns>
|
|
||||||
public override async Task<GetUserResponse> GetUser(GetUserRequest request, ServerCallContext _)
|
|
||||||
{
|
|
||||||
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId);
|
|
||||||
ThrowIfUserNotFound(user);
|
|
||||||
|
|
||||||
return user!.MapToResponse();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Accept EULA for user
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="_"></param>
|
|
||||||
/// <returns>Status of operation</returns>
|
|
||||||
public override async Task<AcceptEulaResponse> AcceptEula(AcceptEulaRequest request, ServerCallContext _)
|
|
||||||
{
|
|
||||||
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId);
|
|
||||||
if (user == null)
|
|
||||||
return new AcceptEulaResponse { Success = false };
|
|
||||||
|
|
||||||
user.Eula = request.EulaAccepted;
|
|
||||||
await dbContext.SaveChangesAsync();
|
|
||||||
|
|
||||||
return new AcceptEulaResponse { Success = true };
|
|
||||||
}
|
|
||||||
|
|
||||||
public override Task<GetHeadHunterAuthHookResponse> GetHeadHunterAuthHook(
|
|
||||||
GetHeadHunterAuthHookRequest request,
|
|
||||||
ServerCallContext context)
|
ServerCallContext context)
|
||||||
{
|
{
|
||||||
return Task.Run(() => new GetHeadHunterAuthHookResponse
|
if(!dbContext.Users
|
||||||
|
.Any(x => x.TelegramId == request.UserId))
|
||||||
{
|
{
|
||||||
RegistrationUrl = hhService.GenerateAuthLink(request.UserId)
|
dbContext.Users.Add(new Models.User
|
||||||
|
{
|
||||||
|
TelegramId = request.UserId,
|
||||||
|
Username = !string.IsNullOrEmpty(request.Username) ? request.Username : null
|
||||||
|
});
|
||||||
|
|
||||||
|
dbContext.SaveChanges();
|
||||||
|
return Task.FromResult(new RegisterResponse
|
||||||
|
{
|
||||||
|
Success = true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(new RegisterResponse
|
||||||
|
{
|
||||||
|
Success = false
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
public override Task<GetUserResponse> GetUser(
|
||||||
/// Throw RPCException if user not found
|
GetUserRequest request,
|
||||||
/// </summary>
|
ServerCallContext context)
|
||||||
/// <param name="user"></param>
|
|
||||||
/// <exception cref="RpcException"></exception>
|
|
||||||
private static void ThrowIfUserNotFound(User? user)
|
|
||||||
{
|
{
|
||||||
if (user == null)
|
return null;
|
||||||
throw new RpcException(new Status(StatusCode.NotFound, "User not found"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,53 +1,27 @@
|
|||||||
using JOBot.Backend.DAL.Context;
|
using JOBot.Backend.DAL.Context;
|
||||||
using JOBot.Backend.Infrastructure.Config;
|
|
||||||
using JOBot.Backend.Services;
|
|
||||||
using JOBot.Backend.Services.gRPC;
|
using JOBot.Backend.Services.gRPC;
|
||||||
using JOBot.Infrastructure.Config;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace JOBot.Backend;
|
namespace JOBot.Backend;
|
||||||
|
|
||||||
public class Startup(IConfiguration configuration)
|
public class Startup
|
||||||
{
|
{
|
||||||
private IConfiguration Configuration { get; } = configuration;
|
public Startup(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
Configuration = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IConfiguration Configuration { get; }
|
||||||
|
|
||||||
public void ConfigureServices(IServiceCollection services)
|
public void ConfigureServices(IServiceCollection services)
|
||||||
{
|
{
|
||||||
services.AddGrpc();
|
services.AddGrpc();
|
||||||
services.AddGrpcReflection();
|
|
||||||
services.AddControllers();
|
|
||||||
services.AddLogging();
|
|
||||||
|
|
||||||
services.AddDbContext<AppDbContext>(options =>
|
services.AddDbContext<AppDbContext>(options =>
|
||||||
options.UseNpgsql(Configuration.GetConnectionString("PostgreSQL")));
|
options.UseNpgsql(Configuration.GetConnectionString("PostgreSQL")));
|
||||||
|
|
||||||
|
|
||||||
services.AddSingleton<IChannel>(x =>
|
|
||||||
{
|
|
||||||
var rabbitMqConnection = new ConnectionFactory
|
|
||||||
{
|
|
||||||
HostName = "rabbitmq"
|
|
||||||
}.CreateConnectionAsync().Result;
|
|
||||||
var channel = rabbitMqConnection.CreateChannelAsync().Result;
|
|
||||||
channel.QueueDeclareAsync(
|
|
||||||
RabbitQueues.AuthQueue,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
arguments: null).Wait();
|
|
||||||
return channel;
|
|
||||||
});
|
|
||||||
|
|
||||||
services.Configure<HeadHunterConfig>(Configuration.GetSection(HeadHunterConfig.SectionName));
|
|
||||||
|
|
||||||
services.AddScoped<HeadHunterService>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Configure(WebApplication app, IWebHostEnvironment env)
|
public void Configure(WebApplication app, IWebHostEnvironment env)
|
||||||
{
|
{
|
||||||
app.MapGrpcReflectionService().AllowAnonymous();
|
|
||||||
app.MapGrpcService<UserService>();
|
app.MapGrpcService<UserService>();
|
||||||
app.MapControllers();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
8
JOBot.Backend/appsettings.Development.json
Normal file
8
JOBot.Backend/appsettings.Development.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
12
JOBot.Backend/appsettings.Staging.json
Normal file
12
JOBot.Backend/appsettings.Staging.json
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*",
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"PostgreSQL": "Host=localhost;Port=5432;Database=jobot_test;Username=postgres;Password=LocalDbPass"
|
||||||
|
}
|
||||||
|
}
|
@ -1,35 +1,24 @@
|
|||||||
{
|
{
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"AllowedHosts": "*",
|
|
||||||
"ConnectionStrings": {
|
|
||||||
"PostgreSQL": "Host=postgres;Port=5432;Database=jobot;Username=postgres;Password=LocalDbPass"
|
|
||||||
},
|
|
||||||
"HeadHunter": {
|
|
||||||
"Links": {
|
|
||||||
"AuthLink": "https://hh.ru/oauth/authorize?response_type=code&client_id={0}&redirect_uri={1}",
|
|
||||||
"HookDomain": "jobot.lisoveliy.su",
|
|
||||||
"HookRoute": "/auth",
|
|
||||||
"HeadHunterApiDomain": "api.hh.ru",
|
|
||||||
"HeadHunterTokenRoute": "/token"
|
|
||||||
},
|
},
|
||||||
"ClientId": "",
|
"AllowedHosts": "*",
|
||||||
"Secret": ""
|
"ConnectionStrings": {
|
||||||
},
|
"PostgreSQL": "Host=postgres;Port=5432;Database=jobot;Username=postgres;Password=LocalDbPass"
|
||||||
"Kestrel": {
|
},
|
||||||
"Endpoints": {
|
"Kestrel": {
|
||||||
"gRPC": {
|
"Endpoints": {
|
||||||
"Url": "http://*:5001",
|
"gRPC": {
|
||||||
"Protocols": "Http2"
|
"Url": "http://*:5001",
|
||||||
},
|
"Protocols": "Http2"
|
||||||
"REST": {
|
},
|
||||||
"Url": "http://*:5000",
|
"REST": {
|
||||||
"Protocols": "Http1"
|
"Url": "http://*:5000",
|
||||||
}
|
"Protocols": "Http1"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
@ -1,6 +0,0 @@
|
|||||||
namespace JOBot.Infrastructure.Config;
|
|
||||||
|
|
||||||
public static class RabbitQueues
|
|
||||||
{
|
|
||||||
public const string AuthQueue = "auth";
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
71
JOBot.TClient/ButtonResource.Designer.cs
generated
71
JOBot.TClient/ButtonResource.Designer.cs
generated
@ -1,71 +0,0 @@
|
|||||||
//------------------------------------------------------------------------------
|
|
||||||
// <auto-generated>
|
|
||||||
// This code was generated by a tool.
|
|
||||||
//
|
|
||||||
// Changes to this file may cause incorrect behavior and will be lost if
|
|
||||||
// the code is regenerated.
|
|
||||||
// </auto-generated>
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
namespace JOBot.TClient {
|
|
||||||
using System;
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
|
||||||
/// </summary>
|
|
||||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
|
||||||
// class via a tool like ResGen or Visual Studio.
|
|
||||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
|
||||||
// with the /str option, or rebuild your VS project.
|
|
||||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
|
||||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
|
||||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
|
||||||
public class ButtonResource {
|
|
||||||
|
|
||||||
private static global::System.Resources.ResourceManager resourceMan;
|
|
||||||
|
|
||||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
|
||||||
|
|
||||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
|
||||||
internal ButtonResource() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns the cached ResourceManager instance used by this class.
|
|
||||||
/// </summary>
|
|
||||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
|
||||||
public static global::System.Resources.ResourceManager ResourceManager {
|
|
||||||
get {
|
|
||||||
if (object.ReferenceEquals(resourceMan, null)) {
|
|
||||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JOBot.TClient.ButtonResource", typeof(ButtonResource).Assembly);
|
|
||||||
resourceMan = temp;
|
|
||||||
}
|
|
||||||
return resourceMan;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Overrides the current thread's CurrentUICulture property for all
|
|
||||||
/// resource lookups using this strongly typed resource class.
|
|
||||||
/// </summary>
|
|
||||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
|
||||||
public static global::System.Globalization.CultureInfo Culture {
|
|
||||||
get {
|
|
||||||
return resourceCulture;
|
|
||||||
}
|
|
||||||
set {
|
|
||||||
resourceCulture = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Соглашаюсь с условиями использования ✅.
|
|
||||||
/// </summary>
|
|
||||||
public static string EULAAgrement {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("EULAAgrement", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,29 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
|
|
||||||
<root>
|
|
||||||
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root"
|
|
||||||
xmlns="">
|
|
||||||
<xsd:element name="root" msdata:IsDataSet="true">
|
|
||||||
|
|
||||||
</xsd:element>
|
|
||||||
</xsd:schema>
|
|
||||||
<resheader name="resmimetype">
|
|
||||||
<value>text/microsoft-resx</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="version">
|
|
||||||
<value>1.3</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="reader">
|
|
||||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
|
||||||
PublicKeyToken=b77a5c561934e089
|
|
||||||
</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="writer">
|
|
||||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
|
||||||
PublicKeyToken=b77a5c561934e089
|
|
||||||
</value>
|
|
||||||
</resheader>
|
|
||||||
<data name="EULAAgrement" xml:space="preserve">
|
|
||||||
<value>Соглашаюсь с условиями использования ✅</value>
|
|
||||||
</data>
|
|
||||||
</root>
|
|
@ -1,16 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Infrastructure.Attributes.Authorization;
|
|
||||||
using JOBot.TClient.Statements;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Commands.Buttons;
|
|
||||||
|
|
||||||
[AcceptNotPrepared]
|
|
||||||
public class EulaAgreementButtonCommand(PrepareUserState prepareUserState) : IAuthorizedTelegramCommand
|
|
||||||
{
|
|
||||||
public async Task ExecuteAsync(Update update, GetUserResponse user, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!user.Eula)
|
|
||||||
await prepareUserState.AcceptEula(user, update, ct);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
using JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Commands.Commands;
|
|
||||||
|
|
||||||
public class InfoCommand(ITelegramBotClient bot) : ITelegramCommand
|
|
||||||
{
|
|
||||||
public async Task ExecuteAsync(Update update, CancellationToken ct)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
await bot.SendMessageRemK(update.Message.From.Id, TextResource.Info, cancellationToken: ct);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Services;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Commands.Commands;
|
|
||||||
|
|
||||||
public class MenuCommand(MenuService menuService) : IAuthorizedTelegramCommand
|
|
||||||
{
|
|
||||||
public async Task ExecuteAsync(Update update, GetUserResponse user, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await menuService.RenderMenu(update, ct);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
using JOBot.TClient.Statements;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Commands.Commands;
|
|
||||||
|
|
||||||
public class StartCommand(PrepareUserState prepareUserState) : ITelegramCommand
|
|
||||||
{
|
|
||||||
public async Task ExecuteAsync(Update update, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await prepareUserState.TryToPrepareUser(update, ct);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,18 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Commands;
|
|
||||||
|
|
||||||
public interface IAuthorizedTelegramCommand : ITelegramCommand
|
|
||||||
{
|
|
||||||
/// <exception cref="UnauthorizedAccessException">
|
|
||||||
/// Throws if you try to use ITelegramCommand.ExecuteAsync
|
|
||||||
/// instead of IAuthorizedTelegramCommand.ExecuteAsync
|
|
||||||
/// </exception>
|
|
||||||
Task ITelegramCommand.ExecuteAsync(Update update, CancellationToken ct)
|
|
||||||
{
|
|
||||||
throw new UnauthorizedAccessException("You do not have permission to access this command.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task ExecuteAsync(Update update, GetUserResponse user, CancellationToken ct);
|
|
||||||
}
|
|
22
JOBot.TClient/Commands/StartCommand.cs
Normal file
22
JOBot.TClient/Commands/StartCommand.cs
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
using JOBot.TClient.Core.Services;
|
||||||
|
using Telegram.Bot;
|
||||||
|
using Telegram.Bot.Types;
|
||||||
|
|
||||||
|
namespace JOBot.TClient.Commands;
|
||||||
|
|
||||||
|
public class StartCommand(ITelegramBotClient bot, UserService userService) : ITelegramCommand
|
||||||
|
{
|
||||||
|
private const string ReturnMessage = "Привет! Я JOBot, помощник по поиску работы в IT.";
|
||||||
|
public async Task ExecuteAsync(Update update, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await userService.RegisterAsync(
|
||||||
|
update.Message!.Chat.Id,
|
||||||
|
update.Message.Chat.Username);
|
||||||
|
|
||||||
|
await bot.SendMessage(chatId: update.Message.Chat.Id,
|
||||||
|
"Продолжая, вы принимаете политику конфиденциальности и правила сервиса" +
|
||||||
|
"\nhttps://hh.ru/article/personal_data?backurl=%2F&role=applicant" +
|
||||||
|
"\nhttps://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant",
|
||||||
|
cancellationToken: ct);
|
||||||
|
}
|
||||||
|
}
|
@ -1,29 +1,24 @@
|
|||||||
using JOBot.TClient.Commands;
|
using JOBot.TClient.Commands;
|
||||||
using JOBot.TClient.Commands.Buttons;
|
|
||||||
using JOBot.TClient.Commands.Commands;
|
|
||||||
using JOBot.TClient.Infrastructure.Attributes.Authorization;
|
|
||||||
using JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
using JOBot.TClient.Services;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Core.HostedServices;
|
namespace JOBot.TClient.Core.HostedServices;
|
||||||
|
|
||||||
|
using Telegram.Bot;
|
||||||
|
using Telegram.Bot.Types;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
public sealed class BotBackgroundService(
|
public sealed class BotBackgroundService(
|
||||||
ITelegramBotClient botClient,
|
ITelegramBotClient botClient,
|
||||||
IServiceProvider services,
|
IServiceProvider services,
|
||||||
ILogger<BotBackgroundService> logger,
|
ILogger<BotBackgroundService> logger)
|
||||||
UserService userService)
|
|
||||||
: BackgroundService
|
: BackgroundService
|
||||||
{
|
{
|
||||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
{
|
{
|
||||||
botClient.StartReceiving(
|
botClient.StartReceiving(
|
||||||
HandleUpdateAsync,
|
updateHandler: HandleUpdateAsync,
|
||||||
HandleErrorAsync,
|
errorHandler: HandleErrorAsync,
|
||||||
cancellationToken: stoppingToken);
|
cancellationToken: stoppingToken);
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
@ -34,51 +29,11 @@ public sealed class BotBackgroundService(
|
|||||||
using var scope = services.CreateScope();
|
using var scope = services.CreateScope();
|
||||||
var commands = new Dictionary<string, ITelegramCommand>
|
var commands = new Dictionary<string, ITelegramCommand>
|
||||||
{
|
{
|
||||||
//Commands
|
["/start"] = scope.ServiceProvider.GetRequiredService<StartCommand>()
|
||||||
["/start"] = scope.ServiceProvider.GetRequiredService<StartCommand>(),
|
|
||||||
["/menu"] = scope.ServiceProvider.GetRequiredService<MenuCommand>(),
|
|
||||||
["/info"] = scope.ServiceProvider.GetRequiredService<InfoCommand>(),
|
|
||||||
|
|
||||||
//Buttons
|
|
||||||
[ButtonResource.EULAAgrement] = scope.ServiceProvider.GetRequiredService<EulaAgreementButtonCommand>()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (update.Message is { Text: { } text, From: not null })
|
if (update.Message?.Text is { } text && commands.TryGetValue(text, out var command))
|
||||||
{
|
await command.ExecuteAsync(update, ct);
|
||||||
var user = await userService.GetUser(update, ct); //Проверка существования пользователя
|
|
||||||
|
|
||||||
if (user == null)
|
|
||||||
{
|
|
||||||
await commands["/start"].ExecuteAsync(update, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (commands.TryGetValue(text, out var command))
|
|
||||||
{
|
|
||||||
if (command is IAuthorizedTelegramCommand authorizedTelegramCommand)
|
|
||||||
{
|
|
||||||
var attribute = Attribute.GetCustomAttribute(
|
|
||||||
command.GetType(),
|
|
||||||
typeof(AcceptNotPreparedAttribute));
|
|
||||||
if (!user.IsPrepared() && attribute is not AcceptNotPreparedAttribute)
|
|
||||||
{
|
|
||||||
await commands["/start"].ExecuteAsync(update, ct);
|
|
||||||
//заставляем пользователя завершить регистрацию
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await authorizedTelegramCommand.ExecuteAsync(update, user, ct);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
await command.ExecuteAsync(update, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await bot.SendMessageRemK(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task HandleErrorAsync(ITelegramBotClient bot, Exception ex, CancellationToken ct)
|
private Task HandleErrorAsync(ITelegramBotClient bot, Exception ex, CancellationToken ct)
|
||||||
|
18
JOBot.TClient/Core/Services/UserService.cs
Normal file
18
JOBot.TClient/Core/Services/UserService.cs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
using User = JOBot.Proto.User;
|
||||||
|
|
||||||
|
namespace JOBot.TClient.Core.Services;
|
||||||
|
|
||||||
|
public class UserService(User.UserClient client)
|
||||||
|
{
|
||||||
|
public async Task<bool> RegisterAsync(long userId, string? username)
|
||||||
|
{
|
||||||
|
|
||||||
|
var response = await client.RegisterAsync(new()
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
Username = username
|
||||||
|
});
|
||||||
|
|
||||||
|
return response.Success;
|
||||||
|
}
|
||||||
|
}
|
38
JOBot.TClient/DependencyInjection.cs
Normal file
38
JOBot.TClient/DependencyInjection.cs
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using Grpc.Net.Client;
|
||||||
|
using JOBot.Proto;
|
||||||
|
using JOBot.TClient.Commands;
|
||||||
|
using JOBot.TClient.Core.Services;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Telegram.Bot;
|
||||||
|
|
||||||
|
namespace JOBot.TClient;
|
||||||
|
|
||||||
|
public static class DependencyInjection
|
||||||
|
{
|
||||||
|
public static IServiceCollection ConfigureServices(this IServiceCollection services, IConfiguration config)
|
||||||
|
{
|
||||||
|
services.AddSingleton(config);
|
||||||
|
|
||||||
|
services.AddScoped<ChannelBase, GrpcChannel>(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
|
||||||
|
?? throw new MissingFieldException("Host is not defined")));
|
||||||
|
|
||||||
|
//Commands
|
||||||
|
services.AddScoped<StartCommand>();
|
||||||
|
|
||||||
|
services.AddSingleton<UserService>();
|
||||||
|
|
||||||
|
//gRPC Clients
|
||||||
|
services.AddScoped<User.UserClient>();
|
||||||
|
|
||||||
|
// Telegram Bot
|
||||||
|
services.AddSingleton<ITelegramBotClient>(_ =>
|
||||||
|
new TelegramBotClient(config.GetValue<string>("TelegramToken")
|
||||||
|
?? throw new MissingFieldException("TelegramToken is not set")));
|
||||||
|
|
||||||
|
services.AddLogging(builder => builder.AddConsole());
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +0,0 @@
|
|||||||
namespace JOBot.TClient.Infrastructure.Attributes.Authorization;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Атрибут допуска к команде пользователя не завершившего стадию PrepareUser
|
|
||||||
/// </summary>
|
|
||||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
|
|
||||||
public class AcceptNotPreparedAttribute : Attribute;
|
|
@ -1,18 +0,0 @@
|
|||||||
using JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Infrastructure.Exceptions;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Exception for fallback
|
|
||||||
/// WARNING: Don't create new exception without throwing it
|
|
||||||
/// </summary>
|
|
||||||
public class FallbackException : Exception
|
|
||||||
{
|
|
||||||
public FallbackException(string message, Message botMessage, ITelegramBotClient botClient) : base(message)
|
|
||||||
{
|
|
||||||
botClient.SendMessageRemK(botMessage.Chat.Id,
|
|
||||||
TextResource.FallbackMessage);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
|
|
||||||
public static class GRpcModelsExtensions
|
|
||||||
{
|
|
||||||
public static bool IsPrepared(this GetUserResponse user)
|
|
||||||
{
|
|
||||||
return user is { Eula: true, IsLogged: true } &&
|
|
||||||
!string.IsNullOrEmpty(user.CVUrl);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
using Telegram.Bot.Types.Enums;
|
|
||||||
using Telegram.Bot.Types.ReplyMarkups;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
|
|
||||||
public static class TelegramBotClientExtensions
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Extension method for auto-remove of reply keyboard if is null
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bot"></param>
|
|
||||||
/// <param name="chatId"></param>
|
|
||||||
/// <param name="text"></param>
|
|
||||||
/// <param name="parseMode"></param>
|
|
||||||
/// <param name="replyParameters"></param>
|
|
||||||
/// <param name="replyMarkup"></param>
|
|
||||||
/// <param name="linkPreviewOptions"></param>
|
|
||||||
/// <param name="messageThreadId"></param>
|
|
||||||
/// <param name="entities"></param>
|
|
||||||
/// <param name="disableNotification"></param>
|
|
||||||
/// <param name="protectContent"></param>
|
|
||||||
/// <param name="messageEffectId"></param>
|
|
||||||
/// <param name="businessConnectionId"></param>
|
|
||||||
/// <param name="allowPaidBroadcast"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public static Task<Message> SendMessageRemK(
|
|
||||||
this ITelegramBotClient bot,
|
|
||||||
ChatId chatId,
|
|
||||||
string text,
|
|
||||||
ParseMode parseMode = default,
|
|
||||||
ReplyParameters? replyParameters = null,
|
|
||||||
ReplyMarkup? replyMarkup = null,
|
|
||||||
LinkPreviewOptions? linkPreviewOptions = null,
|
|
||||||
int? messageThreadId = null,
|
|
||||||
IEnumerable<MessageEntity>? entities = null,
|
|
||||||
bool disableNotification = false,
|
|
||||||
bool protectContent = false,
|
|
||||||
string? messageEffectId = null,
|
|
||||||
string? businessConnectionId = null,
|
|
||||||
bool allowPaidBroadcast = false,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
replyMarkup ??= new ReplyKeyboardRemove();
|
|
||||||
|
|
||||||
return bot.SendMessage(chatId, text, parseMode, replyParameters, replyMarkup, linkPreviewOptions, messageThreadId,
|
|
||||||
entities, disableNotification, protectContent, messageEffectId, businessConnectionId, allowPaidBroadcast,
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,71 +1,39 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Google.Protobuf" Version="3.30.2"/>
|
<PackageReference Include="Google.Protobuf" Version="3.30.2" />
|
||||||
<PackageReference Include="Grpc.Net.Client" Version="2.71.0"/>
|
<PackageReference Include="Grpc.Net.Client" Version="2.71.0" />
|
||||||
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.71.0"/>
|
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.71.0" />
|
||||||
<PackageReference Include="Grpc.Tools" Version="2.71.0">
|
<PackageReference Include="Grpc.Tools" Version="2.71.0">
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0"/>
|
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.4"/>
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.4"/>
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4"/>
|
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4"/>
|
<PackageReference Include="Telegram.Bot" Version="22.5.1" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.1.2"/>
|
</ItemGroup>
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.5.1"/>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Protobuf Include="..\Proto\*" GrpcServices="Client"></Protobuf>
|
<Protobuf Include="..\Proto\*" GrpcServices="Client"></Protobuf>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<None Update="appsettings.Example.json">
|
<None Update="appsettings.Example.json">
|
||||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="ButtonResource.Designer.cs">
|
<Folder Include="Infrastucture\" />
|
||||||
<DesignTime>True</DesignTime>
|
</ItemGroup>
|
||||||
<AutoGen>True</AutoGen>
|
|
||||||
<DependentUpon>ButtonResource.resx</DependentUpon>
|
|
||||||
</Compile>
|
|
||||||
<Compile Update="TextResource.Designer.cs">
|
|
||||||
<DesignTime>True</DesignTime>
|
|
||||||
<AutoGen>True</AutoGen>
|
|
||||||
<DependentUpon>TextResource.resx</DependentUpon>
|
|
||||||
</Compile>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<EmbeddedResource Update="TextResource.resx">
|
|
||||||
<Generator>PublicResXFileCodeGenerator</Generator>
|
|
||||||
<LastGenOutput>TextResource.Designer.cs</LastGenOutput>
|
|
||||||
</EmbeddedResource>
|
|
||||||
<EmbeddedResource Update="ButtonResource.resx">
|
|
||||||
<Generator>PublicResXFileCodeGenerator</Generator>
|
|
||||||
<LastGenOutput>ButtonResource.Designer.cs</LastGenOutput>
|
|
||||||
</EmbeddedResource>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Content Include="appsettings.json">
|
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
|
||||||
</Content>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\JOBot.Infrastructure\JOBot.Infrastructure.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
@ -1,4 +1,9 @@
|
|||||||
using JOBot.TClient;
|
using JOBot.Proto;
|
||||||
|
using JOBot.TClient;
|
||||||
|
using JOBot.TClient.Commands;
|
||||||
|
using JOBot.TClient.Core.HostedServices;
|
||||||
|
using JOBot.TClient.Core.Services;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
var host = Host.CreateDefaultBuilder(args)
|
var host = Host.CreateDefaultBuilder(args)
|
||||||
@ -6,6 +11,13 @@ var host = Host.CreateDefaultBuilder(args)
|
|||||||
{
|
{
|
||||||
// Настройка DI
|
// Настройка DI
|
||||||
services.ConfigureServices(context.Configuration);
|
services.ConfigureServices(context.Configuration);
|
||||||
|
|
||||||
|
// Фоновый сервис для бота
|
||||||
|
services.AddHostedService<BotBackgroundService>();
|
||||||
|
|
||||||
|
services.AddScoped<StartCommand>();
|
||||||
|
services.AddSingleton<UserService>();
|
||||||
|
services.AddGrpcClient<User.UserClient>(o => o.Address = new Uri("http://backend:5001"));
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
|
@ -1,24 +0,0 @@
|
|||||||
using System.Text;
|
|
||||||
using JOBot.Infrastructure.Config;
|
|
||||||
using JOBot.TClient.Services;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Queues;
|
|
||||||
|
|
||||||
public class AuthQueue(IChannel channel, PrepareUserService prepareUserService) : BackgroundService
|
|
||||||
{
|
|
||||||
|
|
||||||
private async Task OnDataReceivedAsync(object sender, BasicDeliverEventArgs eventArgs)
|
|
||||||
{
|
|
||||||
await prepareUserService.AuthHookReceived(Convert.ToInt64(Encoding.UTF8.GetString(eventArgs.Body.ToArray())));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
||||||
{
|
|
||||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
|
||||||
consumer.ReceivedAsync += OnDataReceivedAsync;
|
|
||||||
await channel.BasicConsumeAsync(RabbitQueues.AuthQueue, autoAck: true, consumer: consumer, cancellationToken: stoppingToken);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
using JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Services;
|
|
||||||
|
|
||||||
public class MenuService(ITelegramBotClient bot)
|
|
||||||
{
|
|
||||||
public async Task RenderMenu(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
await bot.SendMessageRemK(update.Message.From.Id, "PrepareUser stage is done.", cancellationToken: ct);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,121 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Infrastructure.Exceptions;
|
|
||||||
using JOBot.TClient.Infrastructure.Extensions;
|
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
using User = JOBot.Proto.User;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Services;
|
|
||||||
|
|
||||||
public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClient) : UserService(bot, userClient)
|
|
||||||
{
|
|
||||||
private readonly ITelegramBotClient _bot = bot;
|
|
||||||
private readonly User.UserClient _userClient = userClient;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Get or register user on system
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="update">Telegram Update object</param>
|
|
||||||
/// <param name="ct">Cancellation Token</param>
|
|
||||||
/// <returns>RPC User Response</returns>
|
|
||||||
/// <exception cref="FallbackException">If something in server logic went wrong</exception>
|
|
||||||
/// <exception cref="ArgumentNullException">update.Message is null</exception>
|
|
||||||
public async Task<GetUserResponse> RegisterUser(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
var result = await _userClient.RegisterAsync(new RegisterRequest
|
|
||||||
{
|
|
||||||
UserId = update.Message.From.Id,
|
|
||||||
Username = update.Message.From.Username
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.Success)
|
|
||||||
{
|
|
||||||
await _bot.SendMessageRemK(update.Message.Chat.Id,
|
|
||||||
TextResource.FallbackMessage,
|
|
||||||
cancellationToken: ct);
|
|
||||||
|
|
||||||
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
|
|
||||||
}
|
|
||||||
|
|
||||||
var user = await _userClient.GetUserAsync(new GetUserRequest
|
|
||||||
{
|
|
||||||
UserId = update.Message.From.Id
|
|
||||||
});
|
|
||||||
|
|
||||||
if (user == null)
|
|
||||||
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
|
|
||||||
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Get Eula Agreement from user
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="update">Telegram Update object</param>
|
|
||||||
/// <param name="ct">Cancellation Token</param>
|
|
||||||
/// <exception cref="ArgumentNullException">update.Message is null</exception>
|
|
||||||
public async Task AskForEulaAgreement(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
await _bot.SendMessageRemK(
|
|
||||||
update.Message.From.Id,
|
|
||||||
TextResource.EULA,
|
|
||||||
replyMarkup: new[] { ButtonResource.EULAAgrement }, cancellationToken: ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Accept EULA for user
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="update">Telegram update object</param>
|
|
||||||
/// <param name="ct">Cancellation Token</param>
|
|
||||||
/// <exception cref="FallbackException">If something in server logic went wrong</exception>
|
|
||||||
public async Task AcceptEula(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
var result = await _userClient.AcceptEulaAsync(new AcceptEulaRequest
|
|
||||||
{
|
|
||||||
EulaAccepted = true,
|
|
||||||
UserId = update.Message.From.Id
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.Success)
|
|
||||||
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Auth(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
var url = await _userClient.GetHeadHunterAuthHookAsync(new GetHeadHunterAuthHookRequest
|
|
||||||
{
|
|
||||||
UserId = update.Message.From.Id
|
|
||||||
});
|
|
||||||
|
|
||||||
await _bot.SendMessageRemK(
|
|
||||||
update.Message.From.Id,
|
|
||||||
string.Format(TextResource.AskForAuth, [url.RegistrationUrl]),
|
|
||||||
cancellationToken: ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AuthHookReceived(long userId, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await _bot.SendMessageRemK(userId, "✅ Авторизация завершена успешно!", cancellationToken: ct);
|
|
||||||
await SelectCv(userId, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SelectCv(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
await SelectCv(update.Message.From.Id, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SelectCv(long userId, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await _bot.SendMessageRemK(userId, "Давайте выберем одно из доступных резюме:",
|
|
||||||
cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Infrastructure.Exceptions;
|
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
using User = JOBot.Proto.User;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Services;
|
|
||||||
|
|
||||||
public class UserService(ITelegramBotClient bot, User.UserClient userClient)
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Get user
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="update">Telegram Update object</param>
|
|
||||||
/// <param name="ct">Cancellation Token</param>
|
|
||||||
/// <returns>RPC User Response or null if user not exists</returns>
|
|
||||||
/// <exception cref="FallbackException">If something in server logic went wrong</exception>
|
|
||||||
/// <exception cref="ArgumentNullException">If update.Message is null</exception>
|
|
||||||
public async Task<GetUserResponse?> GetUser(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
|
||||||
|
|
||||||
GetUserResponse? user;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
user = await userClient.GetUserAsync(new GetUserRequest() //Получаем пользователя
|
|
||||||
{
|
|
||||||
UserId = update.Message.From.Id
|
|
||||||
});
|
|
||||||
}
|
|
||||||
catch (RpcException e) //Пользователь не найден?
|
|
||||||
{
|
|
||||||
if (e.StatusCode != StatusCode.NotFound)
|
|
||||||
throw new FallbackException(TextResource.FallbackMessage, update.Message, bot);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,87 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using Grpc.Net.Client;
|
|
||||||
using JOBot.Infrastructure.Config;
|
|
||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Commands.Buttons;
|
|
||||||
using JOBot.TClient.Commands.Commands;
|
|
||||||
using JOBot.TClient.Core.HostedServices;
|
|
||||||
using JOBot.TClient.Queues;
|
|
||||||
using JOBot.TClient.Services;
|
|
||||||
using JOBot.TClient.Statements;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
using Telegram.Bot;
|
|
||||||
|
|
||||||
namespace JOBot.TClient;
|
|
||||||
|
|
||||||
public static class Startup
|
|
||||||
{
|
|
||||||
public static IServiceCollection ConfigureServices(this IServiceCollection services, IConfiguration config)
|
|
||||||
{
|
|
||||||
services.AddSingleton(config);
|
|
||||||
|
|
||||||
services.AddSingleton(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
|
|
||||||
?? throw new MissingFieldException("Host is not defined")));
|
|
||||||
|
|
||||||
#region Commands
|
|
||||||
|
|
||||||
services.AddSingleton<StartCommand>();
|
|
||||||
services.AddSingleton<MenuCommand>();
|
|
||||||
services.AddSingleton<InfoCommand>();
|
|
||||||
|
|
||||||
//buttons
|
|
||||||
services.AddSingleton<EulaAgreementButtonCommand>();
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region gRPC Clients
|
|
||||||
|
|
||||||
services.AddGrpcClient<User.UserClient>(o => o.Address = new Uri("http://backend:5001"));
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Services
|
|
||||||
|
|
||||||
services.AddSingleton<UserService>();
|
|
||||||
services.AddSingleton<PrepareUserService>();
|
|
||||||
services.AddSingleton<MenuService>();
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region States
|
|
||||||
|
|
||||||
services.AddSingleton<PrepareUserState>();
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region RabbitMQ Clients
|
|
||||||
|
|
||||||
var factory = new ConnectionFactory { HostName = "rabbitmq" };
|
|
||||||
var connection = factory.CreateConnectionAsync().Result;
|
|
||||||
var channel = connection.CreateChannelAsync().Result;
|
|
||||||
|
|
||||||
channel.QueueDeclareAsync(
|
|
||||||
RabbitQueues.AuthQueue,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
arguments: null).Wait();
|
|
||||||
|
|
||||||
services.AddSingleton(channel);
|
|
||||||
services.AddHostedService<AuthQueue>();
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
// Bot service
|
|
||||||
services.AddHostedService<BotBackgroundService>();
|
|
||||||
services.AddSingleton<ITelegramBotClient>(_ =>
|
|
||||||
new TelegramBotClient(config.GetValue<string>("TelegramToken")
|
|
||||||
?? throw new MissingFieldException("TelegramToken is not set")));
|
|
||||||
|
|
||||||
services.AddLogging(builder => builder.AddConsole());
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
using JOBot.Proto;
|
|
||||||
using JOBot.TClient.Services;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
|
|
||||||
namespace JOBot.TClient.Statements;
|
|
||||||
|
|
||||||
public class PrepareUserState(PrepareUserService prepareUserService, MenuService menuService)
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Try to prepare user if is not registered
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="update">Update telegram object</param>
|
|
||||||
/// <param name="ct">Cancellation token</param>
|
|
||||||
public async Task TryToPrepareUser(Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var user = await prepareUserService.GetUser(update, ct) ?? await prepareUserService.RegisterUser(update, ct);
|
|
||||||
|
|
||||||
if (!user.Eula)
|
|
||||||
{
|
|
||||||
await prepareUserService.AskForEulaAgreement(update, ct);
|
|
||||||
return; //interrupt while eula isn't accepted
|
|
||||||
}
|
|
||||||
|
|
||||||
await OnUserEulaValidStage(user, update, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Signal for accepted eula
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="user"></param>
|
|
||||||
/// <param name="update"></param>
|
|
||||||
/// <param name="ct"></param>
|
|
||||||
public async Task AcceptEula(GetUserResponse user, Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await prepareUserService.AcceptEula(update, ct);
|
|
||||||
await OnUserEulaValidStage(user, update, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Check user logged
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="user"></param>
|
|
||||||
/// <param name="update"></param>
|
|
||||||
/// <param name="ct"></param>
|
|
||||||
private async Task OnUserEulaValidStage(GetUserResponse user, Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
if (!user.IsLogged)
|
|
||||||
{
|
|
||||||
await prepareUserService.Auth(update, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await OnAuthStage(user, update, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Check user selected CV
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="user"></param>
|
|
||||||
/// <param name="update"></param>
|
|
||||||
/// <param name="ct"></param>
|
|
||||||
private async Task OnAuthStage(GetUserResponse user, Update update, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrEmpty(user.CVUrl)) await prepareUserService.SelectCv(update, ct);
|
|
||||||
await menuService.RenderMenu(update, ct); //boilerplate
|
|
||||||
}
|
|
||||||
}
|
|
111
JOBot.TClient/TextResource.Designer.cs
generated
111
JOBot.TClient/TextResource.Designer.cs
generated
@ -1,111 +0,0 @@
|
|||||||
//------------------------------------------------------------------------------
|
|
||||||
// <auto-generated>
|
|
||||||
// This code was generated by a tool.
|
|
||||||
//
|
|
||||||
// Changes to this file may cause incorrect behavior and will be lost if
|
|
||||||
// the code is regenerated.
|
|
||||||
// </auto-generated>
|
|
||||||
//------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
namespace JOBot.TClient {
|
|
||||||
using System;
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
|
||||||
/// </summary>
|
|
||||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
|
||||||
// class via a tool like ResGen or Visual Studio.
|
|
||||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
|
||||||
// with the /str option, or rebuild your VS project.
|
|
||||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
|
||||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
|
||||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
|
||||||
public class TextResource {
|
|
||||||
|
|
||||||
private static global::System.Resources.ResourceManager resourceMan;
|
|
||||||
|
|
||||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
|
||||||
|
|
||||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
|
||||||
internal TextResource() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns the cached ResourceManager instance used by this class.
|
|
||||||
/// </summary>
|
|
||||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
|
||||||
public static global::System.Resources.ResourceManager ResourceManager {
|
|
||||||
get {
|
|
||||||
if (object.ReferenceEquals(resourceMan, null)) {
|
|
||||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JOBot.TClient.TextResource", typeof(TextResource).Assembly);
|
|
||||||
resourceMan = temp;
|
|
||||||
}
|
|
||||||
return resourceMan;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Overrides the current thread's CurrentUICulture property for all
|
|
||||||
/// resource lookups using this strongly typed resource class.
|
|
||||||
/// </summary>
|
|
||||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
|
||||||
public static global::System.Globalization.CultureInfo Culture {
|
|
||||||
get {
|
|
||||||
return resourceCulture;
|
|
||||||
}
|
|
||||||
set {
|
|
||||||
resourceCulture = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Авторизируйтесь на сайте HeadHunter для получения доступа к резюме и вакансиям {0}.
|
|
||||||
/// </summary>
|
|
||||||
public static string AskForAuth {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("AskForAuth", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Команда не найдена, попробуйте что-то другое.
|
|
||||||
/// </summary>
|
|
||||||
public static string CommandNotFound {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("CommandNotFound", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Продолжая, вы принимаете политику конфиденциальности и правила сервиса
|
|
||||||
///
|
|
||||||
///https://hh.ru/article/personal_data?backurl=%2F&role=applicant
|
|
||||||
///
|
|
||||||
///https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant".
|
|
||||||
/// </summary>
|
|
||||||
public static string EULA {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("EULA", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Something went REALLY wrong. Service can't continue process..
|
|
||||||
/// </summary>
|
|
||||||
public static string FallbackMessage {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("FallbackMessage", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks up a localized string similar to Это бот для упрощения поиска работы на HH.ru.
|
|
||||||
/// </summary>
|
|
||||||
public static string Info {
|
|
||||||
get {
|
|
||||||
return ResourceManager.GetString("Info", resourceCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,45 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
|
|
||||||
<root>
|
|
||||||
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root"
|
|
||||||
xmlns="">
|
|
||||||
<xsd:element name="root" msdata:IsDataSet="true">
|
|
||||||
|
|
||||||
</xsd:element>
|
|
||||||
</xsd:schema>
|
|
||||||
<resheader name="resmimetype">
|
|
||||||
<value>text/microsoft-resx</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="version">
|
|
||||||
<value>1.3</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="reader">
|
|
||||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
|
||||||
PublicKeyToken=b77a5c561934e089
|
|
||||||
</value>
|
|
||||||
</resheader>
|
|
||||||
<resheader name="writer">
|
|
||||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
|
||||||
PublicKeyToken=b77a5c561934e089
|
|
||||||
</value>
|
|
||||||
</resheader>
|
|
||||||
<data name="EULA" xml:space="preserve">
|
|
||||||
<value>Продолжая, вы принимаете политику конфиденциальности и правила сервиса
|
|
||||||
|
|
||||||
https://hh.ru/article/personal_data?backurl=%2F&role=applicant
|
|
||||||
|
|
||||||
https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant"</value>
|
|
||||||
</data>
|
|
||||||
<data name="FallbackMessage" xml:space="preserve">
|
|
||||||
<value>Something went REALLY wrong. Service can't continue process.</value>
|
|
||||||
</data>
|
|
||||||
<data name="CommandNotFound" xml:space="preserve">
|
|
||||||
<value>Команда не найдена, попробуйте что-то другое</value>
|
|
||||||
</data>
|
|
||||||
<data name="Info" xml:space="preserve">
|
|
||||||
<value>Это бот для упрощения поиска работы на HH.ru</value>
|
|
||||||
</data>
|
|
||||||
<data name="AskForAuth" xml:space="preserve">
|
|
||||||
<value>Авторизируйтесь на сайте HeadHunter для получения доступа к резюме и вакансиям {0}</value>
|
|
||||||
</data>
|
|
||||||
</root>
|
|
14
JOBot.sln
14
JOBot.sln
@ -7,8 +7,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JOBot.Backend", "JOBot.Back
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JOBot.TClient", "JOBot.TClient\JOBot.TClient.csproj", "{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JOBot.TClient", "JOBot.TClient\JOBot.TClient.csproj", "{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JOBot.Infrastructure", "JOBot.Infrastructure\JOBot.Infrastructure.csproj", "{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}"
|
|
||||||
EndProject
|
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@ -43,18 +41,6 @@ Global
|
|||||||
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x64.Build.0 = Release|Any CPU
|
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x86.ActiveCfg = Release|Any CPU
|
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x86.Build.0 = Release|Any CPU
|
{4526BCB1-DAD3-430C-BD7C-9C114DFE9A2A}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{32006B71-E6F7-4264-A8B4-AC3A6B77CC54}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
@ -1,16 +1,13 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
option csharp_namespace = "JOBot.Proto";
|
option csharp_namespace = "JOBot.Proto";
|
||||||
|
|
||||||
import "google/protobuf/wrappers.proto";
|
|
||||||
import "google/protobuf/empty.proto";
|
|
||||||
|
|
||||||
service User {
|
service User {
|
||||||
rpc Register (RegisterRequest) returns (RegisterResponse);
|
rpc Register (RegisterRequest) returns (RegisterResponse);
|
||||||
rpc GetUser (GetUserRequest) returns (GetUserResponse);
|
rpc GetUser (GetUserRequest) returns (GetUserResponse);
|
||||||
rpc AcceptEula (AcceptEulaRequest) returns (AcceptEulaResponse);
|
|
||||||
rpc GetHeadHunterAuthHook(GetHeadHunterAuthHookRequest) returns (GetHeadHunterAuthHookResponse);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
import "google/protobuf/wrappers.proto";
|
||||||
|
|
||||||
message RegisterRequest{
|
message RegisterRequest{
|
||||||
int64 user_id = 1;
|
int64 user_id = 1;
|
||||||
google.protobuf.StringValue username = 2;
|
google.protobuf.StringValue username = 2;
|
||||||
@ -25,26 +22,5 @@ message GetUserRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
message GetUserResponse {
|
message GetUserResponse {
|
||||||
int64 user_id = 1;
|
bool logged_to_hh = 1;
|
||||||
google.protobuf.StringValue username = 2;
|
|
||||||
bool eula = 3;
|
|
||||||
bool is_logged = 4;
|
|
||||||
google.protobuf.StringValue CVUrl = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AcceptEulaRequest {
|
|
||||||
int64 user_id = 1;
|
|
||||||
bool eula_accepted = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AcceptEulaResponse{
|
|
||||||
bool success = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GetHeadHunterAuthHookRequest{
|
|
||||||
int64 user_id = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GetHeadHunterAuthHookResponse{
|
|
||||||
string registration_url = 1;
|
|
||||||
}
|
}
|
46
README.md
46
README.md
@ -5,62 +5,58 @@ Telegram-бот для автоматизации поиска работы че
|
|||||||
|
|
||||||
## 🔥 Возможности
|
## 🔥 Возможности
|
||||||
|
|
||||||
Привяжите аккаунт HeadHunter для доступа к резюме и вакансиям.
|
- **Авторизация через HH**
|
||||||
|
Привяжите аккаунт HeadHunter для доступа к резюме и вакансиям.
|
||||||
- **Отклик по предпочтениям**
|
|
||||||
|
|
||||||
Выбор откликаемых вакансий по предпочтениям.
|
|
||||||
- **Умные отклики**
|
- **Умные отклики**
|
||||||
|
|
||||||
Автоматическая отправка откликов на подходящие вакансии.
|
Автоматическая отправка откликов на подходящие вакансии.
|
||||||
- **Проверка резюме**
|
- **Проверка резюме**
|
||||||
|
Уведомления, если резюме требует обновления.
|
||||||
Правка резюме, под ваши приоритеты.
|
|
||||||
- **Аналитика**
|
- **Аналитика**
|
||||||
|
|
||||||
Статистика по откликам и приглашениям.
|
Статистика по откликам и приглашениям.
|
||||||
|
|
||||||
## 🛠 Технологии
|
## 🛠 Технологии
|
||||||
|
|
||||||
- **Backend**: .NET 8 + gRPC
|
- **Backend**: .NET 8 + gRPC
|
||||||
- **Frontend** Telegram клиент через Telegram.Bot
|
- **База данных**: PostgreSQL
|
||||||
- **БД**: PostgreSQL
|
- **Авторизация**: OAuth 2.0 (HH API)
|
||||||
- **Авторизация**: OAuth 2.0 (HH API), Telegram API
|
- **Инфраструктура**: Docker + Kubernetes (опционально)
|
||||||
- **Инфраструктура**: Docker / Docker compose
|
|
||||||
|
|
||||||
## 🚀 Запуск
|
## 🚀 Запуск
|
||||||
|
|
||||||
### Требования
|
### Требования
|
||||||
|
|
||||||
- .NET 8 SDK
|
- .NET 8 SDK
|
||||||
- Docker (для работы с БД)
|
- Docker (для работы с БД)
|
||||||
- Аккаунт разработчика на [dev.hh.ru](https://dev.hh.ru)
|
- Аккаунт разработчика на [dev.hh.ru](https://dev.hh.ru)
|
||||||
|
|
||||||
### 1. Настройка конфигурации
|
### 1. Настройка конфигурации
|
||||||
|
|
||||||
Создайте `appsettings.json` в `JOBot.TClient` на основе `appsettings.Example.json`
|
Создайте `appsettings.json` в `JOBot.TClient` на основе `appsettings.Example.json`
|
||||||
|
|
||||||
### 2. Запуск через Docker
|
### 2. Запуск через Docker
|
||||||
|
|
||||||
```
|
```
|
||||||
docker-compose up -d --build
|
docker-compose up -d
|
||||||
|
dotnet run --project JoBot.Backend
|
||||||
|
dotnet run --project JoBot.Client
|
||||||
```
|
```
|
||||||
|
|
||||||
## 📌 Команды бота
|
## 📌 Команды бота
|
||||||
|
|Команда|Описание|
|
||||||
|
|-------|--------|
|
||||||
|
|/start |Начало работы|
|
||||||
|
|/connect_hh|Привязать аккаунт HH|
|
||||||
|
|/jobs |Поиск вакансий|
|
||||||
|
|/profile|Проверить резюме|
|
||||||
|
|/stats |Статистика откликов|
|
||||||
|
|
||||||
| Команда | Описание |
|
## 🔒 Безопасность
|
||||||
|---------|----------------------------------------------|
|
Токены пользователей шифруются (AES-256)
|
||||||
| /start | Начало работы |
|
|
||||||
| /menu | Настройка откликов и резюме по предпочтениям |
|
Все данные передаются через HTTPS
|
||||||
| /info | Информация о боте |
|
|
||||||
|
|
||||||
📄 Лицензия
|
📄 Лицензия
|
||||||
MIT License. Подробнее в файле LICENSE.
|
MIT License. Подробнее в файле LICENSE.
|
||||||
|
|
||||||
## Отказ от ответственности
|
## Отказ от ответственности
|
||||||
|
|
||||||
Продолжая, вы принимаете [политику конфиденциальности](https://hh.ru/article/personal_data?backurl=%2F&role=applicant)
|
Продолжая, вы принимаете [политику конфиденциальности](https://hh.ru/article/personal_data?backurl=%2F&role=applicant) и [правила сервиса](https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant) hh.ru
|
||||||
и [правила сервиса](https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant)
|
|
||||||
hh.ru
|
|
||||||
|
|
||||||
Этот сервис никак не связан с HeadHunter™ (далее hh.ru), не выдаёт себя за hh.ru и не является hh.ru
|
Этот сервис никак не связан с HeadHunter™ (далее hh.ru), не выдаёт себя за hh.ru и не является hh.ru
|
@ -1,54 +0,0 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
|
||||||
rabbitmq:
|
|
||||||
hostname: jobot-rabbit
|
|
||||||
image: rabbitmq:4
|
|
||||||
ports:
|
|
||||||
- "5672:5672"
|
|
||||||
- "15672:15672"
|
|
||||||
volumes:
|
|
||||||
- rabbitmq_data:/var/lib/rabbitmq/
|
|
||||||
networks:
|
|
||||||
- jobot
|
|
||||||
|
|
||||||
postgres:
|
|
||||||
image: postgres:15
|
|
||||||
environment:
|
|
||||||
POSTGRES_PASSWORD: LocalDbPass
|
|
||||||
POSTGRES_DB: jobot
|
|
||||||
ports:
|
|
||||||
- "5432:5432"
|
|
||||||
volumes:
|
|
||||||
- postgres_data:/var/lib/postgresql/data
|
|
||||||
networks:
|
|
||||||
- jobot
|
|
||||||
|
|
||||||
backend:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: JOBot.Backend/Dockerfile
|
|
||||||
depends_on:
|
|
||||||
- postgres
|
|
||||||
- rabbitmq
|
|
||||||
ports:
|
|
||||||
- "5000:5000"
|
|
||||||
- "5001:5001"
|
|
||||||
networks:
|
|
||||||
- jobot
|
|
||||||
|
|
||||||
bot:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: JOBot.TClient/Dockerfile
|
|
||||||
depends_on:
|
|
||||||
- backend
|
|
||||||
networks:
|
|
||||||
- jobot
|
|
||||||
|
|
||||||
networks:
|
|
||||||
jobot:
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
postgres_data:
|
|
||||||
rabbitmq_data:
|
|
20
compose.yml
20
compose.yml
@ -1,21 +1,15 @@
|
|||||||
version: '3.8'
|
version: '3.8'
|
||||||
|
|
||||||
services:
|
services:
|
||||||
rabbitmq:
|
|
||||||
hostname: jobot-rabbit
|
|
||||||
image: rabbitmq:4
|
|
||||||
volumes:
|
|
||||||
- rabbitmq_data:/var/lib/rabbitmq/
|
|
||||||
networks:
|
|
||||||
- jobot
|
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:15
|
image: postgres:15
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_PASSWORD: LocalDbPass
|
POSTGRES_PASSWORD: LocalDbPass
|
||||||
POSTGRES_DB: jobot
|
POSTGRES_DB: jobot
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- ./.docker/postgres_data:/var/lib/postgresql/data
|
||||||
networks:
|
networks:
|
||||||
- jobot
|
- jobot
|
||||||
|
|
||||||
@ -25,9 +19,6 @@ services:
|
|||||||
dockerfile: JOBot.Backend/Dockerfile
|
dockerfile: JOBot.Backend/Dockerfile
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- postgres
|
||||||
- rabbitmq
|
|
||||||
ports:
|
|
||||||
- "5000:5000"
|
|
||||||
networks:
|
networks:
|
||||||
- jobot
|
- jobot
|
||||||
|
|
||||||
@ -42,8 +33,3 @@ services:
|
|||||||
|
|
||||||
networks:
|
networks:
|
||||||
jobot:
|
jobot:
|
||||||
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
postgres_data:
|
|
||||||
rabbitmq_data:
|
|
Loading…
x
Reference in New Issue
Block a user