Skip to content

Commit

Permalink
add dates field to homework, fix attaches upload [DEPLOY]
Browse files Browse the repository at this point in the history
  • Loading branch information
leonard-pak committed Dec 12, 2023
1 parent a3c56a8 commit 2990937
Show file tree
Hide file tree
Showing 7 changed files with 293 additions and 131 deletions.
4 changes: 3 additions & 1 deletion src/grpc/proto/model.proto
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ message HomeworkData {
int32 homeworkID = 1;
string title = 2;
string description = 3;
repeated TaskData tasks = 4;
string createDate = 4;
string deadlineDate = 5;
repeated TaskData tasks = 6;
}

message GetHomeworksRequest {
Expand Down
85 changes: 71 additions & 14 deletions src/scenes/homeworkScene.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Composer, Markup, Scenes } from 'telegraf';
import { message } from 'telegraf/filters';
import { CustomContext, Homework, RawFile } from '../../types/interfaces';
import { MEDIA_GROUP_WAIT } from '../utils/configs';
import { dateToString } from '../utils/date';
import { logger } from '../utils/logger';

export interface IHomeworkSceneController {
Expand Down Expand Up @@ -110,10 +112,11 @@ export class HomeworkSceneBuilder {
ctx.wizard.state.curretSolution ??= {
text: '',
rawAttachList: [],
isWaitGroup: false
};
await ctx.editMessageText(
'Всё, что ты отправишь, будет добавлено в твоё решение\\. Как закончешь, нажми на кнопку *Отправить 📦*\\.\n' +
'Обязательно дождишь сообжения `Сохранено`, чтобы быть уверенным, что твоё сообщение добавится в решение\\.\n' +
'Всё, что вы отправите, будет добавлено в ваше решение\\. По завершению, нажмите на кнопку *Отправить 📦*\\.\n' +
'Обязательно дождиcь ответа *Сохранено* на каждое ваше сообщение, чтобы быть уверенным, что оно добавилось в решение\\.\n' +
'Записываю \\.\\.\\.',
{
parse_mode: 'MarkdownV2',
Expand All @@ -138,7 +141,10 @@ export class HomeworkSceneBuilder {
}

await ctx.editMessageText(
'Полное условие ДЗ ' + hw.title + '\n' + hw.description,
'Полное условие ДЗ ' + hw.title + '\n' +
hw.description + '\n' +
'Дата выдачи: ' + dateToString(hw.createDate) + "\n" +
'Срок сдачи: ' + dateToString(hw.deadlineDate),
Markup.inlineKeyboard([]),
);

Expand Down Expand Up @@ -180,17 +186,29 @@ export class HomeworkSceneBuilder {

private sendSolutionStep(): Composer<CustomContext> {
const handler = new Composer<CustomContext>();
handler.on(message('document'), async (ctx) => {
if (ctx.message.caption) {
ctx.wizard.state.curretSolution.text +=
ctx.message.caption + '\n';
handler.on(message('photo', 'media_group_id'), async (ctx) => {
if (!ctx.wizard.state.curretSolution.isWaitGroup) {
ctx.wizard.state.curretSolution.isWaitGroup = true;
setTimeout(
async () => {
ctx.wizard.state.curretSolution.isWaitGroup = false;
await ctx.reply('Сохранено');
},
MEDIA_GROUP_WAIT
);
}
const fileID = ctx.message.photo.pop()?.file_id;
if (fileID === undefined) {
logger.error('sendSolutionStep: fileID === undefined');
return await this.replyExitWithError(ctx);
}
ctx.wizard.state.curretSolution.rawAttachList.push({
fileID: ctx.message.document.file_id,
fileName: ctx.message.document.file_name,
mimeType: ctx.message.document.mime_type,
fileID: fileID,
});
await ctx.reply('Сохранено');

if (ctx.message.caption) {
ctx.wizard.state.curretSolution.text += ctx.message.caption + '\n';
}
});
handler.on(message('photo'), async (ctx) => {
const fileID = ctx.message.photo.pop()?.file_id;
Expand All @@ -200,12 +218,47 @@ export class HomeworkSceneBuilder {
}

if (ctx.message.caption) {
ctx.wizard.state.curretSolution.text +=
ctx.message.caption + '\n';
ctx.wizard.state.curretSolution.text += ctx.message.caption + '\n';
}
ctx.wizard.state.curretSolution.rawAttachList.push({
fileID: fileID,
});

await ctx.reply('Сохранено');
});
handler.on(message('document', 'media_group_id'), async (ctx) => {
if (!ctx.wizard.state.curretSolution.isWaitGroup) {
ctx.wizard.state.curretSolution.isWaitGroup = true;
setTimeout(
async () => {
ctx.wizard.state.curretSolution.isWaitGroup = false;
await ctx.reply('Сохранено');
},
MEDIA_GROUP_WAIT
);
}

ctx.wizard.state.curretSolution.rawAttachList.push({
fileID: ctx.message.document.file_id,
fileName: ctx.message.document.file_name,
mimeType: ctx.message.document.mime_type,
});

if (ctx.message.caption) {
ctx.wizard.state.curretSolution.text += ctx.message.caption + '\n';
}
});
handler.on(message('document'), async (ctx) => {
ctx.wizard.state.curretSolution.rawAttachList.push({
fileID: ctx.message.document.file_id,
fileName: ctx.message.document.file_name,
mimeType: ctx.message.document.mime_type,
});

if (ctx.message.caption) {
ctx.wizard.state.curretSolution.text += ctx.message.caption + '\n';
}

await ctx.reply('Сохранено');
});
handler.on(message('text'), async (ctx) => {
Expand All @@ -228,7 +281,11 @@ export class HomeworkSceneBuilder {
if (!res) {
return await this.replyExitWithError(ctx);
}
await ctx.reply('Решение отправлено!');
await ctx.answerCbQuery('Решение отправлено!');
await ctx.editMessageText(
'Решение отправлено!',
Markup.inlineKeyboard([]),
);
return this.replyExit(ctx);
});
handler.action('exit', async (ctx) => {
Expand Down
99 changes: 54 additions & 45 deletions src/slaveBot/netSlaveBot.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Event,
Homework,
ProtoAttach,
ProtoMessageBase,
ProtoMessageRecieve,
ProtoMessageSend,
Expand Down Expand Up @@ -76,6 +77,8 @@ export default class NetSlaveBot implements ISlaveBotController {
homeworkid: hw.getHomeworkid(),
title: hw.getTitle(),
description: hw.getDescription(),
createDate: new Date(hw.getCreatedate()),
deadlineDate: new Date(hw.getDeadlinedate()),
tasks,
};
});
Expand All @@ -85,65 +88,71 @@ export default class NetSlaveBot implements ISlaveBotController {
});
}

sendMessageWithAttachToClient(message: ProtoMessageSend) {
logger.info(`sendMessageToClient: chatID: ${message.chatid}, text = ${message.text},
mimeType: ${message.file.mimeType}, fileLink: ${message.file.fileLink}`);

uploadAttach(attach: ProtoAttach) {
const request = new FileUploadRequest();
request.setMimetype(message.file.mimeType);
request.setFileurl(message.file.fileLink);

return new Promise<void>((resolve, reject) => {
request.setMimetype(attach.mimeType);
request.setFileurl(attach.fileLink);
return new Promise<string>((resolve, reject) => {
client.uploadFile(request, (error, response) => {
if (error) {
logger.error('sendMessageWithAttachToClient: ' + error);
reject();
} else {
logger.info(
`response inner file url: ${response.getInternalfileurl()}`,
logger.error(
'sendSolutionToClient, uploadFile: ' + error,
);
const request2 = new Message();
request2.setText(message.text);
request2.setChatid(message.chatid);
// нужно ставить тип сообщения
//request2.setMessagetype('message');
request2.setAttachmenturlsList([
response.getInternalfileurl(),
]);
// если это домашка, поставить id домашки
// request2.setHomeworkid(-1);
streamInstance.self.write(request2);
console.log(streamInstance.self.write);
resolve();
reject();
}
logger.info(
`response inner file url: ${response.getInternalfileurl()}`,
);
return resolve(response.getInternalfileurl());
});
});
}

async sendMessageWithAttachToClient(message: ProtoMessageSend) {
logger.info(`sendMessageWithAttachToClient: chatID: ${message.chatid}, text = ${message.text},
files: ${message.attachList.length}`);

const promiseAttachList = message.attachList.map((attach) => this.uploadAttach(attach));
const attachList = await Promise.all(promiseAttachList);
const request = new Message();
request.setText(message.text);
request.setChatid(message.chatid);
request.setAttachmenturlsList(attachList);
streamInstance.self.write(request);

// return new Promise<void>((resolve, reject) => {
// client.uploadFile(request, (error, response) => {
// if (error) {
// logger.error('sendMessageWithAttachToClient: ' + error);
// reject();
// } else {
// logger.info(
// `response inner file url: ${response.getInternalfileurl()}`,
// );
// const request2 = new Message();
// request2.setText(message.text);
// request2.setChatid(message.chatid);
// // нужно ставить тип сообщения
// //request2.setMessagetype('message');
// request2.setAttachmenturlsList([
// response.getInternalfileurl(),
// ]);
// // если это домашка, поставить id домашки
// // request2.setHomeworkid(-1);
// streamInstance.self.write(request2);
// console.log(streamInstance.self.write);
// resolve();
// }
// });
// });
}

async sendSolutionToClient(message: ProtoSolution) {
logger.info(
`sendSolutionToClient: homeworkID = ${message.homeworkID}, studentID = ${message.studentID}`,
);

const promiseAttachList = message.data.attachList.map((attach) => {
const request = new FileUploadRequest();
request.setMimetype(attach.mimeType);
request.setFileurl(attach.fileLink);
return new Promise<string>((resolve, reject) => {
client.uploadFile(request, (error, response) => {
if (error) {
logger.error(
'sendSolutionToClient, uploadFile: ' + error,
);
reject();
}
logger.info(
`response inner file url: ${response.getInternalfileurl()}`,
);
return resolve(response.getInternalfileurl());
});
});
});
const promiseAttachList = message.data.attachList.map((attach) => this.uploadAttach(attach));

const attachList = await Promise.all(promiseAttachList);
const request_2 = new SendSolutionRequest();
Expand Down
Loading

0 comments on commit 2990937

Please sign in to comment.