TIL 작성 할 때 서비스 흐름

  1. 프론트에서 백으로 html을 string으로 보냄
  2. (백에서) 1에서 받은 string을 파일로 저장
  3. (백에서) 2에서 저장한 파일을 .md파일로 변환 후 저장
  4. (백에서) 3에서 저장한 파일을 읽어서 base64로 인코딩

현재 코드

// til 만들기
	@Override
	public String createTIL(TILCreateReq tILCreateReq) {
		String gitLink = "";
		String gitLink2 = "";
		String pixelaId = tILCreateReq.getId().toLowerCase();

		// user id로 user 정보 얻어오기
		User user = userRepository.getUsersById(tILCreateReq.getId()).get();
		String repoName = user.getRepo();
		String personalAccessToken = user.getPat();

		// mission uid로 dir 정보 얻어오기
		Mission mission = missionRepository.findMissionByUid(tILCreateReq.getMissionUid());
		MissionDirRes mdr = MissionDirRes.of(mission);
		String dir = (mdr.getPlanetName() + "/" + mdr.getSatellitesName()).replace(" ", "_");
		String fileName = (tILCreateReq.getFileName()).replace(" ", "_");

		//////// 파일 변환 시작
		String filePath = "./json/testDir/"; // 파일 경로
		File file1 = new File(filePath + "document.html");
		File file2 = new File(filePath + "Output.md");

		// 이전에 파일이 있다면 삭제하기
		if (file1.exists() || file2.exists()) {
			if (file1.delete() && file2.delete()) {
				System.out.println("파일삭제 성공");
			} else {
				System.out.println("파일삭제 실패");
			}
		}

		// 사용자가 입력한 content
		String content = tILCreateReq.getContent();

		// 전달 받은 내용(html)으로 파일 생성하기
		FileWriter fw;
		try {
			fw = new FileWriter(filePath + "document.html");
			fw.write(content);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// html to markdown
		Document doc;
		try {
			doc = new Document(filePath + "document.html");
			doc.save(filePath + "Output.md");
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// markdown 파일 입력받기
		byte[] binary = getFileBinary(filePath + "Output.md");

		// markdown to base64
		String base64data = Base64.getEncoder().encodeToString(binary);
		//////// 파일 변환 끝

		// git API 사용, til 작성하기
		try {

			URL url = new URL("https://api.github.com/repos/" + tILCreateReq.getId() + "/" + repoName + "/contents/"
					+ URLEncoder.encode(dir, "UTF-8") + "/" + URLEncoder.encode(fileName, "UTF-8"));
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("PUT"); // http 메서드
			conn.setRequestProperty("Authorization", "Bearer " + personalAccessToken); // header의 auth 정보
			conn.setRequestProperty("Accept", "application/vnd.github+json");
			conn.setRequestProperty("Content-Type", "application/json;utf-8");
			conn.setDoInput(true);
			conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true

			JSONObject object = new JSONObject();
			object.put("message", tILCreateReq.getMessage());
			object.put("content", base64data);
			String jsonInputString = object.toString();

			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bw.write(jsonInputString); // 버퍼에 담기
			bw.flush(); // 버퍼에 담긴 데이터 전달
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			StringBuilder sb = new StringBuilder();

			while ((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
				sb.append(line);
			}
			JSONObject json = new JSONObject(sb.toString()); // json으로 변경 (역직렬화)
			JSONObject info = json.getJSONObject("content");
			JSONObject link = info.getJSONObject("_links");

			gitLink = (String) link.get("html");
			gitLink2 = URLDecoder.decode(gitLink, "UTF-8");

			// db에 til 저장
			TIL til = new TIL();
			til.setAddress(gitLink2);
			til.setMission(mission);
			til.setUser(user);
			til.setFileName(fileName);
			// 경험치 + 5
			user.addExp(user.getExp());
			userRepository.save(user);
			tilRepository.save(til);

		} catch (Exception e) {
			System.err.println(e);
			return gitLink2;
		}

		boolean isSuccess = false;
		int i = 0; // 이거 나중에 지우삼
		// pixela update 하기
		while (!isSuccess) {
			isSuccess = updatePixela(pixelaId);
		}

		return gitLink2;
	}

// 파일 읽어드리는 함수
	private static byte[] getFileBinary(String filePath) {
		File file = new File(filePath);
		byte[] data = new byte[(int) file.length()];
		try (FileInputStream stream = new FileInputStream(file)) {
			stream.read(data, 0, data.length);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return data;
	}

현재 상황

유정 추측