statistics.js 14 KB

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