index.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. import Awesome from '../background/awesome.js'
  2. import MSG_TYPE from '../static/js/common.js';
  3. import Settings from './settings.js';
  4. import Statistics from '../background/statistics.js';
  5. import toolMap from '../background/tools.js';
  6. // 工具分类定义
  7. const TOOL_CATEGORIES = [
  8. { key: 'dev', name: '开发工具类', tools: ['json-format', 'json-diff', 'code-beautify', 'code-compress', 'postman', 'websocket', 'regexp','page-timing'] },
  9. { key: 'encode', name: '编解码转换类', tools: ['en-decode', 'trans-radix', 'timestamp', 'trans-color'] },
  10. { key: 'image', name: '图像处理类', tools: ['qr-code', 'image-base64', 'svg-converter', 'chart-maker', 'poster-maker' ,'screenshot', 'color-picker'] },
  11. { key: 'productivity', name: '效率工具类', tools: ['aiagent', 'sticky-notes', 'html2markdown', 'page-monkey'] },
  12. { key: 'calculator', name: '计算工具类', tools: ['crontab', 'loan-rate', 'password'] },
  13. { key: 'other', name: '其他工具', tools: [] }
  14. ];
  15. // Vue实例
  16. new Vue({
  17. el: '#marketContainer',
  18. data: {
  19. manifest: { version: '0.0.0' },
  20. searchKey: '',
  21. currentCategory: '',
  22. sortType: 'default',
  23. viewMode: 'list', // 默认网格视图
  24. categories: TOOL_CATEGORIES,
  25. favorites: new Set(),
  26. recentUsed: [],
  27. loading: true,
  28. originalTools: {}, // 保存原始工具数据
  29. currentView: 'all', // 当前视图类型(all/installed/favorites/recent)
  30. activeTools: {}, // 当前显示的工具列表
  31. installedCount: 0, // 已安装工具数量
  32. // 版本相关
  33. latestVersion: '', // 最新版本号
  34. needUpdate: false, // 是否需要更新
  35. // 设置相关
  36. showSettingsModal: false,
  37. defaultKey: 'Alt+Shift+J', // 默认快捷键
  38. countDown: 0, // 夜间模式倒计时
  39. selectedOpts: [], // 选中的选项
  40. menuDownloadCrx: false, // 菜单-插件下载
  41. menuFeHelperSeting: false, // 菜单-FeHelper设置
  42. isFirefox: false, // 是否Firefox浏览器
  43. // 打赏相关
  44. showDonateModal: false,
  45. donate: {
  46. text: '感谢你对FeHelper的认可和支持!',
  47. image: './donate.jpeg'
  48. },
  49. // 确认对话框
  50. confirmDialog: {
  51. show: false,
  52. title: '操作确认',
  53. message: '',
  54. callback: null,
  55. data: null
  56. },
  57. recentCount: 0,
  58. versionChecked: false,
  59. // 推荐卡片配置,后续可从服务端获取
  60. recommendationCards: [
  61. {
  62. toolKey: 'qr-code',
  63. icon: '📱',
  64. title: '二维码工具',
  65. desc: '快速生成和识别二维码,支持自定义样式',
  66. tag: '必装',
  67. tagClass: 'must-tag',
  68. isAd: false
  69. },
  70. {
  71. toolKey: 'chart-maker',
  72. icon: '📊',
  73. title: '图表制作工具',
  74. desc: '支持多种数据可视化图表,快速生成专业图表',
  75. tag: '最新',
  76. tagClass: 'new-tag',
  77. isAd: false
  78. },
  79. {
  80. toolKey: 'poster-maker',
  81. icon: '🖼️',
  82. title: '海报快速生成',
  83. desc: '快速生成和识别二维码,支持自定义样式',
  84. tag: '推荐',
  85. tagClass: 'recommend-tag',
  86. isAd: false
  87. },
  88. {
  89. icon: '🔔',
  90. title: '推广位',
  91. desc: '广告位招租,欢迎流量主联系,开放合作,流量主请到github联系',
  92. tag: '广告',
  93. tagClass: 'ad-tag',
  94. isAd: true,
  95. url: 'https://github.com/zxlie/FeHelper'
  96. }
  97. ],
  98. },
  99. async created() {
  100. await this.initData();
  101. this.recentCount = (await Statistics.getRecentUsedTools(10)).length;
  102. // 初始化后更新已安装工具数量
  103. this.updateInstalledCount();
  104. // 恢复用户的视图模式设置
  105. this.loadViewMode();
  106. // 加载设置项
  107. this.loadSettings();
  108. // 检查浏览器类型
  109. this.checkBrowserType();
  110. // 检查版本更新
  111. this.checkVersionUpdate();
  112. // 加载远程推荐卡片配置
  113. this.loadRemoteRecommendationCards();
  114. // 检查URL中是否有donate_from参数
  115. this.checkDonateParam();
  116. // 埋点:自动触发options
  117. chrome.runtime.sendMessage({
  118. type: 'fh-dynamic-any-thing',
  119. thing: 'statistics-tool-usage',
  120. params: {
  121. tool_name: 'options'
  122. }
  123. });
  124. },
  125. computed: {
  126. filteredTools() {
  127. if (this.loading) {
  128. return [];
  129. }
  130. // 获取当前工具列表
  131. let result = Object.values(this.activeTools).map(tool => ({
  132. ...tool,
  133. favorite: this.favorites.has(tool.key)
  134. }));
  135. // 搜索过滤
  136. if (this.searchKey) {
  137. const key = this.searchKey.toLowerCase();
  138. result = result.filter(tool =>
  139. tool.name.toLowerCase().includes(key) ||
  140. tool.tips.toLowerCase().includes(key)
  141. );
  142. }
  143. // 分类过滤,在所有视图下生效
  144. if (this.currentCategory) {
  145. const category = TOOL_CATEGORIES.find(c => c.key === this.currentCategory);
  146. const categoryTools = category ? category.tools : [];
  147. result = result.filter(tool => categoryTools.includes(tool.key));
  148. }
  149. // 排序
  150. switch (this.sortType) {
  151. case 'newest':
  152. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  153. break;
  154. case 'hot':
  155. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  156. break;
  157. default:
  158. const allTools = TOOL_CATEGORIES.reduce((acc, category) => {
  159. acc.push(...category.tools);
  160. return acc;
  161. }, []);
  162. result.sort((a, b) => {
  163. const indexA = allTools.indexOf(a.key);
  164. const indexB = allTools.indexOf(b.key);
  165. // 如果工具不在任何类别中,放到最后
  166. if (indexA === -1 && indexB === -1) {
  167. return a.key.localeCompare(b.key); // 字母顺序排序
  168. }
  169. if (indexA === -1) return 1;
  170. if (indexB === -1) return -1;
  171. return indexA - indexB;
  172. });
  173. }
  174. return result;
  175. }
  176. },
  177. methods: {
  178. async initData() {
  179. try {
  180. this.loading = true;
  181. // 获取manifest信息
  182. const manifest = await chrome.runtime.getManifest();
  183. this.manifest = manifest;
  184. // 从 Awesome.getAllTools 获取工具列表
  185. const tools = await Awesome.getAllTools();
  186. // 获取收藏数据
  187. const favorites = await this.getFavoritesData();
  188. this.favorites = new Set(favorites);
  189. // 获取最近使用数据
  190. const recentUsed = await this.getRecentUsedData();
  191. this.recentUsed = recentUsed;
  192. this.recentCount = recentUsed.length;
  193. // 获取已安装工具列表
  194. const installedTools = await Awesome.getInstalledTools();
  195. // 处理工具数据
  196. const processedTools = {};
  197. Object.entries(tools).forEach(([key, tool]) => {
  198. // 检查工具是否已安装
  199. const isInstalled = installedTools.hasOwnProperty(key);
  200. // 检查是否有右键菜单
  201. const hasMenu = tool.menu || false;
  202. processedTools[key] = {
  203. ...tool,
  204. key, // 添加key到工具对象中
  205. updateTime: Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000,
  206. installed: isInstalled, // 使用实时安装状态
  207. inContextMenu: hasMenu, // 使用实时菜单状态
  208. systemInstalled: tool.systemInstalled || false, // 是否系统预装
  209. favorite: this.favorites.has(key)
  210. };
  211. });
  212. this.originalTools = processedTools;
  213. // 初始化activeTools为所有工具
  214. this.activeTools = { ...processedTools };
  215. // 更新"其他工具"类别
  216. this.updateOtherCategory(Object.keys(processedTools));
  217. // 默认选中"全部分类"
  218. this.currentCategory = '';
  219. } catch (error) {
  220. console.error('初始化数据失败:', error);
  221. } finally {
  222. this.loading = false;
  223. }
  224. },
  225. // 更新"其他工具"类别,将未分类的工具添加到此类别
  226. updateOtherCategory(allToolKeys) {
  227. // 获取所有已分类的工具
  228. const categorizedTools = new Set();
  229. TOOL_CATEGORIES.forEach(category => {
  230. if (category.key !== 'other') {
  231. category.tools.forEach(tool => categorizedTools.add(tool));
  232. }
  233. });
  234. // 找出未分类的工具
  235. const uncategorizedTools = allToolKeys.filter(key => !categorizedTools.has(key));
  236. // 更新"其他工具"类别
  237. const otherCategory = TOOL_CATEGORIES.find(category => category.key === 'other');
  238. if (otherCategory) {
  239. otherCategory.tools = uncategorizedTools;
  240. }
  241. },
  242. // 检查版本更新
  243. async checkVersionUpdate() {
  244. try {
  245. // 获取已安装的版本号
  246. const currentVersion = this.manifest.version;
  247. // 尝试从本地存储获取最新版本信息,避免频繁请求
  248. const cachedData = await new Promise(resolve => {
  249. chrome.storage.local.get('fehelper_latest_version_data', data => {
  250. resolve(data.fehelper_latest_version_data || null);
  251. });
  252. });
  253. // 检查是否需要重新获取版本信息:
  254. // 1. 缓存不存在
  255. // 2. 缓存已过期(超过24小时)
  256. // 3. 缓存的当前版本与实际版本不同(说明插件已更新)
  257. const now = Date.now();
  258. const cacheExpired = !cachedData || !cachedData.timestamp || (now - cachedData.timestamp > 24 * 60 * 60 * 1000);
  259. const versionChanged = cachedData && cachedData.currentVersion !== currentVersion;
  260. this.versionChecked = !(cacheExpired || versionChanged);
  261. if (!this.versionChecked) {
  262. try {
  263. // 使用shields.io的JSON API获取最新版本号
  264. const response = await fetch('https://img.shields.io/chrome-web-store/v/pkgccpejnmalmdinmhkkfafefagiiiad.json');
  265. if (!response.ok) {
  266. throw new Error(`HTTP错误:${response.status}`);
  267. }
  268. this.versionChecked = true;
  269. const data = await response.json();
  270. // 提取版本号 - shields.io返回的数据中包含版本信息
  271. let latestVersion = '';
  272. if (data && data.value) {
  273. // 去掉版本号前的'v'字符(如果有)
  274. latestVersion = data.value.replace(/^v/, '');
  275. }
  276. // 比较版本号
  277. const needUpdate = this.compareVersions(currentVersion, latestVersion) < 0;
  278. // 保存到本地存储中
  279. await chrome.storage.local.set({
  280. 'fehelper_latest_version_data': {
  281. timestamp: now,
  282. currentVersion, // 保存当前检查时的版本号
  283. latestVersion,
  284. needUpdate
  285. }
  286. });
  287. this.latestVersion = latestVersion;
  288. this.needUpdate = needUpdate;
  289. } catch (fetchError) {
  290. // 获取失败时不显示更新按钮
  291. this.needUpdate = false;
  292. // 如果是版本变更导致的重新检查,但获取失败,则使用缓存数据
  293. if (versionChanged && cachedData) {
  294. this.latestVersion = cachedData.latestVersion || '';
  295. // 比较新的currentVersion和缓存的latestVersion
  296. this.needUpdate = this.compareVersions(currentVersion, cachedData.latestVersion) < 0;
  297. }
  298. }
  299. } else {
  300. // 使用缓存数据
  301. this.latestVersion = cachedData.latestVersion || '';
  302. this.needUpdate = cachedData.needUpdate || false;
  303. }
  304. } catch (error) {
  305. this.needUpdate = false; // 出错时不显示更新提示
  306. }
  307. },
  308. // 比较版本号:如果v1 < v2返回-1,v1 = v2返回0,v1 > v2返回1
  309. compareVersions(v1, v2) {
  310. // 将版本号拆分为数字数组
  311. const v1Parts = v1.split('.').map(Number);
  312. const v2Parts = v2.split('.').map(Number);
  313. // 计算两个版本号中较长的长度
  314. const maxLength = Math.max(v1Parts.length, v2Parts.length);
  315. // 比较每一部分
  316. for (let i = 0; i < maxLength; i++) {
  317. // 获取当前部分,如果不存在则视为0
  318. const part1 = v1Parts[i] || 0;
  319. const part2 = v2Parts[i] || 0;
  320. // 比较当前部分
  321. if (part1 < part2) return -1;
  322. if (part1 > part2) return 1;
  323. }
  324. // 所有部分都相等
  325. return 0;
  326. },
  327. // 打开Chrome商店页面
  328. openStorePage() {
  329. try {
  330. // 使用Chrome Extension API请求检查更新
  331. // Manifest V3中requestUpdateCheck返回Promise,结果是一个对象而不是数组
  332. chrome.runtime.requestUpdateCheck().then(result => {
  333. // 正确获取status和details,它们是result对象的属性
  334. this.handleUpdateStatus(result.status, result.details);
  335. }).catch(error => {
  336. this.handleUpdateError(error);
  337. });
  338. } catch (error) {
  339. this.handleUpdateError(error);
  340. }
  341. },
  342. // 处理更新状态
  343. handleUpdateStatus(status, details) {
  344. if (status === 'update_available') {
  345. // 显示更新通知
  346. this.showNotification({
  347. title: 'FeHelper 更新',
  348. message: '已发现新版本,正在更新...'
  349. });
  350. // 重新加载扩展以应用更新
  351. setTimeout(() => {
  352. chrome.runtime.reload();
  353. }, 1000);
  354. } else if (status === 'no_update') {
  355. // 如果没有可用更新,但用户点击了更新按钮
  356. this.showNotification({
  357. title: 'FeHelper 更新',
  358. message: '您的FeHelper已经是最新版本。'
  359. });
  360. } else {
  361. // 其他情况,如更新检查失败等
  362. // 备选方案:跳转到官方网站
  363. chrome.tabs.create({
  364. url: 'https://baidufe.com/fehelper'
  365. });
  366. this.showNotification({
  367. title: 'FeHelper 更新',
  368. message: '自动更新失败,请访问FeHelper官网手动获取最新版本。'
  369. });
  370. }
  371. },
  372. // 处理更新错误
  373. handleUpdateError(error) {
  374. // 出错时跳转到官方网站
  375. chrome.tabs.create({
  376. url: 'https://baidufe.com/fehelper'
  377. });
  378. this.showNotification({
  379. title: 'FeHelper 更新错误',
  380. message: '更新过程中出现错误,请手动检查更新。'
  381. });
  382. },
  383. // 显示通知的统一方法
  384. showNotification(options) {
  385. try {
  386. // 定义通知ID,方便后续关闭
  387. const notificationId = 'fehelper-update-notification';
  388. const simpleNotificationId = 'fehelper-simple-notification';
  389. // 直接尝试创建通知,不检查权限
  390. // Chrome扩展在manifest中已声明notifications权限,应该可以直接使用
  391. const notificationOptions = {
  392. type: 'basic',
  393. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  394. title: options.title || 'FeHelper',
  395. message: options.message || '',
  396. priority: 2,
  397. requireInteraction: false, // 改为false,因为我们会手动关闭
  398. silent: false // 播放音效
  399. };
  400. // 首先尝试直接创建通知
  401. chrome.notifications.create(notificationId, notificationOptions, (createdId) => {
  402. const error = chrome.runtime.lastError;
  403. if (error) {
  404. // 通知创建失败,尝试使用alert作为备选方案
  405. alert(`${options.title}: ${options.message}`);
  406. // 再尝试使用不同的选项创建通知
  407. const simpleOptions = {
  408. type: 'basic',
  409. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  410. title: options.title || 'FeHelper',
  411. message: options.message || ''
  412. };
  413. // 使用简化选项再次尝试
  414. chrome.notifications.create(simpleNotificationId, simpleOptions, (simpleId) => {
  415. if (chrome.runtime.lastError) {
  416. console.error('简化通知创建也失败:', chrome.runtime.lastError);
  417. } else {
  418. // 3秒后自动关闭简化通知
  419. setTimeout(() => {
  420. chrome.notifications.clear(simpleId);
  421. }, 3000);
  422. }
  423. });
  424. } else {
  425. // 3秒后自动关闭通知
  426. setTimeout(() => {
  427. chrome.notifications.clear(createdId);
  428. }, 3000);
  429. }
  430. });
  431. // 同时使用内置UI显示消息
  432. this.showInPageNotification(options);
  433. } catch (error) {
  434. // 降级为alert
  435. alert(`${options.title}: ${options.message}`);
  436. }
  437. },
  438. // 在页面内显示通知消息
  439. showInPageNotification(options) {
  440. try {
  441. // 创建一个通知元素
  442. const notificationEl = document.createElement('div');
  443. notificationEl.className = 'in-page-notification';
  444. notificationEl.innerHTML = `
  445. <div class="notification-content">
  446. <div class="notification-title">${options.title || 'FeHelper'}</div>
  447. <div class="notification-message">${options.message || ''}</div>
  448. </div>
  449. <button class="notification-close">×</button>
  450. `;
  451. // 添加样式
  452. const style = document.createElement('style');
  453. style.textContent = `
  454. .in-page-notification {
  455. position: fixed;
  456. bottom: 20px;
  457. right: 20px;
  458. background-color: #4285f4;
  459. color: white;
  460. padding: 15px;
  461. border-radius: 8px;
  462. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  463. z-index: 9999;
  464. display: flex;
  465. align-items: center;
  466. justify-content: space-between;
  467. min-width: 300px;
  468. animation: slideIn 0.3s ease-out;
  469. }
  470. .notification-content {
  471. flex: 1;
  472. }
  473. .notification-title {
  474. font-weight: bold;
  475. margin-bottom: 5px;
  476. }
  477. .notification-message {
  478. font-size: 14px;
  479. }
  480. .notification-close {
  481. background: none;
  482. border: none;
  483. color: white;
  484. font-size: 20px;
  485. cursor: pointer;
  486. margin-left: 10px;
  487. padding: 0 5px;
  488. }
  489. @keyframes slideIn {
  490. from { transform: translateX(100%); opacity: 0; }
  491. to { transform: translateX(0); opacity: 1; }
  492. }
  493. @keyframes slideOut {
  494. from { transform: translateX(0); opacity: 1; }
  495. to { transform: translateX(100%); opacity: 0; }
  496. }
  497. `;
  498. // 添加到页面
  499. document.head.appendChild(style);
  500. document.body.appendChild(notificationEl);
  501. // 点击关闭按钮移除通知
  502. const closeBtn = notificationEl.querySelector('.notification-close');
  503. if (closeBtn) {
  504. closeBtn.addEventListener('click', () => {
  505. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  506. notificationEl.addEventListener('animationend', () => {
  507. notificationEl.remove();
  508. });
  509. });
  510. }
  511. // 3秒后自动移除(从5秒改为3秒)
  512. setTimeout(() => {
  513. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  514. notificationEl.addEventListener('animationend', () => {
  515. notificationEl.remove();
  516. });
  517. }, 3000);
  518. } catch (error) {
  519. console.error('创建页内通知出错:', error);
  520. }
  521. },
  522. async getFavoritesData() {
  523. return new Promise((resolve) => {
  524. chrome.storage.local.get('favorites', (result) => {
  525. resolve(result.favorites || []);
  526. });
  527. });
  528. },
  529. async getRecentUsedData() {
  530. // 直接从Statistics模块获取最近使用的工具
  531. return await Statistics.getRecentUsedTools(10);
  532. },
  533. async saveFavorites() {
  534. try {
  535. await chrome.storage.local.set({
  536. favorites: Array.from(this.favorites)
  537. });
  538. // 更新工具的收藏状态
  539. Object.keys(this.originalTools).forEach(key => {
  540. this.originalTools[key].favorite = this.favorites.has(key);
  541. });
  542. } catch (error) {
  543. console.error('保存收藏失败:', error);
  544. }
  545. },
  546. handleSearch() {
  547. // 搜索时不重置视图类型,允许在已过滤的结果中搜索
  548. },
  549. handleCategoryChange(category) {
  550. // 切换到全部工具视图
  551. if (this.currentView !== 'all') {
  552. this.currentView = 'all';
  553. this.updateActiveTools('all');
  554. }
  555. this.currentCategory = category;
  556. this.searchKey = '';
  557. // 确保工具显示正确
  558. this.activeTools = { ...this.originalTools };
  559. },
  560. handleSort() {
  561. // 排序逻辑已在computed中实现
  562. },
  563. getCategoryCount(categoryKey) {
  564. const category = TOOL_CATEGORIES.find(c => c.key === categoryKey);
  565. const categoryTools = category ? category.tools : [];
  566. return categoryTools.length;
  567. },
  568. async getInstalledCount() {
  569. try {
  570. // 使用Awesome.getInstalledTools实时获取已安装工具数量
  571. const installedTools = await Awesome.getInstalledTools();
  572. return Object.keys(installedTools).length;
  573. } catch (error) {
  574. // 回退到本地数据
  575. return Object.values(this.originalTools).filter(tool =>
  576. tool.installed || tool.systemInstalled || false
  577. ).length;
  578. }
  579. },
  580. getFavoritesCount() {
  581. return this.favorites.size;
  582. },
  583. getToolCategory(toolKey) {
  584. for (const category of TOOL_CATEGORIES) {
  585. if (category.tools.includes(toolKey)) {
  586. return category.key;
  587. }
  588. }
  589. return 'other';
  590. },
  591. async showMyInstalled() {
  592. this.currentView = 'installed';
  593. this.currentCategory = '';
  594. this.searchKey = '';
  595. await this.updateActiveTools('installed');
  596. // 更新已安装工具数量
  597. await this.updateInstalledCount();
  598. },
  599. showMyFavorites() {
  600. this.currentView = 'favorites';
  601. this.currentCategory = '';
  602. this.searchKey = '';
  603. this.updateActiveTools('favorites');
  604. },
  605. // 重置工具列表到原始状态
  606. resetTools() {
  607. this.currentView = 'all';
  608. },
  609. // 安装工具
  610. async installTool(toolKey) {
  611. try {
  612. // 查找可能存在的按钮元素
  613. const btnElement = document.querySelector(`button[data-tool="${toolKey}"]`);
  614. let elProgress = null;
  615. // 如果是通过按钮点击调用的,获取进度条元素
  616. if (btnElement) {
  617. if (btnElement.getAttribute('data-undergoing') === '1') {
  618. return false;
  619. }
  620. btnElement.setAttribute('data-undergoing', '1');
  621. elProgress = btnElement.querySelector('span.x-progress');
  622. }
  623. // 显示安装进度
  624. let pt = 1;
  625. await Awesome.install(toolKey);
  626. // 只有当进度条元素存在时才更新文本内容
  627. if (elProgress) {
  628. elProgress.textContent = `(${pt}%)`;
  629. let ptInterval = setInterval(() => {
  630. elProgress.textContent = `(${pt}%)`;
  631. pt += Math.floor(Math.random() * 20);
  632. if(pt > 100) {
  633. clearInterval(ptInterval);
  634. elProgress.textContent = ``;
  635. // 在进度条完成后显示安装成功的通知
  636. this.showInPageNotification({
  637. message: `${this.originalTools[toolKey].name} 安装成功!`,
  638. type: 'success',
  639. duration: 3000
  640. });
  641. }
  642. }, 100);
  643. } else {
  644. // 如果没有进度条元素,直接显示通知
  645. this.showInPageNotification({
  646. message: `${this.originalTools[toolKey].name} 安装成功!`,
  647. type: 'success',
  648. duration: 3000
  649. });
  650. }
  651. // 更新原始数据和当前活动数据
  652. this.originalTools[toolKey].installed = true;
  653. if (this.activeTools[toolKey]) {
  654. this.activeTools[toolKey].installed = true;
  655. }
  656. // 更新已安装工具数量
  657. this.updateInstalledCount();
  658. // 如果按钮存在,更新其状态
  659. if (btnElement) {
  660. btnElement.setAttribute('data-undergoing', '0');
  661. }
  662. // 发送消息通知后台更新
  663. chrome.runtime.sendMessage({
  664. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  665. toolName: toolKey,
  666. action: 'install',
  667. showTips: true
  668. });
  669. } catch (error) {
  670. // 显示安装失败的通知
  671. this.showInPageNotification({
  672. message: `安装失败:${error.message || '未知错误'}`,
  673. type: 'error',
  674. duration: 5000
  675. });
  676. }
  677. },
  678. // 卸载工具
  679. async uninstallTool(toolKey) {
  680. try {
  681. // 使用自定义确认对话框而非浏览器原生的confirm
  682. this.showConfirm({
  683. title: '卸载确认',
  684. message: `确定要卸载"${this.originalTools[toolKey].name}"工具吗?`,
  685. callback: async (key) => {
  686. try {
  687. await chrome.runtime.sendMessage({
  688. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  689. toolName: key,
  690. action: 'offload',
  691. showTips: true
  692. });
  693. // 调用Awesome.offLoad卸载工具
  694. await Awesome.offLoad(key);
  695. // 更新原始数据和当前活动数据
  696. this.originalTools[key].installed = false;
  697. this.originalTools[key].inContextMenu = false;
  698. if (this.activeTools[key]) {
  699. this.activeTools[key].installed = false;
  700. this.activeTools[key].inContextMenu = false;
  701. }
  702. // 更新已安装工具数量
  703. this.updateInstalledCount();
  704. // 显示卸载成功的通知
  705. this.showInPageNotification({
  706. message: `${this.originalTools[key].name} 已成功卸载!`,
  707. type: 'success',
  708. duration: 3000
  709. });
  710. } catch (error) {
  711. // 显示卸载失败的通知
  712. this.showInPageNotification({
  713. message: `卸载失败:${error.message || '未知错误'}`,
  714. type: 'error',
  715. duration: 5000
  716. });
  717. }
  718. },
  719. data: toolKey
  720. });
  721. } catch (error) {
  722. console.error('准备卸载过程中出错:', error);
  723. }
  724. },
  725. // 切换右键菜单
  726. async toggleContextMenu(toolKey) {
  727. try {
  728. const tool = this.originalTools[toolKey];
  729. const newState = !tool.inContextMenu;
  730. // 更新菜单状态
  731. await Awesome.menuMgr(toolKey, newState ? 'install' : 'offload');
  732. // 更新原始数据和当前活动数据
  733. tool.inContextMenu = newState;
  734. if (this.activeTools[toolKey]) {
  735. this.activeTools[toolKey].inContextMenu = newState;
  736. }
  737. // 发送消息通知后台更新右键菜单
  738. chrome.runtime.sendMessage({
  739. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  740. action: `menu-${newState ? 'install' : 'offload'}`,
  741. showTips: false,
  742. menuOnly: true
  743. });
  744. } catch (error) {
  745. console.error('切换右键菜单失败:', error);
  746. }
  747. },
  748. // 切换收藏状态
  749. async toggleFavorite(toolKey) {
  750. try {
  751. if (this.favorites.has(toolKey)) {
  752. this.favorites.delete(toolKey);
  753. // 更新原始数据和当前活动数据
  754. this.originalTools[toolKey].favorite = false;
  755. if (this.activeTools[toolKey]) {
  756. this.activeTools[toolKey].favorite = false;
  757. }
  758. } else {
  759. this.favorites.add(toolKey);
  760. // 更新原始数据和当前活动数据
  761. this.originalTools[toolKey].favorite = true;
  762. if (this.activeTools[toolKey]) {
  763. this.activeTools[toolKey].favorite = true;
  764. }
  765. }
  766. await this.saveFavorites();
  767. // 如果是在收藏视图,需要更新视图
  768. if (this.currentView === 'favorites') {
  769. this.updateActiveTools('favorites');
  770. }
  771. } catch (error) {
  772. console.error('切换收藏状态失败:', error);
  773. }
  774. },
  775. async updateActiveTools(view) {
  776. if (this.loading || Object.keys(this.originalTools).length === 0) {
  777. return;
  778. }
  779. switch (view) {
  780. case 'installed':
  781. // 使用Awesome.getInstalledTools实时获取已安装工具
  782. try {
  783. const installedTools = await Awesome.getInstalledTools();
  784. // 合并installedTools与originalTools的数据
  785. this.activeTools = Object.fromEntries(
  786. Object.entries(this.originalTools).filter(([key]) =>
  787. installedTools.hasOwnProperty(key)
  788. )
  789. );
  790. } catch (error) {
  791. // 回退到本地数据
  792. this.activeTools = Object.fromEntries(
  793. Object.entries(this.originalTools).filter(([_, tool]) =>
  794. tool.installed || tool.systemInstalled || false
  795. )
  796. );
  797. }
  798. break;
  799. case 'favorites':
  800. this.activeTools = Object.fromEntries(
  801. Object.entries(this.originalTools).filter(([key]) => this.favorites.has(key))
  802. );
  803. break;
  804. case 'recent':
  805. // 切换recent时,recentUsed已在showRecentUsed中实时拉取
  806. this.activeTools = Object.fromEntries(
  807. Object.entries(this.originalTools).filter(([key]) => this.recentUsed.includes(key))
  808. );
  809. break;
  810. case 'all':
  811. default:
  812. this.activeTools = { ...this.originalTools };
  813. // 分类过滤在computed属性中处理
  814. break;
  815. }
  816. },
  817. // 新增更新已安装工具数量的方法
  818. async updateInstalledCount() {
  819. this.installedCount = await this.getInstalledCount();
  820. },
  821. // 加载用户保存的视图模式
  822. async loadViewMode() {
  823. try {
  824. const result = await new Promise(resolve => {
  825. chrome.storage.local.get('fehelper_view_mode', result => {
  826. resolve(result.fehelper_view_mode);
  827. });
  828. });
  829. if (result) {
  830. this.viewMode = result;
  831. }
  832. } catch (error) {
  833. console.error('加载视图模式失败:', error);
  834. }
  835. },
  836. // 保存用户的视图模式选择
  837. async saveViewMode(mode) {
  838. try {
  839. this.viewMode = mode;
  840. await chrome.storage.local.set({
  841. 'fehelper_view_mode': mode
  842. });
  843. } catch (error) {
  844. console.error('保存视图模式失败:', error);
  845. }
  846. },
  847. // 加载设置项
  848. async loadSettings() {
  849. try {
  850. Settings.getOptions(async (opts) => {
  851. let selectedOpts = [];
  852. Object.keys(opts).forEach(key => {
  853. if(String(opts[key]) === 'true') {
  854. selectedOpts.push(key);
  855. }
  856. });
  857. this.selectedOpts = selectedOpts;
  858. // 加载右键菜单设置
  859. this.menuDownloadCrx = await Awesome.menuMgr('download-crx', 'get') === '1';
  860. this.menuFeHelperSeting = await Awesome.menuMgr('fehelper-setting', 'get') !== '0';
  861. // 获取快捷键
  862. chrome.commands.getAll((commands) => {
  863. for (let command of commands) {
  864. if (command.name === '_execute_action') {
  865. this.defaultKey = command.shortcut || 'Alt+Shift+J';
  866. break;
  867. }
  868. }
  869. });
  870. });
  871. } catch (error) {
  872. console.error('加载设置项失败:', error);
  873. }
  874. },
  875. // 检查浏览器类型
  876. checkBrowserType() {
  877. try {
  878. this.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  879. } catch (error) {
  880. this.isFirefox = false;
  881. }
  882. },
  883. // 显示设置模态框
  884. showSettings() {
  885. this.showSettingsModal = true;
  886. },
  887. // 关闭设置模态框
  888. closeSettings() {
  889. this.showSettingsModal = false;
  890. },
  891. // 显示打赏模态框
  892. openDonateModal() {
  893. this.showDonateModal = true;
  894. },
  895. // 关闭打赏模态框
  896. closeDonateModal() {
  897. this.showDonateModal = false;
  898. },
  899. // 显示确认对话框
  900. showConfirm(options) {
  901. this.confirmDialog = {
  902. show: true,
  903. title: options.title || '操作确认',
  904. message: options.message || '确定要执行此操作吗?',
  905. callback: options.callback || null,
  906. data: options.data || null
  907. };
  908. },
  909. // 确认操作
  910. confirmAction() {
  911. if (this.confirmDialog.callback) {
  912. this.confirmDialog.callback(this.confirmDialog.data);
  913. }
  914. this.confirmDialog.show = false;
  915. },
  916. // 取消确认
  917. cancelConfirm() {
  918. this.confirmDialog.show = false;
  919. },
  920. // 保存设置
  921. async saveSettings() {
  922. try {
  923. // 构建设置对象
  924. let opts = {};
  925. ['OPT_ITEM_CONTEXTMENUS', 'FORBID_OPEN_IN_NEW_TAB', 'CONTENT_SCRIPT_ALLOW_ALL_FRAMES',
  926. 'JSON_PAGE_FORMAT', 'AUTO_DARK_MODE', 'ALWAYS_DARK_MODE'].forEach(key => {
  927. opts[key] = this.selectedOpts.includes(key).toString();
  928. });
  929. // 保存设置 - 直接传递对象,settings.js已增加对对象类型的支持
  930. Settings.setOptions(opts, async () => {
  931. try {
  932. // 处理右键菜单
  933. const crxAction = this.menuDownloadCrx ? 'install' : 'offload';
  934. const settingAction = this.menuFeHelperSeting ? 'install' : 'offload';
  935. await Promise.all([
  936. Awesome.menuMgr('download-crx', crxAction),
  937. Awesome.menuMgr('fehelper-setting', settingAction)
  938. ]);
  939. // 通知后台更新右键菜单
  940. chrome.runtime.sendMessage({
  941. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  942. action: 'menu-change',
  943. menuOnly: true
  944. });
  945. // 关闭弹窗
  946. this.closeSettings();
  947. // 显示提示
  948. this.showNotification({
  949. title: 'FeHelper 设置',
  950. message: '设置已保存!'
  951. });
  952. } catch (innerError) {
  953. this.showNotification({
  954. title: 'FeHelper 设置错误',
  955. message: '保存菜单设置失败: ' + innerError.message
  956. });
  957. }
  958. });
  959. } catch (error) {
  960. this.showNotification({
  961. title: 'FeHelper 设置错误',
  962. message: '保存设置失败: ' + error.message
  963. });
  964. }
  965. },
  966. // 设置快捷键
  967. setShortcuts() {
  968. chrome.tabs.create({
  969. url: 'chrome://extensions/shortcuts'
  970. });
  971. },
  972. // 体验夜间模式
  973. turnLight(event) {
  974. event.preventDefault();
  975. // 获取body元素
  976. const body = document.body;
  977. // 切换夜间模式
  978. if (body.classList.contains('dark-mode')) {
  979. body.classList.remove('dark-mode');
  980. } else {
  981. body.classList.add('dark-mode');
  982. // 设置倒计时
  983. this.countDown = 10;
  984. // 启动倒计时
  985. const timer = setInterval(() => {
  986. this.countDown--;
  987. if (this.countDown <= 0) {
  988. clearInterval(timer);
  989. body.classList.remove('dark-mode');
  990. }
  991. }, 1000);
  992. }
  993. },
  994. // 检查URL中的donate_from参数并显示打赏弹窗
  995. checkDonateParam() {
  996. try {
  997. const urlParams = new URLSearchParams(window.location.search);
  998. const donateFrom = urlParams.get('donate_from');
  999. if (donateFrom) {
  1000. // 记录打赏来源
  1001. chrome.storage.local.set({
  1002. 'fehelper_donate_from': donateFrom,
  1003. 'fehelper_donate_time': Date.now()
  1004. });
  1005. // 等待工具数据加载完成
  1006. this.$nextTick(() => {
  1007. // 在所有工具中查找匹配项
  1008. let matchedTool = null;
  1009. // 首先尝试直接匹配工具key
  1010. if (this.originalTools && this.originalTools[donateFrom]) {
  1011. matchedTool = this.originalTools[donateFrom];
  1012. } else if (this.originalTools) {
  1013. // 如果没有直接匹配,尝试在所有工具中查找部分匹配
  1014. for (const [key, tool] of Object.entries(this.originalTools)) {
  1015. if (key.includes(donateFrom) || donateFrom.includes(key) ||
  1016. (tool.name && tool.name.includes(donateFrom)) ||
  1017. (donateFrom && donateFrom.includes(tool.name))) {
  1018. matchedTool = tool;
  1019. break;
  1020. }
  1021. }
  1022. }
  1023. // 更新打赏文案
  1024. if (matchedTool) {
  1025. this.donate.text = `看起来【${matchedTool.name}】工具帮助到了你,感谢你的认可!`;
  1026. } else {
  1027. // 没有匹配到特定工具,使用通用文案
  1028. this.donate.text = `感谢你对FeHelper的认可和支持!`;
  1029. }
  1030. // 显示打赏弹窗
  1031. this.showDonateModal = true;
  1032. });
  1033. // 埋点:自动触发options
  1034. chrome.runtime.sendMessage({
  1035. type: 'fh-dynamic-any-thing',
  1036. thing: 'statistics-tool-usage',
  1037. params: {
  1038. tool_name: 'donate'
  1039. }
  1040. });
  1041. }
  1042. } catch (error) {
  1043. console.error('处理打赏参数时出错:', error);
  1044. }
  1045. },
  1046. // 补充 getRecentCount,保证模板调用不报错,且数据源唯一
  1047. async getRecentCount() {
  1048. const recent = await Statistics.getRecentUsedTools(10);
  1049. return recent.length;
  1050. },
  1051. async showRecentUsed() {
  1052. this.currentView = 'recent';
  1053. this.currentCategory = '';
  1054. this.searchKey = '';
  1055. // 重新获取最近使用的工具数据
  1056. this.recentUsed = await Statistics.getRecentUsedTools(10);
  1057. this.recentCount = this.recentUsed.length;
  1058. // activeTools会通过currentView的watcher自动更新
  1059. },
  1060. handleRecommendClick(card) {
  1061. if (card.isAd && card.url) {
  1062. window.open(card.url, '_blank');
  1063. } else if (card.toolKey) {
  1064. this.installTool(card.toolKey);
  1065. }
  1066. },
  1067. // 加载远程推荐卡片配置
  1068. async loadRemoteRecommendationCards() {
  1069. try {
  1070. // 通过background代理请求,解决CORS问题
  1071. const result = await new Promise((resolve) => {
  1072. chrome.runtime.sendMessage({
  1073. type: 'fh-dynamic-any-thing',
  1074. thing: 'fetch-hotfix-json',
  1075. }, resolve);
  1076. });
  1077. if (!result || !result.success) {
  1078. throw new Error('获取远程配置失败: ' + (result && result.error ? result.error : '未知错误'));
  1079. }
  1080. // 获取脚本内容
  1081. const scriptContent = result.content;
  1082. // 解析脚本内容,提取GlobalRecommendationCards变量
  1083. let remoteCards = null;
  1084. try {
  1085. remoteCards = JSON.parse(scriptContent);
  1086. } catch (parseError) {
  1087. console.error('解析远程推荐卡片配置失败:', parseError);
  1088. }
  1089. // 如果成功解析到配置,则更新本地配置
  1090. if (remoteCards && Array.isArray(remoteCards) && remoteCards.length > 0) {
  1091. this.recommendationCards = remoteCards;
  1092. }
  1093. } catch (error) {
  1094. console.error('获取远程推荐卡片配置失败:', error);
  1095. }
  1096. },
  1097. },
  1098. watch: {
  1099. // 监听currentView变化
  1100. currentView: {
  1101. immediate: true,
  1102. handler(newView) {
  1103. this.updateActiveTools(newView);
  1104. }
  1105. },
  1106. // 监听currentCategory变化
  1107. currentCategory: {
  1108. handler(newCategory) {
  1109. // 保证在视图模式之外的分类切换也能正确显示
  1110. if (this.currentView === 'all') {
  1111. this.activeTools = { ...this.originalTools };
  1112. }
  1113. // 重置搜索条件
  1114. if (this.searchKey) {
  1115. this.searchKey = '';
  1116. }
  1117. }
  1118. },
  1119. },
  1120. });
  1121. // 添加滚动事件监听
  1122. window.addEventListener('scroll', () => {
  1123. const header = document.querySelector('.market-header');
  1124. const sidebar = document.querySelector('.market-sidebar');
  1125. if (window.scrollY > 10) {
  1126. header.classList.add('scrolled');
  1127. sidebar && sidebar.classList.add('scrolled');
  1128. } else {
  1129. header.classList.remove('scrolled');
  1130. sidebar && sidebar.classList.remove('scrolled');
  1131. }
  1132. });
  1133. // 页面加载后自动采集
  1134. if (window.chrome && chrome.runtime && chrome.runtime.sendMessage) {
  1135. Awesome.collectAndSendClientInfo();
  1136. }