Subversion Repositories SmartDukaan

Rev

Rev 37184 | Rev 37214 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25380 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
30080 amit.gupta 4
import com.jcraft.jsch.*;
25380 amit.gupta 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.solr.SolrService;
35583 ranu 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
37208 amit 8
import com.spice.profitmandi.dao.entity.catalog.Catalog;
25380 amit.gupta 9
import com.spice.profitmandi.dao.entity.catalog.Item;
36404 amit 10
import com.spice.profitmandi.dao.entity.catalog.MonitorType;
35549 ranu 11
import com.spice.profitmandi.dao.entity.cs.Bulletin;
33443 ranu 12
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
13
import com.spice.profitmandi.dao.entity.cs.Region;
28264 tejbeer 14
import com.spice.profitmandi.dao.entity.dtr.DocumentUrl;
33443 ranu 15
import com.spice.profitmandi.dao.entity.fofo.PrintResource;
16
import com.spice.profitmandi.dao.entity.fofo.PrintResourceRegion;
17
import com.spice.profitmandi.dao.entity.user.User;
35487 ranu 18
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
33443 ranu 19
import com.spice.profitmandi.dao.model.*;
20
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
37184 ranu 21
import com.spice.profitmandi.dao.repository.catalog.*;
35549 ranu 22
import com.spice.profitmandi.dao.repository.cs.BulletinRepository;
33443 ranu 23
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
24
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 26
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 27
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
28
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
29
import com.spice.profitmandi.dao.repository.user.UserRepository;
32952 amit.gupta 30
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 31
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 32
import com.spice.profitmandi.web.model.LoginDetails;
33
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 34
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 35
import org.apache.commons.csv.CSVFormat;
36
import org.apache.commons.csv.CSVParser;
37
import org.apache.commons.csv.CSVRecord;
38
import org.apache.commons.lang3.StringUtils;
39
import org.apache.logging.log4j.LogManager;
40
import org.apache.logging.log4j.Logger;
31330 tejbeer 41
import org.json.JSONArray;
42
import org.json.JSONObject;
30080 amit.gupta 43
import org.springframework.beans.factory.annotation.Autowired;
35346 ranu 44
import org.springframework.http.ResponseEntity;
30080 amit.gupta 45
import org.springframework.stereotype.Controller;
35487 ranu 46
import org.springframework.transaction.annotation.Transactional;
30080 amit.gupta 47
import org.springframework.ui.Model;
48
import org.springframework.web.bind.annotation.*;
49
import org.springframework.web.multipart.MultipartFile;
25380 amit.gupta 50
 
30080 amit.gupta 51
import javax.servlet.http.HttpServletRequest;
52
import javax.xml.bind.DatatypeConverter;
53
import java.io.*;
54
import java.sql.Timestamp;
55
import java.time.LocalDate;
56
import java.time.LocalDateTime;
57
import java.time.ZoneOffset;
58
import java.util.*;
59
import java.util.stream.Collectors;
60
 
