• 사용자가 동영상을 처음으로 시청할 때 시청기록이 생성되고 이후 시청할 때마다 업데이트되어 생성일자와 마지막 업데이트 일자만 저장되어 기간별 조회가 불가능함.

    // 동영상 조회수, 재생시간 시청기록에 업데이트
    @Transactional
    public VideoDto stopVideo(WatchedVideoRequestDto requestDto) throws Exception {
        Video video = videoRepository.findById(requestDto.getVideoId())
                .orElseThrow(() -> new Exception("해당 동영상을 찾을 수 없습니다."));
    
        // 현재 사용자의 시청 기록 조회
        Views views = viewsRepository.findByUser_UserIdAndVideo_VideoId(requestDto.getUserId(), requestDto.getVideoId())
                .orElseThrow(() -> new Exception("사용자의 시청 기록을 찾을 수 없습니다."));
    
        // 마지막 재생시점이 동영상 길이보다 길다면
        if (requestDto.getLastWatchedTime() > video.getVideoLength()) {
            throw new Exception("재생시간이 동영상의 길이를 초과했습니다.");
        }
        // 현 재생시점 - 저장되었던 재생시점 = 방금 시청한 재생시간
        long playTime = requestDto.getLastWatchedTime() - views.getViewsLastWatchedTime();
        long totalPlayTimeOfYou = views.getViewsPlaytime() + playTime;
        long totalPlayTimeOfVideo = video.getVideoTotalPlaytime() + playTime;
    
        views.setViewsLastWatchedTime(requestDto.getLastWatchedTime()); // 마지막 재생시점 저장
        views.setViewsPlaytime(totalPlayTimeOfYou);// 시청기록 갱신
        video.setVideoTotalPlaytime(totalPlayTimeOfVideo); // 해당 동영상의 총 재생시간 갱신
        videoRepository.save(video);
        viewsRepository.save(views);
    
        return video.toDto();
    }
    
    // 광고 조회수 시청기록에 업데이트
    public VideoDto stopVideo(WatchedVideoRequestDto requestDto) throws Exception {
    	...
    	// 심어놓은 광고 리스트 조회
    	List<VideoAd> vas = videoAdRepository.findByVideo(video);
    	int adWatchedCntOfUser = 0; // 광고 시청 횟수 카운트
    	for (VideoAd va : vas) {
    	    // 저장된 마지막 재생시점보다 크고, 전송된 마지막 재생시점보다 작은 경우 카운트
    	    if (va.getVaPosition() > views.getViewsLastWatchedTime() && va.getVaPosition() <= requestDto.getLastWatchedTime()) {
    	        adWatchedCntOfUser++;
    	    }
    	}
    	video.setAdWatchedCount(video.getAdWatchedCount() + adWatchedCntOfUser);
    }
    
  • 사용자가 동영상을 시청할 때마다 시청기록을 생성하고, 기간별로 시청기록 개수를 쿼리로 COUNT해서 조회수를 계산하도록 서비스 로직을 수정해 1일치 통계와 정산만 DB에 저장시킴.

    Untitled

    @Transactional
    public VideoDto watchVideo(Long videoId) throws Exception {
        Video video = getVideo(videoId);
        User user = getAuthenticatedUser();
        try {
          // 본인이 본인 동영상을 보면 조회수 카운트 X - 누적조회수는 배치 돌리고 나서 시청기록 세서 한꺼번에 플러스
          // 동영상 업로더의 ID와 인증된 사용자 ID를 비교해서 일치하지 않을 때
          if (!video.getUser().getUserId().equals(user.getUserId())) {
              Optional<Views> recentViewsOptional = viewsRepository.findLatestViewByUserAndVideo(user, video);
              if (recentViewsOptional.isPresent()) {  // 이전 시청기록이 있다면
                  Views recentViews = recentViewsOptional.get();
                // 해당 동영상에 대한 개인의 시청기록 생성일자가 현재 시간보다 30초 이후일 때 +1 카운트
                if (recentViews.getCreatedAt().isBefore(LocalDateTime.now().minusSeconds(30))) {
                      // 시청기록 생성
                      Views views = Views.of(user, video);
                      viewsRepository.save(views);
                  }
              } else {    // 이전 시청기록이 없다면
            // 그냥 시청기록 생성
            Views views = Views.of(user, video);
            viewsRepository.save(views);
                    }
                }
            return new VideoDto(video);
        } catch (Exception e) {
            throw new Exception(ErrorMessage.FAILED_WATCH_VIDEO.getMessage());
        }
     }
    
    @Transactional
    public VideoDto stopVideo(Long videoId, long lastWatchedTime) throws Exception {
        User user = getAuthenticatedUser();
        Video video = getVideo(videoId);
        // 이전 시청기록 조회
        List<Views> recentViews = viewsRepository.find2ViewsByUserAndVideo(user, video);
        Views views = recentViews.get(0);  // 비디오 생성했을 때 만들어진 시청기록
        Views previousViews;    // 이전 시청기록
        if (recentViews.size() == 1) {  // 만약 이전 시청기록이 없다면
            previousViews = views;
        } else {
            previousViews = recentViews.get(1);
        }
        // 심어놓은 광고 리스트 조회
        List<VideoAd> vas = videoAdRepository.findByVideo(video);
        List<VideoAd> vasToSave = new ArrayList<>();
        List<AdViews> adViewsToSave = new ArrayList<>();
        for (int i = 1; i <= vas.size(); i++) {
            VideoAd va = vas.get(i-1);
            int position = i * (60 * 5);
            // 저장된 마지막 재생시점보다 크고, 전송된 마지막 재생시점보다 작은 경우 카운트
            if (position > previousViews.getViewsLastWatchedTime() && position <= lastWatchedTime) {
                AdViews adViews = AdViews.of(va, va.getAd());   // 광고 시청기록 생성 - 배치할 때 va.getAdWatchedCount에 한꺼번에 조회수 저장
                adViewsToSave.add(adViews);
            }
        }
        // 동영상 시청 시간
        long playTime = 0;
        long previousLastWatchedTime = previousViews.getViewsLastWatchedTime();
        // 마지막 재생시점이 동영상 길이보다 길다면
        if (lastWatchedTime >= video.getVideoLength()) {
            // 동영상 시청 시간 = 동영상 길이 - 저장되었던 재생시점
            playTime = video.getVideoLength() - previousLastWatchedTime;
            // 처음부터 재생되도록 마지막 재생시점 0 저장
            views.saveViewsLastWatchedTime(0);
        } else {
            // 동영상 시청 시간 = 현 재생시점 - 저장되었던 재생시점
            playTime = lastWatchedTime - previousLastWatchedTime;
            // 마지막 재생시간 갱신
            views.saveViewsLastWatchedTime(lastWatchedTime);
        }
        // 마지막 재생시점 저장
        views.saveViewsPlaytime(playTime);
        viewsRepository.save(views);
        try {
            // 본인이 만든 동영상이 아닐 때
            if (!video.getUser().getUserId().equals(user.getUserId())) {
            // 30초 전에 본 시청기록이 있다면
                if (previousViews.getCreatedAt().isBefore(LocalDateTime.now().minusSeconds(30))) {
                adViewsRepository.saveAll(adViewsToSave);   // 광고 시청기록 생성
                videoAdRepository.saveAll(vasToSave);   // 각 광고 누적조회수 갱신
                }
            }
    	      return new VideoDto(video);
        } catch (Exception e) {
            throw new Exception(ErrorMessage.FAILED_STOP_VIDEO.getMessage());
        }
    }
    }
    
  • 오늘이 포함된 1주일치, 1달치 범위에 맞게 집계된 통계/정산 리스트 조회가 가능해짐.

    // VideoStatRepository
    @Query("SELECT v.video, SUM(v.dailyViewCount) cnt FROM VideoStat v " +
            "WHERE v.createdAt >= :start AND v.createdAt < :end " +
            "AND v.createdAt = (SELECT MAX(vs.createdAt) FROM VideoStat vs " +
                                "WHERE vs.video = v.video AND vs.createdAt >= :start AND vs.createdAt < :end) " +
            "GROUP BY v.video ORDER BY cnt DESC LIMIT 5")
    List<Object[]> findVideoViewCount(@Param("start") LocalDate start, @Param("end") LocalDate end);
    
    @Query("SELECT v.video, SUM(v.dailyPlayTime) pt FROM VideoStat v " +
            "WHERE v.createdAt >= :start AND v.createdAt < :end " +
            "AND v.createdAt = (SELECT MAX(vs.createdAt) FROM VideoStat vs " +
                                "WHERE vs.video = v.video AND vs.createdAt >= :start AND vs.createdAt < :end) " +
            "GROUP BY v.video ORDER BY pt DESC LIMIT 5")
    List<Object[]> findVideoPlayTime(@Param("start") LocalDate start, @Param("end") LocalDate end);
    
    • 결과
      • 1일, 1주일, 1달치 조회수 TOP5
      • 1일, 1주일, 1달치 재생시간 TOP5