statistics.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. return ''; // 暂时关闭统计
  118. };
  119. /**
  120. * 记录每日活跃用户
  121. * @returns {Promise<void>}
  122. */
  123. const recordDailyActiveUser = async () => {
  124. try {
  125. // 获取上次活跃日期
  126. const lastActiveDate = await Awesome.StorageMgr.get(LAST_ACTIVE_DATE_KEY);
  127. // 如果今天还没有记录,则记录今天的活跃
  128. if (lastActiveDate !== todayStr) {
  129. await Awesome.StorageMgr.set(LAST_ACTIVE_DATE_KEY, todayStr);
  130. // 确保该日期的记录存在
  131. if (!usageData.dailyUsage[todayStr]) {
  132. usageData.dailyUsage[todayStr] = {
  133. date: todayStr,
  134. tools: {}
  135. };
  136. }
  137. // 发送每日活跃记录到自建服务器
  138. sendToServer('daily_active_user', {
  139. date: todayStr
  140. });
  141. }
  142. } catch (error) {
  143. console.error('记录日活跃用户失败:', error);
  144. }
  145. };
  146. /**
  147. * 记录插件安装事件
  148. */
  149. const recordInstallation = async () => {
  150. sendToServer('extension_installed');
  151. };
  152. /**
  153. * 记录插件更新事件
  154. * @param {string} previousVersion - 更新前的版本
  155. */
  156. const recordUpdate = async (previousVersion) => {
  157. sendToServer('extension_updated', {
  158. previous_version: previousVersion
  159. });
  160. };
  161. /**
  162. * 记录插件卸载事件
  163. */
  164. const recordUninstall = async () => {
  165. sendToServer('extension_uninstall');
  166. };
  167. /**
  168. * 记录工具使用情况
  169. * @param {string} toolName - 工具名称
  170. */
  171. const recordToolUsage = async (toolName, params = {}) => {
  172. // 确保今天的记录存在
  173. if (!usageData.dailyUsage[todayStr]) {
  174. usageData.dailyUsage[todayStr] = {
  175. date: todayStr,
  176. tools: {}
  177. };
  178. }
  179. // 增加工具使用计数
  180. if (!usageData.tools[toolName]) {
  181. usageData.tools[toolName] = 0;
  182. }
  183. usageData.tools[toolName]++;
  184. // 增加今天该工具的使用计数
  185. if (!usageData.dailyUsage[todayStr].tools[toolName]) {
  186. usageData.dailyUsage[todayStr].tools[toolName] = 0;
  187. }
  188. usageData.dailyUsage[todayStr].tools[toolName]++;
  189. // 保存使用数据
  190. await saveUsageData();
  191. // 发送工具使用记录到自建服务器
  192. sendToServer('tool_used', {
  193. tool_name: toolName,
  194. date: todayStr,
  195. ...params
  196. });
  197. };
  198. /**
  199. * 定期发送使用摘要数据
  200. */
  201. const scheduleSyncStats = () => {
  202. // 每周发送一次摘要数据
  203. const ONE_WEEK = 7 * 24 * 60 * 60 * 1000;
  204. setInterval(async () => {
  205. // 发送工具使用排名
  206. const toolRanking = Object.entries(usageData.tools)
  207. .sort((a, b) => b[1] - a[1])
  208. .slice(0, 5)
  209. .map(([name, count]) => ({name, count}));
  210. sendToServer('usage_summary', {
  211. top_tools: JSON.stringify(toolRanking)
  212. });
  213. // 清理过旧的日期数据(保留30天数据)
  214. const now = new Date();
  215. const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  216. const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split('T')[0];
  217. Object.keys(usageData.dailyUsage).forEach(date => {
  218. if (date < thirtyDaysAgoStr) {
  219. delete usageData.dailyUsage[date];
  220. }
  221. });
  222. // 保存清理后的数据
  223. await saveUsageData();
  224. }, ONE_WEEK);
  225. };
  226. /**
  227. * 初始化统计模块
  228. */
  229. const init = async () => {
  230. await getUserId();
  231. await loadUsageData();
  232. await recordDailyActiveUser();
  233. scheduleSyncStats();
  234. };
  235. /**
  236. * 获取最近使用的工具(按最近使用时间倒序,默认最近10个)
  237. * @param {number} limit - 返回的最大数量
  238. * @returns {Promise<string[]>} 工具名称数组
  239. */
  240. const getRecentUsedTools = async (limit = 10) => {
  241. // 确保数据已加载
  242. await loadUsageData();
  243. // 收集所有日期,按新到旧排序
  244. const dates = Object.keys(usageData.dailyUsage).sort((a, b) => b.localeCompare(a));
  245. const toolSet = [];
  246. for (const date of dates) {
  247. const tools = Object.keys(usageData.dailyUsage[date].tools || {});
  248. for (const tool of tools) {
  249. if (!toolSet.includes(tool)) {
  250. toolSet.push(tool);
  251. if (toolSet.length >= limit) {
  252. return toolSet;
  253. }
  254. }
  255. }
  256. }
  257. return toolSet;
  258. };
  259. /**
  260. * 获取DashBoard统计数据
  261. * @returns {Promise<Object>} 统计数据对象
  262. */
  263. const getDashboardData = async () => {
  264. await loadUsageData();
  265. // 最近10次使用的工具及时间
  266. const recent = [];
  267. const recentDetail = [];
  268. const dates = Object.keys(usageData.dailyUsage).sort((a, b) => b.localeCompare(a));
  269. for (const date of dates) {
  270. for (const tool of Object.keys(usageData.dailyUsage[date].tools || {})) {
  271. if (!recent.includes(tool)) {
  272. recent.push(tool);
  273. recentDetail.push({ tool, date });
  274. if (recent.length >= 10) break;
  275. }
  276. }
  277. if (recent.length >= 10) break;
  278. }
  279. // 工具使用总次数排行
  280. const mostUsed = Object.entries(usageData.tools)
  281. .sort((a, b) => b[1] - a[1])
  282. .slice(0, 10)
  283. .map(([name, count]) => ({ name, count }));
  284. const totalCount = Object.values(usageData.tools).reduce((a, b) => a + b, 0);
  285. const activeDays = Object.keys(usageData.dailyUsage).length;
  286. const allDates = Object.keys(usageData.dailyUsage).sort();
  287. // 最近10天每日使用情况
  288. const dailyTrend = allDates.slice(-10).map(date => ({
  289. date,
  290. count: Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0)
  291. }));
  292. // 首次和最近活跃日期
  293. const firstDate = allDates[0] || '';
  294. const lastDate = allDates[allDates.length - 1] || '';
  295. // 连续活跃天数
  296. let maxStreak = 0, curStreak = 0, prev = '';
  297. for (let i = 0; i < allDates.length; i++) {
  298. if (i === 0 || (new Date(allDates[i]) - new Date(prev) === 86400000)) {
  299. curStreak++;
  300. } else {
  301. maxStreak = Math.max(maxStreak, curStreak);
  302. curStreak = 1;
  303. }
  304. prev = allDates[i];
  305. }
  306. maxStreak = Math.max(maxStreak, curStreak);
  307. // 本月/本周统计
  308. const now = new Date();
  309. const thisMonth = now.toISOString().slice(0, 7);
  310. const thisWeekMonday = new Date(now.setDate(now.getDate() - now.getDay() + 1)).toISOString().slice(0, 10);
  311. let monthCount = 0, weekCount = 0;
  312. allDates.forEach(date => {
  313. const cnt = Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0);
  314. if (date.startsWith(thisMonth)) monthCount += cnt;
  315. if (date >= thisWeekMonday) weekCount += cnt;
  316. });
  317. // 平均每日使用次数
  318. const avgPerDay = activeDays ? Math.round(totalCount / activeDays * 10) / 10 : 0;
  319. // 最活跃的一天
  320. let maxDay = { date: '', count: 0 };
  321. allDates.forEach(date => {
  322. const cnt = Object.values(usageData.dailyUsage[date].tools || {}).reduce((a, b) => a + b, 0);
  323. if (cnt > maxDay.count) maxDay = { date, count: cnt };
  324. });
  325. // 最近未使用天数
  326. let daysSinceLast = 0;
  327. if (lastDate) {
  328. const diff = Math.floor((new Date() - new Date(lastDate)) / 86400000);
  329. daysSinceLast = diff > 0 ? diff : 0;
  330. }
  331. return {
  332. recent,
  333. recentDetail,
  334. mostUsed,
  335. totalCount,
  336. activeDays,
  337. dailyTrend,
  338. firstDate,
  339. lastDate,
  340. maxStreak,
  341. monthCount,
  342. weekCount,
  343. avgPerDay,
  344. maxDay,
  345. daysSinceLast,
  346. allDates
  347. };
  348. };
  349. return {
  350. init,
  351. recordInstallation,
  352. recordUpdate,
  353. recordToolUsage,
  354. getRecentUsedTools,
  355. getDashboardData,
  356. recordUninstall
  357. };
  358. })();
  359. export default Statistics;