Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
25728f8
Небольшой фикс.
thepro545 Aug 2, 2022
9f4740f
fix
thepro545 Aug 2, 2022
ad8ee1f
Merge pull request #10 from thepro545/feature_AnswersAndContacts
thepro545 Aug 2, 2022
fb160ad
Добавил кнопку контакта, Логика обработки контакта, Переформатировал …
J0ker001 Aug 6, 2022
ed5a2e5
Contact processing (#12)
J0ker001 Aug 6, 2022
ea4954e
Сократил код в KeyBoardShelter (добавил методы) (#13)
thepro545 Aug 7, 2022
9261b24
Обработка текстовой части отчета (#14)
J0ker001 Aug 10, 2022
2b6aede
Что-то делал, но не доделал (#15)
thepro545 Aug 10, 2022
4870148
fix (#16)
thepro545 Aug 10, 2022
23c06bd
fix upload report
J0ker001 Aug 10, 2022
a0a0e0b
fix upload report 2
J0ker001 Aug 10, 2022
cb708eb
Fix, но не полностью. Почистил базу, убрал ошибки в объектах.
thepro545 Aug 11, 2022
b5bf716
fix - вернул caption (#17)
thepro545 Aug 11, 2022
a73acdb
FIX photo, swagger (#18)
thepro545 Aug 11, 2022
3949783
fix
thepro545 Aug 12, 2022
45779bc
fix
thepro545 Aug 15, 2022
2920914
tests for controllers, renamed fields
Aug 15, 2022
a2a5548
Merge branch 'dev' into feature_tests1
Aug 15, 2022
8ee75c9
Merge branch 'tryChange' into dev
thepro545 Aug 16, 2022
19f423a
Merge
thepro545 Aug 16, 2022
25e5166
fix
thepro545 Aug 16, 2022
cb8f179
Добавил выбор между кошкой и собакой в меню.
thepro545 Aug 16, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 18 additions & 24 deletions src/main/java/pro/sky/GroupWorkJava/KeyBoard/KeyBoardShelter.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pro.sky.GroupWorkJava.KeyBoard;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.*;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
Expand All @@ -16,13 +17,28 @@

@Service
public class KeyBoardShelter {

@Autowired
private TelegramBot telegramBot;

private org.slf4j.Logger logger = LoggerFactory.getLogger(TelegramBotUpdatesListener.class);


/**
* Меню выбора
*
* @param chatId
*/

public void chooseMenu(long chatId) {
logger.info("Method sendMessage has been run: {}, {}", chatId, "Вызвано меню выбора ");
String emoji_cat = EmojiParser.parseToUnicode(":cat:");
String emoji_dog = EmojiParser.parseToUnicode(":dog:");
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(
new KeyboardButton(emoji_cat + " CAT"));
replyKeyboardMarkup.addRow(new KeyboardButton(emoji_dog + " DOG"));

returnResponseReplyKeyboardMarkup(replyKeyboardMarkup, chatId, "Выберите, кого хотите приютить:");
}

/**
* Основеное Меню
Expand All @@ -31,9 +47,8 @@ public class KeyBoardShelter {
*/
public void sendMenu(long chatId) {
logger.info("Method sendMessage has been run: {}, {}", chatId, "Вызвано основное меню ");
String emoji_kissing = EmojiParser.parseToUnicode(":pig:");
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(
new KeyboardButton(emoji_kissing + "Информация о возможностях бота"),
new KeyboardButton("Информация о возможностях бота"),
new KeyboardButton("Узнать информацию о приюте"));
replyKeyboardMarkup.addRow(new KeyboardButton("Как взять питомца из приюта"),
new KeyboardButton("Прислать отчет о питомце"));
Expand All @@ -56,27 +71,6 @@ public void sendMenuInfoShelter(long chatId) {
returnResponseReplyKeyboardMarkup(replyKeyboardMarkup, chatId, "Информация о приюте");
}

public void checkInline(Long chatId) {
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(
new InlineKeyboardButton("Тут гугл").url("www.google.com"),
new InlineKeyboardButton("Расскажите о нас!").switchInlineQuery("Бот, которые поможет взять питомца"));
returnResponse(inlineKeyboardMarkup, chatId, "TEXT TYT");
}

public void returnResponse(InlineKeyboardMarkup o, Long chatId, String text) {
SendMessage request = new SendMessage(chatId, text)
.replyMarkup(o)
.parseMode(ParseMode.HTML)
.disableWebPagePreview(false);
SendResponse sendResponse = telegramBot.execute(request);
if (!sendResponse.isOk()) {
int codeError = sendResponse.errorCode();
String description = sendResponse.description();
logger.info("code of error: {}", codeError);
logger.info("description -: {}", description);
}
}

/**
* Меню как взять питомца
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package pro.sky.GroupWorkJava.controller;

import com.pengrad.telegrambot.model.File;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pro.sky.GroupWorkJava.model.ReportData;
import pro.sky.GroupWorkJava.service.PhotoService;
import pro.sky.GroupWorkJava.service.PhotoReportService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
Expand All @@ -24,24 +21,24 @@
*/
@RestController
@RequestMapping("photoReports")
public class PhotoController {
public class PhotoReportController {

private final PhotoService photoService;
private final PhotoReportService photoReportService;

private final String fileType = "image/jpeg";

public PhotoController(PhotoService photoService) {
this.photoService = photoService;
public PhotoReportController(PhotoReportService photoReportService) {
this.photoReportService = photoReportService;
}

@GetMapping(value = "/{id}/check")
public ReportData downloadPhoto1(@PathVariable Long id) {
return photoService.findPhoto(id);
public ReportData downloadReport(@PathVariable Long id) {
return photoReportService.findPhotoReport(id);
}

@GetMapping(value = "/{id}/check-photo")
public ResponseEntity<byte[]> downloadPhoto(@PathVariable Long id) {
ReportData reportData = photoService.findPhoto(id);
@GetMapping(value = "/{id}/photo-from-db")
public ResponseEntity<byte[]> downloadPhotoFromDB(@PathVariable Long id) {
ReportData reportData = photoReportService.findPhotoReport(id);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(fileType));
Expand All @@ -50,13 +47,13 @@ public ResponseEntity<byte[]> downloadPhoto(@PathVariable Long id) {
return ResponseEntity.status(HttpStatus.OK).headers(headers).body(reportData.getData());
}

@GetMapping(value = "/{id}/avatar-from-file")
public void downloadPhoto(@PathVariable Long id, HttpServletResponse response) throws IOException {
ReportData reportData = photoService.findPhoto(id);
@GetMapping(value = "/{id}/photo-from-file")
public void downloadPhotoFromFile(@PathVariable Long id, HttpServletResponse response) throws IOException {
ReportData reportData = photoReportService.findPhotoReport(id);
Path path = Path.of(reportData.getFilePath());

try (InputStream is = Files.newInputStream(path);
OutputStream os = response.getOutputStream();) {
OutputStream os = response.getOutputStream()) {
response.setStatus(200);
response.setContentType(fileType);
response.setContentLength((int) reportData.getFileSize());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,16 @@
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.GetFileResponse;
import com.pengrad.telegrambot.response.SendResponse;
import org.apache.catalina.webresources.ClasspathURLStreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pro.sky.GroupWorkJava.KeyBoard.KeyBoardShelter;
import pro.sky.GroupWorkJava.model.Person;

import pro.sky.GroupWorkJava.model.ReportData;
import pro.sky.GroupWorkJava.repository.PersonRepository;
import pro.sky.GroupWorkJava.repository.ReportRepository;
import pro.sky.GroupWorkJava.service.PhotoService;
import pro.sky.GroupWorkJava.service.PhotoReportService;

import javax.annotation.PostConstruct;
import java.io.IOException;
Expand All @@ -29,6 +27,8 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.vdurmont.emoji.EmojiParser;


@Service
public class TelegramBotUpdatesListener implements UpdatesListener {
Expand Down Expand Up @@ -74,7 +74,7 @@ public class TelegramBotUpdatesListener implements UpdatesListener {
@Autowired
private KeyBoardShelter keyBoardShelter;
@Autowired
private PhotoService photoService;
private PhotoReportService photoReportService;
@Autowired
private TelegramBot telegramBot;

Expand All @@ -95,7 +95,8 @@ public int process(List<Update> updates) {
String nameUser = update.message().chat().firstName();
String textUpdate = update.message().text();
Integer messageId = update.message().messageId();

// String emoji_cat = EmojiParser.parseToUnicode(":cat:");
// String emoji_dog = EmojiParser.parseToUnicode(":dog:");

long chatId = update.message().chat().id();

Expand All @@ -109,13 +110,27 @@ public int process(List<Update> updates) {
if (update.message() != null && update.message().contact() != null) {
shareContact(update);
}



switch (textUpdate) {
case START_CMD:
sendMessage(chatId, nameUser + GREETING_TEXT);
keyBoardShelter.chooseMenu(chatId);
break;

case "\uD83D\uDC31 CAT":
//что-то сделать
keyBoardShelter.sendMenu(chatId);
sendMessage(chatId, "Вы выбрали кошку, МЯУ:D");
break;
case "Как взять питомца из приюта":
keyBoardShelter.sendMenuTakeAnimal(chatId);
case "\uD83D\uDC36 DOG":
//что-то сделать
keyBoardShelter.sendMenu(chatId);
sendMessage(chatId, "Вы выбрали собаку, ГАВ:D");
break;
case "Главное меню":
keyBoardShelter.sendMenu(chatId);
break;
case "Узнать информацию о приюте":
keyBoardShelter.sendMenuInfoShelter(chatId);
Expand All @@ -130,13 +145,15 @@ public int process(List<Update> updates) {
sendMessage(chatId, infoAboutReport);
sendMessage(chatId, reportExample);
break;
case "Как взять питомца из приюта":
keyBoardShelter.sendMenuTakeAnimal(chatId);
break;
case "Вернуться в меню":
keyBoardShelter.sendMenu(chatId);
break;
case "Привет":
if (messageId != null) {
sendReplyMessage(chatId, "И тебе привет", messageId);
keyBoardShelter.checkInline(chatId);
break;
}
case "Позвать волонтера":
Expand All @@ -156,15 +173,13 @@ public int process(List<Update> updates) {
break;

}
// if (update.message().chat() != null) {
// sendReplyMessage(chatId, "Я не знаю что это. Попробуйте другую функцию",messageId);
// }
} catch (NullPointerException e) {
// sendReplyMessage(chatId, "Ошибка. Я не понимаю это сообщение", messageId);
System.out.println("Ошибка");
}



});

return UpdatesListener.CONFIRMED_UPDATES_ALL;
Expand Down Expand Up @@ -229,7 +244,7 @@ public void getReport(Update update) {
long timeDate = update.message().date();
Date dateSendMessage = new Date(timeDate * 1000);
byte[] fileContent = telegramBot.getFileContent(file);
photoService.uploadPhoto(update.message().chat().id(), fileContent, file,
photoReportService.uploadPhoto(update.message().chat().id(), fileContent, file,
ration, health, habits, fullPathPhoto, dateSendMessage);

telegramBot.execute(new SendMessage(update.message().chat().id(), "Отчет успешно принят"));
Expand All @@ -248,7 +263,7 @@ public void getReport(Update update) {
long timeDate = update.message().date();
Date dateSendMessage = new Date(timeDate * 1000);
byte[] fileContent = telegramBot.getFileContent(file);
photoService.uploadPhoto(update.message().chat().id(), fileContent, file, update.message().caption(),
photoReportService.uploadPhoto(update.message().chat().id(), fileContent, file, update.message().caption(),
fullPathPhoto, dateSendMessage);

telegramBot.execute(new SendMessage(update.message().chat().id(), "Отчет успешно принят"));
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/pro/sky/GroupWorkJava/service/CatService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package pro.sky.GroupWorkJava.service;

import org.springframework.stereotype.Service;

/**
* @author Maxon4ik
* @date 16.08.2022 13:13
*/

@Service
public class CatService {

}
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
package pro.sky.GroupWorkJava.service;

import com.pengrad.telegrambot.model.Update;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.pengrad.telegrambot.model.File;
import pro.sky.GroupWorkJava.model.ReportData;
import pro.sky.GroupWorkJava.repository.ReportRepository;

import javax.transaction.Transactional;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Maxon4ik
Expand All @@ -24,16 +16,16 @@

@Service
@Transactional
public class PhotoService {
public class PhotoReportService {
private final ReportRepository reportRepository;

public PhotoService(ReportRepository reportRepository) {
public PhotoReportService(ReportRepository reportRepository) {
this.reportRepository = reportRepository;
}

public void uploadPhoto(Long personId, byte[] pictureFile, File file, String ration, String health, String habits, String filePath, Date dateSendMessage) throws IOException {

ReportData photo = findPhoto(personId);
ReportData photo = findPhotoReport(personId);
photo.setLastMessage(dateSendMessage);
photo.setFilePath(filePath);
photo.setFileSize(file.fileSize());
Expand All @@ -49,7 +41,7 @@ public void uploadPhoto(Long personId, byte[] pictureFile, File file, String rat
public void uploadPhoto(Long personId, byte[] pictureFile, File file,
String caption, String filePath, Date dateSendMessage) throws IOException {

ReportData photo = findPhoto(personId);
ReportData photo = findPhotoReport(personId);
photo.setLastMessage(dateSendMessage);
photo.setFilePath(filePath);
photo.setFileSize(file.fileSize());
Expand All @@ -61,7 +53,7 @@ public void uploadPhoto(Long personId, byte[] pictureFile, File file,
}


public ReportData findPhoto(Long personId) {
public ReportData findPhotoReport(Long personId) {
return reportRepository.findById(personId).orElse(new ReportData());
}

Expand Down
Loading