35458 amit 61
@Transactional(rollbackFor = Throwable.class)
25380 amit.gupta 62
@Controller
63
public class ContentController {
64
	@Autowired
65
	MVCResponseSender mvcResponseSender;
66
 
67
	@Autowired
68
	Mongo mongoClient;
69
 
70
	@Autowired
71
	SolrService solrService;
72
 
73
	@Autowired
74
	ItemRepository itemRepository;
75
 
28264 tejbeer 76
	@Autowired
77
	DocumentUrlRepository documentUrlRepository;
78
 
31330 tejbeer 79
	@Autowired
80
	FocusedModelRepository focusedModelRepository;
33443 ranu 81
 
82
	@Autowired
83
	PrintResourceRepository printResourceRepository;
84
	@Autowired
85
	AuthRepository authRepository;
86
	@Autowired
87
	RegionRepository regionRepository;
88
	@Autowired
89
	PrintResourceRegionRepository printResourceRegionRepository;
90
	@Autowired
91
	PartnerRegionRepository partnerRegionRepository;
33973 tejus.loha 92
	@Autowired
93
	SuperCatalogRepository superCatalogRepository;
35487 ranu 94
	@Autowired
95
	CatalogRepository catalogRepository;
35549 ranu 96
	@Autowired
36404 amit 97
	CatalogMonitorTypeRepository catalogMonitorTypeRepository;
98
	@Autowired
35549 ranu 99
	BulletinRepository bulletinRepository;
25380 amit.gupta 100
	private Gson gson = new Gson();
101
 
102
	public static final int Entity_Id = 0;
103
	public static final int Title = 1;
104
	public static final int KeySpec1 = 2;
105
	public static final int KeySpec2 = 3;
106
	public static final int KeySpec3 = 4;
107
	public static final int KeySpec4 = 5;
108
	public static final int Warranty = 6;
109
	public static final int Package_Contents = 7;
28264 tejbeer 110
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
111
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
25380 amit.gupta 112
 
29900 amit.gupta 113
	private static final String REMOTE_DIR = "/var/www/static.saholic.com/images/media/";
31330 tejbeer 114
	// private static final String REMOTE_DIR = "/tmp";
25986 amit.gupta 115
	private static final String STATIC_SERVER_URL = "https://static%d.smartdukaan.com/images/media/";
25380 amit.gupta 116
 
117
	private static final String THUMBNAIL = "thumbnail";
118
	private static final String ICON = "icon";
119
	private static final String DEFAULT = "default";
120
	private static final String NONE = "";
25409 amit.gupta 121
 
25400 amit.gupta 122
	private static final Logger LOGGER = LogManager.getLogger(ContentController.class);
25380 amit.gupta 123
 
124
	private String getFileName(int entityId, String description, String extension) {
125
		List<Item> items = itemRepository.selectAllByCatalogItemId(entityId);
25409 amit.gupta 126
		String imageString = getMediaPrefix(items.get(0).getItemDescriptionNoColor() + " " + description) + "-"
25380 amit.gupta 127
				+ LocalDateTime.now().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30));
25413 amit.gupta 128
		return imageString + "." + extension;
25380 amit.gupta 129
	}
130
 
35529 ranu 131
	@PostMapping(value = "/content/upload")
35525 ranu 132
	public String uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
133
			throws Exception {
134
		List<ContentPojo> contentPojos = readFile(file);
35529 ranu 135
		if (contentPojos.size() < 1) {
136
			throw new RuntimeException("please check your file first ...may be content are wrong");
137
		}
35525 ranu 138
		for (ContentPojo contentPojo : contentPojos) {
139
			mongoClient.persistEntity(contentPojo);
140
		}
141
		//List<SuperCatalog> superCatalog = superCatalogRepository.selectAll();
142
 
143
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
144
		return "response";
25380 amit.gupta 145
	}
146
 
32952 amit.gupta 147
	@Autowired
148
	ItemLoaderService itemLoaderService;
149
	@PostMapping(value = "/catalog/upload")
