diff --git a/src/main/java/com/health/HealthNutrition.java b/src/main/java/com/health/HealthNutrition.java index 32383c52..21234a26 100644 --- a/src/main/java/com/health/HealthNutrition.java +++ b/src/main/java/com/health/HealthNutrition.java @@ -59,6 +59,7 @@ public void run(String... args) throws Exception { try { taskProcessingService.createOutlineFile(); + taskProcessingService.addTokenInTrainingResource(); taskProcessingService.addAllBrochureToQueue(); taskProcessingService.addAllResearchPapertoQueue(); taskProcessingService.addAllTuttorialsToQueue(); diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 89a57846..3ee25ff3 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -59,7 +59,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/Training-Resource/**", "/Training-Resources/**", "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", "/loadTopicAndLanByFileType/**", "/downloadTrainingResource/**", "/shared-Training-Resource/**", - "/shared-training-resource-file/**", "/check-deployment" }; + "/shared-training-resource-file/**", "/check-deployment", "/training-resources/view-share/**" }; /** * url matcher for SUPERADMIN diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 06647767..5f03aa6f 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -32,6 +32,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; +import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; @@ -42,6 +43,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -2133,11 +2135,80 @@ public ResponseEntity deleteTrainingResource(@RequestParam("trainingReso } + /* + * @GetMapping("/downloadTrainingResource") public ResponseEntity + * downloadTrainingResourcePost(@RequestParam(name = "filePath") String + * filePath) { + * + * try { + * + * String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + * + * Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), + * finalUrl); + * + * if (!Files.exists(path)) { return + * ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); } + * + * Resource resource = new UrlResource(path.toUri()); + * + * String contentType = Files.probeContentType(path); if (contentType == null) { + * contentType = "application/octet-stream"; } + * + * String originalFilename = path.getFileName().toString(); + * + * String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + * + * String encodedFilename = URLEncoder.encode(safeFilename, + * "UTF-8").replace("+", "%20"); + * + * return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + * .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + + * encodedFilename) .body(resource); + * + * } catch (Exception e) { logger.error("Error in download", e); return + * ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } + */ + @GetMapping("/downloadTrainingResource") - public ResponseEntity downloadTrainingResourcePost(@RequestParam(name = "filePath") String filePath) { + public ResponseEntity downloadTrainingResource(@RequestParam(name = "fileType") String fileTypeString, + @RequestParam(name = "token") String token) { try { + int fileType = ServiceUtility.getFileTypeIdByValue(fileTypeString); + TrainingResource tr = null; + + if (fileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (fileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (fileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + + String filePath = null; + + if (fileType == CommonData.DOC) { + filePath = tr.getDocPath(); + } else if (fileType == CommonData.EXCEL) { + filePath = tr.getExcelPath(); + } else if (fileType == CommonData.PDF) { + filePath = tr.getPdfPath(); + } else if (fileType == CommonData.IMAGE) { + filePath = tr.getImgPath(); + } + + if (filePath == null || filePath.trim().isEmpty()) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalUrl); @@ -2164,7 +2235,80 @@ public ResponseEntity downloadTrainingResourcePost(@RequestParam(name .body(resource); } catch (Exception e) { - logger.error("Error in download", e); + logger.error("Error while downloading training resource", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); + } + } + + @GetMapping("/training-resources/view-share/{topic}/{lang}/{fileType}/{token}/{page}/{fileName}") + public ResponseEntity viewOrSharePdfOrImage(@PathVariable String topic, @PathVariable String lang, + @PathVariable String fileType, @PathVariable String token, @PathVariable int page, + @PathVariable String fileName) { + + try { + + int fileTypeId = ServiceUtility.getFileTypeIdByValue(fileType); + + TrainingResource tr = null; + if (fileTypeId == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileTypeId == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.notFound().build(); + } + + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, fileTypeId); + + List filePaths = new ArrayList<>(); + if (filePath.toLowerCase().endsWith(".zip")) { + List extracted = ServiceUtility.extractZipIfNeeded(filePath, env); + List sorted = ServiceUtility.sortFilePathsNumericOtherwiseLexical(extracted); + + if (fileType.equalsIgnoreCase("Pdf")) { + for (String str : sorted) { + if (!str.endsWith(".png")) { + filePaths.add(str); + } + } + } else { + filePaths.addAll(sorted); + } + + } else { + filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); + } + + if (page < 0 || page >= filePaths.size()) { + return ResponseEntity.badRequest().build(); + } + + String finalFilePath = filePaths.get(page); + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalFilePath); + + if (!Files.exists(path)) { + return ResponseEntity.notFound().build(); + } + + String contentType = Files.probeContentType(path); + if (contentType == null) { + contentType = "application/octet-stream"; + } + + String originalFilename = path.getFileName().toString(); + String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + String encodedFilename = URLEncoder.encode(safeFilename, "UTF-8").replace("+", "%20"); + + InputStreamResource resource = new InputStreamResource(Files.newInputStream(path)); + + return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename*=UTF-8''" + encodedFilename) + .body(resource); + + } catch (Exception e) { + logger.error("Error viewing shared file", e); return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 3ee7205a..c13cc87f 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -29,6 +29,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; +import java.util.stream.IntStream; import javax.servlet.http.HttpServletRequest; @@ -5365,6 +5366,22 @@ private List getEnglishTrainingMouduleFirst(List * Assign Tutorial on Week And Package End ********************/ + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + @GetMapping("/addTrainingResource") public String addTrainingResourceGet(HttpServletRequest req, Principal principal, Model model) { User usr = getUser(principal); @@ -5480,10 +5497,11 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String token = generateUniqueTokenForTrainingResource(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); Set extentions = new HashSet<>(); String document = ""; @@ -5509,6 +5527,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { @@ -5521,6 +5540,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { @@ -5533,6 +5553,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { @@ -5545,6 +5566,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { @@ -5562,6 +5584,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (ext.equals(CommonData.DOC_EXTENSION)) { @@ -5574,6 +5597,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (ext.equals(CommonData.EXCEL_EXTENSION)) { @@ -5586,6 +5610,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (ext.equals(CommonData.IMAGE_EXTENSION)) { @@ -5598,6 +5623,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { @@ -5900,11 +5926,13 @@ public String updateTrainingResourcePost(HttpServletRequest req, Model model, Pr } boolean fileMatch = false; + String token = ""; if (fileType.equals("Doc")) { originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getDocPath(); + token = oldTrainingResource.getDocToken(); } } @@ -5912,6 +5940,7 @@ else if (fileType.equals("Pdf")) { originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getPdfPath(); + token = oldTrainingResource.getPdfToken(); } } @@ -5919,12 +5948,14 @@ else if (fileType.equals("Image")) { originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getImgPath(); + token = oldTrainingResource.getImgToken(); } } else if (fileType.equals("Excel")) { originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getExcelPath(); + token = oldTrainingResource.getExcelToken(); } } @@ -5966,16 +5997,16 @@ else if (fileType.equals("Image")) { } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); // To get exact Id of new trainining Resource Data if (newTrainingData) { - + newTrainingResource.setDateAdded(dateAdded); trainingResourceService.save(newTrainingResource); trIdInt = newTrainingResource.getTrainingResourceId(); + token = generateUniqueTokenForTrainingResource(); } @@ -5985,10 +6016,10 @@ else if (fileType.equals("Image")) { Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); boolean fileFlag = false; if (!file.isEmpty()) { @@ -6009,6 +6040,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) oldTrainingResource.setPdfPath(""); fileMatch = true; @@ -6018,6 +6050,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) oldTrainingResource.setDocPath(""); fileMatch = true; @@ -6027,6 +6060,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) oldTrainingResource.setExcelPath(""); fileMatch = true; @@ -6036,6 +6070,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) oldTrainingResource.setImgPath(""); fileMatch = true; @@ -6050,6 +6085,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) { oldTrainingResource.setPdfPath(""); } @@ -6062,6 +6098,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) { oldTrainingResource.setDocPath(""); } @@ -6073,6 +6110,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) { oldTrainingResource.setExcelPath(""); } @@ -6084,6 +6122,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) { oldTrainingResource.setImgPath(""); } @@ -6118,14 +6157,18 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { FileUtils.deleteDirectory(extractDirPath.toFile()); } + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); if (fileMatch) { - newTrainingResource.setDateAdded(dateAdded); + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } newTrainingResource.setTopicLanMapping(topicLan); trainingResourceService.save(newTrainingResource); if (newTrainingData) { @@ -6155,6 +6198,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); oldTrainingResource.setDocPath(""); } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { @@ -6163,6 +6207,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { env); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); oldTrainingResource.setExcelPath(""); } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { @@ -6170,6 +6215,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); oldTrainingResource.setPdfPath(""); } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { @@ -6177,6 +6223,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, env); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); oldTrainingResource.setImgPath(""); } @@ -6204,13 +6251,23 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } - private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, int trId, + private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, String token, Principal principal, Model model) { int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); logger.info("FileType:{}", fileType); logger.info("intFileType:{}", intFileType); - TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + + TrainingResource tr = null; + if (intFileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (intFileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (intFileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (intFileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } boolean isZipFile = false; String filePath = ""; @@ -6229,6 +6286,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("topicName", topic_name); model.addAttribute("langName", lang_name); model.addAttribute("fileTypeString", fileType); + model.addAttribute("token", token); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), filePath); String fileName = path.getFileName().toString(); @@ -6245,7 +6303,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("isZipFile", isZipFile); String res = ServiceUtility.convertFilePathToUrl(filePath); - model.addAttribute("filePath", res); + // model.addAttribute("filePath", res); if (res == null || res.trim().isEmpty()) { @@ -6255,7 +6313,17 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, return "sharedTrainingResource"; } res = ServiceUtility.convertFilePathToUrlWithUTFforBrowserRedirect(filePath); - return "redirect:/files/" + res; + String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + String encodedFileName = ""; + try { + encodedFileName = URLEncoder.encode(fileName, "UTF-8"); + } catch (UnsupportedEncodingException e) { + + logger.error("Exception", e); + } + + return "redirect:" + normalizedBaseUrl + "/training-resources/view-share/" + topicName + "/" + langName + "/" + + fileType + "/" + token + "/" + 0 + "/" + encodedFileName; } @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}/{trId}") @@ -6263,10 +6331,39 @@ public String getShareLinkofTrainingResource(HttpServletRequest req, @PathVariab @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceByToken(req, topicName, fileType, langName, token, principal, model); + } + + } + + @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Image") || fileType.equals("Pdf")) { return res; } else { @@ -6280,10 +6377,40 @@ public String getShareLinkofTrainingResourceDoc_Excel(HttpServletRequest req, @P @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceDoc_ExcelByToken(req, topicName, fileType, langName, token, principal, + model); + } + + } + + @GetMapping("/shared-training-resource-file/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceDoc_ExcelByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Doc") || fileType.equals("Excel")) { return "sharedTrainingResource"; } else { @@ -6373,6 +6500,18 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, TrainingResource tr = trList.get(0); int trId = tr.getTrainingResourceId(); model.addAttribute("trId", trId); + + String token = ""; + if (fileTypeString.equals("Doc")) { + token = tr.getDocToken(); + } else if (fileTypeString.equals("Excel")) { + token = tr.getExcelToken(); + } else if (fileTypeString.equals("Pdf")) { + token = tr.getPdfToken(); + } else if (fileTypeString.equals("Image")) { + token = tr.getImgToken(); + } + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, inputFileType); if (filePath.isEmpty()) { getModelTrainingResource(model); @@ -6381,10 +6520,23 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, } String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + boolean allowed = true; + + if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + + allowed = false; + + } + + if (allowed) { + model.addAttribute("token", token); + } else { + model.addAttribute("token", ""); + } if (action != null && !action.isEmpty() && action.equals("download")) { model.addAttribute("action", action); - if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + if (!allowed) { model.addAttribute("error_msg", "Authentication Error"); @@ -6394,9 +6546,14 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; - return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?filePath=" - + URLEncoder.encode(finalUrl, "UTF-8"); - } catch (UnsupportedEncodingException e) { + // return "redirect:" + normalizedBaseUrl + + // "/downloadTrainingResource?filePath=" + // + URLEncoder.encode(finalUrl, "UTF-8"); + + return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?fileType=" + fileTypeString + + "&token=" + token; + + } catch (Exception e) { logger.error("Error in Download Package", e); } } @@ -6441,7 +6598,22 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); } - model.addAttribute("filePaths", filePaths); + List fileNames = new ArrayList<>(); + for (String str : filePaths) { + + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), str); + String fileName = path.getFileName().toString(); + + fileNames.add(fileName); + + } + List pageIndexes = IntStream.range(0, filePaths.size()).boxed().collect(Collectors.toList()); + + if (allowed) { + model.addAttribute("pageIndexes", pageIndexes); + // model.addAttribute("filePaths", filePaths); + model.addAttribute("fileNames", fileNames); + } model.addAttribute("action", action); } @@ -6449,8 +6621,8 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, if (action != null && !action.isEmpty() && action.equals("share")) { model.addAttribute("action", action); - - model.addAttribute("shareUrl", finalUrl); + if (allowed) + model.addAttribute("shareUrl", finalUrl); } diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 33664880..1fff2802 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.nio.file.Paths; import java.sql.Timestamp; +import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,6 +14,8 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; +import com.health.utility.CommonData; + @Entity @Table(name = "training_resource") public class TrainingResource implements Serializable { @@ -50,6 +53,18 @@ public class TrainingResource implements Serializable { @Column(name = "img_path", length = 1000) private String imgPath; + @Column(unique = true, length = 1000) + private String pdfToken; + + @Column(unique = true, length = 1000) + private String docToken; + + @Column(unique = true, length = 1000) + private String imgToken; + + @Column(unique = true, length = 1000) + private String excelToken; + @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User user; @@ -126,6 +141,38 @@ public void setUser(User user) { this.user = user; } + public String getPdfToken() { + return pdfToken; + } + + public void setPdfToken(String pdfToken) { + this.pdfToken = pdfToken; + } + + public String getDocToken() { + return docToken; + } + + public void setDocToken(String docToken) { + this.docToken = docToken; + } + + public String getImgToken() { + return imgToken; + } + + public void setImgToken(String imgToken) { + this.imgToken = imgToken; + } + + public String getExcelToken() { + return excelToken; + } + + public void setExcelToken(String excelToken) { + this.excelToken = excelToken; + } + public String getPdfFileNameWithorWitoutZip() { if (pdfPath == null || pdfPath.trim().isEmpty()) { return "NA"; @@ -166,6 +213,31 @@ public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } + public boolean isAfterImplementationDate() { + + LocalDate resourceDate = this.dateAdded.toLocalDateTime().toLocalDate(); + + return !resourceDate.isBefore(CommonData.IMPL_DATE_TRAINING_RESOURCE); + } + + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, Category category, String pdfPath, + String docPath, String excelPath, String imgPath, String pdfToken, String docToken, String imgToken, + String excelToken, User user) { + super(); + this.dateAdded = dateAdded; + this.topicLanMapping = topicLanMapping; + this.category = category; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + this.pdfToken = pdfToken; + this.docToken = docToken; + this.imgToken = imgToken; + this.excelToken = excelToken; + this.user = user; + } + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, String pdfPath, String docPath, String excelPath, String imgPath) { diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java index ac83a2fd..643f03a2 100644 --- a/src/main/java/com/health/repository/TrainingResourceRepository.java +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -17,4 +17,15 @@ public interface TrainingResourceRepository extends JpaRepository findAllByStatusTrue(); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String docToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java index c82f9b29..4a7f7691 100644 --- a/src/main/java/com/health/service/TrainingResourceService.java +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -21,4 +21,15 @@ public interface TrainingResourceService { void saveAll(List trainingResourceList); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String imgToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java index 5fcf20a1..c2814063 100644 --- a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -62,4 +62,35 @@ public List findAllByStatusTrue() { return repo.findAllByStatusTrue(); } + @Override + public TrainingResource findByPdfToken(String pdfToken) { + + return repo.findByPdfToken(pdfToken); + } + + @Override + public TrainingResource findByDocToken(String docToken) { + + return repo.findByDocToken(docToken); + } + + @Override + public TrainingResource findByExcelToken(String excelToken) { + + return repo.findByExcelToken(excelToken); + } + + @Override + public TrainingResource findByImgToken(String imgToken) { + + return repo.findByImgToken(imgToken); + } + + @Override + public boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken) { + + return repo.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(pdfToken, docToken, excelToken, imgToken); + } + } diff --git a/src/main/java/com/health/threadpool/TaskProcessingService.java b/src/main/java/com/health/threadpool/TaskProcessingService.java index 7034d12e..16065329 100644 --- a/src/main/java/com/health/threadpool/TaskProcessingService.java +++ b/src/main/java/com/health/threadpool/TaskProcessingService.java @@ -43,6 +43,7 @@ import com.health.model.QueueManagement; import com.health.model.ResearchPaper; import com.health.model.TopicCategoryMapping; +import com.health.model.TrainingResource; import com.health.model.Tutorial; import com.health.model.Version; import com.health.repository.QueueManagementRepository; @@ -55,6 +56,7 @@ import com.health.service.QueueManagementService; import com.health.service.ResearchPaperService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TrainingResourceService; import com.health.service.TutorialService; import com.health.utility.CommonData; import com.health.utility.ServiceUtility; @@ -79,6 +81,9 @@ public class TaskProcessingService { @Autowired private ThreadPoolTaskExecutor taskExecutor; + @Autowired + private TrainingResourceService trainingResourceService; + @Autowired private QueueManagementService queueService; @@ -962,4 +967,51 @@ public void stop() { logger.info("stopping QueueProcessor thread"); taskExecutor.shutdown(); } + + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + + public void addTokenInTrainingResource() { + + List trList = trainingResourceService.findAll(); + + for (TrainingResource temp : trList) { + + if ((temp.getPdfToken() == null || temp.getPdfToken().isEmpty()) + && (temp.getPdfPath() != null && !temp.getPdfPath().isEmpty())) { + temp.setPdfToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getDocToken() == null || temp.getDocToken().isEmpty()) + && (temp.getDocPath() != null && !temp.getDocPath().isEmpty())) { + temp.setDocToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getExcelToken() == null || temp.getExcelToken().isEmpty()) + && (temp.getExcelPath() != null && !temp.getExcelPath().isEmpty())) { + temp.setExcelToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getImgToken() == null || temp.getImgToken().isEmpty()) + && (temp.getImgPath() != null && !temp.getImgPath().isEmpty())) { + temp.setImgToken(generateUniqueTokenForTrainingResource()); + } + + trainingResourceService.save(temp); + } + } + } diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 33a013fe..7424114a 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -1,5 +1,7 @@ package com.health.utility; +import java.time.LocalDate; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -312,6 +314,7 @@ public class CommonData { public static final String image_OR_ZIP_OF_IMAGES = "imageOrZipOfImages"; public static final String PDF_OR_ZIP_OF_PDFS = "pdfOrZipOfPdfs"; public static final String Excel_OR_ZIP_OF_EXCELS = "excelOrZipOfexcels"; + public static final LocalDate IMPL_DATE_TRAINING_RESOURCE = LocalDate.of(2026, 3, 5); public static final String DOCUMENT_ID_TUTORIAL_TIMESCRIPT = "Tts"; public static final String DOCUMENT_ID_TUTORIAL_ORIGINAL_SCRIPT = "Tos"; diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index 35545363..60101215 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -18,12 +18,14 @@ import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; +import java.security.SecureRandom; import java.sql.Timestamp; import java.text.Normalizer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -77,6 +79,7 @@ import com.health.model.TrainingResource; import com.health.model.User; import com.health.repository.UserRepository; +import com.health.service.TrainingResourceService; import com.health.threadpool.TimeoutOutputStream; /** @@ -100,6 +103,9 @@ public class ServiceUtility { @Autowired private JavaMailSender mailSender; + @Autowired + private TrainingResourceService trainingResourceService; + public static Timestamp getCurrentTime() { // Current Date Date date = new Date(); @@ -1261,6 +1267,13 @@ public static String copyFileAndGetRelativePath(File sourceFile, String destinat return resultantPath; } + public static String generateToken() { + byte[] bytes = new byte[8]; + new SecureRandom().nextBytes(bytes); + + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, 10); + } + public static boolean hasAnyResourceFile(TrainingResource tr) { boolean hasData = true; if ((tr.getPdfPath() == null || tr.getPdfPath().isEmpty()) diff --git a/src/main/resources/templates/sharedTrainingResource.html b/src/main/resources/templates/sharedTrainingResource.html index 690f320c..cd1026bb 100644 --- a/src/main/resources/templates/sharedTrainingResource.html +++ b/src/main/resources/templates/sharedTrainingResource.html @@ -90,7 +90,7 @@

Download @@ -119,6 +119,61 @@

+ +