AnalyticsDashboard.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { useState, useEffect } from 'react';
  2. import { useBaaS } from '@picobaas/client/react';
  3. import type { ImageAnalytics, ViewLog, ShareLink } from '../types';
  4. import { listShareLinks } from '../api/shareLinks';
  5. import { getSessionToken } from '../utils/session';
  6. import LoadingSpinner from './LoadingSpinner';
  7. interface ImageInfo {
  8. imageUrl: string;
  9. shortUrl: string;
  10. path: string;
  11. }
  12. interface AnalyticsDashboardProps {
  13. shortCode: string;
  14. onClose?: () => void;
  15. }
  16. export default function AnalyticsDashboard({ shortCode, onClose }: AnalyticsDashboardProps) {
  17. const { client } = useBaaS();
  18. const [analytics, setAnalytics] = useState<ImageAnalytics | null>(null);
  19. const [imageInfo, setImageInfo] = useState<ImageInfo | null>(null);
  20. const [shareLinks, setShareLinks] = useState<ShareLink[]>([]);
  21. const [isLoading, setIsLoading] = useState(true);
  22. const [error, setError] = useState<string | null>(null);
  23. useEffect(() => {
  24. fetchData();
  25. }, [shortCode]);
  26. const fetchData = async () => {
  27. setIsLoading(true);
  28. setError(null);
  29. try {
  30. const token = client.accessToken;
  31. const headers = {
  32. 'Authorization': token ? `Bearer ${token}` : '',
  33. };
  34. // Fetch image info, analytics, and share links in parallel
  35. const sessionToken = getSessionToken();
  36. const [imageResponse, analyticsResponse, links] = await Promise.all([
  37. fetch(`/api/images/${shortCode}`, { headers }),
  38. fetch(`/api/images/${shortCode}/analytics`, { headers }),
  39. listShareLinks(shortCode, token || undefined, sessionToken),
  40. ]);
  41. // Handle image info
  42. if (imageResponse.ok) {
  43. const imgData = await imageResponse.json();
  44. setImageInfo({
  45. imageUrl: imgData.image_url,
  46. shortUrl: imgData.short_url || `/i/${shortCode}`,
  47. path: imgData.path,
  48. });
  49. }
  50. // Handle share links
  51. setShareLinks(links);
  52. // Handle analytics
  53. if (!analyticsResponse.ok) {
  54. const errorData = await analyticsResponse.json().catch(() => ({}));
  55. throw new Error(errorData.error || 'Failed to load analytics');
  56. }
  57. const data = await analyticsResponse.json();
  58. setAnalytics({
  59. totalViews: data.total_views,
  60. uniqueVisitors: data.unique_visitors,
  61. proxyViewsCount: data.proxy_views_count,
  62. viewsByReferrer: data.views_by_referrer || {},
  63. recentViews: (data.recent_views || []).map((v: Record<string, unknown>) => ({
  64. id: v.id as string,
  65. viewerIp: v.viewer_ip as string,
  66. userAgent: v.user_agent as string,
  67. referrer: v.referrer as string | null,
  68. country: v.country as string | null,
  69. isProxyDetected: v.is_proxy_detected as boolean,
  70. viewedAt: new Date(v.viewed_at as string),
  71. })),
  72. });
  73. } catch (err) {
  74. setError(err instanceof Error ? err.message : 'Failed to load analytics');
  75. } finally {
  76. setIsLoading(false);
  77. }
  78. };
  79. if (isLoading) {
  80. return (
  81. <div className="flex items-center justify-center p-8">
  82. <LoadingSpinner size="lg" />
  83. </div>
  84. );
  85. }
  86. if (error) {
  87. return (
  88. <div className="p-6 text-center">
  89. <div className="text-red-600 dark:text-red-400 mb-4">{error}</div>
  90. <button onClick={fetchData} className="btn btn-secondary">
  91. Try Again
  92. </button>
  93. </div>
  94. );
  95. }
  96. if (!analytics) {
  97. return null;
  98. }
  99. return (
  100. <div className="space-y-6">
  101. {/* Header with image preview */}
  102. <div className="flex justify-between items-start gap-4">
  103. <div className="flex items-center gap-4">
  104. {imageInfo && (
  105. <a
  106. href={imageInfo.shortUrl}
  107. target="_blank"
  108. rel="noopener noreferrer"
  109. className="flex-shrink-0"
  110. >
  111. <img
  112. src={imageInfo.imageUrl}
  113. alt="Image preview"
  114. className="w-16 h-16 object-cover rounded-lg hover:opacity-80 transition-opacity"
  115. />
  116. </a>
  117. )}
  118. <div>
  119. <h2
  120. className="text-xl font-semibold"
  121. style={{ color: 'var(--text-primary)' }}
  122. >
  123. Image Analytics
  124. </h2>
  125. {imageInfo && (
  126. <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
  127. {imageInfo.path.split('/').pop()}
  128. </p>
  129. )}
  130. </div>
  131. </div>
  132. {onClose && (
  133. <button
  134. onClick={onClose}
  135. className="transition-colors flex-shrink-0"
  136. style={{ color: 'var(--text-muted)' }}
  137. >
  138. <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  139. <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
  140. </svg>
  141. </button>
  142. )}
  143. </div>
  144. {/* Stats Grid */}
  145. <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
  146. <div
  147. className="rounded-lg p-4"
  148. style={{ backgroundColor: 'var(--bg-tertiary)' }}
  149. >
  150. <div className="text-sm mb-1" style={{ color: 'var(--text-muted)' }}>
  151. Total Views
  152. </div>
  153. <div
  154. className="text-2xl font-bold"
  155. style={{ color: 'var(--text-primary)' }}
  156. >
  157. {analytics.totalViews}
  158. </div>
  159. </div>
  160. <div
  161. className="rounded-lg p-4"
  162. style={{ backgroundColor: 'var(--bg-tertiary)' }}
  163. >
  164. <div className="text-sm mb-1" style={{ color: 'var(--text-muted)' }}>
  165. Unique Visitors
  166. </div>
  167. <div
  168. className="text-2xl font-bold"
  169. style={{ color: 'var(--text-primary)' }}
  170. >
  171. {analytics.uniqueVisitors}
  172. </div>
  173. </div>
  174. <div
  175. className="rounded-lg p-4"
  176. style={{ backgroundColor: 'var(--bg-tertiary)' }}
  177. >
  178. <div className="text-sm mb-1" style={{ color: 'var(--text-muted)' }}>
  179. Proxy/VPN Views
  180. </div>
  181. <div
  182. className="text-2xl font-bold"
  183. style={{ color: 'var(--text-primary)' }}
  184. >
  185. {analytics.proxyViewsCount}
  186. </div>
  187. </div>
  188. </div>
  189. {/* Referrers */}
  190. {Object.keys(analytics.viewsByReferrer).length > 0 && (
  191. <div>
  192. <h3
  193. className="text-sm font-medium mb-3"
  194. style={{ color: 'var(--text-secondary)' }}
  195. >
  196. Top Referrers
  197. </h3>
  198. <div
  199. className="rounded-lg divide-y"
  200. style={{
  201. backgroundColor: 'var(--bg-tertiary)',
  202. borderColor: 'var(--border)',
  203. }}
  204. >
  205. {Object.entries(analytics.viewsByReferrer)
  206. .sort(([, a], [, b]) => b - a)
  207. .slice(0, 5)
  208. .map(([referrer, count]) => (
  209. <div
  210. key={referrer}
  211. className="px-4 py-3 flex justify-between items-center"
  212. style={{ borderColor: 'var(--border)' }}
  213. >
  214. <span
  215. className="text-sm truncate max-w-xs"
  216. style={{ color: 'var(--text-secondary)' }}
  217. title={referrer}
  218. >
  219. {referrer}
  220. </span>
  221. <span
  222. className="text-sm font-medium"
  223. style={{ color: 'var(--text-primary)' }}
  224. >
  225. {count}
  226. </span>
  227. </div>
  228. ))}
  229. </div>
  230. </div>
  231. )}
  232. {/* Share Links Section */}
  233. {shareLinks.length > 0 && (
  234. <div>
  235. <h3
  236. className="text-sm font-medium mb-3"
  237. style={{ color: 'var(--text-secondary)' }}
  238. >
  239. Share Links ({shareLinks.length})
  240. </h3>
  241. <div
  242. className="rounded-lg divide-y"
  243. style={{
  244. backgroundColor: 'var(--bg-tertiary)',
  245. borderColor: 'var(--border)',
  246. }}
  247. >
  248. {shareLinks
  249. .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
  250. .map((link) => (
  251. <div
  252. key={link.id}
  253. className="px-4 py-3"
  254. style={{ borderColor: 'var(--border)' }}
  255. >
  256. <div className="flex justify-between items-start mb-2">
  257. <div className="flex items-center gap-2">
  258. <code
  259. className="text-sm font-mono px-2 py-0.5 rounded"
  260. style={{ backgroundColor: 'var(--bg-secondary)' }}
  261. >
  262. {link.linkCode}
  263. </code>
  264. {link.isRevoked ? (
  265. <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400">
  266. Revoked
  267. </span>
  268. ) : !link.isValid ? (
  269. <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400">
  270. Expired
  271. </span>
  272. ) : (
  273. <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
  274. Active
  275. </span>
  276. )}
  277. </div>
  278. <div
  279. className="text-sm font-medium"
  280. style={{ color: 'var(--text-primary)' }}
  281. >
  282. {link.viewCount} {link.viewCount === 1 ? 'view' : 'views'}
  283. </div>
  284. </div>
  285. <div
  286. className="text-xs flex flex-wrap gap-x-4 gap-y-1"
  287. style={{ color: 'var(--text-muted)' }}
  288. >
  289. <span>Created: {formatDate(link.createdAt)}</span>
  290. <span>
  291. Expires: {formatDate(link.expiresAt)}
  292. </span>
  293. {link.lastViewedAt && (
  294. <span>Last viewed: {formatDate(link.lastViewedAt)}</span>
  295. )}
  296. </div>
  297. </div>
  298. ))}
  299. </div>
  300. </div>
  301. )}
  302. {/* Recent Views Table */}
  303. <div>
  304. <h3
  305. className="text-sm font-medium mb-3"
  306. style={{ color: 'var(--text-secondary)' }}
  307. >
  308. Recent Views
  309. </h3>
  310. {analytics.recentViews.length === 0 ? (
  311. <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
  312. No views recorded yet
  313. </p>
  314. ) : (
  315. <div className="overflow-x-auto">
  316. <table
  317. className="min-w-full divide-y"
  318. style={{ borderColor: 'var(--border)' }}
  319. >
  320. <thead style={{ backgroundColor: 'var(--bg-tertiary)' }}>
  321. <tr>
  322. <th
  323. className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider"
  324. style={{ color: 'var(--text-muted)' }}
  325. >
  326. Time
  327. </th>
  328. <th
  329. className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider"
  330. style={{ color: 'var(--text-muted)' }}
  331. >
  332. IP Address
  333. </th>
  334. <th
  335. className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider"
  336. style={{ color: 'var(--text-muted)' }}
  337. >
  338. Referrer
  339. </th>
  340. <th
  341. className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider"
  342. style={{ color: 'var(--text-muted)' }}
  343. >
  344. Proxy
  345. </th>
  346. </tr>
  347. </thead>
  348. <tbody
  349. className="divide-y"
  350. style={{
  351. backgroundColor: 'var(--bg-secondary)',
  352. borderColor: 'var(--border)',
  353. }}
  354. >
  355. {analytics.recentViews.slice(0, 20).map((view: ViewLog) => (
  356. <tr key={view.id}>
  357. <td
  358. className="px-4 py-3 whitespace-nowrap text-sm"
  359. style={{ color: 'var(--text-secondary)' }}
  360. >
  361. {formatDate(view.viewedAt)}
  362. </td>
  363. <td
  364. className="px-4 py-3 whitespace-nowrap text-sm"
  365. style={{ color: 'var(--text-secondary)' }}
  366. >
  367. {view.viewerIp}
  368. </td>
  369. <td
  370. className="px-4 py-3 text-sm max-w-xs truncate"
  371. style={{ color: 'var(--text-secondary)' }}
  372. title={view.referrer || undefined}
  373. >
  374. {view.referrer || '-'}
  375. </td>
  376. <td className="px-4 py-3 whitespace-nowrap text-sm">
  377. {view.isProxyDetected ? (
  378. <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
  379. Detected
  380. </span>
  381. ) : (
  382. <span style={{ color: 'var(--text-muted)' }}>-</span>
  383. )}
  384. </td>
  385. </tr>
  386. ))}
  387. </tbody>
  388. </table>
  389. </div>
  390. )}
  391. </div>
  392. {/* Refresh Button */}
  393. <div className="flex justify-end">
  394. <button onClick={fetchData} className="btn btn-secondary text-sm">
  395. Refresh
  396. </button>
  397. </div>
  398. </div>
  399. );
  400. }
  401. function formatDate(date: Date): string {
  402. const now = new Date();
  403. const diff = now.getTime() - date.getTime();
  404. if (diff < 60000) {
  405. return 'Just now';
  406. }
  407. if (diff < 3600000) {
  408. const mins = Math.floor(diff / 60000);
  409. return `${mins}m ago`;
  410. }
  411. if (diff < 86400000) {
  412. const hours = Math.floor(diff / 3600000);
  413. return `${hours}h ago`;
  414. }
  415. return date.toLocaleDateString(undefined, {
  416. month: 'short',
  417. day: 'numeric',
  418. hour: '2-digit',
  419. minute: '2-digit',
  420. });
  421. }