150
	public String uploadCatalog(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
151
			throws Exception {
152
		itemLoaderService.parse(file);
153
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
154
		return "response";
155
	}
156
 
25380 amit.gupta 157
	@PostMapping(value = "/content/media/upload")
158
	public String uploadMediaContent(HttpServletRequest request, @RequestBody EntityMediaPojo entityMediaPojo,
159
			Model model) throws Exception {
160
		ContentPojo contentPojo = mongoClient.getEntityById(entityMediaPojo.getEntityId());
161
		Map<String, InputStream> fileStreamsMap = getStreamFileMap(contentPojo, entityMediaPojo);
25400 amit.gupta 162
		LOGGER.info("fileStreamsMap {}, " + fileStreamsMap.keySet());
29900 amit.gupta 163
		uploadContentFiles(fileStreamsMap, entityMediaPojo.getEntityId());
25380 amit.gupta 164
		mongoClient.persistEntity(contentPojo);
31238 amit.gupta 165
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
25380 amit.gupta 166
		return "response";
167
	}
168
 
35346 ranu 169
	@PostMapping(value = "/content/video/upload")
170
	public String uploadVideoUrls(HttpServletRequest request,
171
								  @RequestPart("file") MultipartFile file,
172
								  Model model) throws Exception {
173
 
174
		List<VideoUrlPojo> videoRows = readVideoFile(file);
175
 
176
		LOGGER.info("Received {} video rows", videoRows.size());
177
 
178
		// group by catalogId
179
		Map<Integer, List<VideoUrlPojo>> videoCatalogMap =
180
				videoRows.stream().collect(Collectors.groupingBy(VideoUrlPojo::getCatalogId));
181
 
35348 ranu 182
		LOGGER.info("videoCatalogMap {}", videoCatalogMap);
183
 
35346 ranu 184
		for (Map.Entry<Integer, List<VideoUrlPojo>> entry : videoCatalogMap.entrySet()) {
185
 
186
			int catalogId = entry.getKey();
35348 ranu 187
 
188
			LOGGER.info("catalogId {}", catalogId);
189
 
35346 ranu 190
			List<VideoUrlPojo> rowsForCatalog = entry.getValue();
191
 
192
			ContentPojo content = mongoClient.getEntityById(catalogId);
193
 
194
			if (content == null) {
195
				LOGGER.warn("No content found for catalogId {}", catalogId);
196
				continue;
197
			}
198
 
199
			updateVideoUrls(content, rowsForCatalog);
200
 
201
			mongoClient.persistEntity(content);
202
 
203
			LOGGER.info("Updated video URLs for catalogId {}", catalogId);
204
		}
205
 
206
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
207
		return "response";
208
	}
209
 
210
 
211
	private void updateVideoUrls(ContentPojo content, List<VideoUrlPojo> rows) {
212
 
213
		if (content.getVideoUrls() == null) {
214
			content.setVideoUrls(new ArrayList<>());
215
		}
216
 
217
		List<VideoUrlsContentPojo> existing = content.getVideoUrls();
218
 
219
		for (VideoUrlPojo row : rows) {
220
			VideoUrlsContentPojo newUrl = new VideoUrlsContentPojo(row.getUrl());
221
 
222
			// add only if not duplicate
223
			if (!existing.contains(newUrl)) {
224
				existing.add(newUrl);
225
			}
226
		}
227
 
228
		content.setVideoUrls(existing);
229
 
230
		LOGGER.info("Final video list = {}", existing);
231
	}
232
 
233
 
234
 
235
 
28264 tejbeer 236
	@PostMapping(value = "/image/media/upload")
237
	public String uploadImageMediaContent(HttpServletRequest request, @RequestBody MediaPojo mediaPojo, Model model)
238
			throws Exception {
239
 
240
		LOGGER.info("mediaPojo" + mediaPojo);
241
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
242
		String extension;
243
		String base64String = mediaPojo.getImageData();
244
		String[] strings = base64String.split(",");
245
		switch (strings[0]) {// check image's extension
246
		case "data:image/jpeg;base64":
247
			extension = "jpeg";
248
			break;
249
		case "data:image/png;base64":
250
			extension = "png";
251
			break;
32304 amit.gupta 252
			case "data:image/webp;base64":
32305 amit.gupta 253
				extension = "webp";
32304 amit.gupta 254
				break;
28264 tejbeer 255
		default:// should write cases for more images types
32304 amit.gupta 256
			extension = "jpg";
28264 tejbeer 257
			break;
258
		}
259
		LOGGER.info("After switch statement = {}", extension);
260
		// convert base64 string to binary data
261
		byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
262
		Timestamp tm = new Timestamp(System.currentTimeMillis());
28320 tejbeer 263
		String urlTitle = mediaPojo.getTitle().toLowerCase();
264
		String fileName = urlTitle.replace(' ', '-') + tm.getTime() + "." + extension;
28264 tejbeer 265
		LOGGER.info("After switch statement Filename = {}", fileName);
266
		mediaPojo.setImageData(null);
267
		mediaPojo.setUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
268
		fileStreamsMap.put(fileName, new ByteArrayInputStream(data));
269
		LOGGER.info("fileStreamsMap" + fileStreamsMap);
270
 
271
		uploadFile(fileStreamsMap);
272
 
273
		DocumentUrl du = new DocumentUrl();
274
		du.setTitle(mediaPojo.getTitle());
275
		du.setUrl(mediaPojo.getUrl());
276
		du.setCreatedTimestamp(LocalDateTime.now());
277
		documentUrlRepository.persist(du);
278
 
279
		model.addAttribute("documents", du);
280
		return "image-url";
281
	}
282
 
283
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
284
			throws SftpException, FileNotFoundException {
285
 
286
		channelSftp.cd(destinationPath);
287
		String folderName = "image" + LocalDate.now();
288
 
289
		channelSftp.cd(destinationPath);
290
		SftpATTRS attrs = null;
291
 
292
		// check if the directory is already existing
293
		try {
294
			attrs = channelSftp.stat(folderName);
295
		} catch (Exception e) {
296
			System.out.println(destinationPath + "/" + "image" + LocalDate.now() + " not found");
297
		}
298
 
299
		// else create a directory
300
		if (attrs == null) {
301
			channelSftp.mkdir(folderName);
302
			channelSftp.chmod(0755, ".");
303
		}
304
		channelSftp.cd(folderName);
305
 
306
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
307
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
308
		}
309
 
310
	}
