diff --git a/src/main/java/com/health/HealthNutrition.java b/src/main/java/com/health/HealthNutrition.java index 72cce91c..32383c52 100644 --- a/src/main/java/com/health/HealthNutrition.java +++ b/src/main/java/com/health/HealthNutrition.java @@ -38,6 +38,9 @@ public class HealthNutrition extends org.springframework.boot.web.servlet.suppor @Value("${git.commit.id}") private String gitCommitId; + @Value("${createdby}") + private String createdBy; + @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(HealthNutrition.class); @@ -51,6 +54,7 @@ public static void main(String[] args) { @Override public void run(String... args) throws Exception { logger.info("Starting application {}", gitCommitId); + logger.info("Checking application properties: created by {}", createdBy); try { diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index efdf6fed..c6fe94ab 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -56,7 +56,10 @@ public static BCryptPasswordEncoder passwordEncoder() { "/api/scriptPublished/**", "/loadLanguageByPackage/**", "/promoVideoView/**", "/trainingModules/**", "/downloadTrainingModules", "/loadMessageByPackageAndLan/**", "/loadLanguageByWeek/**", "/loadWeekByLanguage/**", "/trainingTutorials/**", "/hstTrainingModuleView/**", "/downloadManager/**", - "/downloadManagerforhst/**", "/downloadHealthTutorials/**" }; + "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/Training-Resource/**", + "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", "/loadTopicAndLanByFileType/**", + "/downloadTrainingResource/**", "/shared-Training-Resource/**", "/shared-training-resource-file/**", + "/check-deployment" }; /** * url matcher for SUPERADMIN @@ -94,8 +97,11 @@ public static BCryptPasswordEncoder passwordEncoder() { "/addScript/**", "/listTutorialForContributorReview/**", "/Contributor/review/**", "/uploadTimescript/**", "/addLiveTutorial", "/updateLiveTutorial", "/addSpokenVideo", "/spokenVideo/edit/**", "/addVideoResource", "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", + "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", + "/addTrainingResource", "/trainingReource/view/**", "/trainingReourceAdminView/**", + "/trainingReource/edit/**", "/enableDisableTrainingResource", "/delete-trainingResource", }; @@ -155,11 +161,13 @@ protected void configure(HttpSecurity http) throws Exception { "/addTestimonial/**", "/addPromoVideo/**", "/addResearchPaper/**", "/brochure/edit/**", "/promoVideo/edit/**", "/carousel/edit/**", "/event/edit/**", "/testimonial/edit/**", "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", + "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/researchPaper/edit/**", "/enableDisableBrouchure/**", "/enableDisableConsultant/**", "/enableDisableTestimonial/**", "/addCitation/**", "/citation/edit/**", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", - "/updateCourseName") + "/updateCourseName", "/addTrainingResource") + .hasAnyAuthority("SUPER_USER", "CONTRIBUTOR").antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest() .authenticated().and().exceptionHandling().accessDeniedPage("/access-denied"); diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 0655115a..289fa799 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -3,6 +3,9 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; @@ -28,6 +31,10 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @@ -70,8 +77,10 @@ import com.health.model.Testimonial; import com.health.model.Topic; import com.health.model.TopicCategoryMapping; +import com.health.model.TopicLanMapping; import com.health.model.TraineeInformation; import com.health.model.TrainingInformation; +import com.health.model.TrainingResource; import com.health.model.TrainingTopic; import com.health.model.Tutorial; import com.health.model.TutorialWithWeekAndPackage; @@ -106,9 +115,11 @@ import com.health.service.StateService; import com.health.service.TestimonialService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TopicLanMappingService; import com.health.service.TopicService; import com.health.service.TraineeInformationService; import com.health.service.TrainingInformationService; +import com.health.service.TrainingResourceService; import com.health.service.TrainingTopicService; import com.health.service.TutorialService; import com.health.service.TutorialWithWeekAndPackageService; @@ -147,6 +158,9 @@ public class AjaxController { @Autowired private PromoVideoService promoVideoService; + @Autowired + private TopicLanMappingService topicLanMapiingService; + @Autowired private VideoResourceService videoResourceService; @@ -161,6 +175,11 @@ public class AjaxController { @Autowired private PackageLanguageService packLanService; + @Autowired + private TrainingResourceService trainingResourceService; + + @Autowired + private TopicLanMappingService topicLanMappingService; @Autowired private PackLanTutorialResourceService packLanTutorialResourceService; @@ -654,6 +673,31 @@ private HashMap setResponse(Integer status) { } + @GetMapping("/enableDisableTrainingResource") + public @ResponseBody boolean enableDisableTrainingResource(int trainingResourceId) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trainingResourceId); + + try { + if (tr.isStatus()) { + tr.setStatus(false); + trainingResourceService.save(tr); + return true; + + } else { + tr.setStatus(true); + trainingResourceService.save(tr); + return true; + + } + + } catch (Exception e) { + + logger.error("Error in Enable Disbale Training Resource: {}", tr, e); + return false; + } + + } + @GetMapping("/enableDisableResearchPaper") public @ResponseBody boolean enableDisableResearchPaper(int id) { ResearchPaper res = researchPaperService.findById(id); @@ -1494,6 +1538,42 @@ public ResponseEntity deleteTutorialFromCourse( /******************* Course End *****************************/ + @RequestMapping("/delete-trainingResource") + public ResponseEntity deleteTrainingResource(@RequestParam("trainingResourceId") int trainingResourceId, + @RequestParam("fileType") String fileType) { + + try { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trainingResourceId); + if (tr != null) { + switch (fileType.toLowerCase()) { + case "image": + tr.setImgPath(""); + break; + case "pdf": + tr.setPdfPath(""); + break; + case "doc": + tr.setDocPath(""); + break; + case "excel": + tr.setExcelPath(""); + break; + default: + return ResponseEntity.badRequest().body("Unsupported file type: " + fileType); + } + + trainingResourceService.save(tr); + return ResponseEntity.ok("Deleted successfully"); + } else { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).body("Training resource not found"); + } + + } catch (Exception e) { + logger.error("Error in deleting training resource", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).body("Error in deleting!"); + } + } + @RequestMapping("/loadPromoVideoByLanguage") public @ResponseBody String getPathofPromoVideo(@RequestParam(value = "lanId") int lanId, @RequestParam(value = "promoId") int promoId) { @@ -1822,6 +1902,231 @@ public ResponseEntity deleteTutorialFromCourse( } + /*************************************** + * Training Resource Start + **********************************************************/ + + @RequestMapping("/loadLanAndFileTypeByTopic") + public @ResponseBody ArrayList> getLanAndFileTypeByTopic( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + + ArrayList> arlist = new ArrayList<>(); + + Map fileTypes = new TreeMap<>(); + + Map languages = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + Map fileTypeIdAndValue = fileTypeId != 0 ? ServiceUtility.getFileTypeIdAndValue(fileTypeId) + : null; + + List localTopicList = new ArrayList<>(); + if (topic != null && language != null) { + TopicLanMapping tlm = topicLanMappingService.findByTopicAndLan(topic, language); + if (tlm != null) + localTopicList.add(tlm); + } else if (topic != null) { + localTopicList = topicLanMappingService.findByTopic(topic); + } else { + localTopicList = topicLanMappingService.findAll(); + } + + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(localTopicList); + + if (!trList.isEmpty()) { + + for (TrainingResource temp : trList) { + // To find languages + Language lan = temp.getTopicLanMapping().getLan(); + languages.put(lan.getLangName(), lan.getLanId()); + + // To find FileType + ServiceUtility.getFileTypeIdAndValue(temp).forEach((id, type) -> fileTypes.put(type, id)); + + } + } + arlist.add(languages); + arlist.add(fileTypes); + + return arlist; + + } + + /* + * Function to load Topic and FileType by Lan Author: Alok Kumar + */ + + @RequestMapping("/loadTopicAndFileTypeByLan") + public @ResponseBody ArrayList> getTopicAndFileTypeByLan( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + ArrayList> arlist = new ArrayList<>(); + + Map topics = new TreeMap<>(); + Map fileTypes = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + Map fileTypeIdAndValue = fileTypeId != 0 ? ServiceUtility.getFileTypeIdAndValue(fileTypeId) + : null; + + List tlm = language != null ? topicLanMappingService.findByLan(language) + : topicLanMappingService.findAll(); + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(tlm); + List newtrList = new ArrayList<>(); + if (fileTypeIdAndValue != null && !fileTypeIdAndValue.isEmpty()) { + Map.Entry entry = fileTypeIdAndValue.entrySet().iterator().next(); + int id = entry.getKey(); + for (TrainingResource temp : trList) { + if (ServiceUtility.isTrainingResourceFilePresent(temp, id)) { + newtrList.add(temp); + } + } + } + + if (!newtrList.isEmpty()) + trList = newtrList; + + for (TrainingResource tr : trList) { + // To find Topic + Topic topicTemp = tr.getTopicLanMapping().getTopic(); + int trTopicId = topicTemp.getTopicId(); + topics.put(topicTemp.getTopicName(), topicTemp.getTopicId()); + + // To find FileType + if (topicId == 0 || trTopicId == topicId) { + ServiceUtility.getFileTypeIdAndValue(tr).forEach((id, type) -> fileTypes.put(type, id)); + } + + } + + arlist.add(topics); + arlist.add(fileTypes); + + return arlist; + + } + + /* + * Function to load Topic and Language by FileType Author: Alok Kumar + */ + + @RequestMapping("/loadTopicAndLanByFileType") + public @ResponseBody ArrayList> getTopicAndLanByFileType( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + + ArrayList> arlist = new ArrayList<>(); + Map topics = new TreeMap<>(); + Map languages = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + + Map fileTypeIdAndValue = fileTypeId != 0 ? ServiceUtility.getFileTypeIdAndValue(fileTypeId) + : null; + + List localTopicList = new ArrayList<>(); + if (language != null) { + localTopicList = topicLanMappingService.findByLan(language); + } else { + localTopicList = topicLanMappingService.findAll(); + } + + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(localTopicList); + List newtrList = new ArrayList<>(); + if (fileTypeIdAndValue != null && !fileTypeIdAndValue.isEmpty()) { + Map.Entry entry = fileTypeIdAndValue.entrySet().iterator().next(); + int id = entry.getKey(); + for (TrainingResource temp : trList) { + if (ServiceUtility.isTrainingResourceFilePresent(temp, id)) { + newtrList.add(temp); + } + } + } + + if (!newtrList.isEmpty()) + trList = newtrList; + + for (TrainingResource tr : trList) { + // To find Topic + Topic topicTemp = tr.getTopicLanMapping().getTopic(); + topics.put(topicTemp.getTopicName(), topicTemp.getTopicId()); + + // To find languages + Language lan = tr.getTopicLanMapping().getLan(); + languages.put(lan.getLangName(), lan.getLanId()); + + } + + arlist.add(topics); + arlist.add(languages); + + return arlist; + + } + + @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(); + } + } + + @RequestMapping("/loadTopicByCategoryforTR") + public @ResponseBody TreeMap loadTopicByCategoryforTR(@RequestParam(value = "catId") int catId) { + TreeMap topicMaps = new TreeMap<>(); + + Category cat = catService.findByid(catId); + + List tcm = topicCatService.findAllByCategory(cat); + + for (TopicCategoryMapping temp : tcm) { + + Topic topic = temp.getTopic(); + + topicMaps.put(topic.getTopicName(), topic.getTopicId()); + + } + + return topicMaps; + } + + /*************************************** + * Training Resource End + *************************************************************/ + @RequestMapping("/loadTopicByCategoryInAssignContri") public @ResponseBody HashMap getTopicByCategoryAssignContri(@RequestParam(value = "id") int id) { diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 66347547..69bb7023 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -4,6 +4,8 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -116,8 +118,10 @@ import com.health.model.Testimonial; import com.health.model.Topic; import com.health.model.TopicCategoryMapping; +import com.health.model.TopicLanMapping; import com.health.model.TraineeInformation; import com.health.model.TrainingInformation; +import com.health.model.TrainingResource; import com.health.model.TrainingTopic; import com.health.model.Tutorial; import com.health.model.TutorialWithWeekAndPackage; @@ -161,9 +165,11 @@ import com.health.service.StateService; import com.health.service.TestimonialService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TopicLanMappingService; import com.health.service.TopicService; import com.health.service.TraineeInformationService; import com.health.service.TrainingInformationService; +import com.health.service.TrainingResourceService; import com.health.service.TrainingTopicService; import com.health.service.TutorialService; import com.health.service.TutorialWithWeekAndPackageService; @@ -178,6 +184,7 @@ import com.health.threadpool.ZipCreationThreadService; import com.health.threadpool.ZipHealthTutorialThreadService; import com.health.utility.CommonData; +import com.health.utility.FileConversionUtility; import com.health.utility.MailConstructor; import com.health.utility.SecurityUtility; import com.health.utility.ServiceUtility; @@ -204,6 +211,9 @@ public class HomeController { @Value("${downloadTimeOut}") private long downloadTimeOut; + @Value("${app.base-url}") + private String baseUrl; + private AtomicInteger downloadCount = new AtomicInteger(0); @Autowired @@ -212,6 +222,9 @@ public class HomeController { @Autowired private CommonData commonData; + @Autowired + private FileConversionUtility fileConversionUtility; + @Autowired private LiveTutorialService liveTutorialService; @@ -281,6 +294,12 @@ public class HomeController { @Autowired private WeekTitleVideoService weekTitleVideoService; + @Autowired + private TopicLanMappingService topicLanMapiingService; + + @Autowired + private TrainingResourceService trainingResourceService; + @Autowired private TopicCategoryMappingService topicCatService; @@ -383,6 +402,9 @@ public class HomeController { @Value("${scriptmanager_path}") private String scriptmanager_path; + @Value("${doc_to_pdf.command}") + private String doctoPdfCommand; + private static YouTube youtube; private static final String VIDEO_FILE_FORMAT = "video/*"; @@ -735,6 +757,7 @@ private void navigationLinkCheck(Model model) { List researchPapersList = researchPaperService.findAllByShowOnHomePage(); List trainingModuleTutorialList = tutorialWithWeekAndPackageService.findAll(); List citationTuorials = tutService.findAllEnabledEnglishTuorialsWithCitationNotNull(); + List trainingResourceList = trainingResourceService.findAllByStatusTrue(); boolean eventFlag = !eventList.isEmpty(); boolean testimonialFlag = !testimonialList.isEmpty(); @@ -744,6 +767,7 @@ private void navigationLinkCheck(Model model) { boolean researchPaperFlag = !researchPapersList.isEmpty(); boolean traininngModuleFlag = !trainingModuleTutorialList.isEmpty(); boolean citationFlag = !citationTuorials.isEmpty(); + boolean trainingResourceFlag = !trainingResourceList.isEmpty(); model.addAttribute("testimonialFlag", testimonialFlag); model.addAttribute("eventFlag", eventFlag); @@ -753,6 +777,7 @@ private void navigationLinkCheck(Model model) { model.addAttribute("researchPaperFlag", researchPaperFlag); model.addAttribute("traininngModuleFlag", traininngModuleFlag); model.addAttribute("citationFlag", citationFlag); + model.addAttribute("trainingResourceFlag", trainingResourceFlag); } @@ -861,6 +886,29 @@ private void getPackageAndLanguageData(Model model) { getPackageAndLanguageData(model, "", ""); } + private void getModelTrainingResource(Model model, int topicId, int lanId, int fileTypeId) { + + ArrayList> arlist = ajaxController.getLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + ArrayList> arlist1 = ajaxController.getTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + Map topic = arlist1.get(0); + Map fileType = arlist1.get(1); + Map lan = arlist.get(0); + + model.addAttribute("topics", topic); + model.addAttribute("languages", lan); + model.addAttribute("fileTypes", fileType); + + model.addAttribute("localTopic", topicId); + model.addAttribute("localLan", lanId); + model.addAttribute("localFile", fileTypeId); + model.addAttribute("languageCount", lan.size()); + + } + + private void getModelTrainingResource(Model model) { + getModelTrainingResource(model, 0, 0, 0); + } + @RequestMapping("/") public String index(Model model) { @@ -901,6 +949,7 @@ public String index(Model model) { List trainingModuleTutorialList = tutorialWithWeekAndPackageService.findAll(); List citationTuorials = tutService.findAllEnabledEnglishTuorialsWithCitationNotNull(); + List trainingResourceList = trainingResourceService.findAllByStatusTrue(); boolean eventFlag = !events.isEmpty(); boolean testimonialFlag = !testi.isEmpty(); @@ -910,6 +959,7 @@ public String index(Model model) { boolean researchPaperFlag = !researchPapers.isEmpty(); boolean traininngModuleFlag = !trainingModuleTutorialList.isEmpty(); boolean citationFlag = !citationTuorials.isEmpty(); + boolean trainingResourceFlag = !trainingResourceList.isEmpty(); model.addAttribute("testimonialFlag", testimonialFlag); model.addAttribute("eventFlag", eventFlag); @@ -919,6 +969,7 @@ public String index(Model model) { model.addAttribute("researchPaperFlag", researchPaperFlag); model.addAttribute("traininngModuleFlag", traininngModuleFlag); model.addAttribute("citationFlag", citationFlag); + model.addAttribute("trainingResourceFlag", trainingResourceFlag); /************ Navigation Link Check Separate Code End ********/ @@ -5300,6 +5351,979 @@ private List getEnglishTrainingMouduleFirst(List * Assign Tutorial on Week And Package End ********************/ + @GetMapping("/addTrainingResource") + public String addTrainingResourceGet(HttpServletRequest req, Principal principal, Model model) { + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + List languages = getLanguages(); + + languages.sort(Comparator.comparing(Language::getLangName)); + + model.addAttribute("languages", languages); + + List categories = catService.findAllEnabledCategories(); + model.addAttribute("categories", categories); + List trainingResourceList = new ArrayList<>(); + List tempResourceList = trainingResourceService.findAll(); + for (TrainingResource temp : tempResourceList) { + if (ServiceUtility.hasAnyResourceFile(temp)) { + trainingResourceList.add(temp); + } + } + + model.addAttribute("trainingResourceList", trainingResourceList); + + return "addTrainingResource"; + } + + @PostMapping("/addTrainingResource") + public String addTrainingResourcePost(HttpServletRequest req, Model model, Principal principal, + @RequestParam(name = "catIdTR") int catId, @RequestParam(name = "topicIdTR") int topicId, + @RequestParam("langName") List lanIds, @RequestParam(name = "file") List files) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + boolean viewSection = false; + + if (catId == 0) { + model.addAttribute("error_msg", "Category should not be null"); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + if (topicId == 0) { + model.addAttribute("error_msg", "Topic should not be null"); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + if (lanIds.isEmpty() || files.isEmpty()) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", "Language and Files should not be null"); + return addTrainingResourceGet(req, principal, model); + } + + Topic topic = topicService.findById(topicId); + Category cat = catService.findByid(catId); + + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + Set addedLan = new HashSet<>(); + + try { + + for (int i = 0; i < lanIds.size(); i++) { + if (i < files.size()) + logger.info("File: {}", files.get(i)); + if (lanIds.get(i) != 0 && !files.get(i).isEmpty()) { + Language language = lanService.getById(lanIds.get(i)); + + if (language != null) { + String langName = language.getLangName(); + TopicLanMapping topicLanMapping = topicLanMapiingService.findByTopicAndLan(topic, language); + + boolean addedLanFlag = addedLan.add(language); + + if (topicLanMapping == null && addedLanFlag) { + topicLanMapping = new TopicLanMapping(dateAdded, topic, language); + + topicLanMapiingService.save(topicLanMapping); + logger.info(" iter:{} TopicLanMapping :{}", i, topicLanMapping); + } + + List trList = trainingResourceService.findByTopicLanMapping(topicLanMapping); + TrainingResource tr = null; + + if (trList.isEmpty()) { + tr = new TrainingResource(); + logger.info("iter:{} TrainingResource :{}", i, tr); + + } else { + tr = trList.get(0); + } + + tr.setDateAdded(dateAdded); + tr.setTopicLanMapping(topicLanMapping); + tr.setUser(usr); + tr.setCategory(cat); + trainingResourceService.save(tr); // Saved first to get exact Id + int trId = tr.getTrainingResourceId(); + + Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); + String docFolder = Paths.get(rootPath.toString(), "docs").toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); + String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + + Set extentions = new HashSet<>(); + String document = ""; + + MultipartFile file = files.get(i); + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file Error at language:" + langName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + tr.setPdfPath(document); + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + tr.setDocPath(document); + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + tr.setExcelPath(document); + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + tr.setImgPath(document); + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + tr.setPdfPath(document); + } + + else if (ext.equals(CommonData.DOC_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + tr.setDocPath(document); + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + tr.setExcelPath(document); + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + tr.setImgPath(document); + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", + "Unsupported file Error at language:" + langName); + + return addTrainingResourceGet(req, principal, model); + } + + } + } + + else { + model.addAttribute("error_msg", + "Zip contains different types of files Error at language:" + langName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + } + tr.setUser(usr); + trainingResourceService.save(tr); + + } + + } + + } + + } catch (Exception e) { + model.addAttribute("error_msg", "Some errors occurred, please contact the Admin"); + logger.error("Error:", e); + return addTrainingResourceGet(req, principal, model); + } + + model.addAttribute("viewSection", viewSection); + model.addAttribute("success_msg", CommonData.RECORD_SAVE_SUCCESS_MSG); + return addTrainingResourceGet(req, principal, model); + } + + @GetMapping("/trainingReourceAdminView/{fileType}/{id}") + public String TrainingResourceViewforAdmin(@PathVariable String fileType, @PathVariable int id, + HttpServletRequest req, Model model, Principal principal) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + TrainingResource tr = trainingResourceService.findByTrainingResourceId(id); + List filePaths = new ArrayList<>(); + + if (tr == null) { + + return "redirect:/addTrainingResource"; + } + String filePath = ""; + + if (fileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + filePath = tr.getDocPath(); + model.addAttribute("fileType", "Doc"); + + } + + else if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + filePath = tr.getPdfPath(); + model.addAttribute("fileType", "Pdf"); + } + + else if (fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + filePath = tr.getImgPath(); + model.addAttribute("fileType", "Image"); + } + + else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + filePath = tr.getExcelPath(); + model.addAttribute("fileType", "Excel"); + } + + if (filePath.toLowerCase().endsWith(".zip")) { + try { + filePaths = ServiceUtility.extractZipIfNeeded(filePath, env); + } catch (IOException e) { + logger.error("Zip Extraction or zip error", e); + + return "redirect:/addTrainingResource"; + + } + } + + else { + filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); + + } + + // Conversion of doc/excel to pdf and pdf to thumbnails. + List finalFilePath = new ArrayList<>(); + + if (!fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + for (String str : filePaths) { + + /* + * Here we check png beacuse parent folder may have alreday created thumnails + * and their paths have been added in filePaths from extractZipIfNeeded function + * if zip is alreday extracted then that folder is used for pdf and thumnails + * too. + * + */ + if (!str.endsWith(".png")) { + finalFilePath.add(str); + fileConversionUtility.generateThumbnailFromPdfAndSave(str); + } + + } + } + + else { + // Intially we convert both doc and excel using same libreoffice cmd + for (String str : filePaths) { + /* + * Here we check png and pdf beacuse parent folder may have alreday created + * thumnails and pdfs and their respective paths have been added in filePaths + * from extractZipIfNeeded function if zip is alreday extracted then that folder + * is used for pdf and thumnails too. + * + */ + if (!str.endsWith(".png") && !str.endsWith(".pdf")) { + finalFilePath.add(str); + String pdfPath = fileConversionUtility.convertDoctoPdf(str, doctoPdfCommand); + fileConversionUtility.generateThumbnailFromPdfAndSave(pdfPath); + } + + } + } + } else { + finalFilePath.addAll(filePaths); + } + + model.addAttribute("trainingResource", tr); + model.addAttribute("filePaths", finalFilePath); + + for (String str : filePaths) { + logger.info("file Path :{}", str); + } + + return "trainingResourceViewAdmin"; + } + + @GetMapping("/trainingReource/edit/{fileType}/{id}") + public String trainingResourceEditGet(@PathVariable String fileType, @PathVariable int id, HttpServletRequest req, + Model model, Principal principal) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + TrainingResource tr = trainingResourceService.findByTrainingResourceId(id); + + if (tr == null) { + + return "redirect:/addTrainingResource"; + } + Topic topic = tr.getTopicLanMapping().getTopic(); + Language lan = tr.getTopicLanMapping().getLan(); + List languages = getLanguages(); + languages.sort(Comparator.comparing(Language::getLangName)); + List topics = new ArrayList<>(); + Category cat = tr.getCategory(); + Set tcmList = cat.getTopicCategoryMap(); + for (TopicCategoryMapping temp : tcmList) { + topics.add(temp.getTopic()); + } + + List trainingResourceList = new ArrayList<>(); + List tempTrainingResourceList = trainingResourceService.findAll(); + for (TrainingResource temp : tempTrainingResourceList) { + if (ServiceUtility.hasAnyResourceFile(temp)) { + trainingResourceList.add(temp); + } + } + model.addAttribute("languages", languages); + model.addAttribute("topics", topics); + model.addAttribute("trainingResourceList", trainingResourceList); + model.addAttribute("trainingResource", tr); + model.addAttribute("topic", topic); + model.addAttribute("language", lan); + model.addAttribute("id", id); + String filePath = ""; + + if (fileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + filePath = tr.getDocPath(); + model.addAttribute("fileType", "Doc"); + + } + + else if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + filePath = tr.getPdfPath(); + model.addAttribute("fileType", "Pdf"); + } + + else if (fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + filePath = tr.getImgPath(); + model.addAttribute("fileType", "Image"); + } + + else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + filePath = tr.getExcelPath(); + model.addAttribute("fileType", "Excel"); + } + + if (filePath.toLowerCase().endsWith(".zip")) { + model.addAttribute("zipFile", filePath); + } + + else { + model.addAttribute("nonZipFile", filePath); + + } + + return "updateTrainingResource"; + } + + @PostMapping("/updateTrainingResource") + public String updateTrainingResourcePost(HttpServletRequest req, Model model, Principal principal, + @RequestParam("file") MultipartFile file) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + + model.addAttribute("userInfo", usr); + + String trId = req.getParameter("trId"); + String topicId = req.getParameter("topicId"); + String lanId = req.getParameter("lanId"); + String fileType = req.getParameter("fileType"); + int trIdInt = Integer.parseInt(trId); + int topicIdInt = Integer.parseInt(topicId); + int lanIdInt = Integer.parseInt(lanId); + int oldtrId = trIdInt; + + Topic topic = topicService.findById(topicIdInt); + Language lan = lanService.getById(lanIdInt); + + TopicLanMapping topicLan = topicLanMapiingService.findByTopicAndLan(topic, lan); + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + String originalFileType = ""; + String oldPath = ""; + TrainingResource oldTrainingResource = trainingResourceService.findByTrainingResourceId(trIdInt); + + if (oldTrainingResource == null) { + model.addAttribute("error_msg", "TrainingResource doesn't exist"); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + Category cat = oldTrainingResource.getCategory(); + + if (cat == null) { + model.addAttribute("error_msg", "Category doesn't exist in Training-Resource"); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + boolean fileMatch = false; + + if (fileType.equals("Doc")) { + originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getDocPath(); + } + } + + else if (fileType.equals("Pdf")) { + originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getPdfPath(); + } + } + + else if (fileType.equals("Image")) { + originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getImgPath(); + } + + } else if (fileType.equals("Excel")) { + originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getExcelPath(); + } + } + + if (oldPath == null || oldPath.isEmpty()) { + model.addAttribute("error_msg", + "The data has already moved to another Training Resource. Please check the View section to edit."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + if (topic == null || lan == null) { + model.addAttribute("error_msg", "Topic or Language not found."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + TrainingResource newTrainingResource; + boolean newTrainingData = true; + + if (topicLan != null) { + List trList = trainingResourceService.findByTopicLanMapping(topicLan); + + if (trList.isEmpty()) { + newTrainingResource = new TrainingResource(); + logger.info("new Training Resource Data"); + + } else if (!trList.contains(oldTrainingResource)) { + newTrainingResource = trList.get(0); + logger.info("new Training Resource Data from trList"); + } else { + newTrainingData = false; + newTrainingResource = oldTrainingResource; // or some appropriate fallback + logger.info("old Training resource data"); + } + } else { + + topicLan = new TopicLanMapping(dateAdded, topic, lan); + + topicLanMapiingService.save(topicLan); + newTrainingResource = new TrainingResource(); + + } + + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); + newTrainingResource.setUser(usr); + newTrainingResource.setCategory(cat); + + // To get exact Id of new trainining Resource Data + if (newTrainingData) { + + trainingResourceService.save(newTrainingResource); + trIdInt = newTrainingResource.getTrainingResourceId(); + + } + + try { + + String langName = lan.getLangName(); + + Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); + String docFolder = Paths.get(rootPath.toString(), "docs").toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); + String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + boolean fileFlag = false; + + if (!file.isEmpty()) { + fileFlag = true; + + Set extentions = new HashSet<>(); + String document = ""; + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file"); + + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newTrainingResource.setPdfPath(document); + if (newTrainingData) + oldTrainingResource.setPdfPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newTrainingResource.setDocPath(document); + if (newTrainingData) + oldTrainingResource.setDocPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newTrainingResource.setExcelPath(document); + if (newTrainingData) + oldTrainingResource.setExcelPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newTrainingResource.setImgPath(document); + if (newTrainingData) + oldTrainingResource.setImgPath(""); + fileMatch = true; + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newTrainingResource.setPdfPath(document); + if (newTrainingData) { + oldTrainingResource.setPdfPath(""); + } + + fileMatch = true; + + } + + else if (ext.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newTrainingResource.setDocPath(document); + if (newTrainingData) { + oldTrainingResource.setDocPath(""); + } + + fileMatch = true; + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newTrainingResource.setExcelPath(document); + if (newTrainingData) { + oldTrainingResource.setExcelPath(""); + } + + fileMatch = true; + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newTrainingResource.setImgPath(document); + if (newTrainingData) { + oldTrainingResource.setImgPath(""); + } + + fileMatch = true; + + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + + model.addAttribute("error_msg", "Unsupported file Error "); + + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + } + } + + else { + model.addAttribute("error_msg", "Zip contains different types of files Error"); + + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + } + + if (oldPath != null && oldPath.endsWith(".zip")) { + + String extractDir = oldPath.replace(".zip", ""); + + Path extractDirPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), extractDir); + FileUtils.deleteDirectory(extractDirPath.toFile()); + + } + + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); + newTrainingResource.setUser(usr); + newTrainingResource.setCategory(cat); + + if (fileMatch) { + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); + trainingResourceService.save(newTrainingResource); + if (newTrainingData) { + logger.info("1st old data save is called"); + oldTrainingResource.setUser(usr); + trainingResourceService.save(oldTrainingResource); + } + } else { + model.addAttribute("error_msg", "Please upload a file of the same type. E.g., DOC for DOC type."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + } + + // File Empty + else { + if (newTrainingData && !fileFlag && oldPath != null && !oldPath.isEmpty()) { + + Path sourcePath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), oldPath); + File sourceFile = sourcePath.toFile(); + String fileName = sourcePath.getFileName().toString(); + + String document = ""; + + if (sourceFile.exists()) { + if (originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); + + newTrainingResource.setDocPath(document); + oldTrainingResource.setDocPath(""); + + } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, excelFolder, fileName, + env); + + newTrainingResource.setExcelPath(document); + oldTrainingResource.setExcelPath(""); + + } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); + + newTrainingResource.setPdfPath(document); + oldTrainingResource.setPdfPath(""); + + } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, + env); + newTrainingResource.setImgPath(document); + oldTrainingResource.setImgPath(""); + + } + + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setUser(usr); + newTrainingResource.setCategory(cat); + trainingResourceService.save(newTrainingResource); + logger.info("2nd old data save is called"); + trainingResourceService.save(oldTrainingResource); + } + + } + } + + } catch (Exception e) { + logger.error("Exception while updating Training Resource: {} {} {}", topic, lan, file, e); + model.addAttribute("error_msg", CommonData.RECORD_ERROR); + + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + model.addAttribute("success_msg", CommonData.RECORD_UPDATE_SUCCESS_MSG); + + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + + private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, int trId, + Principal principal, Model model) { + + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + + boolean isZipFile = false; + String filePath = ""; + + if (tr != null && intFileType != 0) { + filePath = ServiceUtility.getTrainingResourceFilePath(tr, intFileType); + } else { + return "redirect:/error"; + } + + Topic topic = tr.getTopicLanMapping().getTopic(); + Language lan = tr.getTopicLanMapping().getLan(); + String topic_name = topic.getTopicName(); + String lang_name = lan.getLangName(); + + model.addAttribute("topicName", topic_name); + model.addAttribute("langName", lang_name); + model.addAttribute("fileTypeString", fileType); + + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), filePath); + String fileName = path.getFileName().toString(); + + String fileSize = ServiceUtility.getZipSizeInKB_OR_MB(filePath, env); + model.addAttribute("fileName", fileName); + model.addAttribute("fileSizeInMb", fileSize); + if (filePath.toLowerCase().endsWith(".zip")) { + + isZipFile = true; + + } + navigationLinkCheck(model); + model.addAttribute("isZipFile", isZipFile); + String res = ServiceUtility.convertFilePathToUrl(filePath); + model.addAttribute("filePath", res); + + if (res == null || res.trim().isEmpty()) { + + return "redirect:/error"; + } + if (isZipFile) { + return "sharedTrainingResource"; + } + + return "redirect:/files/" + res; + } + + @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}/{trId}") + public String getShareLinkofTrainingResource(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, 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); + if (fileType.equals("Image") || fileType.equals("Pdf")) { + return res; + } else { + return "redirect:/error"; + } + + } + + @GetMapping("/shared-training-resource-file/{topicName}/{fileType}/{langName}/{trId}") + public String getShareLinkofTrainingResourceDoc_Excel(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, 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); + if (fileType.equals("Doc") || fileType.equals("Excel")) { + return "sharedTrainingResource"; + } else { + return "redirect:/error"; + } + + } + + @GetMapping("/Training-Resource") + public String viewAndDownloadTrainingResource(HttpServletRequest req, + @RequestParam(name = "topicNameTR", required = false, defaultValue = "0") int topicId, + @RequestParam(name = "langNameTR", required = false, defaultValue = "0") int lanId, + @RequestParam(name = "inputFileType", required = false, defaultValue = "0") int inputFileType, + + @RequestParam(name = "action", required = false, defaultValue = "") String action, + + Principal principal, Model model) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("usr", usr.getUsername()); + boolean authorizedUsr = false; + if (usr.getUsername() != null) { + Role role = roleService.findByname(CommonData.contributorRole); + int roleId = role.getRoleId(); + Set usrRoles = usr.getUserRoles(); + + for (UserRole ur : usrRoles) { + if (ur.getRole().getRoleId() == roleId) { + authorizedUsr = true; + break; + } + } + + } + model.addAttribute("authorizedUsr", authorizedUsr); + + model.addAttribute("topic", topicId); + model.addAttribute("lanId", lanId); + model.addAttribute("inputFileType", inputFileType); + model.addAttribute("baseUrl", baseUrl); + + navigationLinkCheck(model); + + Topic topic = topicService.findById(topicId); + Language lan = lanService.getById(lanId); + if (topic == null || lan == null || inputFileType == 0) { + getModelTrainingResource(model); + + model.addAttribute("error_msg", "Please select all fields"); + return "trainingResources"; + + } + Topic tempTopic = topicService.findById(topicId); + String topicName = tempTopic.getTopicName().replace(" ", "_").replaceAll("_+", "_"); + Language tempLan = lanService.getById(lanId); + String langName = tempLan.getLangName().replace(" ", "_").replaceAll("_+", "_"); + model.addAttribute("topicName", topicName); + model.addAttribute("langName", langName); + + Map fileTypeAndValue = ServiceUtility.getFileTypeIdAndValue(inputFileType); + String fileTypeString = fileTypeAndValue.get(inputFileType); + model.addAttribute("fileTypeString", fileTypeString); + + TopicLanMapping tlm = topicLanMapiingService.findByTopicAndLan(topic, lan); + List trList = trainingResourceService.findByTopicLanMapping(tlm); + if (trList.isEmpty() || trList.size() > 1) { + getModelTrainingResource(model); + model.addAttribute("error_msg", "Invalid Data"); + return "trainingResources"; + } + + TrainingResource tr = trList.get(0); + int trId = tr.getTrainingResourceId(); + model.addAttribute("trId", trId); + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, inputFileType); + if (filePath.isEmpty()) { + getModelTrainingResource(model); + model.addAttribute("error_msg", "No File Found"); + return "trainingResources"; + } + + String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + + if (action != null && !action.isEmpty() && action.equals("download")) { + model.addAttribute("action", action); + if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + + model.addAttribute("error_msg", "Authentication Error"); + + } else { + try { + + return "redirect:/downloadTrainingResource?filePath=" + URLEncoder.encode(finalUrl, "UTF-8"); + } catch (UnsupportedEncodingException e) { + logger.error("Error in Download Package", e); + } + } + + } + + if (action != null && !action.isEmpty() && action.equals("view")) { + List filePaths = new ArrayList<>(); + List tempFilepPaths = new ArrayList<>(); + if (filePath.toLowerCase().endsWith(".zip")) { + try { + tempFilepPaths = ServiceUtility.extractZipIfNeeded(filePath, env); + filePaths = ServiceUtility.sortFilesIfAllNamesNumeric(tempFilepPaths); + } catch (IOException e) { + logger.error("Zip Extraction or zip error", e); + + model.addAttribute("error_msg", "ZIP extraction failed. Please try again later."); + return "trainingResources"; + + } + } + + else { + filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); + + } + model.addAttribute("filePaths", filePaths); + + model.addAttribute("action", action); + } + + if (action != null && !action.isEmpty() && action.equals("share")) { + + model.addAttribute("action", action); + + model.addAttribute("shareUrl", finalUrl); + + } + + Topic localTopic = null; + Language localLan = null; + String localFile = null; + + getModelTrainingResource(model, topicId, lanId, inputFileType); + + if (topicId != 0) { + localTopic = topicService.findById(topicId); + model.addAttribute("topicforQuery", localTopic); + } + if (lanId != 0) { + localLan = lanService.getById(lanId); + model.addAttribute("lanforQuery", localLan); + } + if (inputFileType != 0) { + // add some code + model.addAttribute("fileTypeQuery", localFile); + } + + return "trainingResources"; + } + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/java/com/health/controller/RestControllerClass.java b/src/main/java/com/health/controller/RestControllerClass.java index ec91e140..9cdbdaa9 100644 --- a/src/main/java/com/health/controller/RestControllerClass.java +++ b/src/main/java/com/health/controller/RestControllerClass.java @@ -24,6 +24,12 @@ @RestController public class RestControllerClass { + @Value("${git.commit.id}") + private String gitCommitId; + + @Value("${git.commit.time:NA}") + private String gitCommitTime; + @Value("${scriptmanager_api}") private String scriptmanager_api; @@ -86,4 +92,10 @@ public Map checkTutorial1(@PathVariable int id) { } } + @GetMapping("/check-deployment") + public String checkDeployment() { + return "Git Commit ID : " + gitCommitId + "
" + "Git Commit Time : " + gitCommitTime; + + } + } diff --git a/src/main/java/com/health/model/Category.java b/src/main/java/com/health/model/Category.java index 7b471a3c..8752593a 100644 --- a/src/main/java/com/health/model/Category.java +++ b/src/main/java/com/health/model/Category.java @@ -86,6 +86,17 @@ public class Category implements Comparable, Serializable { @OneToMany(mappedBy = "cat", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set userRoles = new HashSet(); + @OneToMany(mappedBy = "category", cascade = CascadeType.ALL) + private Set trainingResources = new HashSet(); + + public Set getTrainingResources() { + return trainingResources; + } + + public void setTrainingResources(Set trainingResources) { + this.trainingResources = trainingResources; + } + public int getCategoryId() { return categoryId; } diff --git a/src/main/java/com/health/model/Language.java b/src/main/java/com/health/model/Language.java index 1c791ed1..8d8b1f92 100644 --- a/src/main/java/com/health/model/Language.java +++ b/src/main/java/com/health/model/Language.java @@ -94,6 +94,17 @@ public class Language implements Comparable, Serializable { @OneToMany(mappedBy = "lan", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set packageLanguages = new HashSet(); + @OneToMany(mappedBy = "lan", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set topicLanMappings = new HashSet(); + + public Set getTopicLanMappings() { + return topicLanMappings; + } + + public void setTopicLanMappings(Set topicLanMappings) { + this.topicLanMappings = topicLanMappings; + } + public Set getLiveTutorial() { return liveTutorial; } diff --git a/src/main/java/com/health/model/Topic.java b/src/main/java/com/health/model/Topic.java index ce5f1f2c..d30c449a 100644 --- a/src/main/java/com/health/model/Topic.java +++ b/src/main/java/com/health/model/Topic.java @@ -67,6 +67,17 @@ public class Topic implements Comparable, Serializable { @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set courseCatTopicMappings = new HashSet(); + @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set topicLanMappingd = new HashSet(); + + public Set getTopicLanMappingd() { + return topicLanMappingd; + } + + public void setTopicLanMappingd(Set topicLanMappingd) { + this.topicLanMappingd = topicLanMappingd; + } + public int getTopicId() { return topicId; } diff --git a/src/main/java/com/health/model/TopicLanMapping.java b/src/main/java/com/health/model/TopicLanMapping.java new file mode 100644 index 00000000..a1cf0216 --- /dev/null +++ b/src/main/java/com/health/model/TopicLanMapping.java @@ -0,0 +1,117 @@ +package com.health.model; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "topic_lan_mapping") +public class TopicLanMapping implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "topic_lan_id", nullable = false, updatable = false) + private int topicLanId; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @ManyToOne + @JoinColumn(name = "topic_id") + private Topic topic; + + @ManyToOne + @JoinColumn(name = "lang_id") + private Language lan; + + @OneToMany(mappedBy = "topicLanMapping", cascade = CascadeType.ALL) + private Set trainingResources = new HashSet(); + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public Topic getTopic() { + return topic; + } + + public void setTopic(Topic topic) { + this.topic = topic; + } + + public int getTopicLanId() { + return topicLanId; + } + + public void setTopicLanId(int topicLanId) { + this.topicLanId = topicLanId; + } + + public Language getLan() { + return lan; + } + + public void setLan(Language lan) { + this.lan = lan; + } + + public Set getTrainingResources() { + return trainingResources; + } + + public void setTrainingResources(Set trainingResources) { + this.trainingResources = trainingResources; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public TopicLanMapping() { + + } + + public TopicLanMapping(Timestamp dateAdded, Topic topic, Language lan) { + + this.dateAdded = dateAdded; + this.topic = topic; + this.lan = lan; + } + + public static Comparator SortByTopicName = new Comparator() { + + @Override + public int compare(TopicLanMapping t1, TopicLanMapping t2) { + + return t1.getTopic().getTopicName().compareTo(t2.getTopic().getTopicName()); + + } + }; + +} diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java new file mode 100644 index 00000000..33664880 --- /dev/null +++ b/src/main/java/com/health/model/TrainingResource.java @@ -0,0 +1,184 @@ +package com.health.model; + +import java.io.Serializable; +import java.nio.file.Paths; +import java.sql.Timestamp; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "training_resource") +public class TrainingResource implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "training_res_id", nullable = false, updatable = false) + private int trainingResourceId; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @ManyToOne + @JoinColumn(name = "topic_lan_id") + private TopicLanMapping topicLanMapping; + + @ManyToOne + @JoinColumn(name = "cat_id") + private Category category; + + @Column(name = "pdf_path", length = 1000) + private String pdfPath; + + @Column(name = "doc_path", length = 1000) + private String docPath; + + @Column(name = "excel_path", length = 1000) + private String excelPath; + + @Column(name = "img_path", length = 1000) + private String imgPath; + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private User user; + + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public int getTrainingResourceId() { + return trainingResourceId; + } + + public void setTrainingResourceId(int trainingResourceId) { + this.trainingResourceId = trainingResourceId; + } + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public TopicLanMapping getTopicLanMapping() { + return topicLanMapping; + } + + public void setTopicLanMapping(TopicLanMapping topicLanMapping) { + this.topicLanMapping = topicLanMapping; + } + + public String getPdfPath() { + return pdfPath; + } + + public void setPdfPath(String pdfPath) { + this.pdfPath = pdfPath; + } + + public String getDocPath() { + return docPath; + } + + public void setDocPath(String docPath) { + this.docPath = docPath; + } + + public String getExcelPath() { + return excelPath; + } + + public void setExcelPath(String excelPath) { + this.excelPath = excelPath; + } + + public String getImgPath() { + return imgPath; + } + + public void setImgPath(String imgPath) { + this.imgPath = imgPath; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getPdfFileNameWithorWitoutZip() { + if (pdfPath == null || pdfPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(pdfPath).getFileName().toString(); + return fileName; + } + + public String getDocFileNameWithorWitoutZip() { + if (docPath == null || docPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(docPath).getFileName().toString(); + return fileName; + } + + public String getExcelFileNameWithorWitoutZip() { + if (excelPath == null || excelPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(excelPath).getFileName().toString(); + return fileName; + } + + public String getImageFileNameWithorWitoutZip() { + if (imgPath == null || imgPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(imgPath).getFileName().toString(); + return fileName; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, String pdfPath, String docPath, + String excelPath, String imgPath) { + + this.dateAdded = dateAdded; + this.topicLanMapping = topicLanMapping; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + } + + public TrainingResource() { + + } + +} diff --git a/src/main/java/com/health/model/User.java b/src/main/java/com/health/model/User.java index ecdce179..64f261c5 100644 --- a/src/main/java/com/health/model/User.java +++ b/src/main/java/com/health/model/User.java @@ -179,6 +179,10 @@ public void setOrgRolev(OrganizationRole orgRolev) { @JsonIgnore private Set weekTitleVideos = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JsonIgnore + private Set trainingResources = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonIgnore private Set topics = new HashSet(); @@ -332,6 +336,14 @@ public void setUserRoles(Set userRoles) { this.userRoles = userRoles; } + public Set getTrainingResources() { + return trainingResources; + } + + public void setTrainingResources(Set trainingResources) { + this.trainingResources = trainingResources; + } + @Override public Collection getAuthorities() { Set authorites = new HashSet<>(); diff --git a/src/main/java/com/health/repository/TopicLanMappingRepository.java b/src/main/java/com/health/repository/TopicLanMappingRepository.java new file mode 100644 index 00000000..ffd2204c --- /dev/null +++ b/src/main/java/com/health/repository/TopicLanMappingRepository.java @@ -0,0 +1,21 @@ +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; + +public interface TopicLanMappingRepository extends JpaRepository { + + TopicLanMapping findByTopicLanId(int topicLanId); + + List findByLan(Language lan); + + List findByTopic(Topic topic); + + TopicLanMapping findByTopicAndLan(Topic topic, Language lan); + +} diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java new file mode 100644 index 00000000..ac83a2fd --- /dev/null +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -0,0 +1,20 @@ +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; + +public interface TrainingResourceRepository extends JpaRepository { + + TrainingResource findByTrainingResourceId(int trainingResourceId); + + List findByTopicLanMapping(TopicLanMapping topicLanMapping); + + List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList); + + List findAllByStatusTrue(); + +} diff --git a/src/main/java/com/health/service/TopicLanMappingService.java b/src/main/java/com/health/service/TopicLanMappingService.java new file mode 100644 index 00000000..24f00fc8 --- /dev/null +++ b/src/main/java/com/health/service/TopicLanMappingService.java @@ -0,0 +1,25 @@ +package com.health.service; + +import java.util.List; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; + +public interface TopicLanMappingService { + + TopicLanMapping findBTopicLanId(int topicLanId); + + List findByLan(Language lan); + + List findByTopic(Topic topic); + + TopicLanMapping findByTopicAndLan(Topic topic, Language lan); + + List findAll(); + + void save(TopicLanMapping topicLanMapping); + + void saveAll(List topicLanMappingList); + +} diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java new file mode 100644 index 00000000..c82f9b29 --- /dev/null +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -0,0 +1,24 @@ +package com.health.service; + +import java.util.List; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; + +public interface TrainingResourceService { + + TrainingResource findByTrainingResourceId(int trainingResourceId); + + List findByTopicLanMapping(TopicLanMapping topicLanMapping); + + List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList); + + List findAll(); + + List findAllByStatusTrue(); + + void save(TrainingResource trainingResource); + + void saveAll(List trainingResourceList); + +} diff --git a/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java b/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java new file mode 100644 index 00000000..88f5cbf3 --- /dev/null +++ b/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java @@ -0,0 +1,66 @@ +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; +import com.health.repository.TopicLanMappingRepository; +import com.health.service.TopicLanMappingService; + +@Service +public class TopicLanMappingServiceImpl implements TopicLanMappingService { + + private static final Logger logger = LoggerFactory.getLogger(TopicLanMappingServiceImpl.class); + + @Autowired + private TopicLanMappingRepository repo; + + @Override + public TopicLanMapping findBTopicLanId(int topicLanId) { + + return repo.findByTopicLanId(topicLanId); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public void save(TopicLanMapping topicLanMapping) { + repo.save(topicLanMapping); + + } + + @Override + public void saveAll(List topicLanMappingList) { + repo.saveAll(topicLanMappingList); + + } + + @Override + public List findByLan(Language lan) { + + return repo.findByLan(lan); + } + + @Override + public List findByTopic(Topic topic) { + + return repo.findByTopic(topic); + } + + @Override + public TopicLanMapping findByTopicAndLan(Topic topic, Language lan) { + + return repo.findByTopicAndLan(topic, lan); + } + +} diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java new file mode 100644 index 00000000..5fcf20a1 --- /dev/null +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -0,0 +1,65 @@ +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; +import com.health.repository.TrainingResourceRepository; +import com.health.service.TrainingResourceService; + +@Service +public class TrainingReourceServiceImpl implements TrainingResourceService { + + private static final Logger logger = LoggerFactory.getLogger(TrainingReourceServiceImpl.class); + + @Autowired + private TrainingResourceRepository repo; + + @Override + public TrainingResource findByTrainingResourceId(int trainingResourceId) { + + return repo.findByTrainingResourceId(trainingResourceId); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public void save(TrainingResource trainingResource) { + repo.save(trainingResource); + + } + + @Override + public void saveAll(List trainingResourceList) { + repo.saveAll(trainingResourceList); + + } + + @Override + public List findByTopicLanMapping(TopicLanMapping topicLanMapping) { + + return repo.findByTopicLanMapping(topicLanMapping); + } + + @Override + public List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList) { + + return repo.findByTopicLanMappingInAndStatusTrue(topicLanMappingList); + } + + @Override + public List findAllByStatusTrue() { + + return repo.findAllByStatusTrue(); + } + +} diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 4b9541b1..33a013fe 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -163,6 +163,8 @@ public class CommonData { public static String uploadBrouchure = "Media/Content/Brochure/"; + public static String uploadTrainingResource = "Media/Content/TrainingResource/"; + public static String uploadPromoVideo = "Media/Content/PromoVideo/"; public static String uploadVersion = "Media/Content/Version/"; @@ -270,6 +272,18 @@ public class CommonData { public int HANDLER_DATA = 10000000; + public static final String PDF_EXTENSION = "pdf"; + public static final String EXCEL_EXTENSION = "excel"; + public static final String DOC_EXTENSION = "doc"; + public static final String IMAGE_EXTENSION = "img"; + public static final String ZIP_EXTENSION = "zip"; + public static final String UNSUPPORTED_EXTENSION = "unsupported"; + + public static final int DOC = 1; + public static final int EXCEL = 2; + public static final int IMAGE = 3; + public static final int PDF = 4; + public static final String STATUS = "status"; public static final String STATUS_QUEUED = "queued"; public static final String STATUS_PROCESSING = "processing"; @@ -294,6 +308,11 @@ public class CommonData { public static final String DOCUMENT_TYPE_FILES_OF_BROCHURE = "Files_Of_Brochure"; public static final String DOCUMENT_TYPE_RESEARCHPAPER = "ResearchPaper"; + public static final String Doc_OR_ZIP_OF_DOCS = "docOrZipOfDocs"; + 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 String DOCUMENT_ID_TUTORIAL_TIMESCRIPT = "Tts"; public static final String DOCUMENT_ID_TUTORIAL_ORIGINAL_SCRIPT = "Tos"; public static final String DOCUMENT_ID_BROCHURE = "Bro"; @@ -316,6 +335,7 @@ public class CommonData { public static final Long TASK_SLEEP_TIME = 10L * 1000; public static final Long NO_TASK_SLEEP_TIME_FOR_DELETE = 60L * 1000 * 60; public static final Long TASK_SLEEP_TIME_FOR_DELETE = 60L * 1000 * 60; + public static final int TIME_UNIT_FOR_WAIT = 60; // public static String SCRIPT_MANAGER_VIEW= "view/healthnutrition"; diff --git a/src/main/java/com/health/utility/FileConversionUtility.java b/src/main/java/com/health/utility/FileConversionUtility.java new file mode 100644 index 00000000..9790a950 --- /dev/null +++ b/src/main/java/com/health/utility/FileConversionUtility.java @@ -0,0 +1,195 @@ +package com.health.utility; + +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import javax.imageio.ImageIO; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class FileConversionUtility { + + private static final Logger logger = LoggerFactory.getLogger(FileConversionUtility.class); + + @Value("${spring.applicationexternalPath.name}") + private String mediaRoot; + + public String convertDoctoPdf(String inputFilePath, String libreOfficeCommand) { + String document = ""; + boolean shouldConvert = true; + + Path docPath = Paths.get(mediaRoot, inputFilePath); + Path pdfDirPath = docPath.getParent(); + + try { + if (docPath == null || pdfDirPath == null || !Files.exists(docPath)) { + logger.warn("Invalid document or directory path."); + return ""; + } + + String fileNameWithoutExt = docPath.getFileName().toString().replaceFirst("[.][^.]+$", ""); + Path pdfPath = Paths.get(pdfDirPath.toString(), fileNameWithoutExt + ".pdf"); + + if (Files.exists(pdfPath)) { + if (Files.getLastModifiedTime(pdfPath).toMillis() > Files.getLastModifiedTime(docPath).toMillis()) { + shouldConvert = false; + } + } + + if (shouldConvert) { + // Replace placeholders + String commandStr = libreOfficeCommand.replace("{input}", docPath.toString()).replace("{outdir}", + pdfDirPath.toString()); + + logger.debug("Resolved command: {}", commandStr); + + List commandTokens = tokenizeCommand(commandStr); + + ProcessBuilder processBuilder = new ProcessBuilder(commandTokens); + Process process = processBuilder.start(); + + // Read standard output + try (InputStream inputStream = process.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = reader.readLine()) != null) { + logger.info("LibreOffice Output: {}", line); + } + } + + // Read error output + try (InputStream errorStream = process.getErrorStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { + String line; + while ((line = reader.readLine()) != null) { + logger.warn("LibreOffice Error: {}", line); + } + } + + boolean finished = process.waitFor(CommonData.TIME_UNIT_FOR_WAIT, TimeUnit.SECONDS); + int exitCode = finished ? process.exitValue() : 1; + + if (!finished) { + logger.warn("LibreOffice process did not finish in time. Destroying process..."); + process.destroy(); + } + + if (exitCode == 0 && Files.exists(pdfPath)) { + String absolutePath = pdfPath.toString(); + int indexToStart = absolutePath.indexOf("Media"); + document = (indexToStart != -1) ? absolutePath.substring(indexToStart) : absolutePath; + } else { + logger.error("Document conversion failed or timed out: {}", docPath); + } + } + + } catch (IOException | InterruptedException e) { + logger.error("Exception during document conversion", e); + Thread.currentThread().interrupt(); // preserve interrupt status + } + + return document; + } + + /** + * Tokenizes a command string into individual arguments, respecting quoted + * segments that may contain spaces. + */ + private List tokenizeCommand(String commandTemplate) { + List tokens = new ArrayList<>(); + boolean inQuotes = false; + StringBuilder current = new StringBuilder(); + + for (char c : commandTemplate.toCharArray()) { + if (c == '"') { + inQuotes = !inQuotes; + } else if (c == ' ' && !inQuotes) { + if (current.length() > 0) { + tokens.add(current.toString()); + current.setLength(0); + } + } else { + current.append(c); + } + } + + if (current.length() > 0) { + tokens.add(current.toString()); + } + + return tokens; + } + + public String generateThumbnailFromPdfAndSave(String pdfFilePath) { + Path pdfPath = Paths.get(mediaRoot, pdfFilePath); + Path thumbnailDirPath = pdfPath.getParent(); + String fileNameWithoutExt = pdfPath.getFileName().toString().replaceFirst("[.][^.]+$", ""); + boolean shouldConvert = true; + String resultPathofThumbnail = ""; + + // Check if the PDF path is valid + if (pdfFilePath.isEmpty() || pdfFilePath.equals("") || pdfPath == null || !Files.exists(pdfPath)) { + logger.warn("PDF file does not exist: {}", pdfPath); + return ""; + } + if (!Files.isReadable(pdfPath)) { + logger.error("PDF file is not readable (access denied): {}", pdfPath); + return ""; + } + + // Define thumbnail path + Path thumbnailPath = Paths.get(thumbnailDirPath.toString(), fileNameWithoutExt + ".png"); + String thumbnailPathStr = thumbnailPath.toString(); + + try (PDDocument document = PDDocument.load(pdfPath.toFile())) { + if (Files.exists(thumbnailPath)) { + if (Files.getLastModifiedTime(thumbnailPath).toMillis() > Files.getLastModifiedTime(pdfPath) + .toMillis()) { + shouldConvert = false; + } + } + + if (shouldConvert) { + PDFRenderer pdfRenderer = new PDFRenderer(document); + BufferedImage image = pdfRenderer.renderImageWithDPI(0, 15); // Render first page at 15 DPI + + if (image.getHeight() > 200) { + int newDPI = (int) Math.ceil(15.0 * 200 / image.getHeight()); + if (newDPI > 2 && newDPI < 15) { + image = pdfRenderer.renderImageWithDPI(0, newDPI); + } + } + + // Save thumbnail image + File outputFile = thumbnailPath.toFile(); + ImageIO.write(image, "png", outputFile); + } + + int indexToStart = thumbnailPathStr.indexOf("Media"); + resultPathofThumbnail = (indexToStart != -1) ? thumbnailPathStr.substring(indexToStart) : thumbnailPathStr; + + ServiceUtility.convertFilePathToUrl(resultPathofThumbnail); + + } catch (Exception e) { + logger.error("Error in thumbnail creation for file: {}", pdfPath, e); + } + + return resultPathofThumbnail; + } +} diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index cb49d229..40f80de6 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -4,6 +4,7 @@ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -13,6 +14,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.sql.Timestamp; @@ -21,13 +23,21 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.imageio.ImageIO; @@ -37,6 +47,8 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; @@ -58,6 +70,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.health.model.TrainingResource; import com.health.model.User; import com.health.repository.UserRepository; import com.health.threadpool.TimeoutOutputStream; @@ -378,6 +391,170 @@ public static boolean checkFileExtensionImage(MultipartFile temp) { // validate return true; } + /* + * check FileExtention of Training Resource + * + */ + + public static String checkFileExtensions(MultipartFile file) { + String filename = file.getOriginalFilename(); + if (filename == null) { + return CommonData.UNSUPPORTED_EXTENSION; + } + + String lowerCaseFilename = filename.toLowerCase(); + + if (lowerCaseFilename.endsWith(".pdf")) { + return CommonData.PDF_EXTENSION; + } else if (lowerCaseFilename.endsWith(".csv") || lowerCaseFilename.endsWith(".ods") + || lowerCaseFilename.endsWith(".xlsx")) { + return CommonData.EXCEL_EXTENSION; + } else if (lowerCaseFilename.endsWith(".docx") || lowerCaseFilename.endsWith(".odt") + || lowerCaseFilename.endsWith(".rtf")) { + return CommonData.DOC_EXTENSION; + } else if (lowerCaseFilename.endsWith(".png") || lowerCaseFilename.endsWith(".jpg") + || lowerCaseFilename.endsWith(".jpeg")) { + return CommonData.IMAGE_EXTENSION; + } else if (lowerCaseFilename.endsWith(".zip")) { + return CommonData.ZIP_EXTENSION; + } else { + return CommonData.UNSUPPORTED_EXTENSION; + } + } + + /** + * Check file extentions of zip for training Resource + * + * @throws IOException + * @throws FileNotFoundException + * + */ + + public static Set checkFileExtentionsInZip(MultipartFile file) { + Set extensions = new HashSet<>(); + + try (ZipInputStream zis = new ZipInputStream(file.getInputStream())) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (!entry.isDirectory()) { + String ext = FilenameUtils.getExtension(entry.getName()).toLowerCase(); + if (ext.equals("pdf")) { + extensions.add(CommonData.PDF_EXTENSION); + } else if (ext.equals("csv") || ext.equals("ods") || ext.equals("xlsx")) { + extensions.add(CommonData.EXCEL_EXTENSION); + } else if (ext.equals("png") || ext.equals("jpg") || ext.equals("jpeg")) { + extensions.add(CommonData.IMAGE_EXTENSION); + } else if (ext.equals("docx") || ext.equals("odt") || ext.equals("rtf")) { + extensions.add(CommonData.DOC_EXTENSION); + } + + else { + extensions.add(CommonData.UNSUPPORTED_EXTENSION); + } + } + } + } catch (Exception e) { + logger.error("Exception Error in checkFileExtentionsINZip", e); + } + + logger.info("Extensions found in zip: {}", extensions); + + return extensions; + + } + + public static List extractZipIfNeeded(String zipFilePathStr, Environment env) throws IOException { + + Path zipFilePath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), zipFilePathStr); + String zipFileName = zipFilePath.getFileName().toString(); + String folderName = zipFileName.substring(0, zipFileName.lastIndexOf('.')); + Path extractDir = zipFilePath.getParent().resolve(folderName); + + List filePaths = new ArrayList<>(); + + if (!Files.exists(extractDir)) { + Files.createDirectories(extractDir); + try (ZipInputStream zipIn = new ZipInputStream(Files.newInputStream(zipFilePath))) { + ZipEntry entry; + while ((entry = zipIn.getNextEntry()) != null) { + if (!entry.isDirectory()) { + Path outputFile = extractDir.resolve(entry.getName()); + Files.createDirectories(outputFile.getParent()); + Files.copy(zipIn, outputFile, StandardCopyOption.REPLACE_EXISTING); + + } + } + } + } + + // Collect all file paths from the folder (whether just extracted or already + // existed) + try (Stream files = Files.walk(extractDir)) { + files.filter(Files::isRegularFile).map(Path::toString).filter(p -> p.contains("Media")) // ensure "Media" + // exists in path + .map(p -> { + int indexToStart = p.indexOf("Media"); + return convertFilePathToUrl(p.substring(indexToStart)); + }).forEach(filePaths::add); + } + + return filePaths; + } + + public static List sortFilesIfAllNamesNumeric(List filePaths) { + + if (filePaths == null || filePaths.isEmpty()) { + return filePaths; + } + + boolean allNumeric = filePaths.stream().map(path -> Paths.get(path).getFileName().toString()) + .map(name -> name.substring(0, name.lastIndexOf('.'))).allMatch(name -> name.matches("\\d+")); + + if (allNumeric) { + Collections.sort(filePaths, Comparator.comparingInt(path -> { + String fileName = Paths.get(path).getFileName().toString(); + String numberPart = fileName.substring(0, fileName.lastIndexOf('.')); + return Integer.parseInt(numberPart); + })); + } + + return filePaths; + } + + public static Set checkFileExtentionsInZip(ZipFile zip) { + Set extensions = new HashSet<>(); + + try { + + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + ZipEntry entry = (ZipEntry) e.nextElement(); + if (!entry.isDirectory()) { + String ext = FilenameUtils.getExtension(entry.getName()).toLowerCase(); + if (ext.equals("pdf")) { + extensions.add(CommonData.PDF_EXTENSION); + } else if (ext.equals("csv") || ext.equals("ods") || ext.equals("xlsx")) { + extensions.add(CommonData.EXCEL_EXTENSION); + } else if (ext.equals("png") || ext.equals("jpg") || ext.equals("jpeg")) { + extensions.add(CommonData.IMAGE_EXTENSION); + } else if (ext.equals("docx") || ext.equals("odt") || ext.equals("rtf")) { + extensions.add(CommonData.DOC_EXTENSION); + } + + else { + extensions.add(CommonData.UNSUPPORTED_EXTENSION); + } + } + } + } catch (Exception e) { + logger.error("Exception Error in checkFileExtentionsINZip", e); + } + + logger.info("Extensions found in zip: {}", extensions); + + return extensions; + + } + /** * to check whether MP4 file or not * @@ -930,11 +1107,6 @@ public static void deleteFilesOlderThanNDays(int days, Environment env, String d }); } - /* - * dowanload Manager - * - */ - public static String downloadManager(String zipUrl, AtomicInteger downloadCount, int downloadLimit, long downloadTimeOut, Environment env, HttpServletResponse response) { String message = "Please try again after 30 minutes."; @@ -991,6 +1163,29 @@ public static double getZipSizeInMB(String zipUrl, Environment env) { } + public static String getZipSizeInKB_OR_MB(String zipUrl, Environment env) { + Path zipFilePath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), zipUrl); + File zipFile = zipFilePath.toFile(); + String result = ""; + double fileSizeInMB = 0; + double fileSizeInKB = 0; + if (zipFile.exists() && zipFile.isFile()) { + long fileSizeInBytes = zipFile.length(); + fileSizeInKB = fileSizeInBytes / (1024.0); + if (fileSizeInKB < 100) { + fileSizeInKB = new BigDecimal(fileSizeInKB).setScale(2, RoundingMode.HALF_UP).doubleValue(); + result = String.valueOf(fileSizeInKB) + " KB"; + } else { + fileSizeInMB = fileSizeInKB / (1024.0); + fileSizeInMB = new BigDecimal(fileSizeInMB).setScale(2, RoundingMode.HALF_UP).doubleValue(); + result = String.valueOf(fileSizeInMB) + " MB"; + } + + } + return result; + + } + public static String getVideoResolutionPath(String VideoPath, String resolution) { int dotIndex = VideoPath.lastIndexOf('.'); @@ -1002,6 +1197,163 @@ public static String getVideoResolutionPath(String VideoPath, String resolution) } + public static String copyFileAndGetRelativePath(File sourceFile, String destinationFolder, String fileName, + Environment env) throws IOException { + + logger.info("destination Folder: {}", destinationFolder); + logger.info("fileName: {}", fileName); + + Path destinationFolderPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), + destinationFolder); + boolean flag = createFolder(destinationFolderPath); + + Path destinationPath = destinationFolderPath.resolve(fileName); + + File destinationFile = destinationPath.toFile(); + + if (flag && sourceFile.exists() && sourceFile.isFile()) { + FileUtils.copyFile(sourceFile, destinationFile); + logger.info("file is copied"); + } + + String temp = destinationPath.toString(); + int indexToStart = temp.indexOf("Media"); + String document = temp.substring(indexToStart, temp.length()); + String resultantPath = convertFilePathToUrl(document); + logger.info("resultant Path: {}", resultantPath); + + return resultantPath; + } + + public static boolean hasAnyResourceFile(TrainingResource tr) { + boolean hasData = true; + if ((tr.getPdfPath() == null || tr.getPdfPath().isEmpty()) + && (tr.getDocPath() == null || tr.getDocPath().isEmpty()) + && (tr.getExcelPath() == null || tr.getExcelPath().isEmpty()) + && (tr.getImgPath() == null || tr.getImgPath().isEmpty())) { + + hasData = false; + } + + return hasData; + + } + + public static Map getFileTypeIdAndValue(int fileTypeId) { + Map result = new HashMap<>(); + + switch (fileTypeId) { + case CommonData.DOC: + result.put(fileTypeId, "Doc"); + break; + case CommonData.EXCEL: + result.put(fileTypeId, "Excel"); + break; + case CommonData.IMAGE: + result.put(fileTypeId, "Image"); + break; + case CommonData.PDF: + result.put(fileTypeId, "Pdf"); + break; + default: + return null; + } + + return result; + } + + public static int getFileTypeIdByValue(String fileTypeValue) { + + if (fileTypeValue == null) { + return 0; + } + + switch (fileTypeValue) { + case "Doc": + return CommonData.DOC; + case "Excel": + return CommonData.EXCEL; + case "Image": + return CommonData.IMAGE; + case "Pdf": + return CommonData.PDF; + default: + return 0; + } + } + + public static Map getFileTypeIdAndValue(TrainingResource tr) { + Map result = new HashMap<>(); + + if (isNotBlank(tr.getDocPath())) { + result.put(CommonData.DOC, "Doc"); + + } + if (isNotBlank(tr.getExcelPath())) { + result.put(CommonData.EXCEL, "Excel"); + + } + if (isNotBlank(tr.getImgPath())) { + result.put(CommonData.IMAGE, "Image"); + + } + if (isNotBlank(tr.getPdfPath())) { + result.put(CommonData.PDF, "Pdf"); + + } + + return result; + } + + public static boolean isTrainingResourceFilePresent(TrainingResource tr, int fileId) { + if (tr == null) { + return false; + } + + switch (fileId) { + case CommonData.DOC: + return isNotBlank(tr.getDocPath()); + case CommonData.EXCEL: + return isNotBlank(tr.getExcelPath()); + case CommonData.IMAGE: + return isNotBlank(tr.getImgPath()); + case CommonData.PDF: + return isNotBlank(tr.getPdfPath()); + default: + return false; + } + } + + public static String getTrainingResourceFilePath(TrainingResource tr, int fileId) { + if (tr == null) { + return ""; + } + + String path; + switch (fileId) { + case CommonData.DOC: + path = tr.getDocPath(); + break; + case CommonData.EXCEL: + path = tr.getExcelPath(); + break; + case CommonData.IMAGE: + path = tr.getImgPath(); + break; + case CommonData.PDF: + path = tr.getPdfPath(); + break; + default: + return ""; + } + + return isNotBlank(path) ? path : ""; + } + + public static boolean isNotBlank(String s) { + return s != null && !s.isEmpty(); + } + /** * to validate email * diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 919d84dd..3461255a 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -2667,7 +2667,7 @@ var clipboard = new ClipboardJS('#copyButtonViewPage', { contentType : "application/json", success : function(result) { - var html = ''; + var html = ''; var len = result.length; $.each(result , function( key, value ) { html += ''; + var len = result.length; + $.each(result , function( key, value ) { + html += ''; + }) + + $("#topicIdTR").prop('disabled',false); + $('#topicIdTR').html(html); + + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + + } + + }); + + }); + + +$('.enableTrainingResource').click(function() { + + var test_id=$(this).attr('value'); + + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableTrainingResource", + data : { + "trainingResourceId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + $('#'+test_id).addClass('fas fa-times-circle'); + $('#'+test_id).removeClass('fas fa-check-circle'); + $('#'+test_id).css({"color": "red"}); + $('#Success').css({"display": "block"}); + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + $('.disableTrainingResource').click(function() { + + var test_id=$(this).attr('value'); + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableTrainingResource", + data : { + "trainingResourceId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + + $('#'+test_id).addClass('fas fa-check-circle'); + $('#'+test_id).removeClass('fas fa-times-circle'); + $('#'+test_id).css({"color": "green"}); + $('#Success').css({"display": "block"}); + + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + + +$(".deleteTrainingResource-btn").click(function(){ + var row = $(this).closest("tr"); + var trainingResourceId = $(this).data("trainingresourceid"); + var topicName = $(this).data("topicname"); + var langName = $(this).data("langname"); + var fileName = $(this).data("filename"); + var fileType = $(this).data("filetype"); + + + Swal.fire({ + title: "Are you sure?", + html: "Do you want to delete this Training Resource?

" + + "Topic: " + topicName + "
" + + "Language: " + langName + "
" + + "file Type: " + fileType + "
" + + "file Name: " + fileName, + + icon: "warning", + showCancelButton: true, + confirmButtonText: "Yes", + cancelButtonText: "No", + dangerMode: true + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: "/delete-trainingResource/", + data: { + + + "trainingResourceId": trainingResourceId, + "fileType": fileType + }, + type: "DELETE", + success: function(result) { + Swal.fire("Deleted!", "Deleted successfully!", "success"); + $("#" + fileType + trainingResourceId).text("Deleted"); + }, + error: function(err) { + Swal.fire("Error!", "Error in deleting!", "error"); + } + }); + } + }); +}); + + + + /** + function to load language and fileType by topic + author: Alok Kumar + + */ + + function loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId) { + $.ajax({ + type : "GET", + url : projectPath+"loadLanAndFileTypeByTopic", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + + $.each(result, function (value, key) { + var selected = (lanId == key) ? "selected" : ""; + html += ``; + }); + + $("#langNameTR").prop('disabled', false); + $('#langNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value ,key ) { + var selected=(fileTypeId==key)?"selected":""; + html += ``; + }) + $("#inputFileType").prop('disabled',false); + $('#inputFileType').html(html); + if (topicId != 0) { + $("#topicResetDivTR").show(); + } else { + $("#topicResetDivTR").hide(); + } + + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + } + + $( "#topicNameTR" ).change(function() { + + var topicId = $(this).val(); + var lanId = $("#langNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + + }); + + $( "#topicResetTR" ).click(function() { + + var topicId = 0; + + $("#topicNameTR").val("0"); + var lanId = $("#langNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + return false; + + }); + + + + + + /* + Function to load Topic and FileType by language + author:Alok Kumar + + */ + + function loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId){ + $.ajax({ + type : "GET", + url : projectPath+"loadTopicAndFileTypeByLan", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + $.each(result , function( value ,key) { + var selected=(topicId==key)?"selected":""; + html += ``; + }) + $("#topicNameTR").prop('disabled',false); + $('#topicNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value,key ) { + var selected=(fileTypeId==key)?"selected":""; + html += ``; + }) + $("#inputFileType").prop('disabled',false); + $('#inputFileType').html(html); + if (lanId != 0) { + $("#lanResetDivTR").show(); + } else { + $("#lanResetDivTR").hide(); + } + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + + } + + $( "#langNameTR" ).change(function() { + var lanId = $(this).val(); + var topicId = $("#topicNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + + }); + + $( "#lanResetTR" ).click(function() { + var lanId = 0; + $("#langNameTR").val("0"); + var fileTypeId = $("#inputFileType").val(); + var topicId=$("#topicNameTR").val(); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + return false; + + }); + + + + /* + Function to load Topic and Language by FileType + author:Alok Kumar + + */ + + function loadTopicAndLanByFileType(topicId, lanId, fileTypeId){ + + $.ajax({ + type : "GET", + url : projectPath+"loadTopicAndLanByFileType", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + $.each(result , function( value ,key ) { + var selected=(topicId==key)?"selected":""; + html += ``; + }) + $("#topicNameTR").prop('disabled',false); + $('#topicNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value ,key ) { + var selected=(lanId==key)?"selected":""; + html += ``; + }) + $("#langNameTR").prop('disabled',false); + $('#langNameTR').html(html); + + if (fileTypeId != 0) { + $("#fileResetDivTR").show(); + } else { + $("#fileResetDivTR").hide(); + } + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + + } + + $('#inputFileType').change(function() { + var fileTypeId = $(this).val(); + var topicId = $("#topicNameTR").val(); + var lanId=$("#langNameTR").val(); + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + + + }); + + $( "#fileResetTR" ).click(function() { + + var fileTypeId = 0; + $("#inputFileType").val("0"); + var lanId = $("#langNameTR").val(); + var topicId=$("#topicNameTR").val(); + + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + + return false; + + }); + + $( "#btnClearTriningResource" ).click(function() { + + // Reset radio buttons + $("input[name='action']").prop("checked", false); + + var fileTypeId = 0; + $("#inputFileType").val("0"); + var lanId =0; + $("#langNameTR").val("0"); + var topicId=0; + $("#topicNameTR").val("0"); + + + + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + + return false; + + }); + + + + + +$(document).ready(function () { + + $("#formTrainingResource").on("submit", function (e) { + + + var topicId = $("#topicNameTR").val(); + var langId = $("#langNameTR").val(); + var fileType = $("#inputFileType").val(); + var action = $("input[name='action']:checked").val(); + const usrLoggedIn =$("#usrValue").val() == "true"; + const authorizedUsr =$("#authorizedUsrValue").val() == "true"; + var fileTypeString=$("#fileTypeString").val(); + + $("#formError").addClass("d-none").text(""); + + if (!topicId || topicId == 0) { + e.preventDefault(); + showError("Please select Topic"); + return; + } + if (!langId || langId == 0) { + e.preventDefault(); + showError("Please select Language"); + return; + } + if (!fileType || fileType == 0) { + e.preventDefault(); + showError("Please select File Type"); + return; + } + if (!action) { + e.preventDefault(); + showError("Please select an action (View / Download / Share)"); + return; + } + + var baseUrl = "/Training-Resource" + + "?topicNameTR=" + encodeURIComponent(topicId) + + "&langNameTR=" + encodeURIComponent(langId) + + "&inputFileType=" + encodeURIComponent(fileType); + + + if (action === "download") { + if (fileTypeString === "Pdf" || fileTypeString === "Image") { + e.preventDefault(); + window.location.href = baseUrl + "&action=download"; + } + + if (fileTypeString === "Doc" || fileTypeString === "Excel") { + if (usrLoggedIn && authorizedUsr) { + e.preventDefault(); + window.location.href = baseUrl + "&action=download"; + } + + } + } + }); + + function showError(msg) { + $("#formError").removeClass("d-none").text(msg); + } + + // Copy link button + $("#copyShareLink").click(function () { + var text = $(".shareLink").val(); + + if (navigator.clipboard) { + // Modern API (async, works in Chrome, Edge, Firefox, Safari) + navigator.clipboard.writeText(text).then(function () { + alert("Link copied to clipboard"); + }).catch(function (err) { + console.error("Failed to copy: ", err); + alert("Unable to copy link"); + }); + } else { + // Fallback for older browsers + var copyText = document.querySelector(".shareLink"); + copyText.select(); + copyText.setSelectionRange(0, 99999); + document.execCommand("copy"); + alert("Link copied to clipboard"); + } +}); + + +}); + + +/******************************** Training Resource End ****************************************/ /***************** changes made by om prakash *********************************************/ diff --git a/src/main/resources/templates/addTrainingResource.html b/src/main/resources/templates/addTrainingResource.html new file mode 100644 index 00000000..c046f1de --- /dev/null +++ b/src/main/resources/templates/addTrainingResource.html @@ -0,0 +1,433 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+ +
+
+
+
+

Add Training Resource

+
+
+
+
+ +
+
+ +
+ +
+ + +
+ + +
+ + +
+ + + + + + +
+ +
+ +
+
+ +
+ + +
+ +
+ + + +
+ +
+ + + + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) + Max file size : 700 MB + +
+ +
+
+
+ + + + + + +
+
+
+ + + + +
+ + +
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Date AddedTopicLanguageEnable/DisablePdf FileDoc FileExcel FileImage File
+ +
+ +
+
+ +
+ +
+
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Pdf available +
+
+
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Doc available +
+
+ +
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Excel available +
+
+ + +
+
+
+ + + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Image available +
+
+ + +
+
+ + + + + +
+ + + +
+ +
+ + +
+ + +
+ + + + + + + diff --git a/src/main/resources/templates/common/commonItemsTrainingResource.html b/src/main/resources/templates/common/commonItemsTrainingResource.html new file mode 100644 index 00000000..2423a22e --- /dev/null +++ b/src/main/resources/templates/common/commonItemsTrainingResource.html @@ -0,0 +1,234 @@ + + + + +
+

+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+ + + Only authorized users can access Doc or Excel files. + + + + Login + + + + +
+ + + + + diff --git a/src/main/resources/templates/common/sidebar.html b/src/main/resources/templates/common/sidebar.html index ca30f3c6..c3afe394 100644 --- a/src/main/resources/templates/common/sidebar.html +++ b/src/main/resources/templates/common/sidebar.html @@ -296,10 +296,19 @@ + + + @@ -510,10 +519,19 @@ + + + diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index 94b203ac..45b97a8f 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -145,6 +145,7 @@ Promotional-Materials Citations HST Training Modules + Tarining Resources Dr. Rupal's Hindi Video diff --git a/src/main/resources/templates/sharedTrainingResource.html b/src/main/resources/templates/sharedTrainingResource.html new file mode 100644 index 00000000..690f320c --- /dev/null +++ b/src/main/resources/templates/sharedTrainingResource.html @@ -0,0 +1,154 @@ + + + + Training Resource - Health And Nutrition + + + + + + + + + + +
+ + +
+ +

+ Training Resource +

+ + +
+
+ + + + + +
+
+ + +
+ +
+ +
+
+ + +
+ + + + + + + + + + +
+ + + +
+
+ File Name: +
+
+ +
+ File Size: +
+
+
+ + + + +
+
+ +
+
+ + +
+
+
+ Changes Updated Successfully +
+ +
+ Please Try Again +
+
+
+ +
+ + +
+ + + + + + + diff --git a/src/main/resources/templates/trainingResourceViewAdmin.html b/src/main/resources/templates/trainingResourceViewAdmin.html new file mode 100644 index 00000000..b5d09422 --- /dev/null +++ b/src/main/resources/templates/trainingResourceViewAdmin.html @@ -0,0 +1,199 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+ + +
+
+
+
+
+

+
+
+
+ Add Training Resource +
+
+
+
+
+
+ + Image + + +
+
+ + + + Download Image + +
+ +
+
+ +
+ +
+
+
+ + +
+
+ +
+ + + Thumbnail + + + + + Download PDF + +
+
+ + +
+ +
+ + +
+ +
+ + + + +
+
+ +
+ +
+
+
+ + +
+ +
+
+
+ + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/trainingResources.html b/src/main/resources/templates/trainingResources.html new file mode 100644 index 00000000..aaae1f0d --- /dev/null +++ b/src/main/resources/templates/trainingResources.html @@ -0,0 +1,465 @@ + + + + + + + Training Resources - Health And Nutrition + + + + + + +
+
+
+
+ +
+ +
+
+
+ +
+
+ +
+
+
+ + + + +
+
+ + + + +
+ +
+ + + +
+ + + + +
+

+

+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/tutorialList.html b/src/main/resources/templates/tutorialList.html index 08f95c10..5a4fbea1 100644 --- a/src/main/resources/templates/tutorialList.html +++ b/src/main/resources/templates/tutorialList.html @@ -29,6 +29,7 @@ Promotional-Materials Citations HST Training Modules + Tarining Resources Dr. Rupal's Hindi Video diff --git a/src/main/resources/templates/updateTrainingResource.html b/src/main/resources/templates/updateTrainingResource.html new file mode 100644 index 00000000..f1a55547 --- /dev/null +++ b/src/main/resources/templates/updateTrainingResource.html @@ -0,0 +1,122 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+ + +
+
+
+
+

Update Training Resource

+ Add Training Resource +
+
+
+
+
+ + + + +
+ + +
+ +
+ + +
+ + + +
+ The following data contains a zip file, which may include multiple files.
+ If you want to update a single file or multiple files, please download the zip file, extract all files, make your changes, and re-create the zip file including both the new and existing files. Then upload the updated zip file.
+ For any questions or assistance, please contact the system administrator.
+ + + Download Zip File + +
+ + + +
+ + + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) + Max file size : 700 MB +
+
+ + + +
+ + +
+
+
+
+
+ + +
+ +
+
+
+
+ +
+ + + + + + + + \ No newline at end of file