statistics.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /**
  2. * FeHelper数据统计模块
  3. * @author fehelper
  4. */
  5. import Awesome from './awesome.js';
  6. // 数据上报服务器地址
  7. let manifest = chrome.runtime.getManifest();
  8. let SERVER_TRACK_URL = '';
  9. if (manifest.name && manifest.name.endsWith('-Dev')) {
  10. SERVER_TRACK_URL = 'https://chrome.fehelper.com/api/track';
  11. } else {
  12. SERVER_TRACK_URL = 'https://localhost:3001/api/track';
  13. }
  14. // 用户ID存储键名
  15. const USER_ID_KEY = 'FH_USER_ID';
  16. // 上次使用日期存储键名
  17. const LAST_ACTIVE_DATE_KEY = 'FH_LAST_ACTIVE_DATE';
  18. // 用户日常使用数据存储键名
  19. const USER_USAGE_DATA_KEY = 'FH_USER_USAGE_DATA';
  20. // 记录background启动时间
  21. const FH_TIME_OPENED = Date.now();
  22. let Statistics = (function() {
  23. // 用户唯一标识
  24. let userId = '';
  25. // 今天的日期字符串 YYYY-MM-DD
  26. let todayStr = new Date().toISOString().split('T')[0];
  27. // 本地存储的使用数据
  28. let usageData = {
  29. dailyUsage: {}, // 按日期存储的使用记录
  30. tools: {} // 各工具的使用次数
  31. };
  32. /**
  33. * 生成唯一的用户ID
  34. * @returns {string} 用户ID
  35. */
  36. const generateUserId = () => {
  37. return 'fh_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  38. };
  39. /**
  40. * 获取或创建用户ID
  41. * @returns {Promise<string>} 用户ID
  42. */
  43. const getUserId = async () => {
  44. if (userId) return userId;
  45. try {
  46. const result = await Awesome.StorageMgr.get(USER_ID_KEY);
  47. if (result) {
  48. userId = result;
  49. } else {
  50. userId = generateUserId();
  51. await Awesome.StorageMgr.set(USER_ID_KEY, userId);
  52. }
  53. return userId;
  54. } catch (error) {
  55. console.error('获取用户ID失败:', error);
  56. return generateUserId(); // 失败时生成临时ID
  57. }
  58. };
  59. /**
  60. * 加载本地存储的使用数据
  61. * @returns {Promise<void>}
  62. */
  63. const loadUsageData = async () => {
  64. try {
  65. const data = await Awesome.StorageMgr.get(USER_USAGE_DATA_KEY);
  66. if (data) {
  67. usageData = JSON.parse(data);
  68. }
  69. } catch (error) {
  70. console.error('加载使用数据失败:', error);
  71. }
  72. };
  73. /**
  74. * 保存使用数据到本地存储
  75. * @returns {Promise<void>}
  76. */
  77. const saveUsageData = async () => {
  78. try {
  79. await Awesome.StorageMgr.set(USER_USAGE_DATA_KEY, JSON.stringify(usageData));
  80. } catch (error) {
  81. console.error('保存使用数据失败:', error);
  82. }
  83. };
  84. /**
  85. * 获取客户端详细信息,对标百度统计/GA/友盟
  86. * @returns {Object}
  87. */
  88. const getClientInfo = () => {
  89. const nav = navigator;
  90. const screenInfo = window.screen;
  91. const lang = nav.language || nav.userLanguage || '';
  92. const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
  93. const ua = nav.userAgent;
  94. const platform = nav.platform;
  95. const vendor = nav.vendor;
  96. const colorDepth = screenInfo.colorDepth;
  97. const screenWidth = screenInfo.width;
  98. const screenHeight = screenInfo.height;
  99. const deviceMemory = nav.deviceMemory || '';
  100. const hardwareConcurrency = nav.hardwareConcurrency || '';
  101. // 网络信息
  102. const connection = nav.connection || nav.mozConnection || nav.webkitConnection || {};
  103. // 屏幕方向
  104. const screenOrientation = screenInfo.orientation ? screenInfo.orientation.type : '';
  105. // 触摸支持
  106. const touchSupport = ('ontouchstart' in window) || (nav.maxTouchPoints > 0);
  107. // JS堆内存(仅Chrome)
  108. let memoryJSHeapSize = '';
  109. if (window.performance && window.performance.memory) {
  110. memoryJSHeapSize = window.performance.memory.jsHeapSizeLimit;
  111. }
  112. return {
  113. language: lang,
  114. timezone,
  115. userAgent: ua,
  116. platform,
  117. vendor,
  118. colorDepth,
  119. screenWidth,
  120. screenHeight,
  121. deviceMemory,
  122. hardwareConcurrency,
  123. extensionVersion: chrome.runtime.getManifest().version,
  124. // 新增字段
  125. networkType: connection.effectiveType || '',
  126. downlink: connection.downlink || '',
  127. rtt: connection.rtt || '',
  128. online: nav.onLine,
  129. touchSupport,
  130. cookieEnabled: nav.cookieEnabled,
  131. doNotTrack: nav.doNotTrack,
  132. appVersion: nav.appVersion,
  133. appName: nav.appName,
  134. product: nav.product,
  135. vendorSub: nav.vendorSub,
  136. screenOrientation,
  137. memoryJSHeapSize,
  138. timeOpened: FH_TIME_OPENED
  139. };
  140. };
  141. /**
  142. * 使用自建服务器发送事件数据
  143. * @param {string} eventName - 事件名称
  144. * @param {Object} params - 事件参数
  145. */
  146. const sendToServer = async (eventName, params = {}) => {
  147. const uid = await getUserId();
  148. const clientInfo = getClientInfo();
  149. const payload = {
  150. event: eventName,
  151. userId: uid,
  152. date: todayStr,
  153. timestamp: Date.now(),
  154. ...clientInfo,
  155. ...params
  156. };
  157. try {
  158. fetch(SERVER_TRACK_URL, {
  159. method: 'POST',
  160. body: JSON.stringify(payload),
  161. headers: {
  162. 'Content-Type': 'application/json'
  163. },
  164. keepalive: true
  165. }).catch(e => console.log('自建统计服务器发送失败:', e));
  166. } catch (error) {
  167. console.log('自建统计发送失败:', error);
  168. }
  169. };
  170. /**
  171. * 记录每日活跃用户
  172. * @returns {Promise<void>}
  173. */
  174. const recordDailyActiveUser = async () => {
  175. try {
  176. // 获取上次活跃日期
  177. const lastActiveDate = await Awesome.StorageMgr.get(LAST_ACTIVE_DATE_KEY);
  178. // 如果今天还没有记录,则记录今天的活跃
  179. if (lastActiveDate !== todayStr) {
  180. await Awesome.StorageMgr.set(LAST_ACTIVE_DATE_KEY, todayStr);
  181. // 确保该日期的记录存在
  182. if (!usageData.dailyUsage[todayStr]) {
  183. usageData.dailyUsage[todayStr] = {
  184. date: todayStr,
  185. tools: {}
  186. };
  187. }
  188. // 发送每日活跃记录到自建服务器
  189. sendToServer('daily_active_user', {
  190. date: todayStr
  191. });
  192. }
  193. } catch (error) {
  194. console.error('记录日活跃用户失败:', error);
  195. }
  196. };
  197. /**
  198. * 记录插件安装事件
  199. */
  200. const recordInstallation = async () => {
  201. sendToServer('extension_installed');
  202. };
  203. /**
  204. * 记录插件更新事件
  205. * @param {string} previousVersion - 更新前的版本
  206. */
  207. const recordUpdate = async (previousVersion) => {
  208. sendToServer('extension_updated', {
  209. previous_version: previousVersion
  210. });
  211. };
  212. /**
  213. * 记录插件卸载事件
  214. */
  215. const recordUninstall = async () => {
  216. sendToServer('extension_uninstall');
  217. };
  218. /**
  219. * 记录工具使用情况
  220. * @param {string} toolName - 工具名称
  221. */
  222. const recordToolUsage = async (toolName) => {
  223. // 确保今天的记录存在
  224. if (!usageData.dailyUsage[todayStr]) {
  225. usageData.dailyUsage[todayStr] = {
  226. date: todayStr,
  227. tools: {}
  228. };
  229. }
  230. // 增加工具使用计数
  231. if (!usageData.tools[toolName]) {
  232. usageData.tools[toolName] = 0;
  233. }
  234. usageData.tools[toolName]++;
  235. // 增加今天该工具的使用计数
  236. if (!usageData.dailyUsage[todayStr].tools[toolName]) {
  237. usageData.dailyUsage[todayStr].tools[toolName] = 0;
  238. }
  239. usageData.dailyUsage[todayStr].tools[toolName]++;
  240. // 保存使用数据
  241. await saveUsageData();
  242. // 发送工具使用记录到自建服务器
  243. sendToServer('tool_used', {
  244. tool_name: toolName,
  245. date: todayStr
  246. });
  247. };
  248. /**
  249. * 定期发送使用摘要数据
  250. */
  251. const scheduleSyncStats = () => {
  252. // 每周发送一次摘要数据
  253. const ONE_WEEK = 7 * 24 * 60 * 60 * 1000;
  254. setInterval(async () => {
  255. // 发送工具使用排名
  256. const toolRanking = Object.entries(usageData.tools)
  257. .sort((a, b) => b[1] - a[1])
  258. .slice(0, 5)
  259. .map(([name, count]) => ({name, count}));
  260. sendToServer('usage_summary', {
  261. top_tools: JSON.stringify(toolRanking)
  262. });
  263. // 清理过旧的日期数据(保留30天数据)
  264. const now = new Date();
  265. const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  266. const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split('T')[0];
  267. Object.keys(usageData.dailyUsage).forEach(date => {
  268. if (date < thirtyDaysAgoStr) {
  269. delete usageData.dailyUsage[date];
  270. }
  271. });
  272. // 保存清理后的数据
  273. await saveUsageData();
  274. }, ONE_WEEK);
  275. };
  276. /**
  277. * 初始化统计模块
  278. */
  279. const init = async () => {
  280. await getUserId();
  281. await loadUsageData();
  282. await recordDailyActiveUser();
  283. scheduleSyncStats();
  284. };
  285. /**
  286. * 获取最近使用的工具(按最近使用时间倒序,默认最近10个)
  287. * @param {number} limit - 返回的最大数量
  288. * @returns {Promise<string[]>} 工具名称数组
  289. */
  290. const getRecentUsedTools = async (limit = 10) => {
  291. // 确保数据已加载
  292. await loadUsageData();
  293. // 收集所有日期,按新到旧排序
  294. const dates = Object.keys(usageData.dailyUsage).sort((a, b) => b.localeCompare(a));
  295. const toolSet = [];
  296. for (const date of dates) {
  297. const tools = Object.keys(usageData.dailyUsage[date].tools || {});
  298. for (const tool of tools) {
  299. if (!toolSet.includes(tool)) {
  300. toolSet.push(tool);
  301. if (toolSet.length >= limit) {
  302. return toolSet;
  303. }
  304. }
  305. }
  306. }
  307. return toolSet;
  308. };
  309. /**
  310. * 获取DashBoard统计数据
  311. * @returns {Promise<Object>} 统计数据对象
  312. */
  313. const getDashboardData = async () => {
  314. await loadUsageData();
  315. // 最近10次使用的工具及时间
  316. const recent = [];
  317. const recentDetail = [];
  318. const dates = Object.keys(usageData.dailyUsage).sort((a, b) => b.localeCompare(a));
  319. for (const date of dates) {
  320. for (const tool of Object.keys(usageData.dailyUsage[date].tools || {})) {
  321. if (!recent.includes(tool)) {
  322. recent.push(tool);
  323. recentDetail.push({ tool, date });
  324. if (recent.length >= 10) break;
  325. }
  326. }
  327. if (recent.length >= 10) break;
  328. }
  329. // 工具使用总次数排行
  330. const mostUsed = Object.entries(usageData.tools)
  331. .sort((a, b) => b[1] - a[1])
  332. .slice(0, 10)
  333. .map(([name, count]) => ({ name, count }));
  334. const totalCount = Object.values(usageData.tools).reduce((a, b) => a + b, 0);
  335. const activeDays = Object.keys(usageData.dailyUsage).length;
  336. const allDates = Object.keys(usageData.dailyUsage).sort();
  337. // 最近10天每日使用情况
  338. const dailyTrend = allDates.slice(-10).map(date => ({
  339. date,
  340. count: Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0)
  341. }));
  342. // 首次和最近活跃日期
  343. const firstDate = allDates[0] || '';
  344. const lastDate = allDates[allDates.length - 1] || '';
  345. // 连续活跃天数
  346. let maxStreak = 0, curStreak = 0, prev = '';
  347. for (let i = 0; i < allDates.length; i++) {
  348. if (i === 0 || (new Date(allDates[i]) - new Date(prev) === 86400000)) {
  349. curStreak++;
  350. } else {
  351. maxStreak = Math.max(maxStreak, curStreak);
  352. curStreak = 1;
  353. }
  354. prev = allDates[i];
  355. }
  356. maxStreak = Math.max(maxStreak, curStreak);
  357. // 本月/本周统计
  358. const now = new Date();
  359. const thisMonth = now.toISOString().slice(0, 7);
  360. const thisWeekMonday = new Date(now.setDate(now.getDate() - now.getDay() + 1)).toISOString().slice(0, 10);
  361. let monthCount = 0, weekCount = 0;
  362. allDates.forEach(date => {
  363. const cnt = Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0);
  364. if (date.startsWith(thisMonth)) monthCount += cnt;
  365. if (date >= thisWeekMonday) weekCount += cnt;
  366. });
  367. // 平均每日使用次数
  368. const avgPerDay = activeDays ? Math.round(totalCount / activeDays * 10) / 10 : 0;
  369. // 最活跃的一天
  370. let maxDay = { date: '', count: 0 };
  371. allDates.forEach(date => {
  372. const cnt = Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0);
  373. if (cnt > maxDay.count) maxDay = { date, count: cnt };
  374. });
  375. // 最近未使用天数
  376. let daysSinceLast = 0;
  377. if (lastDate) {
  378. const diff = Math.floor((new Date() - new Date(lastDate)) / 86400000);
  379. daysSinceLast = diff > 0 ? diff : 0;
  380. }
  381. return {
  382. recent,
  383. recentDetail,
  384. mostUsed,
  385. totalCount,
  386. activeDays,
  387. dailyTrend,
  388. firstDate,
  389. lastDate,
  390. maxStreak,
  391. monthCount,
  392. weekCount,
  393. avgPerDay,
  394. maxDay,
  395. daysSinceLast,
  396. allDates
  397. };
  398. };
  399. return {
  400. init,
  401. recordInstallation,
  402. recordUpdate,
  403. recordToolUsage,
  404. getRecentUsedTools,
  405. getDashboardData,
  406. recordUninstall
  407. };
  408. })();
  409. export default Statistics;