311
 
312
	@GetMapping(value = "/search/image/media")
313
	public String getImage(HttpServletRequest request, Model model, @RequestParam String title) throws Exception {
314
		List<DocumentUrl> documents = documentUrlRepository.selectBySearch(title);
315
 
316
		model.addAttribute("documents", documents);
317
		return "image-url";
318
 
319
	}
320
 
25380 amit.gupta 321
	@GetMapping(value = "/content/media")
322
	public String getMediaContent(HttpServletRequest request, Model model, @RequestParam int entityId)
323
			throws Exception {
324
		ContentPojo contentPojo = mongoClient.getEntityById(entityId);
25409 amit.gupta 325
		if (contentPojo == null) {
25380 amit.gupta 326
			throw new Exception("Please add content first");
327
		}
328
		EntityMediaPojo empojo = getEntityMediaPojo(contentPojo);
31238 amit.gupta 329
		model.addAttribute("response1", mvcResponseSender.createResponseString(empojo));
25380 amit.gupta 330
		return "response";
331
	}
28264 tejbeer 332
 
27185 amit.gupta 333
	@GetMapping(value = "/catalog-item")
28264 tejbeer 334
	public String catalogItem(HttpServletRequest request, Model model) throws Exception {
27185 amit.gupta 335
		return "catalog-item";
336
	}
25380 amit.gupta 337
 
338
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
339
		EntityMediaPojo ep = new EntityMediaPojo();
340
		int defaultIndex = 0;
25409 amit.gupta 341
		if (contentPojo.getImages() == null) {
25380 amit.gupta 342
			ep.setMediaPojos(new ArrayList<>());
343
		} else {
344
			ep.setMediaPojos(contentPojo.getImages());
345
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25409 amit.gupta 346
				if (mediaPojo.getUrl() == null)
347
					continue;
348
 
25380 amit.gupta 349
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
350
					defaultIndex++;
351
				}
352
			}
353
		}
354
		ep.setDefaultImageIndex(defaultIndex);
355
		return ep;
356
	}
357
 
37184 ranu 358
	/**
359
	 * Band-aid for URL '+' decode issue: when the front-end sends `brand=Ai+` the servlet
360
	 * decodes the plus as a space and we receive "Ai " with a trailing space, missing the
361
	 * real "Ai+" brand. Restore trailing whitespace back to "+" so lookups match.
362
	 * Front-end should URL-encode with %2B (encodeURIComponent) — this is a temporary
363
	 * safety net until the mobile team ships that fix.
364
	 */
365
	private List<String> normalizeBrandNames(List<String> brands) {
366
		if (brands == null || brands.isEmpty()) return brands;
367
		return brands.stream()
368
				.map(b -> (b != null && b.endsWith(" ")) ? b.replaceAll("\\s+$", "") + "+" : b)
369
				.collect(Collectors.toList());
370
	}
371
 
25380 amit.gupta 372
	@GetMapping(value = "/entity")
28264 tejbeer 373
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 374
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
375
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
376
			Model model) throws Exception {
37184 ranu 377
		brands = normalizeBrandNames(brands);
31330 tejbeer 378
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
31711 amit.gupta 379
				brands, limit, false));
25380 amit.gupta 380
		return "response";
381
	}
382
 
31330 tejbeer 383
	@GetMapping(value = "/focusedEntity")
384
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
385
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
386
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
387
			Model model) throws Exception {
388
 
37184 ranu 389
		brands = normalizeBrandNames(brands);
31330 tejbeer 390
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
391
				.collect(Collectors.toList());
392
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
393
				limit, activeOnly);
394
 
395
		Iterator<Object> jsonIterator = docA.iterator();
396
		while (jsonIterator.hasNext()) {
397
			JSONObject i = (JSONObject) jsonIterator.next();
398
 
399
			if (!catalogIds.contains(i.get("catalogId_i"))) {
400
				jsonIterator.remove();
401
			}
402
 
403
		}
404
 
405
		model.addAttribute("response1", docA.toString());
406
 
407
		return "response";
408
	}
409
 
35487 ranu 410
	@GetMapping(value = "/statusWiseCatalogs")
