Skip to content

Commit

Permalink
Merge pull request #31 from litolax/feature/multiply-teacher-subscrip…
Browse files Browse the repository at this point in the history
…tions

Feature/multiply teacher subscriptions
  • Loading branch information
litolax authored Oct 20, 2023
2 parents 0c24446 + e9dfedf commit a333795
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 70 deletions.
2 changes: 1 addition & 1 deletion TeachersTimetable/Models/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class User
public string? Username { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Teacher { get; set; }
public string?[]? Teachers { get; set; }
public bool Notifications { get; set; }

public User(long userId, string? username, string? firstName, string? lastName)
Expand Down
47 changes: 29 additions & 18 deletions TeachersTimetable/Services/AccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class AccountService : IAccountService
private readonly IMongoService _mongoService;
private readonly IParseService _parseService;
private readonly IBotService _botService;
private const int MaxTeachersCount = 5;

public AccountService(IMongoService mongoService, IParseService parseService, IBotService botService)
{
Expand All @@ -30,10 +31,8 @@ public AccountService(IMongoService mongoService, IParseService parseService, IB
public async Task<Models.User?> CreateAccount(User telegramUser)
{
var userCollection = this._mongoService.Database.GetCollection<Models.User>("Users");

var users = (await userCollection.FindAsync(u => u.UserId == telegramUser.Id)).ToList();
if (users.Count >= 1) return null;

var user = new Models.User(telegramUser.Id, telegramUser.Username, telegramUser.FirstName,
telegramUser.LastName) { Id = ObjectId.GenerateNewId() };

Expand All @@ -44,26 +43,35 @@ public AccountService(IMongoService mongoService, IParseService parseService, IB
public async Task<bool> ChangeTeacher(User telegramUser, string? teacherName)
{
if (teacherName is null) return false;
var teacherNames = teacherName.Split(',', ';', StringSplitOptions.RemoveEmptyEntries);
teacherNames = teacherNames.Length > MaxTeachersCount ? teacherNames[..MaxTeachersCount] : teacherNames;
for (var i = 0; i < teacherNames.Length; i++)
{
teacherNames[i] = teacherNames[i].Trim();
}

var correctTeacherNames = this._parseService.Teachers.Where(g => teacherNames.Any(teacher =>
g.ToLower().Trim().Contains(teacher.ToLower().Trim()))).ToArray();

var correctTeacherName = this._parseService.Teachers.FirstOrDefault(
teacher => teacher.ToLower().Trim().Contains(teacherName.ToLower().Trim()));

if (correctTeacherName is not {})
if (correctTeacherNames is null || correctTeacherNames.Length == 0)
{
await this._botService.SendMessageAsync(new SendMessageArgs(telegramUser.Id, "Преподаватель не найден"));
await this._botService.SendMessageAsync(new SendMessageArgs(telegramUser.Id,
$"Преподовател{(teacherNames.Length == 0 ? 'ь' : 'и')} {Utils.GetTeachersString(teacherNames)} не найден{(teacherNames.Length == 0 ? string.Empty : "ы")}"));
return false;
}

var userCollection = this._mongoService.Database.GetCollection<Models.User>("Users");
var user = (await userCollection.FindAsync(u => u.UserId == telegramUser.Id)).ToList().First() ??
await this.CreateAccount(telegramUser);

user!.Teacher = correctTeacherName;
var update = Builders<Models.User>.Update.Set(u => u.Teacher, user.Teacher);
user!.Teachers = correctTeacherNames;
var update = Builders<Models.User>.Update.Set(u => u.Teachers, user.Teachers);
await userCollection.UpdateOneAsync(u => u.UserId == telegramUser.Id, update);

await this._botService.SendMessageAsync(new SendMessageArgs(telegramUser.Id,
$"Вы успешно подписались на расписание преподавателя {correctTeacherName}"));
await this._botService.SendMessageAsync(new SendMessageArgs(telegramUser.Id, correctTeacherNames.Length == 1
? $"Вы успешно подписались на расписание преподавателя {correctTeacherNames[0]}"
: $"Вы успешно подписались на расписание преподавателей: {Utils.GetTeachersString(correctTeacherNames)}"
));

return true;
}
Expand All @@ -75,11 +83,11 @@ public async Task UpdateNotificationsStatus(User telegramUser)
await this.CreateAccount(telegramUser);

if (user is null) return;
if (user.Teacher is null)

if (user.Teachers is null)
{
this._botService.SendMessage(new SendMessageArgs(telegramUser.Id,
$"Перед оформлением подписки на рассылку необходимо выбрать преподавателя"));
$"Перед оформлением подписки на рассылку необходимо выбрать преподавателя "));
return;
}

Expand All @@ -105,16 +113,19 @@ public async Task UpdateNotificationsStatus(User telegramUser)
},
new[]
{
user.Notifications ? new KeyboardButton("Отписаться от рассылки") : new KeyboardButton("Подписаться на рассылку")
user.Notifications
? new KeyboardButton("Отписаться от рассылки")
: new KeyboardButton("Подписаться на рассылку")
}
},
ResizeKeyboard = true,
InputFieldPlaceholder = "Выберите действие"
};

