summaryrefslogtreecommitdiff
path: root/components/tracking/page-visit-tracker.tsx
blob: 09dfc03e6ccd08e4443b7f9812ffc4644d72d703 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// components/tracking/page-visit-tracker.tsx
"use client"

import { useEffect, useRef } from 'react'
import { useSession } from 'next-auth/react'
import { usePathname } from 'next/navigation'

interface PageVisitTrackerProps {
  children: React.ReactNode
}

export function PageVisitTracker({ children }: PageVisitTrackerProps) {
  const { data: session } = useSession()
  const pathname = usePathname()
  const startTimeRef = useRef<number>(Date.now())
  const isTrackingRef = useRef<boolean>(false)

  // 추적 제외 경로 판단
  const shouldExcludeFromTracking = (path: string): boolean => {
    const excludePaths = [
      '/api',
      '/_next',
      '/favicon.ico',
      '/robots.txt',
      '/sitemap.xml'
    ]
    
    const excludeExtensions = [
      '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico',
      '.css', '.js', '.woff', '.woff2', '.ttf', '.eot'
    ]

    return excludePaths.some(exclude => path.startsWith(exclude)) ||
           excludeExtensions.some(ext => path.includes(ext))
  }

  // 디바이스 타입 감지
  const getDeviceType = (): string => {
    if (typeof window === 'undefined') return 'unknown'
    
    const width = window.innerWidth
    if (width < 768) return 'mobile'
    if (width < 1024) return 'tablet'
    return 'desktop'
  }

  // 브라우저 정보 추출
  const getBrowserInfo = () => {
    if (typeof navigator === 'undefined') return { name: 'unknown', os: 'unknown' }
    
    const userAgent = navigator.userAgent
    let browserName = 'unknown'
    let osName = 'unknown'

    // 간단한 브라우저 감지
    if (userAgent.includes('Chrome')) browserName = 'Chrome'
    else if (userAgent.includes('Firefox')) browserName = 'Firefox'
    else if (userAgent.includes('Safari')) browserName = 'Safari'
    else if (userAgent.includes('Edge')) browserName = 'Edge'

    // 간단한 OS 감지
    if (userAgent.includes('Windows')) osName = 'Windows'
    else if (userAgent.includes('Mac')) osName = 'macOS'
    else if (userAgent.includes('Linux')) osName = 'Linux'
    else if (userAgent.includes('Android')) osName = 'Android'
    else if (userAgent.includes('iOS')) osName = 'iOS'

    return { name: browserName, os: osName }
  }

  // 페이지 제목 추출
  const getPageTitle = (route: string): string => {
    if (typeof document !== 'undefined' && document.title) {
      return document.title
    }
    
    // 경로 기반 제목 매핑
    const titleMap: Record<string, string> = {
      '/': 'Home',
      '/dashboard': 'Dashboard',
      '/profile': 'Profile',
      '/settings': 'Settings',
    }
    
    // 언어 코드 제거 후 매핑
    const cleanRoute = route.replace(/^\/[a-z]{2}/, '') || '/'
    return titleMap[cleanRoute] || cleanRoute
  }

  // 페이지 방문 추적
  const trackPageVisit = async (route: string) => {
    if (shouldExcludeFromTracking(route) || isTrackingRef.current) {
      return
    }

    isTrackingRef.current = true

    try {
      const browserInfo = getBrowserInfo()
      
      const trackingData = {
        route,
        pageTitle: getPageTitle(route),
        referrer: document.referrer || null,
        deviceType: getDeviceType(),
        browserName: browserInfo.name,
        osName: browserInfo.os,
        screenResolution: `${screen.width}x${screen.height}`,
        windowSize: `${window.innerWidth}x${window.innerHeight}`,
        language: navigator.language,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent,
      }

      // 백그라운드로 추적 API 호출 (에러 시에도 메인 기능에 영향 없음)
      fetch('/api/tracking/page-visit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(trackingData),
        // 백그라운드 요청으로 설정
        keepalive: true,
      }).catch(error => {
        console.error('Page visit tracking failed:', error)
      })

    } catch (error) {
      console.error('Client-side tracking error:', error)
    } finally {
      isTrackingRef.current = false
    }
  }

  // 체류 시간 기록
  const trackPageDuration = async (route: string, duration: number) => {
    if (shouldExcludeFromTracking(route) || duration < 5) {
      return // 5초 미만은 기록하지 않음
    }

    try {
      const data = JSON.stringify({
        route,
        duration,
        timestamp: new Date().toISOString(),
      })

      // navigator.sendBeacon 사용 (페이지 이탈 시에도 안전하게 전송)
      if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/tracking/page-duration', data)
      } else {
        // sendBeacon 미지원 시 fallback
        fetch('/api/tracking/page-duration', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: data,
          keepalive: true,
        }).catch(() => {
          // 페이지 이탈 시 에러는 무시
        })
      }
    } catch (error) {
      console.error('Duration tracking error:', error)
    }
  }

  useEffect(() => {
    // 페이지 변경 시 추적
    startTimeRef.current = Date.now()
    trackPageVisit(pathname)

    // 페이지 이탈 시 체류 시간 기록
    return () => {
      const duration = Math.floor((Date.now() - startTimeRef.current) / 1000)
      trackPageDuration(pathname, duration)
    }
  }, [pathname])

  // 브라우저 닫기/새로고침 시 체류 시간 기록
  useEffect(() => {
    const handleBeforeUnload = () => {
      const duration = Math.floor((Date.now() - startTimeRef.current) / 1000)
      trackPageDuration(pathname, duration)
    }

    // visibility change 이벤트로 탭 변경 감지
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        const duration = Math.floor((Date.now() - startTimeRef.current) / 1000)
        trackPageDuration(pathname, duration)
      } else {
        startTimeRef.current = Date.now() // 탭 복귀 시 시간 리셋
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    document.addEventListener('visibilitychange', handleVisibilityChange)

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [pathname])

  return <>{children}</>
}