411
	public String statusWiseCatalogs(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
412
									 @RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
413
									 @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
414
									 Model model) throws Exception {
415
 
37184 ranu 416
		brands = normalizeBrandNames(brands);
35487 ranu 417
		List<CatalogMovingEnum> catalogMovingEnums = Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING);
418
 
419
		List<Integer> catalogIds = catalogRepository.selectAllStatusAndBrandWise(brands, catalogMovingEnums);
420
 
421
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
422
				limit, activeOnly);
423
 
36404 amit 424
		Map<Integer, MonitorType> monitorTypeByCatalogId = catalogMonitorTypeRepository.selectAllAsMap();
425
 
35487 ranu 426
		Iterator<Object> jsonIterator = docA.iterator();
427
		while (jsonIterator.hasNext()) {
428
			JSONObject i = (JSONObject) jsonIterator.next();
429
 
36404 amit 430
			Object cidObj = i.get("catalogId_i");
431
			if (!catalogIds.contains(cidObj)) {
35487 ranu 432
				jsonIterator.remove();
36404 amit 433
				continue;
35487 ranu 434
			}
435
 
36404 amit 436
			if (cidObj instanceof Number) {
437
				MonitorType mt = monitorTypeByCatalogId.get(((Number) cidObj).intValue());
438
				if (mt != null) i.put("monitor_type", mt.dbValue());
439
			}
35487 ranu 440
		}
441
 
442
		model.addAttribute("response1", docA.toString());
443
 
444
		return "response";
445
	}
446
 
25380 amit.gupta 447
	@GetMapping(value = "/content/index")
448
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 449
 
25380 amit.gupta 450
		return "content";
451
	}
452
 
453
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
454
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
455
		List<CSVRecord> records = parser.getRecords();
456
		if (records.size() < 2) {
457
			parser.close();
458
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
459
		}
460
		// Remove header
461
		records.remove(0);
462
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
463
		for (CSVRecord record : records) {
25430 amit.gupta 464
			ContentPojo cp = null;
465
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 466
			try {
25430 amit.gupta 467
				cp = mongoClient.getEntityById(entityId);
468
			} catch (Exception e) {
469
			}
470
			try {
471
				if (cp == null) {
472
					cp = new ContentPojo(entityId);
473
				}
25380 amit.gupta 474
				cp.setWarranty(record.get(Warranty));
475
				cp.setKeySpecs(Arrays
476
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 477
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 478
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
479
				cp.setDetailedSpecs(getDetailedSpecs(record));
37208 amit 480
				if (cp.getCategoryId() == null) {
481
					Catalog catalog = catalogRepository.selectCatalogById(Math.toIntExact(entityId));
482
					if (catalog != null) {
483
						cp.setCategoryId(catalog.getCategoryId());
484
					}
485
				}
25380 amit.gupta 486
				returnList.add(cp);
487
			} catch (Exception e) {
488
				continue;
489
			}
490
		}
491
		parser.close();
492
		return returnList;
493
	}
494
 
35346 ranu 495
 
496
	private List<VideoUrlPojo> readVideoFile(MultipartFile file) throws Exception {
497
 
498
		CSVParser parser = new CSVParser(
499
				new InputStreamReader(file.getInputStream()),
500
				CSVFormat.DEFAULT
501
		);
502
 
503
		List<CSVRecord> records = parser.getRecords();
504
 
505
		if (records.size() < 2) {
506
			parser.close();
507
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records found");
508
		}
509
 
510
		// Remove header
511
		records.remove(0);
512
 
513
		List<VideoUrlPojo> returnList = new ArrayList<>();
514
 
515
		for (CSVRecord record : records) {
516
 
517
			try {
518
				// Must match CSV column order
35348 ranu 519
				Long catalogId = Long.parseLong(record.get(1));
520
				String url = record.get(2);
35346 ranu 521
 
522
				VideoUrlPojo row = new VideoUrlPojo();
523
				row.setCatalogId(Math.toIntExact(catalogId));
524
				row.setUrl(url);
525
 
526
				returnList.add(row);
527
 
528
			} catch (Exception e) {
529
				// skip bad rows, same as your style
530
				continue;
531
			}
532
		}
533
 
534
		parser.close();
535
		return returnList;
536
	}
537
 
538
 