this._botService.SendMessage(new SendMessageArgs(telegramUser.Id, user.Notifications ?
$"Вы успешно подписались на расписание преподавателя {user.Teacher}" :
$"Вы успешно отменили подписку на расписание преподавателя {user.Teacher}")
this._botService.SendMessage(new SendMessageArgs(telegramUser.Id,
user.Notifications
? $"Вы успешно подписались на расписание преподавателя {user.Teachers}"
: $"Вы успешно отменили подписку на расписание преподавателя {user.Teachers}")
{
ReplyMarkup = keyboard
});
Expand Down
6 changes: 3 additions & 3 deletions TeachersTimetable/Services/CommandsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ private async void OnMessageReceive(Message message)
case "Сменить преподавателя":
{
this._botService.SendMessage(new SendMessageArgs(sender.Id,
$"Для оформления подписки на преподавателя отправьте его фамилию."));
$"Для оформления подписки на преподавателей отправьте их фамилии.(Максимум - 5. Пример: Кулецкая, Шавейко, Потоцкий, Левонюк, Протасеня )"));

this._mongoService.CreateState(new UserState(message.Chat.Id, "changeTeacher"));

Expand All @@ -126,7 +126,7 @@ private async void OnMessageReceive(Message message)
var notificationUsers = new List<Models.User>();
notificationUsers.AddRange(
(await this._mongoService.Database.GetCollection<Models.User>("Users")
.FindAsync(u => u.Teacher != null && u.Notifications)).ToList());
.FindAsync(u => u.Teachers != null && u.Notifications)).ToList());

if (notificationUsers.Count == 0) return;

Expand All @@ -138,7 +138,7 @@ private async void OnMessageReceive(Message message)
}

this._botService.SendAdminMessageAsync(new SendMessageArgs(0,
$"{notificationUsers.Count} notifications sent"));
$"After timetablenotify:{notificationUsers.Count} notifications sent"));
});
}
}
Expand Down
90 changes: 47 additions & 43 deletions TeachersTimetable/Services/DistributionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,30 @@ public async Task SendWeek(User telegramUser)
var userCollection = this._mongoService.Database.GetCollection<Models.User>("Users");
var user = (await userCollection.FindAsync(u => u.UserId == telegramUser.Id)).ToList().First();
if (user is null) return;

if (user.Teacher is null || !File.Exists($"./cachedImages/{user.Teacher}.png"))
foreach (var teacher in user.Teachers)
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
"Вы еще не выбрали преподавателя"));
return;
}
if (teacher is null || !File.Exists($"./cachedImages/{teacher}.png"))
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
"Вы еще не выбрали преподавателя"));
return;
}

var image = await Image.LoadAsync($"./cachedImages/{user.Teacher}.png");
var image = await Image.LoadAsync($"./cachedImages/{teacher}.png");

if (image is not { })
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
"Увы, данный преподаватель не найден"));
return;
}
if (image is not { })
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
$"Увы, {teacher} не найден"));
return;
}

using var ms = new MemoryStream();
await image.SaveAsPngAsync(ms);
using var ms = new MemoryStream();
await image.SaveAsPngAsync(ms);

await this._botService.SendPhotoAsync(new SendPhotoArgs(user.UserId,
new InputFile(ms.ToArray(), $"Teacher - {user.Teacher}")));
await this._botService.SendPhotoAsync(new SendPhotoArgs(user.UserId,
new InputFile(ms.ToArray(), $"Teacher - {user.Teachers}")));
}
}