25380 amit.gupta 539
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record) throws Exception {
540
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
541
		int currentIndex = 8;
542
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
543
			int start = currentIndex;
544
			List<Specification> specifications = new ArrayList<>();
545
			int begin = 0;
546
			while (begin < 5) {
547
				int specKeyIndex = (begin * 2) + 1;
548
				int specValueIndex = (begin * 2) + 2;
549
 
550
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
551
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
552
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
553
							Arrays.asList(record.get(currentIndex + specValueIndex)));
554
					specifications.add(specification);
555
				}
556
				begin++;
557
			}
558
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
559
			specificationGroups.add(specificationGroup);
25392 amit.gupta 560
			currentIndex += 11;
25380 amit.gupta 561
		}
562
 
563
		return specificationGroups;
564
	}
565
 
566
	private ChannelSftp setupJsch() throws JSchException {
567
		JSch jsch = new JSch();
33463 amit.gupta 568
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 569
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
570
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
571
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 572
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 573
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 574
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 575
		jschSession.connect();
576
		return (ChannelSftp) jschSession.openChannel("sftp");
577
	}
578
 
29900 amit.gupta 579
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 580
		ChannelSftp channelSftp = setupJsch();
581
		channelSftp.connect();
29900 amit.gupta 582
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
583
		channelSftp.exit();
584
	}
585
 
586
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
587
		ChannelSftp channelSftp = setupJsch();
588
		channelSftp.connect();
25380 amit.gupta 589
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
590
		channelSftp.exit();
591
	}
592
 
593
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
594
			throws SftpException, FileNotFoundException {
595
 
596
		File sourceFile = new File(sourcePath);
597
		if (sourceFile.isFile()) {
598
 
599
			// copy if it is a file
600
			channelSftp.cd(destinationPath);
601
			if (!sourceFile.getName().startsWith("."))
602
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
603
 
604
		} else {
605
 
606
			System.out.println("inside else " + sourceFile.getName());
607
			File[] files = sourceFile.listFiles();
608
 
609
			if (files != null && !sourceFile.getName().startsWith(".")) {
610
 
611
				channelSftp.cd(destinationPath);
612
				SftpATTRS attrs = null;
613
 
614
				// check if the directory is already existing
615
				try {
616
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
617
				} catch (Exception e) {
618
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
619
				}
620
 
621
				// else create a directory
622
				if (attrs != null) {
623
					System.out.println("Directory exists IsDir=" + attrs.isDir());
624
				} else {
625
					System.out.println("Creating dir " + sourceFile.getName());
626
					channelSftp.mkdir(sourceFile.getName());
627
				}
628
 
629
				for (File f : files) {
630
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
631
							destinationPath + "/" + sourceFile.getName());
632
				}
633
 
634
			}
635
		}
636
 
637
	}
638
 
639
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
640
			String folderName) throws SftpException, FileNotFoundException {
641
 
642
		channelSftp.cd(destinationPath);
643
		SftpATTRS attrs = null;
644
 
645
		// check if the directory is already existing
646
		try {
647
			attrs = channelSftp.stat(folderName);
648
		} catch (Exception e) {
649
			System.out.println(destinationPath + "/" + folderName + " not found");
650
		}
651
 
652
		// else create a directory
25413 amit.gupta 653
		if (attrs == null) {
654
			channelSftp.mkdir(folderName);
655
			channelSftp.chmod(0755, ".");
25380 amit.gupta 656
		}
657
		channelSftp.cd(folderName);
25413 amit.gupta 658
		channelSftp.rm("*");
25380 amit.gupta 659
 
660
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
661
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
662
		}
663
 
664
	}
665
 
666
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
667
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 668
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 669
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 670
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
671
			String extension;
672
			String base64String = mediaPojo.getImageData();
673
			String[] strings = base64String.split(",");
674
			switch (strings[0]) {// check image's extension
675
			case "data:image/jpeg;base64":
676
				extension = "jpeg";
677
				break;
678
			case "data:image/png;base64":
679
				extension = "png";
680
				break;
681
			default:// should write cases for more images types
682
				extension = "jpg";
683
				break;
684
			}
25402 amit.gupta 685
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 686
			// convert base64 string to binary data
687
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
688
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 689
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 690
			mediaPojo.setImageData(null);
25430 amit.gupta 691
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 692
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 693
			map.put(fileName, new ByteArrayInputStream(data));
694
			if (i == entityMediaPojo.getDefaultImageIndex()) {
695
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
696
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 697
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 698
			}
699
		}
700
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
701
 
702
		return map;
703
	}
704
 