public async Task SendDayTimetable(User telegramUser)
Expand All @@ -64,40 +66,42 @@ public async Task SendDayTimetable(User telegramUser)
public async Task SendDayTimetable(Models.User? user)
{
if (user is null) return;

if (user.Teacher is null)
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
"Вы еще не выбрали преподавателя"));
return;
}

if (ParseService.Timetable.Count < 1)
foreach (var teacher in user.Teachers)
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId, ${user.Teacher} нет пар"));
return;
}
if (teacher is null)
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
"Вы еще не выбрали преподавателя"));
return;
}

foreach (var day in ParseService.Timetable)
{
var message = string.Empty;
if (ParseService.Timetable.Count < 1)
{
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId, ${teacher} нет пар"));
return;
}

foreach (var teacherInfo in day.TeacherInfos.Where(teacherInfo => user.Teacher == teacherInfo.Name))
foreach (var day in ParseService.Timetable)
{
if (teacherInfo.Lessons.Count < 1)
var message = string.Empty;

foreach (var teacherInfo in day.TeacherInfos.Where(teacherInfo => teacher == teacherInfo.Name))
{
message = ${teacherInfo.Name} нет пар";
continue;
if (teacherInfo.Lessons.Count < 1)
{
message = ${teacher} нет пар";
continue;
}

message = $"День - {day.Date}\n" + Utils.CreateDayTimetableMessage(teacherInfo);
}

message = $"День - {day.Date}\n" + Utils.CreateDayTimetableMessage(teacherInfo);
await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
message.Trim().Length <= 1 ? ${teacher} нет пар" : message)
{
ParseMode = ParseMode.Markdown
});
}

await this._botService.SendMessageAsync(new SendMessageArgs(user.UserId,
message.Trim().Length <= 1 ? "У выбранного преподавателя нет пар" : message)
{
ParseMode = ParseMode.Markdown
});
}
}
}
11 changes: 6 additions & 5 deletions TeachersTimetable/Services/ParseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ await this._botService.SendAdminMessageAsync(new SendMessageArgs(0,

var teacherInfo = new TeacherInfo();
var lessons = new List<Lesson>();

var lessonsElements =
teachersAndLessons[i].FindElements(By.XPath(".//table/tbody/tr")).ToList();

Expand All @@ -148,7 +147,7 @@ await this._botService.SendAdminMessageAsync(new SendMessageArgs(0,
{
Index = int.Parse(lessonNumbers[j].Text.Replace("№", "")),
Cabinet = cabinet,
Group = lessonNames[j].Text.Replace("*",string.Empty)
Group = lessonNames[j].Text.Replace("*", string.Empty)
});
}

Expand Down Expand Up @@ -186,7 +185,8 @@ await this._botService.SendAdminMessageAsync(new SendMessageArgs(0,
{
if (teacherInfoFromTimetable?.Lessons is not null && teacherInfoFromTimetable.Lessons.Count > 0)
notificationUsersList.AddRange((await this._mongoService.Database.GetCollection<User>("Users")
.FindAsync(u => u.Teacher != null && u.Notifications && u.Teacher == teacherInfo.Name))
.FindAsync(u =>
u.Teachers != null && u.Notifications && u.Teachers.Contains(teacherInfo.Name)))
.ToList());
continue;
}
Expand All @@ -205,10 +205,11 @@ await this._botService.SendAdminMessageAsync(new SendMessageArgs(0,

if (teacherInfoFromTimetable is null || teacherInfoFromTimetable.Equals(teacherInfo)) continue;
teacherUpdatedList.Add(teacherInfo.Name);
try
try
{
notificationUsersList.AddRange((await this._mongoService.Database.GetCollection<User>("Users")
.FindAsync(u => u.Teacher != null && u.Notifications && u.Teacher == teacherInfo.Name)).ToList());
.FindAsync(u => u.Teachers != null && u.Notifications && u.Teachers.Contains(teacherInfo.Name)))
.ToList());
}
catch (Exception e)
{
Expand Down
2 changes: 2 additions & 0 deletions TeachersTimetable/Services/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,6 @@ public static bool IsDateBelongsToInterval(DateTime? date, DateTime?[]? interval
DateTimeStyles.None, out var dayTime)) return dayTime;
return null;
}

public static string GetTeachersString(string[] teachers) => string.Join(", ", teachers);
}

0 comments on commit a333795

Please sign in to comment.