25409 amit.gupta 705
	private String getMediaPrefix(String productName) {
706
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
707
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
708
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
709
		return mediaPrefix;
710
	}
711
 
28264 tejbeer 712
	@GetMapping(value = "/urlGeneration")
713
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
714
		return "url-generation";
715
	}
33443 ranu 716
	@Autowired
717
	UserRepository userRepository;
718
	@Autowired
719
	private CookiesProcessor cookiesProcessor;
720
 
721
	@GetMapping(value = "/printResources")
722
	public String printResources(HttpServletRequest request, Model model) throws Exception {
723
		List<Region> regionList = regionRepository.selectAll();
724
		model.addAttribute("regionList", regionList);
725
		return "print-resource";
726
	}
727
 
728
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
729
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
730
									Model model) throws Exception {
731
		LOGGER.info("printResourceModel {}", printResourceModel);
732
		PrintResource printResource = new PrintResource();
733
		printResource.setTitle(printResourceModel.getTitle());
734
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
735
		if (printResourceModel.getEndDate() != null) {
736
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
737
		} else {
738
			printResource.setEndDate(null);
739
		}
740
 
741
		printResource.setCreateTimestamp(LocalDateTime.now());
742
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 743
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 744
		printResourceRepository.persist(printResource);
745
 
746
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
747
		int regionId = Integer.parseInt(printResourceModel.getRegion());
748
		printResourceRegion.setRegionId(regionId);
749
		printResourceRegion.setResourceId(printResource.getId());
750
		printResourceRegionRepository.persist(printResourceRegion);
751
 
752
 
753
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
754
 
755
		return "response";
756
	}
757
 
758
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
759
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
760
								Model model) throws Exception {
761
 
762
		PrintResource printResource = printResourceRepository.selectById(resourceId);
763
		printResource.setEndDate(date.atStartOfDay());
764
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
765
		return "response";
766
	}
767
 
768
	@GetMapping(value = "/partnerPrintResources")
769
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
770
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
771
		int fofoId = loginDetails.getFofoId();
772
		User user = userRepository.selectById(fofoId);
773
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
774
		LocalDateTime currentDate = LocalDateTime.now();
775
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
776
		LOGGER.info("printresourcesList {}", printResources);
777
		model.addAttribute("printResources", printResources);
778
		return "partner_print_resource";
779
	}
780
 
781
	@GetMapping(value = "/allPrintResources")
782
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
783
		LocalDateTime currentDate = LocalDateTime.now();
784
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
785
		model.addAttribute("printResources", printResources);
786
		return "all-print-resource";
787
	}
788
 
35346 ranu 789
	@GetMapping("/content/video/check/{catalogId}")
790
	public ResponseEntity<?> checkVideo(@PathVariable int catalogId) throws Exception {
791
		ContentPojo cp = mongoClient.getEntityById(catalogId);
792
 
793
		LOGGER.info("Video Url {}", cp.getVideoUrls());
794
		return ResponseEntity.ok(cp.getVideoUrls());
795
	}
796
 
797
 
35549 ranu 798
	@GetMapping(value = "/bulletin")
799
	public String bulletin(HttpServletRequest request, Model model) throws Exception {
800
		List<Region> regionList = regionRepository.selectAll();
801
		model.addAttribute("regionList", regionList);
802
		return "post-bulletin";
803
	}
804
 
805
 
806
	@RequestMapping(value = "/bulletinPost", method = RequestMethod.POST)
807
	public String bulletinPost(HttpServletRequest request, @RequestBody BulletinPostModel bulletinPostModel,
808
							   Model model) throws Exception {
35583 ranu 809
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
810
		String email = loginDetails.getEmailId();
811
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35549 ranu 812
		LOGGER.info("bulletinPostModel {}", bulletinPostModel);
813
		Bulletin bulletin = new Bulletin();
814
		bulletin.setRegionId(bulletinPostModel.getRegionId());
815
		bulletin.setDescription(bulletinPostModel.getDescription());
816
		bulletin.setDocumentIds(bulletinPostModel.getDocumentIds());
817
		bulletin.setCreatedAt(LocalDateTime.now());
35583 ranu 818
		bulletin.setCreatedBy(authUser.getFullName());
35549 ranu 819
		bulletinRepository.persist(bulletin);
820
 
821
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
822
 
823
		return "response";
824
	}
825
 
826
 
827
 
828
 
25380 amit.gupta 829
}