Compare commits

...

193 Commits

Author SHA1 Message Date
lencx
fe4f231d48
Merge pull request #1226 from lencx/lencx-patch-4
chore: add Noi
2024-03-11 19:13:34 +08:00
lencx
78b6f9349c
chore: add Noi 2024-03-11 19:13:23 +08:00
lencx
e547ef6c67
Merge pull request #1172 from wubaiqing/main
fix: brew cask version number
2024-03-11 10:52:21 +08:00
lencx
8cf623c7cc
Merge pull request #1223 from webbertakken/patch-1
fix: couple of typos in about
2024-03-11 10:52:08 +08:00
Webber Takken
fc5aa6a650
fix: couple of typos in about 2024-03-10 19:35:50 +01:00
lencx
1c97623156
Merge pull request #1200 from lencx/lencx-patch-3
add Noi
2024-01-29 18:34:14 +08:00
lencx
f9e75ffb2c
add Noi 2024-01-29 18:33:57 +08:00
wubaiqing
ef2bed4996
fix: brew cask version number 2023-12-13 17:25:43 +08:00
lencx
fac5a4399e v1.1.0 2023-08-03 21:30:37 +08:00
lencx
1a53fe62b8 release 2023-08-03 21:29:53 +08:00
lencx
ca1949f502 fix: layout 2023-08-03 21:24:31 +08:00
lencx
c8a79ea0bb
Merge pull request #1017 from djdarcy/main 2023-08-03 16:25:27 +08:00
Dustin Darcy
c68f1ab45b Modifying *all* <code> blocks to remove whitespace after <code>
to fix improper markdown formatting.
2023-07-29 11:23:48 -04:00
Dustin Darcy
f5491b4b15 Swapping all spaces with global &nbsp (non-blocking spaces) causes
issues with word-wrap. To solve this we now only have nbsp when we
encounter spaces or a tab at the start of a line (to maintain indentation).

A fiddle exists to test the regex at:
https://jsfiddle.net/xtraeme/x34ao9jp/13/
2023-07-27 16:09:35 -04:00
Dustin Darcy
66a0dafbc6 Improved exportMarkdown() & getName() to better preserve user input:
* Maintains proper carriage returns in markdown output
* Indented spaces / tabs are converted to &nbsp; then run through ExportMD

Also added stub code to improve readability of exported filenames, but this will likely also require changes to some of the Rust code
2023-07-27 02:31:31 -04:00
lencx
119570c4d0 chore: remove gpt4 mobile 2023-07-20 13:34:23 +08:00
lencx
bcec5775bb fix: export 2023-07-08 15:48:10 +08:00
lencx
5608bf6eb2 fix: export 2023-07-08 15:14:10 +08:00
lencx
7023b04dd2 fix: export icons 2023-07-08 11:10:24 +08:00
lencx
af77ee74b5
Merge pull request #988 from lencx/lencx-patch-3 2023-07-05 22:50:06 +08:00
lencx
85331de85b
readme 2023-07-05 22:49:55 +08:00
lencx
c499ba37bd fix: auto continue 2023-07-05 19:11:14 +08:00
lencx
94d27f0d24 feat: auto continue 2023-07-05 18:28:36 +08:00
lencx
beafad8174
Merge pull request #985 from lencx/lencx-patch-2 2023-07-05 11:27:34 +08:00
lencx
90e0659ffd
readme 2023-07-05 11:27:22 +08:00
lencx
25ca555ec4
Merge pull request #984 from asheroto/main 2023-07-04 14:02:47 +08:00
asheroto
bea27ac0af
Update bug_report.yml
Fix hyperlink
2023-07-01 00:21:25 -05:00
asheroto
3828a56fa6
Update bug_report.yml
Remove link from checkbox label
2023-07-01 00:20:42 -05:00
asheroto
ba0f7c6a82
Update bug_report.yml
Fix spacing bug
2023-07-01 00:20:15 -05:00
asheroto
81ebb7ed4f
Update bug_report.yml
Fix
2023-07-01 00:17:13 -05:00
asheroto
63928b08d2
Update bug_report.yml
Fix tabbing
2023-07-01 00:15:52 -05:00
asheroto
c44b8cc37a
Update bug_report.yml
Fix tabbing
2023-07-01 00:13:17 -05:00
asheroto
62559ad353
Update bug_report.yml 2023-07-01 00:07:28 -05:00
lencx
ce6344b534 fix: mac titlebar 2023-07-01 00:22:58 +08:00
lencx
00aa242c2a
Merge pull request #979 from tk103331/main 2023-06-30 23:59:19 +08:00
tk103331
1e4c1de971 fix: ui adaptation for no titlebar 2023-06-28 15:34:39 +08:00
lencx
b0bb6e201e readme 2023-06-02 00:21:05 +08:00
lencx
6245f73733 readme 2023-06-01 21:10:27 +08:00
lencx
87c01e3568 chore: manifest 2023-06-01 19:33:59 +08:00
lencx
26cf448e48 feat: GPT-4-Mobile 2023-06-01 19:24:14 +08:00
lencx
d9c83fd084 feat: GPT-4-Mobile 2023-06-01 19:15:35 +08:00
lencx
2b03c2ccde fix: log 2023-05-29 12:43:19 +08:00
lencx
0a88431965
Merge pull request #918 from karbassi/patch-1 2023-05-26 16:16:11 +08:00
Ali Karbassi
25dd7aaca3
Update Brewfile to 1.0.0 2023-05-25 10:24:48 -05:00
lencx
fc27ae21ac fix: cmd 2023-05-25 22:34:43 +08:00
lencx
f501607355 Merge branch 'main' of github.com:lencx/ChatGPT 2023-05-25 14:37:29 +08:00
lencx
b904b1e255 fix: export pdf 2023-05-25 14:37:14 +08:00
lencx
59afd74879
Merge pull request #914 from lencx/lencx-patch-1 2023-05-25 14:29:17 +08:00
lencx
2d18d7f457
fix: export.js 2023-05-25 14:29:07 +08:00
lencx
76c10e3662
Merge pull request #912 from lencx/dev 2023-05-25 13:24:45 +08:00
lencx
35e0b9ce66 v1.0.0 2023-05-25 13:05:48 +08:00
lencx
f50dd4fc6a chore: style 2023-05-25 13:04:59 +08:00
lencx
55eb719e5c v1.0.0 2023-05-25 12:41:44 +08:00
lencx
2fc0983860 readme 2023-05-25 12:40:51 +08:00
lencx
8ec4cedc1e chore: style 2023-05-25 12:34:35 +08:00
lencx
ee0829d8db chore: scripts 2023-05-25 09:52:33 +08:00
lencx
882593479b refactor: prompts 2023-05-23 01:33:24 +08:00
lencx
c53524b472 refactor: prompts 2023-05-22 01:59:50 +08:00
lencx
dd91f0f1f2 merge 2023-05-18 15:45:43 +08:00
lencx
de5c8f0f87 chore: scripts 2023-05-18 15:41:13 +08:00
lencx
19ee629517 chore: scripts 2023-05-18 15:34:13 +08:00
lencx
d9612d3bed refactor: conf 2023-05-18 15:32:32 +08:00
lencx
60b7e3148a Merge branch 'main' into dev 2023-04-12 21:18:28 +08:00
lencx
da1e66bb9f chore: config 2023-04-12 21:15:49 +08:00
lencx
73d3b145ad
Merge pull request #723 from cauyxy/main 2023-03-28 11:56:48 +08:00
Xinyu Yang
ac60dbd5ee
Change tray window position position
Change tray window position from center to fixed center on left click event
2023-03-28 11:26:25 +08:00
lencx
9cb4009ec2 Merge branch 'main' into dev 2023-03-26 00:55:58 +08:00
lencx
e99ba830d8
Merge pull request #697 from shengwusuoxi/shengwusuoxi-patch-1 2023-03-26 00:53:39 +08:00
Luke Tang
a6b4e7fa82
Update release.yml 2023-03-23 14:11:03 +08:00
lencx
8453be3e9d
Merge pull request #660 from lencx/doc 2023-03-19 19:46:36 +08:00
lencx
e919ff9f38 readme 2023-03-19 19:43:55 +08:00
lencx
dd86fb9dbe
Update README.md 2023-03-19 18:33:04 +08:00
lencx
6adb6e3989
Update README-ZH_CN.md 2023-03-09 09:16:07 +08:00
lencx
a56356995e
Update README.md 2023-03-09 09:10:19 +08:00
lencx
2b85b607d0 Merge branch 'main' into dev 2023-03-07 19:28:47 +08:00
lencx
a274c4c8de chore: optim 2023-03-07 19:28:20 +08:00
lencx
ce0d8983eb
Merge pull request #572 from tk103331/main 2023-03-06 16:28:08 +08:00
tk103331
fa96092728 fix:windows voices is empty 2023-03-06 12:48:22 +08:00
lencx
488e249193
Merge pull request #561 from lencx/dev 2023-03-05 12:45:10 +08:00
lencx
20adf43859 v0.12.0 2023-03-05 12:44:42 +08:00
lencx
29ffb116cb v0.12.0 2023-03-05 12:17:59 +08:00
lencx
4d761d805e action 2023-03-05 12:17:50 +08:00
lencx
e5299986c0 readme 2023-03-05 12:17:01 +08:00
lencx
6c899634c2 chore: tts 2023-03-05 11:45:52 +08:00
lencx
e3e0c86aaf feat: autofocus (#550) 2023-03-05 10:12:46 +08:00
lencx
ce395e092b feat: tts (##534) 2023-03-05 10:10:42 +08:00
lencx
3176d9081d feat: tts (##534) 2023-03-05 08:51:27 +08:00
lencx
e2969b07e8
Merge pull request #549 from lencx/dev 2023-03-04 10:37:56 +08:00
lencx
15ad1c023d readme 2023-03-04 10:36:39 +08:00
lencx
cf5b93fbf0
Merge pull request #548 from lencx/dev 2023-03-04 10:28:07 +08:00
lencx
3fd46cbed1 chore: action 2023-03-04 10:27:31 +08:00
lencx
3831337767
Merge pull request #547 from lencx/dev 2023-03-04 10:15:15 +08:00
lencx
1f7e91d4cc v0.11.1 2023-03-04 10:00:44 +08:00
lencx
ba32674419 fix: error 2023-03-04 10:00:00 +08:00
lencx
b4a6c0145a v0.11.1 2023-03-04 09:35:44 +08:00
lencx
a913135a27 fix: error 2023-03-04 09:35:03 +08:00
lencx
98aaed5cb9 v0.11.1 2023-03-04 09:16:15 +08:00
lencx
ab43dd3d73 fix: error 2023-03-04 09:14:57 +08:00
lencx
5e16d91a3e v0.11.1 2023-03-04 08:06:27 +08:00
lencx
a0e2af599f fix: error 2023-03-04 08:06:10 +08:00
lencx
4d752c844d v0.11.1 2023-03-04 01:24:07 +08:00
lencx
d968e6ad6d fix: error 2023-03-04 01:23:43 +08:00
lencx
15d0853cdb v0.11.1 2023-03-04 00:17:13 +08:00
lencx
228b55ab0b version 2023-03-04 00:16:59 +08:00
lencx
0ca6cd3db2 fix: mac 2023-03-04 00:15:05 +08:00
lencx
82cf795624 v0.11.1 2023-03-03 23:42:25 +08:00
lencx
930a9de655 readme 2023-03-03 23:41:17 +08:00
lencx
2cf9da20ea chore: menu 2023-03-03 23:39:18 +08:00
lencx
56c0b8616d fix: export btn (#541) 2023-03-03 23:19:51 +08:00
lencx
5e5d6d268e fix: tray uses the Enter key to send a message (#533) 2023-03-03 23:18:37 +08:00
lencx
71b257c0cf chore: allowlist 2023-03-01 19:21:59 +08:00
lencx
0c0197f0b4
Merge pull request #507 from lencx/dev 2023-02-26 00:24:23 +08:00
lencx
d277a5e4fe readme 2023-02-26 00:24:03 +08:00
lencx
482de8e0e4
Merge pull request #506 from lencx/dev 2023-02-26 00:14:37 +08:00
lencx
751912134c readme 2023-02-26 00:13:32 +08:00
lencx
51c9a17de7
Merge pull request #505 from lencx/dev 2023-02-25 23:56:52 +08:00
lencx
528989653b readme 2023-02-25 23:55:19 +08:00
lencx
9530e70098
Merge pull request #504 from lencx/dev 2023-02-25 23:48:05 +08:00
lencx
9b8efd4775 readme 2023-02-25 23:47:46 +08:00
lencx
ad8bed896e readme 2023-02-25 23:46:54 +08:00
lencx
84686e01ed
Merge pull request #491 from sharunkumar/patch-1 2023-02-24 17:56:45 +08:00
lencx
fd851dca6d
Merge pull request #495 from lencx/dev 2023-02-24 10:23:25 +08:00
lencx
eaf0439d70 LICENSE 2023-02-24 10:21:48 +08:00
Sharun
d088e6687b
fix: better user confirmation message 2023-02-23 12:44:53 -05:00
lencx
cc84a66237
Merge pull request #479 from lencx/dev 2023-02-22 15:59:55 +08:00
lencx
a9f221a337 LICENSE 2023-02-22 15:59:20 +08:00
lencx
e3821cac03
Merge pull request #478 from lencx/dev 2023-02-22 14:42:40 +08:00
lencx
9f51644f61 log 2023-02-22 14:41:51 +08:00
lencx
b21368710c
Merge pull request #472 from qbdq/main 2023-02-22 14:25:37 +08:00
lencx
a4844fd2a4
Merge pull request #476 from lencx/dev 2023-02-22 14:23:47 +08:00
lencx
55b06bb127 readme 2023-02-22 14:23:05 +08:00
lencx
a8c61284f9
Merge pull request #475 from lencx/dev 2023-02-22 13:26:43 +08:00
lencx
3fdd6cd51c readme 2023-02-22 13:26:22 +08:00
Abderrahmen Gharsa
c9fc734c91
📝update typo in comments 2023-02-21 22:16:20 +00:00
Abderrahmen Gharsa
767e68d8b3
Update README.md 2023-02-21 22:11:28 +00:00
lencx
d99dee990a
Merge pull request #464 from mrdulin/fix/node-version-compatible-issue 2023-02-21 11:31:40 +08:00
mrdulin
6ae2fc52a1 fix: node version campatible issue 2023-02-21 11:27:12 +08:00
lencx
b36a4ce00b
Merge pull request #421 from missuo/main 2023-02-17 19:11:44 +08:00
lencx
b850043383
Merge pull request #425 from lencx/revert-424-fix/cask_arch_bug 2023-02-17 19:03:20 +08:00
lencx
c9008366fc
Revert "fix: Hardware::CPU.arch may return arm64" 2023-02-17 19:02:13 +08:00
lencx
845fc3a3e7
Merge pull request #424 from zthreefires/fix/cask_arch_bug 2023-02-17 18:52:54 +08:00
zthreefires
a37c1d4282 fix: Hardware::CPU.arch may return arm64 2023-02-17 18:22:43 +08:00
Vincent Young
0297addf4b
fix: Apple silicon cannot be installed 2023-02-17 17:01:04 +08:00
lencx
618f3483d6
Merge pull request #420 from vangie/patch-2 2023-02-17 16:10:58 +08:00
Vangie Du
f13e6690b3
Update menu.rs
rename tray menu item name
2023-02-17 16:04:50 +08:00
lencx
1ab8e1ef47
Merge pull request #417 from vangie/patch-1 2023-02-17 14:14:56 +08:00
Vangie Du
f469635459
Update chatgpt.rb
1. Support version 0.11.0
2. Compatible with aarch64
2023-02-17 11:30:49 +08:00
lencx
3e64c9c616
Merge pull request #415 from lencx/dev 2023-02-17 09:03:34 +08:00
lencx
d95e34fbe0 readme 2023-02-17 09:02:07 +08:00
lencx
da0075cc31
Merge pull request #408 from lencx/dev 2023-02-17 01:22:46 +08:00
lencx
7c6f094c9f log 2023-02-17 01:21:52 +08:00
lencx
08cb74a8df
Merge pull request #407 from lencx/dev 2023-02-17 00:28:34 +08:00
lencx
cd36360f0e v0.11.0 2023-02-16 23:54:37 +08:00
lencx
2398026795 readme 2023-02-16 23:53:56 +08:00
lencx
5426a711e9 feat: set window size (#405) 2023-02-16 22:02:12 +08:00
lencx
5ec9bb5656 chore: action 2023-02-15 23:55:08 +08:00
lencx
9cd30c158c Merge branch 'main' into dev 2023-02-15 21:37:20 +08:00
lencx
8c7e6b0818
Merge pull request #397 from targed/main 2023-02-15 14:12:39 +08:00
lencx
48a2a37fa2
Merge pull request #389 from cyhhao/main 2023-02-15 12:27:52 +08:00
targed
3a7da4b610
Update README.md 2023-02-14 17:34:37 -06:00
cyhhao
fde75aa81e format 2023-02-14 16:18:52 +08:00
cyhhao
95f8c16be0 Fix Chinese input method Enter on Safari 2023-02-14 16:10:44 +08:00
lencx
668d666377 Merge branch 'main' into dev 2023-02-13 16:05:11 +08:00
lencx
0871824093
Merge pull request #377 from lencx/doc 2023-02-13 13:49:32 +08:00
lencx
ce66cdbffb readme 2023-02-13 13:47:19 +08:00
lencx
56dae0017e
Merge pull request #376 from lencx/doc 2023-02-13 13:19:34 +08:00
lencx
2e46cf4e63 readme 2023-02-13 13:18:39 +08:00
lencx
7c4913b499 readme 2023-02-13 13:12:35 +08:00
lencx
7730d626da readme 2023-02-13 13:11:52 +08:00
lencx
64706adec6 readme 2023-02-13 13:10:29 +08:00
lencx
7fe4a73b5e readme 2023-02-13 13:08:49 +08:00
lencx
7479ee905f fix: close (#349) 2023-02-12 23:33:23 +08:00
lencx
522f7b86b8 fix: save window state (#313) 2023-02-12 00:50:21 +08:00
lencx
4cba634d4a chore: casks 2023-02-12 00:33:51 +08:00
lencx
4a93573f4c Merge branch 'main' into dev 2023-02-12 00:21:13 +08:00
lencx
a67bd0468a chore: action 2023-02-12 00:20:42 +08:00
lencx
2d0cac6766 chore: download 2023-02-11 23:30:06 +08:00
lencx
7836c1263b
Merge pull request #330 from cnyy7/patch-1 2023-02-07 22:56:20 +08:00
chennan
b403dea11b
Update chatgpt.rb to version 0.10.3
checked locally:

brew reinstall --cask chatgpt --no-quarantine
==> Downloading https://github.com/lencx/ChatGPT/releases/download/v0.10.3/ChatGPT_0.10.3_x64.dmg
==> Downloading from https://objects.githubusercontent.com/github-production-release-asset-2e65be/575340621/b
######################################################################## 100.0%
Warning: Cannot verify integrity of 'a77703907b8af9fcb951d9e896b73c3424f60799b39b49a6b9a2d2e3fca259e3--ChatGPT_0.10.3_x64.dmg'.
No checksum was provided for this cask.
For your reference, the checksum is:
  sha256 "f44838a80844999191a303684fd7ae1811dd2fae6709aebe8bff23c70f9b8a10"
==> Uninstalling Cask chatgpt
==> Backing App 'ChatGPT.app' up to '/usr/local/Caskroom/chatgpt/0.6.10/ChatGPT.app'
==> Removing App '/Applications/ChatGPT.app'
==> Purging files for version 0.6.10 of Cask chatgpt
==> Installing Cask chatgpt
Warning: macOS's Gatekeeper has been disabled for this Cask
==> Moving App 'ChatGPT.app' to '/Applications/ChatGPT.app'
🍺  chatgpt was successfully installed!
2023-02-07 17:03:26 +08:00
lencx
62cf15d952 chore: action 2023-02-06 15:05:30 +08:00
lencx
d786e3a96c chore: action 2023-02-06 14:37:49 +08:00
lencx
28db6a72e5 chore: action 2023-02-06 14:22:58 +08:00
lencx
bc35164538 chore: action 2023-02-06 14:18:31 +08:00
lencx
c2482224a7 chore: action 2023-02-06 14:16:51 +08:00
lencx
8a0b85905d
Merge pull request #310 from slithery0/patch-1 2023-02-05 13:04:37 +08:00
rukh
baf055388d
Aur repo added, for git version of ChatGPT 2023-02-05 08:36:15 +05:45
lencx
c293f07b3c
Merge pull request #301 from lencx/dev 2023-02-03 14:39:50 +08:00
lencx
c6efaec586 v0.10.3 2023-02-03 13:34:42 +08:00
lencx
01c6e11e8c release 2023-02-03 13:33:26 +08:00
lencx
70aac07f8e feat: markdown export (#233) 2023-02-03 12:22:15 +08:00
lencx
4847bb6fac chore: copy 2023-02-03 01:30:03 +08:00
lencx
041ffb7462 fix: conf error (#295) 2023-02-03 01:11:56 +08:00
lencx
93bb98e9c0
Merge pull request #292 from lencx/dev 2023-02-02 01:12:06 +08:00
79 changed files with 13463 additions and 2106 deletions

View File

@ -6,7 +6,17 @@ labels:
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: 'Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before filing a new one!' value: |
Please **DO NOT** file issues here if you are having problems with ChatGPT itself. Issues should **ONLY** be created here for bugs that pertain to this package, [lencx/ChatGPT](https://github.com/lencx/ChatGPT). If you are experiencing an issue on [chat.openai.com](https://chat.openai.com), please contact **OpenAI** for support or submit feedback through ChatGPT itself. If you **only have an issue with this app** and do not have the issue on [chat.openai.com](https://chat.openai.com), please file an issue here.
Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before filing a new one!
- type: checkboxes
attributes:
label: Non-ChatGPT bug
options:
- label: |
This issue does not occur on chat.openai.com and only occurs on this app.
required: true
- type: markdown - type: markdown
attributes: attributes:
value: | value: |

View File

@ -6,97 +6,192 @@ on:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
jobs: jobs:
create-release: build-chatgpt:
runs-on: ubuntu-20.04 runs-on: ${{ matrix.os }}
outputs:
RELEASE_UPLOAD_ID: ${{ steps.create_release.outputs.id }}
steps:
- uses: actions/checkout@v2
- name: Query version number
id: get_version
shell: bash
run: |
echo "using version tag ${GITHUB_REF:10}"
echo "version=${GITHUB_REF:10}" >> $GITHUB_ENV
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: '${{ env.version }}'
release_name: 'ChatGPT ${{ env.version }}'
body: 'See the assets to download this version and install.'
build-tauri:
needs: create-release
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
platform: [macos-latest, ubuntu-20.04, windows-latest] include:
- build: linux
os: ubuntu-latest
arch: x86_64
target: x86_64-unknown-linux-gnu
- build: macos
os: macos-latest
arch: x86_64
target: x86_64-apple-darwin
- build: macos
os: macos-latest
arch: aarch64
target: aarch64-apple-darwin
- build: windows
os: windows-latest
arch: x86_64
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.platform }}
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: setup node
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 7
run_install: false
- name: Install Node.js
uses: actions/setup-node@v3 uses: actions/setup-node@v3
with: with:
node-version: 16 node-version: 18
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: install Rust stable - name: 'Setup Rust'
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
- name: install dependencies (ubuntu only) with:
if: matrix.platform == 'ubuntu-20.04' targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.target }}
- name: Install dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf
- name: Install app dependencies and build it - name: Build FE
run: yarn && yarn build:fe run: pnpm build:fe
# - name: Rewrite tauri.conf.json - name: Install rust target
# run: yarn fix:conf run: rustup target add ${{ matrix.target }}
- name: fix tray icon - name: fix tray icon
if: matrix.platform != 'macos-latest' if: matrix.os != 'macos-latest'
run: | run: |
yarn fix:tray pnpm fix:tray
- uses: tauri-apps/tauri-action@v0.3 - run: pnpm build --target ${{ matrix.target }}
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# 📝: https://tauri.app/v1/guides/distribution/updater#signing-updates
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }} TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }} TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
- uses: actions/upload-artifact@v3
if: matrix.os == 'ubuntu-latest'
with: with:
releaseId: ${{ needs.create-release.outputs.RELEASE_UPLOAD_ID }} name: artifacts-${{ matrix.arch }}
path: |
./target/${{ matrix.target }}/release/bundle/appimage/**.AppImage.*
./target/${{ matrix.target }}/release/bundle/deb/**.deb
- uses: actions/upload-artifact@v3
if: matrix.os == 'macos-latest'
with:
name: artifacts-${{ matrix.arch }}
path: |
./target/${{ matrix.target }}/release/bundle/dmg/**.dmg
./target/${{ matrix.target }}/release/bundle/macos/**.app.*
- uses: actions/upload-artifact@v3
if: matrix.os == 'windows-latest'
with:
name: artifacts-${{ matrix.arch }}
path: |
./target/${{ matrix.target }}/release/bundle/msi/**
release-chatgpt:
needs: build-chatgpt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Query version number
run: echo "version=${GITHUB_REF:11}" >> $GITHUB_ENV
- name: Download x86_64 artifacts
uses: actions/download-artifact@v3
with:
name: artifacts-x86_64
path: artifacts/x86_64
- name: Download aarch64 artifacts
uses: actions/download-artifact@v3
with:
name: artifacts-aarch64
path: artifacts/aarch64
- name: Rename artifacts
run: |
mv "artifacts/aarch64/dmg/ChatGPT_${{ env.version }}_aarch64.dmg" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.dmg"
mv "artifacts/aarch64/macos/ChatGPT.app.tar.gz" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.app.tar.gz"
mv "artifacts/aarch64/macos/ChatGPT.app.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.app.tar.gz.sig"
mv "artifacts/x86_64/dmg/ChatGPT_${{ env.version }}_x64.dmg" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.dmg"
mv "artifacts/x86_64/macos/ChatGPT.app.tar.gz" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.app.tar.gz"
mv "artifacts/x86_64/macos/ChatGPT.app.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.app.tar.gz.sig"
mv "artifacts/x86_64/deb/chat-gpt_${{ env.version }}_amd64.deb" "artifacts/x86_64/deb/ChatGPT_${{ env.version }}_linux_x86_64.deb"
mv "artifacts/x86_64/appimage/chat-gpt_${{ env.version }}_amd64.AppImage.tar.gz" "artifacts/ChatGPT_${{ env.version }}_linux_x86_64.AppImage.tar.gz"
mv "artifacts/x86_64/appimage/chat-gpt_${{ env.version }}_amd64.AppImage.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_linux_x86_64.AppImage.tar.gz.sig"
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi"
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi.zip" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi.zip"
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi.zip.sig" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi.zip.sig"
- name: Create Release
uses: softprops/action-gh-release@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: v${{ env.version }}
name: ChatGPT v${{ env.version }}
body: See the assets to download this version and install.
prerelease: false
generate_release_notes: false
files: ./artifacts/**/*
updater: updater:
runs-on: ubuntu-20.04 runs-on: ubuntu-latest
needs: [create-release, build-tauri] needs: release-chatgpt
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- run: yarn
- run: yarn updater --token=${{ secrets.GITHUB_TOKEN }} - uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 7
run_install: false
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Updater JSON
run: pnpm updater --token=${{ secrets.GITHUB_TOKEN }}
- name: Deploy install.json - name: Deploy install.json
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v3
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
# 📝: Edit the deployment directory
publish_dir: ./updater publish_dir: ./updater
force_orphan: true # force_orphan: true
- name: Query version number
run: echo "version=${GITHUB_REF:11}" >> $GITHUB_ENV
# publish-winget: # publish-winget:
# # Action can only be run on windows # # Action can only be run on windows
# runs-on: windows-latest # runs-on: windows-latest
# needs: [create-release, build-tauri] # needs: [build-chatgpt, release-chatgpt]
# steps: # steps:
# - uses: vedantmgoyal2009/winget-releaser@v1 # - uses: vedantmgoyal2009/winget-releaser@v1
# with: # with:
# identifier: lencx.ChatGPT # identifier: lencx.ChatGPT
# token: ${{ secrets.WINGET_TOKEN }} # token: ${{ secrets.WINGET_TOKEN }}
# version: ${{ env.version }} # version: ${{ github.event.release.tag_name }}

9
.gitignore vendored
View File

@ -1,11 +1,14 @@
package-lock.json package-lock.json
node_modules/ node_modules/
yarn.lock
*.lock .yarn/*
.pnp.*
# Testing
private/
# rust # rust
target/ target/
Cargo.lock
# Logs # Logs
logs logs

2
.npmrc Normal file
View File

@ -0,0 +1,2 @@
registry=https://registry.npmjs.org/
engine-strict=true

4794
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

798
LICENSE
View File

@ -1,201 +1,661 @@
Apache License GNU AFFERO GENERAL PUBLIC LICENSE
Version 2.0, January 2004 Version 3, 19 November 2007
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions. Preamble
"License" shall mean the terms and conditions for use, reproduction, The GNU Affero General Public License is a free, copyleft license for
and distribution as defined by Sections 1 through 9 of this document. software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
"Licensor" shall mean the copyright owner or entity authorized by The licenses for most software and other practical works are designed
the copyright owner that is granting the License. to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
"Legal Entity" shall mean the union of the acting entity and all When we speak of free software, we are referring to freedom, not
other entities that control, are controlled by, or are under common price. Our General Public Licenses are designed to make sure that you
control with that entity. For the purposes of this definition, have the freedom to distribute copies of free software (and charge for
"control" means (i) the power, direct or indirect, to cause the them if you wish), that you receive source code or can get it if you
direction or management of such entity, whether by contract or want it, that you can change the software or use pieces of it in new
otherwise, or (ii) ownership of fifty percent (50%) or more of the free programs, and that you know you can do these things.
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity Developers that use our General Public Licenses protect your rights
exercising permissions granted by this License. with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
"Source" form shall mean the preferred form for making modifications, A secondary benefit of defending all users' freedom is that
including but not limited to software source code, documentation improvements made in alternate versions of the program, if they
source, and configuration files. receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
"Object" form shall mean any form resulting from mechanical The GNU Affero General Public License is designed specifically to
transformation or translation of a Source form, including but ensure that, in such cases, the modified source code becomes available
not limited to compiled object code, generated documentation, to the community. It requires the operator of a network server to
and conversions to other media types. provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
"Work" shall mean the work of authorship, whether in Source or An older license, called the Affero General Public License and
Object form, made available under the License, as indicated by a published by Affero, was designed to accomplish similar goals. This is
copyright notice that is included in or attached to the work a different license, not a version of the Affero GPL, but Affero has
(an example is provided in the Appendix below). released a new version of the Affero GPL which permits relicensing under
this license.
"Derivative Works" shall mean any work, whether in Source or Object The precise terms and conditions for copying, distribution and
form, that is based on (or derived from) the Work and for which the modification follow.
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including TERMS AND CONDITIONS
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity 0. Definitions.
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of "This License" refers to version 3 of the GNU Affero General Public License.
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of "Copyright" also means copyright-like laws that apply to other kinds of
this License, each Contributor hereby grants to You a perpetual, works, such as semiconductor masks.
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the "The Program" refers to any copyrightable work licensed under this
Work or Derivative Works thereof in any medium, with or without License. Each licensee is addressed as "you". "Licensees" and
modifications, and in Source or Object form, provided that You "recipients" may be individuals or organizations.
meet the following conditions:
(a) You must give any other recipients of the Work or To "modify" a work means to copy from or adapt all or part of the work
Derivative Works a copy of this License; and in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(b) You must cause any modified files to carry prominent notices A "covered work" means either the unmodified Program or a work based
stating that You changed the files; and on the Program.
(c) You must retain, in the Source form of any Derivative Works To "propagate" a work means to do anything with it that, without
that You distribute, all copyright, patent, trademark, and permission, would make you directly or secondarily liable for
attribution notices from the Source form of the Work, infringement under applicable copyright law, except executing it on a
excluding those notices that do not pertain to any part of computer or modifying a private copy. Propagation includes copying,
the Derivative Works; and distribution (with or without modification), making available to the
public, and in some countries other activities as well.
(d) If the Work includes a "NOTICE" text file as part of its To "convey" a work means any kind of propagation that enables other
distribution, then any Derivative Works that You distribute must parties to make or receive copies. Mere interaction with a user through
include a readable copy of the attribution notices contained a computer network, with no transfer of a copy, is not conveying.
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and An interactive user interface displays "Appropriate Legal Notices"
may provide additional or different license terms and conditions to the extent that it includes a convenient and prominently visible
for use, reproduction, or distribution of Your modifications, or feature that (1) displays an appropriate copyright notice, and (2)
for any such Derivative Works as a whole, provided Your use, tells the user that there is no warranty for the work (except to the
reproduction, and distribution of the Work otherwise complies with extent that warranties are provided), that licensees may convey the
the conditions stated in this License. work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
5. Submission of Contributions. Unless You explicitly state otherwise, 1. Source Code.
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade The "source code" for a work means the preferred form of the work
names, trademarks, service marks, or product names of the Licensor, for making modifications to it. "Object code" means any non-source
except as required for reasonable and customary use in describing the form of a work.
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or A "Standard Interface" means an interface that either is an official
agreed to in writing, Licensor provides the Work (and each standard defined by a recognized standards body, or, in the case of
Contributor provides its Contributions) on an "AS IS" BASIS, interfaces specified for a particular programming language, one that
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or is widely used among developers working in that language.
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, The "System Libraries" of an executable work include anything, other
whether in tort (including negligence), contract, or otherwise, than the work as a whole, that (a) is included in the normal form of
unless required by applicable law (such as deliberate and grossly packaging a Major Component, but which is not part of that Major
negligent acts) or agreed to in writing, shall any Contributor be Component, and (b) serves only to enable use of the work with that
liable to You for damages, including any direct, indirect, special, Major Component, or to implement a Standard Interface for which an
incidental, or consequential damages of any character arising as a implementation is available to the public in source code form. A
result of this License or out of the use or inability to use the "Major Component", in this context, means a major essential component
Work (including but not limited to damages for loss of goodwill, (kernel, window system, and so on) of the specific operating system
work stoppage, computer failure or malfunction, or any and all (if any) on which the executable work runs, or a compiler used to
other commercial damages or losses), even if such Contributor produce the work, or an object code interpreter used to run it.
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing The "Corresponding Source" for a work in object code form means all
the Work or Derivative Works thereof, You may choose to offer, the source code needed to generate, install, and (for an executable
and charge a fee for, acceptance of support, warranty, indemnity, work) run the object code and to modify the work, including scripts to
or other liability obligations and/or rights consistent with this control those activities. However, it does not include the work's
License. However, in accepting such obligations, You may act only System Libraries, or general-purpose tools or generally available free
on Your own behalf and on Your sole responsibility, not on behalf programs which are used unmodified in performing those activities but
of any other Contributor, and only if You agree to indemnify, which are not part of the work. For example, Corresponding Source
defend, and hold each Contributor harmless for any liability includes interface definition files associated with source files for
incurred by, or claims asserted against, such Contributor by reason the work, and the source code for shared libraries and dynamically
of your accepting any such warranty or additional liability. linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
END OF TERMS AND CONDITIONS The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
APPENDIX: How to apply the Apache License to your work. The Corresponding Source for a work in source code form is that
same work.
To apply the Apache License to your work, attach the following 2. Basic Permissions.
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner] All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Licensed under the Apache License, Version 2.0 (the "License"); You may make, run and propagate covered works that you do not
you may not use this file except in compliance with the License. convey, without conditions so long as your license otherwise remains
You may obtain a copy of the License at in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
http://www.apache.org/licenses/LICENSE-2.0 Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
Unless required by applicable law or agreed to in writing, software 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. No covered work shall be deemed part of an effective technological
See the License for the specific language governing permissions and measure under any applicable law fulfilling obligations under article
limitations under the License. 11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@ -6,7 +6,6 @@
[![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md) [![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md)
[![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\ [![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\
![License](https://img.shields.io/badge/License-Apache%202-green.svg)
[![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases) [![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases)
[![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr) [![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr)
[![lencx](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_) [![lencx](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_)
@ -15,16 +14,25 @@
<a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a> <a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a>
**它是一个非官方项目仅供个人学习研究。ChatGPT 桌面应用开源的这段时间,受到了很多关注,谢谢大家的支持。随着事情的发展,有两个问题严重影响了项目的下一步开发计划:**
- **有人利用它进行二次打包销售,谋取私利**
- **ChatGPT 因名称和图标问题可能会涉及侵权**
**新仓库https://github.com/lencx/nofwl**
---
## 📦 安装 ## 📦 安装
- [📝 更新日志](./UPDATE_LOG.md) - [📝 更新日志](./UPDATE_LOG.md)
- [🕒 历史版本...](https://github.com/lencx/ChatGPT/releases) - [🕒 历史版本...](https://github.com/lencx/ChatGPT/releases)
<!-- download start --> <!-- tr-download-start -->
### Windows ### Windows
- [ChatGPT_0.10.2_x64_en-US.msi](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT_0.10.2_x64_en-US.msi): - [ChatGPT_1.1.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_windows_x86_64.msi)
- 使用 [winget](https://winstall.app/apps/lencx.ChatGPT): - 使用 [winget](https://winstall.app/apps/lencx.ChatGPT):
```bash ```bash
@ -35,12 +43,12 @@
winget install --id=lencx.ChatGPT -e --version 0.10.0 winget install --id=lencx.ChatGPT -e --version 0.10.0
``` ```
**注意:如果安装路径和应用名称相同,会导致冲突 ([#142](https://github.com/lencx/ChatGPT/issues/142#issuecomment-0.10.2))** **注意:如果安装路径和应用名称相同,会导致冲突 ([#142](https://github.com/lencx/ChatGPT/issues/142))**
### Mac ### Mac
- [ChatGPT_0.10.2_x64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT_0.10.2_x64.dmg) - [ChatGPT_1.1.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_aarch64.dmg)
- [ChatGPT.app.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT.app.tar.gz) - [ChatGPT_1.1.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_x86_64.dmg)
- Homebrew \ - Homebrew \
_[Homebrew 快捷安装](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_ _[Homebrew 快捷安装](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
```sh ```sh
@ -54,16 +62,18 @@
cask "chatgpt", args: { "no-quarantine": true } cask "chatgpt", args: { "no-quarantine": true }
``` ```
如果在 macOS 上安装软件时遇到 `“ChatGPT” is damaged and can't be opened. You should move it to the Trash.` 错误消息,可能是由于 macOS 安全设置的限制导致的。为了解决此问题,请在终端尝试以下命令:
```bash
sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
```
### Linux ### Linux
- [chat-gpt_0.10.2_amd64.deb](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/chat-gpt_0.10.2_amd64.deb) - [ChatGPT_1.1.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.deb)
- [chat-gpt_0.10.2_amd64.AppImage](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/chat-gpt_0.10.2_amd64.AppImage): **工作可靠,`.deb` 运行失败时可以尝试它** - [ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz): **工作可靠,`.deb` 运行失败时可以尝试它**
- 使用 [AUR](https://aur.archlinux.org/packages/chatgpt-desktop-bin):
```bash
yay -S chatgpt-desktop-bin
```
<!-- download end --> <!-- tr-download-end -->
## 📢 公告 ## 📢 公告
@ -87,7 +97,6 @@
- 跨平台: `macOS` `Linux` `Windows` - 跨平台: `macOS` `Linux` `Windows`
- 导出 ChatGPT 聊天记录 (支持 PNG, PDF 和生成分享链接) - 导出 ChatGPT 聊天记录 (支持 PNG, PDF 和生成分享链接)
- 主窗口和系统托盘支持自定义 URL将任意网站包装成一个桌面应用
- 应用自动升级通知 - 应用自动升级通知
- 丰富的快捷键 - 丰富的快捷键
- 系统托盘悬浮窗 - 系统托盘悬浮窗
@ -102,17 +111,14 @@
- `Theme` - `Light`, `Dark`, `System` (仅支持 macOS 和 Windows) - `Theme` - `Light`, `Dark`, `System` (仅支持 macOS 和 Windows)
- `Stay On Top`: 窗口置顶 - `Stay On Top`: 窗口置顶
- `Titlebar`: 是否显示 `Titlebar`,仅 macOS 支持 - `Titlebar`: 是否显示 `Titlebar`,仅 macOS 支持
- `Inject Script`: 用于修改网站的用户自定义脚本
- `Hide Dock Icon` ([#35](https://github.com/lencx/ChatGPT/issues/35)): 隐藏 Dock 中的应用图标 (仅 macOS 支持) - `Hide Dock Icon` ([#35](https://github.com/lencx/ChatGPT/issues/35)): 隐藏 Dock 中的应用图标 (仅 macOS 支持)
- 系统图盘右键单击打开菜单,然后在菜单项中点击 `Show Dock Icon` 可以重新将应用图标显示在 Dock`SystemTrayMenu -> Show Dock Icon` - 系统图盘右键单击打开菜单,然后在菜单项中点击 `Show Dock Icon` 可以重新将应用图标显示在 Dock`SystemTrayMenu -> Show Dock Icon`
- `Control Center`: ChatGPT 应用的控制中心,它将为应用提供无限的可能 - `Control Center`: ChatGPT 应用的控制中心,它将为应用提供无限的可能
- 设置 `Theme``Stay On Top``Titlebar` 等 - 设置 `Theme``Stay On Top``Titlebar` 等
- `User Agent` ([#17](https://github.com/lencx/ChatGPT/issues/17)): 自定义 `user agent` 防止网站安全检测,默认值为空 - `User Agent` ([#17](https://github.com/lencx/ChatGPT/issues/17)): 自定义 `user agent` 防止网站安全检测,默认值为空
- `Switch Origin` ([#14](https://github.com/lencx/ChatGPT/issues/14)): 切换网站源地址,默认为 `https://chat.openai.com`。需要注意的是镜像网站的 UI 需要和原网站一致,否则可能会导致某些功能不工作
- `Go to Config`: 打开 ChatGPT 配置目录 (`path: ~/.chatgpt/*`) - `Go to Config`: 打开 ChatGPT 配置目录 (`path: ~/.chatgpt/*`)
- `Clear Config`: 清除 ChatGPT 配置数据 (`path: ~/.chatgpt/*`), 这是危险操作,请提前备份数据 - `Clear Config`: 清除 ChatGPT 配置数据 (`path: ~/.chatgpt/*`), 这是危险操作,请提前备份数据
- `Restart ChatGPT`: 重启应用。如果注入脚本编辑完成,或者应用可卡死可以通过此菜单重新启动应用 - `Restart ChatGPT`: 重启应用。如果注入脚本编辑完成,或者应用可卡死可以通过此菜单重新启动应用
- `Awesome ChatGPT`: 一个很棒的 ChatGPT 推荐列表
- **Edit** - `Undo`, `Redo`, `Cut`, `Copy`, `SelectAll`, ... - **Edit** - `Undo`, `Redo`, `Cut`, `Copy`, `SelectAll`, ...
- **View** - `Go Back`, `Go Forward`, `Scroll to Top of Screen`, `Scroll to Bottom of Screen`, `Refresh the Screen`, ... - **View** - `Go Back`, `Go Forward`, `Scroll to Top of Screen`, `Scroll to Bottom of Screen`, `Refresh the Screen`, ...
- **Help** - **Help**
@ -130,13 +136,13 @@
- `[.chatgpt]` - 应用配置根路径 - `[.chatgpt]` - 应用配置根路径
- `chat.conf.json` - 应用喜好配置 - `chat.conf.json` - 应用喜好配置
- `chat.awesome.json` - 自定义 URL 列表,类似于浏览器书签。可以将任意 URL 作为主窗口或托盘窗口 (**Control Conter -> Awesome**) <!-- - `chat.awesome.json` - 自定义 URL 列表,类似于浏览器书签。可以将任意 URL 作为主窗口或托盘窗口 (**Control Conter -> Awesome**) -->
- `chat.model.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分: - `chat.prompt.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分:
- `user_custom` - 需要手动录入 (**Control Conter -> Language Model -> User Custom**) - `user_custom` - 需要手动录入 (**Control Conter -> Prompts -> User Custom**)
- `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Language Model -> Sync Prompts**) - `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Prompts -> Sync Prompts**)
- `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Language Model -> Sync Custom**) - `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Prompts -> Sync Custom**)
- `chat.model.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据 - `chat.prompt.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据
- `[cache_model]` - 缓存同步或录入的数据 - `[cache_prompts]` - 缓存同步或录入的数据
- `chatgpt_prompts.json` - 缓存 `sync_prompts` 数据 - `chatgpt_prompts.json` - 缓存 `sync_prompts` 数据
- `user_custom.json` - 缓存 `user_custom` 数据 - `user_custom.json` - 缓存 `user_custom` 数据
- `ae6cf32a6f8541b499d6bfe549dbfca3.json` - 随机生成的文件名,缓存 `sync_custom` 数据 - `ae6cf32a6f8541b499d6bfe549dbfca3.json` - 随机生成的文件名,缓存 `sync_custom` 数据
@ -248,6 +254,8 @@ yarn build
<img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png"> <img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png">
<a href="https://t.zsxq.com/0bQikmcVw"><img width="360" src="./assets/zsxq.png"></a>
## License ## License
Apache License AGPL-3.0 License

225
README.md
View File

@ -1,33 +1,45 @@
<p align="center"> <p align="center">
<img width="180" src="./public/logo.png" alt="ChatGPT"> <img width="180" src="./public/logo.png" alt="ChatGPT">
<h1 align="center">ChatGPT</h1> <h1 align="center">ChatGPT</h1>
<p align="center">ChatGPT Desktop Application (Mac, Windows and Linux)</p> <p align="center">ChatGPT Desktop Application (Available on Mac, Windows, and Linux)</p>
</p> </p>
[![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md) [![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md)
[![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\ [![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\
![License](https://img.shields.io/badge/License-Apache%202-green.svg)
![visitor](https://visitor-badge.glitch.me/badge?page_id=lencx.chatgpt)
[![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases) [![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases)
[![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr) [![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr)
[![lencx](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_) [![twitter](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_)
[![youtube](https://img.shields.io/youtube/channel/subscribers/UC__gTZL-OZKDPic7s_6Ntgg?style=social)](https://www.youtube.com/@lencx)
<!-- [![lencx](https://img.shields.io/twitter/follow/lencx_.svg?style=social)](https://twitter.com/lencx_) -->
<!-- [![中文版 badge](https://img.shields.io/badge/%E4%B8%AD%E6%96%87-Traditional%20Chinese-blue)](./README-ZH.md) -->
<a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a> <a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a>
---
> [!NOTE]
> **If you want to experience a more powerful AI wrapper application, you can try the Noi (https://github.com/lencx/Noi), which is a successor to the ChatGPT desktop application concept.**
---
This is an unofficial project solely intended for personal learning and research. Since the ChatGPT desktop application was open-sourced, it has garnered a lot of attention, and I want to thank everyone for their support. However, as the project progressed, two issues have arisen that greatly impact its future development:
- Some individuals have repackaged and sold it for profit.
- The name and icon of ChatGPT could potentially lead to infringement disputes.
## Live Demo
- [ChatGPT Desktop Application v1.0.0](https://youtu.be/IIuuB5vFFAQ)
- [ChatGPT automatically performs the "Continue generating" button, freeing up your hands.](https://youtu.be/bbL5cPmiGig)
## 📦 Install ## 📦 Install
- [📝 Update Log](./UPDATE_LOG.md) - [📝 Update Log](./UPDATE_LOG.md)
- [🕒 History versions...](https://github.com/lencx/ChatGPT/releases) - [🕒 History versions...](https://github.com/lencx/ChatGPT/releases)
<!-- download start --> <!-- tr-download-start -->
### Windows ### Windows
- [ChatGPT_0.10.2_x64_en-US.msi](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT_0.10.2_x64_en-US.msi): Direct download installer - [ChatGPT_1.1.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_windows_x86_64.msi): Direct download installer
- Use [winget](https://winstall.app/apps/lencx.ChatGPT): - Use [winget](https://winstall.app/apps/lencx.ChatGPT):
```bash ```bash
@ -35,15 +47,15 @@
winget install --id=lencx.ChatGPT -e winget install --id=lencx.ChatGPT -e
# install the specified version # install the specified version
winget install --id=lencx.ChatGPT -e --version 0.10.0 winget install --id=lencx.ChatGPT -e --version 1.1.0
``` ```
**Note: If the installation path and application name are the same, it will lead to conflict ([#142](https://github.com/lencx/ChatGPT/issues/142#issuecomment-0.10.2))** **Note: If the installation path and application name are the same, it will lead to conflict ([#142](https://github.com/lencx/ChatGPT/issues/142))**
### Mac ### Mac
- [ChatGPT_0.10.2_x64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT_0.10.2_x64.dmg): Direct download installer - [ChatGPT_1.1.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_aarch64.dmg): Direct download installer
- [ChatGPT.app.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/ChatGPT.app.tar.gz): Download the `.app` installer - [ChatGPT_1.1.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_x86_64.dmg): Direct download installer
- Homebrew \ - Homebrew \
Or you can install with _[Homebrew](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_ Or you can install with _[Homebrew](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
```sh ```sh
@ -57,41 +69,30 @@
cask "chatgpt", args: { "no-quarantine": true } cask "chatgpt", args: { "no-quarantine": true }
``` ```
**If you encounter the error message `"ChatGPT" is damaged and can't be opened. You should move it to the Trash`. while installing software on macOS, it may be due to security settings restrictions in macOS. To solve this problem, please try the following command in Terminal:**
```bash
sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
```
### Linux ### Linux
- [chat-gpt_0.10.2_amd64.deb](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/chat-gpt_0.10.2_amd64.deb): Download `.deb` installer, advantage small size, disadvantage poor compatibility - [ChatGPT_1.1.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.deb): Download `.deb` installer, advantage small size, disadvantage poor compatibility
- [chat-gpt_0.10.2_amd64.AppImage](https://github.com/lencx/ChatGPT/releases/download/v0.10.2/chat-gpt_0.10.2_amd64.AppImage): Works reliably, you can try it if `.deb` fails to run - [ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz): Works reliably, you can try it if `.deb` fails to run
- Available on [AUR](https://aur.archlinux.org/packages/chatgpt-desktop-bin) with the package name `chatgpt-desktop-bin`, and you can use your favourite AUR package manager to install it.
<!-- download end --> <!-- tr-download-end -->
## 📢 Announcement ## ChatGPT Prompts!
### ChatGPT Prompts!
This is a major and exciting update. It works like a `Telegram bot command` and helps you quickly populate custom models to make chatgpt work the way you want it to. This project has taken a lot of my spare time, so if it helps you, please help spread the word or star it would be a great encouragement to me. I hope I can keep updating it and adding more interesting features.
### How does it work?
You can look at **[awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)** to find interesting features to import into the app. You can also use `Sync Prompts` to sync all in one click, and if you don't want certain prompts to appear in your slash commands, you can disable them. You can look at **[awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)** to find interesting features to import into the app. You can also use `Sync Prompts` to sync all in one click, and if you don't want certain prompts to appear in your slash commands, you can disable them.
![chatgpt cmd](./assets/chatgpt-cmd.png) ![chatgpt cmd](./assets/chatgpt-cmd.png)
![chatgpt sync prompts](./assets/chatgpt-sync-prompts.png)
<!-- After the data import is done, you can restart the app to make the configuration take effect (`Menu -> Preferences -> Restart ChatGPT`). -->
- In the chatgpt text input area, type a character starting with `/` to bring up the command prompt, press the spacebar, and it will fill the input area with the text associated with the command by default (note: if it contains multiple command prompts, it will only select the first one as the fill, you can keep typing until the first prompted command is the one you want, then press the spacebar.
- Or use the mouse to click on one of the multiple commands). When the fill is complete, you simply press the Enter key.
- Under the slash command, use the tab key to modify the contents of the `{q}` tag (only single changes are supported [#54](https://github.com/lencx/ChatGPT/issues/54)). Use the keyboard `⇧` (arrow up) and `⇩` (arrow down) keys to select the slash command.
![chatgpt](assets/chatgpt.gif)
![chatgpt-cmd](assets/chatgpt-cmd.gif)
## ✨ Features ## ✨ Features
- Multi-platform: `macOS` `Linux` `Windows` - Multi-platform: `macOS` `Linux` `Windows`
- Text-to-Speech
- Export ChatGPT history (PNG, PDF and Markdown) - Export ChatGPT history (PNG, PDF and Markdown)
- The main window and system tray support custom URLs to wrap any website into a desktop application
- Automatic application upgrade notification - Automatic application upgrade notification
- Common shortcut keys - Common shortcut keys
- System tray hover window - System tray hover window
@ -100,150 +101,7 @@ You can look at **[awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt
- Customize global shortcuts ([#108](https://github.com/lencx/ChatGPT/issues/108)) - Customize global shortcuts ([#108](https://github.com/lencx/ChatGPT/issues/108))
- Pop-up Search ([#122](https://github.com/lencx/ChatGPT/issues/122) mouse selected content, no more than 400 characters): The application is built using Tauri, and due to its security restrictions, some of the action buttons will not work, so we recommend going to your browser. - Pop-up Search ([#122](https://github.com/lencx/ChatGPT/issues/122) mouse selected content, no more than 400 characters): The application is built using Tauri, and due to its security restrictions, some of the action buttons will not work, so we recommend going to your browser.
## #⃣ MenuItem ## Thanks
- **Preferences**
- `Theme` - `Light`, `Dark`, `System` (Only macOS and Windows are supported).
- `Stay On Top`: The window is stay on top of other windows.
- `Titlebar`: Whether to display the titlebar, supported by macOS only.
- `Hide Dock Icon` ([#35](https://github.com/lencx/ChatGPT/issues/35)): Hide application icons from the Dock(support macOS only).
- Right-click on the SystemTray to open the menu, then click `Show Dock Icon` in the menu item to re-display the application icon in the Dock (`SystemTrayMenu -> Show Dock Icon`).
- `Inject Script`: Using scripts to modify pages.
- `Control Center`: The control center of ChatGPT application, it will give unlimited imagination to the application.
- `Theme`, `Stay On Top`, `Titlebar`, ...
- `User Agent` ([#17](https://github.com/lencx/ChatGPT/issues/17)): Custom `user agent`, which may be required in some scenarios. The default value is the empty string.
- `Switch Origin` ([#14](https://github.com/lencx/ChatGPT/issues/14)): Switch the site source address, the default is `https://chat.openai.com`, please make sure the mirror site UI is the same as the original address. Otherwise, some functions may not be available.
- `Go to Config`: Open the configuration file directory (`path: ~/.chatgpt/*`).
- `Clear Config`: Clear the configuration file (`path: ~/.chatgpt/*`), dangerous operation, please backup the data in advance.
- `Restart ChatGPT`: Restart the application, for example: the program is stuck or the injection script can take effect by restarting the application after editing.
- `Awesome ChatGPT`: Recommended Related Resources.
- **Edit** - `Undo`, `Redo`, `Cut`, `Copy`, `SelectAll`, ...
- **View** - `Go Back`, `Go Forward`, `Scroll to Top of Screen`, `Scroll to Bottom of Screen`, `Refresh the Screen`, ...
- **Help**
- `Update Log`: ChatGPT changelog.
- `Report Bug`: Report a bug or give feedback.
- `Toggle Developer Tools`: Developer debugging tools.
## ⚙️ Application Configuration
| Platform | Path |
| -------- | ------------------------- |
| Linux | `/home/lencx/.chatgpt` |
| macOS | `/Users/lencx/.chatgpt` |
| Windows | `C:\Users\lencx\.chatgpt` |
- `[.chatgpt]` - application configuration root folder
- `chat.conf.json` - preferences configuration
- `chat.awesome.json` - Custom URL lists, similar to browser bookmarks. Any URL can be used as the main window or tray window (**Control Conter -> Awesome**)
- `chat.model.json` - prompts configurationcontains three parts:
- `user_custom` - Requires manual data entry (**Control Conter -> Language Model -> User Custom**)
- `sync_prompts` - Synchronizing data from [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) (**Control Conter -> Language Model -> Sync Prompts**)
- `sync_custom` - Synchronize custom json and csv file data, support local and remote (**Control Conter -> Language Model -> Sync Custom**)
- `chat.model.cmd.json` - filtered (whether to enable) and sorted slash commands
- `[cache_model]` - caching model data
- `chatgpt_prompts.json` - Cache `sync_prompts` data
- `user_custom.json` - Cache `user_custom` data
- `ae6cf32a6f8541b499d6bfe549dbfca3.json` - Randomly generated file names, cache `sync_custom` data
- `4f695d3cfbf8491e9b1f3fab6d85715c.json` - Randomly generated file names, cache `sync_custom` data
- `bd1b96f15a1644f7bd647cc53073ff8f.json` - Randomly generated file names, cache `sync_custom` data
### Sync Custom
Currently, only json and csv are supported for synchronizing custom files, and the following formats need to be met, otherwise the application will be abnormal
`JSON format:`
```json
[
{
"cmd": "a",
"act": "aa",
"prompt": "aaa aaa aaa"
},
{
"cmd": "b",
"act": "bb",
"prompt": "bbb bbb bbb"
}
]
```
`CSV format`
```csv
"cmd","act","prompt"
"a","aa","aaa aaa aaa"
"b","bb","bbb bbb bbb"
```
## 📌 TODO
<!-- - Web access capability ([#20](https://github.com/lencx/ChatGPT/issues/20)) -->
- `Control Center` enhancement
- `Pop-up Search` enhancement
- ...
## 👀 Preview
<img width="320" src="./assets/install.png" alt="install"> <img width="320" src="./assets/chatgpt-popup-search.png" alt="popup search">
<img width="320" src="./assets/chatgpt-control-center-general.png" alt="control center"> <img width="320" src="./assets/chatgpt-export.png" alt="export">
<img width="320" src="./assets/chatgpt-dalle2-tray.png" alt="dalle2 tray"> <img width="320" src="./assets/auto-update.png" alt="auto update">
## ❓FAQ
### Can't open ChatGPT
If you cannot open the application after the upgrade, please try to clear the configuration file, which is in the `~/.chatgpt/*` directory.
### Out of sync login status between multiple windows
If you have already logged in in the main window, but the system tray window shows that you are not logged in, you can fix it by restarting the application (`Menu -> Preferences -> Restart ChatGPT`).
### Is it safe?
It's safe, just a wrapper for [OpenAI ChatGPT](https://chat.openai.com) website, no other data transfer exists (you can check the source code).
### Developer cannot be verified?
- [Open a Mac app from an unidentified developer](https://support.apple.com/en-sg/guide/mac-help/mh40616/mac)
---
### How do I build it?
#### PreInstall
- [Rust (Required)](https://www.rust-lang.org/)
- [Node.js (Required)](https://nodejs.org/)
- [VS Code (Optional)](https://code.visualstudio.com/)
- [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
- [tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode)
#### Start
```bash
# step1:
git clone https://github.com/lencx/ChatGPT.git
# step2:
cd ChatGPT
# step3: install deps
yarn
# step4:
yarn dev
# step5:
# bundle path: src-tauri/target/release/bundle
yarn build
```
- [The distDir configuration is set to "../dist" but this path doesn't exist](https://github.com/lencx/ChatGPT/discussions/180)
- [Error A public key has been found, but no private key. Make sure to set TAURI_PRIVATE_KEY environment variable.](https://github.com/lencx/ChatGPT/discussions/182)
## ❤️ Thanks
- The core implementation of the share button code was copied from the [@liady](https://github.com/liady) extension with some modifications. - The core implementation of the share button code was copied from the [@liady](https://github.com/liady) extension with some modifications.
- Thanks to the [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) repository for inspiring the custom command function for this application. - Thanks to the [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) repository for inspiring the custom command function for this application.
@ -254,10 +112,15 @@ yarn build
## 中国用户 ## 中国用户
> [!NOTE]
> **如果你喜欢 ChatGPT 桌面应用,也可以关注一下 [lencx/Noi](https://github.com/lencx/Noi),它是一个定制化的 AI 浏览器。这里有两篇使用文档,对 Noi 的理念和插件系统做了详细介绍:**
> - [Noi跨平台定制化浏览器最得力 AI 助手](https://mp.weixin.qq.com/s/dAN7LOw7mH609HdAyEvXfg)
> - [Noi插件介绍](https://mp.weixin.qq.com/s/M6gO6MdK5obCvs2LIBZA3w)
国内用户如果遇到使用问题或者想交流 ChatGPT 技巧,可以关注公众号“浮之静”,发送 “chat” 进群参与讨论。公众号会更新[《Tauri 系列》](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzIzNjE2NTI3NQ==&action=getalbum&album_id=2593843659863752704)文章,技术思考等等,如果对 tauri 开发应用感兴趣可以关注公众号后回复 “tauri” 进技术开发群(想私聊的也可以关注公众号,来添加微信)。开源不易,如果这个项目对你有帮助可以分享给更多人,或者微信扫码打赏。 国内用户如果遇到使用问题或者想交流 ChatGPT 技巧,可以关注公众号“浮之静”,发送 “chat” 进群参与讨论。公众号会更新[《Tauri 系列》](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzIzNjE2NTI3NQ==&action=getalbum&album_id=2593843659863752704)文章,技术思考等等,如果对 tauri 开发应用感兴趣可以关注公众号后回复 “tauri” 进技术开发群(想私聊的也可以关注公众号,来添加微信)。开源不易,如果这个项目对你有帮助可以分享给更多人,或者微信扫码打赏。
<img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png"> <img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png">
## License ## License
Apache License AGPL-3.0 License

View File

@ -1,5 +1,75 @@
# UPDATE LOG # UPDATE LOG
**It is an unofficial project intended for personal learning and research purposes only. During the time that the ChatGPT desktop application was open-sourced, it received a lot of attention, and I would like to thank everyone for their support. However, as things have developed, there are two issues that seriously affect the project's next development plan:**
- **Some people have used it for repackaging and selling for profit.**
- **The name and icon of ChatGPT may be involved in infringement issues.**
**New repository: https://github.com/lencx/nofwl**
## v1.1.0
Fix:
- Fixed the issue where the cmd slash command does not work in some cases.
- Moved the export button to the sidebar to prevent layout conflicts.
## v1.0.0
Note: This version modifies some configuration files. It is recommended to backup the `~/.chatgpt` folder in advance to avoid loss of important configurations.
Feat:
- The synchronization method for prompts has been optimized, now supporting local file uploads
- Scripts have been externalized, allowing for editing and synchronization
- Removed the `Awesome` menu from `Control Center`
Fix:
- Chat history export is blank
- Change the export files location to the `Download` directory
## v0.12.0
Feat:
- Add refresh button
- Add text-to-speech (`Control Center -> Settings -> General -> Set Speech Language`) (https://github.com/lencx/ChatGPT/issues/534)
- Automatically focus input field (https://github.com/lencx/ChatGPT/issues/550)
## v0.11.1
Fix:
- Export button blinks (https://github.com/lencx/ChatGPT/issues/541)
- System tray supports sending with Enter key, for text line breaks please use the shortcut key `Shift + Enter` (https://github.com/lencx/ChatGPT/issues/533)
## v0.11.0
Fix:
- User-defined close button behavior (exit or minimize) (`Control Center -> Settings -> Main Window -> Close Exit`). (https://github.com/lencx/ChatGPT/issues/359)
- Markdown content layout (https://github.com/lencx/ChatGPT/issues/378)
Feat:
- Set the main window and tray window size (https://github.com/lencx/ChatGPT/issues/405)
- Save window positions and sizes and restore them when the app is reopened (`Control Center -> Settings -> General -> Save Window State`)
- macOS support for aarch64 installer (https://github.com/lencx/ChatGPT/issues/380)
## v0.10.3
> Note: As of now the ChatGPT desktop app has added a lot of exciting features and it continues to improve, as the app grows it has gone far beyond what ChatGPT was intended for. I want to make it the ultimate goal that any website can be easily wrapped to the desktop through user customization. So it needed an international user guide to guide users to use it more professionally. And https://app.nofwl.com is the manual for the app, which will be built into the app (`Menu -> Window -> ChatGPT User's Guide`) so you can access it anytime. It's just starting at the moment, so stay tuned.
Fix:
- Incompatible configuration data causes program crashes (https://github.com/lencx/ChatGPT/issues/295)
Feat:
- Silent copy text
- Markdown export support distinguishes between users and bots (https://github.com/lencx/ChatGPT/issues/233)
## v0.10.2 ## v0.10.2
Fix: Fix:

BIN
assets/zsxq.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -1,8 +1,14 @@
cask "chatgpt" do cask "chatgpt" do
version "0.6.10" version "1.1.0"
sha256 "e85062565f826d32219c53b184d6df9c89441d4231cdfff775c2de8c50ac9906" arch = Hardware::CPU.arch.to_s
sha256s = {
"x86_64" => "6747e61a507402fa4b36db443c37a79299a4e1d4ba9904298a0b00c3e6a243b6",
"aarch64" => "f870ba135ad990715474cbb038b5b38acb8d08640803e2c79c878e210f4800f6"
}
if arch == "arm64" then arch = "aarch64" end
url "https://github.com/lencx/ChatGPT/releases/download/v#{version}/ChatGPT_#{version}_macos_#{arch}.dmg"
sha256 sha256s[arch]
url "https://github.com/lencx/ChatGPT/releases/download/v#{version}/ChatGPT_#{version}_x64.dmg"
name "ChatGPT" name "ChatGPT"
desc "Desktop wrapper for OpenAI ChatGPT" desc "Desktop wrapper for OpenAI ChatGPT"
homepage "https://github.com/lencx/ChatGPT#readme" homepage "https://github.com/lencx/ChatGPT#readme"

View File

@ -4,14 +4,14 @@
"scripts": { "scripts": {
"dev:fe": "vite", "dev:fe": "vite",
"build:fe": "tsc && vite build", "build:fe": "tsc && vite build",
"dev": "yarn tauri dev", "dev": "tauri dev",
"build": "yarn tauri build", "build": "tauri build",
"updater": "tr updater", "updater": "tr updater",
"release": "tr release --git", "release": "tr release --git",
"fix:conf": "tr override --json.tauri_updater_active=false", "fix:conf": "tr override --json.tauri_updater_active=false",
"fix:tray": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon-light.png\" --json.tauri_systemTray_iconAsTemplate=false", "fix:tray": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon-light.png\" --json.tauri_systemTray_iconAsTemplate=false",
"fix:tray:mac": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon.png\" --json.tauri_systemTray_iconAsTemplate=true", "fix:tray:mac": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon.png\" --json.tauri_systemTray_iconAsTemplate=true",
"download": "node ./scripts/download.js", "download": "tr download --mdfile=README.md,README-ZH_CN.md --f1=43 --f2=43",
"fmt:rs": "cargo fmt", "fmt:rs": "cargo fmt",
"tr": "tr", "tr": "tr",
"tauri": "tauri", "tauri": "tauri",
@ -45,6 +45,7 @@
"dayjs": "^1.11.7", "dayjs": "^1.11.7",
"github-markdown-css": "^5.1.0", "github-markdown-css": "^5.1.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"monaco-editor": "^0.34.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-markdown": "^8.0.4", "react-markdown": "^8.0.4",
@ -57,8 +58,8 @@
"uuid": "^9.0.0" "uuid": "^9.0.0"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^1.2.2", "@tauri-apps/cli": "^1.3.1",
"@tauri-release/cli": "^0.2.3", "@tauri-release/cli": "^0.2.5",
"@types/lodash": "^4.14.191", "@types/lodash": "^4.14.191",
"@types/node": "^18.7.10", "@types/node": "^18.7.10",
"@types/react": "^18.0.15", "@types/react": "^18.0.15",
@ -73,5 +74,8 @@
"typescript": "^4.9.4", "typescript": "^4.9.4",
"vite": "^4.0.0", "vite": "^4.0.0",
"vite-tsconfig-paths": "^4.0.2" "vite-tsconfig-paths": "^4.0.2"
},
"engines": {
"node": "^14.18.0 || ^16.0.0 || ^18.0.0"
} }
} }

4797
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

BIN
public/bmc.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

BIN
public/wxp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

5
scripts/README.md Normal file
View File

@ -0,0 +1,5 @@
# ChatGPT Scripts
> ChatGPT Desktop Application Core Extension Scripts.
[ChatGPT/scripts](https://github.com/lencx/ChatGPT/tree/main/scripts)

157
scripts/chat.js vendored Normal file
View File

@ -0,0 +1,157 @@
/**
* @name chat.js
* @version 0.1.4
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/chat.js
*/
function chatInit() {
const ICONS = {
copy: `<svg class="chatappico copy" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`,
cpok: `<svg class="chatappico cpok" viewBox="0 0 24 24"><g fill="none" stroke="#10a37f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M16 4h2a2 2 0 0 1 2 2v4m1 4H11"/><path d="m15 10l-4 4l4 4"/></g></svg>`,
voice: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="currentColor"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="currentColor"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="currentColor"></path></svg>`,
speaking: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="#10a37f"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="#10a37f"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="#10a37f"></path></svg>`,
};
let currentUtterance = null;
let currentIndex = -1;
let chatConf = {};
async function init() {
chatConf = (await invoke('get_app_conf')) || {};
new MutationObserver(observeMutations).observe(document.body, {
childList: true,
subtree: true,
});
document.addEventListener('visibilitychange', focusOnInput);
autoContinue();
}
function observeMutations(mutationsList) {
for (const mutation of mutationsList) {
if (mutation.target.closest('form')) {
addChatButtons();
}
}
}
function focusOnInput() {
const textArea = document.getElementsByTagName('textarea')[0];
if (textArea) {
textArea.focus();
}
}
function addChatButtons() {
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
list.forEach((item, idx) => {
if (shouldSkip(item)) {
return;
}
const saybtn = item.querySelector('button.rounded-md').cloneNode(true);
saybtn.classList.add('chat-item-voice');
saybtn.title = 'Say';
saybtn.innerHTML = ICONS.voice;
item.querySelector('.self-end').appendChild(saybtn);
saybtn.onclick = () => handleClick(item, idx, saybtn);
});
}
function shouldSkip(item) {
return (
item.querySelector('.chat-item-voice') ||
!item.querySelector('button.rounded-md') ||
!item.querySelector('.self-end')
);
}
function handleClick(item, idx, saybtn) {
const synth = window.speechSynthesis;
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
if (currentUtterance && currentIndex !== -1) {
synth.cancel();
if (idx === currentIndex) {
saybtn.innerHTML = ICONS.voice;
currentUtterance = null;
currentIndex = -1;
return;
} else if (list[currentIndex].querySelector('.chat-item-voice')) {
list[currentIndex].querySelector('.chat-item-voice').innerHTML = ICONS.voice;
list[idx].querySelector('.chat-item-voice').innerHTML = ICONS.speaking;
}
}
const txt = item?.innerText?.trim() || '';
if (!txt) return;
const utterance = new SpeechSynthesisUtterance(txt);
const voices = speechSynthesis.getVoices();
let voice = voices.find((voice) => voice.voiceURI === chatConf.speech_lang);
if (!voice) {
voice = voices.find((voice) => voice.lang === 'en-US');
}
utterance.voice = voice;
currentIndex = idx;
utterance.lang = voice.lang;
synth.speak(utterance);
saybtn.innerHTML = ICONS.speaking;
currentUtterance = utterance;
currentIndex = idx;
utterance.onend = () => {
saybtn.innerHTML = ICONS.voice;
currentUtterance = null;
currentIndex = -1;
};
}
function autoContinue() {
// Create an instance of the observer
const observer = new MutationObserver((mutationsList) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
const btn = Array.from(mutation.target.querySelectorAll('button.btn')).find((btn) =>
btn.innerText.includes('Continue generating'),
);
if (btn) {
console.log("Found the button of 'Continue generating'");
setTimeout(() => {
console.log('Clicked it to continue generating after 1 second');
btn.click();
}, 1000);
return;
}
}
}
});
// Wait until the form exists
const interval = setInterval(() => {
if (document.forms[0]) {
// Start observing the dom change of the form
observer.observe(document.forms[0], {
attributes: false,
childList: true,
subtree: true,
});
clearInterval(interval); // Stop checking when the form exists
}
}, 1000);
}
init();
}
document.addEventListener('DOMContentLoaded', chatInit);

365
scripts/cmd.js vendored Normal file
View File

@ -0,0 +1,365 @@
/**
* @name cmd.js
* @version 0.1.2
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/cmd.js
*/
function cmdInit() {
const styleDom = document.createElement('style');
styleDom.innerHTML = `form {
position: relative;
}
.chat-prompt-cmd-list {
position: absolute;
bottom: 60px;
max-height: 100px;
overflow: auto;
z-index: 9999;
}
.chat-prompt-cmd-list>div {
border: solid 2px rgba(80,80,80,.3);
border-radius: 5px;
background-color: #fff;
}
html.dark .chat-prompt-cmd-list>div {
background-color: #4a4a4a;
}
html.dark .chat-prompt-cmd-list .cmd-item {
border-color: #666;
}
html.dark .chat-prompt-cmd-list .cmd-item b {
color: #e8e8e8;
}
html.dark .chat-prompt-cmd-list .cmd-item i {
color: #999;
}
html.dark .chat-prompt-cmd-list .cmd-item.selected {
background: rgba(59,130,246,.5);
}
.chat-prompt-cmd-list .cmd-item {
font-size: 12px;
border-bottom: solid 1px rgba(80,80,80,.2);
padding: 2px 4px;
display: flex;
user-select: none;
cursor: pointer;
}
.chat-prompt-cmd-list .cmd-item:last-child {
border-bottom: none;
}
.chat-prompt-cmd-list .cmd-item.selected {
background: rgba(59,130,246,.3);
}
.chat-prompt-cmd-list .cmd-item b {
display: inline-block;
width: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border-radius: 4px;
margin-right: 10px;
color: #2a2a2a;
}
.chat-prompt-cmd-list .cmd-item i {
width: 100%;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
color: #888;
}
.chatappico {
width: 1rem;
height: 1rem;
}
.chatappico.png {
width: 0.8rem;
height: 0.9rem;
}
#download-markdown-button,
#download-png-button,
#download-pdf-button,
#refresh-page-button {
border: none;
}
@media screen and (max-width: 767px) {
#download-png-button, #download-pdf-button, #download-html-button {
display: none;
}
}
`;
document.head.append(styleDom);
if (window.formInterval) {
clearInterval(window.formInterval);
}
window.formInterval = setInterval(() => {
const form = document.querySelector('form textarea');
if (!form) return;
clearInterval(window.formInterval);
cmdTip();
new MutationObserver(function (mutationsList) {
for (const mutation of mutationsList) {
if (mutation.target.getAttribute('id') === '__next') {
initDom();
cmdTip();
}
if (mutation.target.getAttribute('class') === 'chat-prompt-cmd-list') {
// The `chatgpt prompt` fill can be done by clicking on the event.
const searchDom = document.querySelector('form .chat-prompt-cmd-list>div');
const searchInput = document.querySelector('form textarea');
if (!searchDom) return;
searchDom.addEventListener('click', (event) => {
const item = event.target.closest('div');
if (item) {
const val = decodeURIComponent(item.getAttribute('data-prompt'));
searchInput.value = val;
document.querySelector('form textarea').focus();
initDom();
}
});
}
if (mutation.type === 'childList' && mutation.removedNodes.length) {
for (let node of mutation.removedNodes) {
if (node.querySelector('form textarea')) {
initDom();
cmdTip();
(async function () {
async function platform() {
return invoke('platform', {
__tauriModule: 'Os',
message: { cmd: 'platform' },
});
}
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
const _platform = await platform();
const chatConf = (await invoke('get_app_conf')) || {};
if (/darwin/.test(_platform) && !chatConf.titlebar) {
const nav = document.body.querySelector('nav');
if (nav) {
nav.style.paddingTop = '25px';
}
}
}
})();
}
}
}
}
}).observe(document.body, {
childList: true,
subtree: true,
});
}, 300);
async function cmdTip() {
initDom();
const chatPromptJson = (await invoke('get_chat_prompt_cmd')) || {};
const data = chatPromptJson.data;
if (data.length <= 0) return;
let promptDom = document.querySelector('.chat-prompt-cmd-list');
if (!promptDom) {
const dom = document.createElement('div');
dom.classList.add('chat-prompt-cmd-list');
document.querySelector('form').appendChild(dom);
promptDom = document.querySelector('.chat-prompt-cmd-list');
// fix: tray window
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
promptDom.style.bottom = '54px';
}
const convertToSafeHtml = (v) => {
return JSON.stringify(v, null, 2)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
};
const itemDom = (v) =>
`<div class="cmd-item" title="${convertToSafeHtml(v.prompt)}" data-cmd="${
v.cmd
}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${
v.act
}</i></div>`;
const renderList = (v) => {
initDom();
promptDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
window.__CHAT_CMD_PROMPT__ = v[0]?.prompt.trim();
window.__CHAT_CMD__ = v[0]?.cmd.trim();
window.__cmd_list = promptDom.querySelectorAll('.cmd-item');
window.__cmd_index = 0;
window.__cmd_list[window.__cmd_index].classList.add('selected');
};
const setPrompt = (v = '') => {
if (v.trim()) {
window.__CHAT_CMD_PROMPT__ = window.__CHAT_CMD_PROMPT__?.replace(
/\{([^{}]*)\}/,
`{${v.trim()}}`,
);
}
};
const searchInput = document.querySelector('form textarea');
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
// If more than one command appears in the search results, the first one will be used by default.
function cmdKeydown(event) {
if (!window.__CHAT_CMD_PROMPT__) {
if (
!event.shiftKey &&
event.keyCode === 13 &&
__TAURI_METADATA__.__currentWindow.label === 'tray'
) {
const btn = document.querySelector('form button');
if (btn) btn.click();
event.preventDefault();
}
return;
}
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
if (event.keyCode === 38 && window.__cmd_index > 0) {
// ArrowUp
window.__cmd_list[window.__cmd_index].classList.remove('selected');
window.__cmd_index = window.__cmd_index - 1;
window.__cmd_list[window.__cmd_index].classList.add('selected');
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
);
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
event.preventDefault();
}
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) {
// ArrowDown
window.__cmd_list[window.__cmd_index].classList.remove('selected');
window.__cmd_index = window.__cmd_index + 1;
window.__cmd_list[window.__cmd_index].classList.add('selected');
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
);
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
event.preventDefault();
}
const containerHeight = promptDom.offsetHeight;
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
const itemBottom = itemTop + itemHeight;
if (itemTop < promptDom.scrollTop || itemBottom > promptDom.scrollTop + containerHeight) {
promptDom.scrollTop = itemTop;
}
// ------------------ TAB key replaces `{q}` tag content -------------------------------
// feat: https://github.com/lencx/ChatGPT/issues/54
if (event.keyCode === 9 && !window.__CHAT_STATUS__) {
const strGroup = window.__CHAT_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
if (strGroup[1]) {
searchInput.value = `/${window.__CHAT_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
window.__CHAT_STATUS__ = 1;
} else {
searchInput.value = window.__CHAT_CMD_PROMPT__;
initDom();
}
event.preventDefault();
}
if (window.__CHAT_STATUS__ === 1 && event.keyCode === 9) {
// TAB
const data = searchInput.value.split('|->');
if (data[1]?.trim()) {
setPrompt(data[1]);
window.__CHAT_STATUS__ = 2;
}
event.preventDefault();
}
// input text
if (window.__CHAT_STATUS__ === 2 && event.keyCode === 9) {
// TAB
searchInput.value = window.__CHAT_CMD_PROMPT__;
promptDom.innerHTML = '';
delete window.__CHAT_STATUS__;
event.preventDefault();
}
// ------------------ type in a space to complete the fill ------------------------------------
if (event.keyCode === 32) {
searchInput.value = window.__CHAT_CMD_PROMPT__;
promptDom.innerHTML = '';
delete window.__CHAT_CMD_PROMPT__;
}
// ------------------ send --------------------------------------------------------------------
if (event.keyCode === 13 && window.__CHAT_CMD_PROMPT__) {
// Enter
const data = searchInput.value.split('|->');
setPrompt(data[1]);
searchInput.value = window.__CHAT_CMD_PROMPT__;
initDom();
event.preventDefault();
}
}
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
function cmdInput() {
if (searchInput.value === '') {
initDom();
}
if (window.__CHAT_STATUS__) return;
const query = searchInput.value;
if (!query || !/^\//.test(query)) {
initDom();
return;
}
// all cmd result
if (query === '/') {
renderList(data);
return;
}
const result = data.filter((i) => new RegExp(query.substring(1)).test(i.cmd));
if (result.length > 0) {
renderList(result);
} else {
initDom();
}
}
searchInput.removeEventListener('input', cmdInput);
searchInput.addEventListener('input', cmdInput);
}
}
function initDom() {
const promptDom = document.querySelector('.chat-prompt-cmd-list');
if (promptDom) {
promptDom.innerHTML = '';
}
delete window.__CHAT_CMD_PROMPT__;
delete window.__CHAT_CMD__;
delete window.__CHAT_STATUS__;
delete window.__cmd_list;
delete window.__cmd_index;
}
}
if (document.readyState === 'complete' || document.readyState === 'interactive') {
cmdInit();
} else {
document.addEventListener('DOMContentLoaded', cmdInit);
}

229
scripts/core.js vendored Normal file
View File

@ -0,0 +1,229 @@
/**
* @name core.js
* @version 0.1.2
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/core.js
*/
function coreInit() {
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
function transformCallback(callback = () => {}, once = false) {
const identifier = uid();
const prop = `_${identifier}`;
Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop);
}
return callback(result);
},
writable: false,
configurable: true,
});
return identifier;
}
async function invoke(cmd, args) {
return new Promise((resolve, reject) => {
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
const callback = transformCallback((e) => {
resolve(e);
Reflect.deleteProperty(window, `_${error}`);
}, true);
const error = transformCallback((e) => {
reject(e);
Reflect.deleteProperty(window, `_${callback}`);
}, true);
window.__TAURI_POST_MESSAGE__({
cmd,
callback,
error,
...args,
});
});
}
async function message(message) {
invoke('messageDialog', {
__tauriModule: 'Dialog',
message: {
cmd: 'messageDialog',
message: message.toString(),
title: null,
type: null,
buttonLabel: null,
},
});
}
window.uid = uid;
window.invoke = invoke;
window.message = message;
window.transformCallback = transformCallback;
async function init() {
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
}
async function platform() {
return invoke('platform', {
__tauriModule: 'Os',
message: { cmd: 'platform' },
});
}
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
const _platform = await platform();
const chatConf = (await invoke('get_app_conf')) || {};
if (/darwin/.test(_platform) && !chatConf.titlebar) {
const topStyleDom = document.createElement('style');
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
document.head.appendChild(topStyleDom);
const topDom = document.createElement('div');
topDom.id = 'chatgpt-app-window-top';
document.body.appendChild(topDom);
if (window.location.host === 'chat.openai.com') {
const intervalId = setInterval(function () {
const nav = document.body.querySelector('nav');
if (nav) {
nav.style.paddingTop = '25px';
clearInterval(intervalId);
}
}, 1000);
}
topDom.addEventListener('mousedown', () => invoke('drag_window'));
topDom.addEventListener('touchstart', () => invoke('drag_window'));
topDom.addEventListener('dblclick', () => invoke('fullscreen'));
}
}
document.addEventListener('click', (e) => {
const origin = e.target.closest('a');
if (!origin || !origin.target) return;
if (origin && origin.href && origin.target !== '_self') {
invoke('open_link', { url: origin.href });
}
});
// Fix Chinese input method "Enter" on Safari
document.addEventListener(
'keydown',
(e) => {
if (e.keyCode == 229) e.stopPropagation();
},
true,
);
if (window.location.host === 'chat.openai.com') {
window.__sync_prompts = async function () {
await invoke('sync_prompts', { time: Date.now() });
};
}
coreZoom();
window.__LoadingMask = LoadingMask;
}
function coreZoom() {
const styleDom = document.createElement('style');
styleDom.innerHTML = `
#ZoomTopTip {
display: none;
position: fixed;
top: 0;
right: 20px;
background: #2a2a2a;
color: #fafafa;
padding: 20px 15px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
font-size: 16px;
font-weight: bold;
z-index: 999999;
box-shadow: 0 2px 2px 2px #d8d8d8;
}
.ZoomTopTipAni {
transition: opacity 200ms, display 200ms;
display: none;
opacity: 0;
}
`;
document.head.append(styleDom);
const zoomTipDom = document.createElement('div');
zoomTipDom.id = 'ZoomTopTip';
document.body.appendChild(zoomTipDom);
function zoom(callback) {
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
const htmlZoom = window.localStorage.getItem('htmlZoom') || '100%';
const html = document.getElementsByTagName('html')[0];
const zoom = callback(htmlZoom);
html.style.zoom = zoom;
window.localStorage.setItem('htmlZoom', zoom);
zoomTipDom.innerHTML = zoom;
zoomTipDom.style.display = 'block';
zoomTipDom.classList.remove('ZoomTopTipAni');
window.zoomSetTimeout = setTimeout(() => {
zoomTipDom.classList.add('ZoomTopTipAni');
}, 2500);
}
function zoomDefault() {
const htmlZoom = window.localStorage.getItem('htmlZoom');
if (htmlZoom) {
document.getElementsByTagName('html')[0].style.zoom = htmlZoom;
}
}
function zoomIn() {
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
}
function zoomOut() {
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
}
function zoom0() {
zoom(() => `100%`);
}
zoomDefault();
window.__zoomIn = zoomIn;
window.__zoomOut = zoomOut;
window.__zoom0 = zoom0;
}
function LoadingMask(text = 'Loading...') {
// 创建遮罩元素
const loadingOverlay = document.createElement('div');
function startLoading() {
loadingOverlay.style = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,.5);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;`;
loadingOverlay.innerHTML = `<div style="color:#fff;font-weight:bold">${text}</div>`;
document.body.style.overflow = 'hidden';
document.body.appendChild(loadingOverlay);
}
function stopLoading() {
document.body.style.overflow = null;
loadingOverlay.remove();
}
return { startLoading, stopLoading };
}
init();
}
if (document.readyState === 'complete' || document.readyState === 'interactive') {
coreInit();
} else {
document.addEventListener('DOMContentLoaded', coreInit);
}

View File

@ -1,8 +1,12 @@
// *** Core Script - DALL·E 2 *** /**
* @name dalle2.js
* @version 0.1.0
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/dalle2.js
*/
function init() { function dalle2Init() {
document.addEventListener("click", (e) => { document.addEventListener('click', (e) => {
const origin = e.target.closest("a"); const origin = e.target.closest('a');
if (!origin || !origin.target) return; if (!origin || !origin.target) return;
if (origin && origin.href && origin.target !== '_self') { if (origin && origin.href && origin.target !== '_self') {
if (/\/(login|signup)$/.test(window.location.href)) { if (/\/(login|signup)$/.test(window.location.href)) {
@ -27,14 +31,11 @@ function init() {
searchInput.focus(); searchInput.focus();
searchInput.value = query; searchInput.value = query;
} }
}, 200) }, 200);
} }
if ( if (document.readyState === 'complete' || document.readyState === 'interactive') {
document.readyState === "complete" || dalle2Init();
document.readyState === "interactive"
) {
init();
} else { } else {
document.addEventListener("DOMContentLoaded", init); document.addEventListener('DOMContentLoaded', dalle2Init);
} }

33
scripts/download.js vendored
View File

@ -1,33 +0,0 @@
const fs = require('fs');
const argv = process.argv.slice(2);
async function rewrite(filename) {
const content = fs.readFileSync(filename, 'utf8').split('\n');
const startRe = /<!-- download start -->/;
const endRe = /<!-- download end -->/;
let flag = false;
for (let i = 0; i < content.length; i++) {
if (startRe.test(content[i])) {
flag = true;
}
if (flag) {
if (!/winget install --id=lencx.ChatGPT -e --version/.test(content[i])) {
content[i] = content[i].replace(/(\d+).(\d+).(\d+)/g, argv[0]);
}
}
if (endRe.test(content[i])) {
break;
}
}
fs.writeFileSync(filename, content.join('\n'), 'utf8');
}
async function init() {
rewrite('README.md');
rewrite('README-ZH_CN.md');
}
init().catch(console.error);

309
scripts/export.js vendored Normal file
View File

@ -0,0 +1,309 @@
/**
* @name export.js
* @version 0.1.5
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/export.js
*/
async function exportInit() {
const SELECTOR = 'main div.group';
const USER_INPUT_SELECTOR = 'div.empty\\:hidden';
const Format = {
PNG: 'png',
PDF: 'pdf',
};
function processNode(node, replaceInUserInput = false) {
let j = node.cloneNode(true);
if (/dark\:bg-gray-800/.test(node.getAttribute('class'))) {
j.innerHTML = `<blockquote>${node.innerHTML}</blockquote>`;
}
if (replaceInUserInput) {
const userInputBlocks = j.querySelectorAll(USER_INPUT_SELECTOR);
userInputBlocks.forEach((block) => {
//For quicker testing use js fiddle: https://jsfiddle.net/xtraeme/x34ao9jp/13/
block.innerHTML = block.innerHTML
.replace(/&nbsp;|\u00A0/g, ' ') //Replace =C2=A0 (nbsp non-breaking space) /w breaking-space
.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') // Replace tab with 4 non-breaking spaces
.replace(/^ +/gm, function (match) {
return '&nbsp;'.repeat(match.length);
}) //Add =C2=A0
.replace(/\n/g, '<br/>');
});
}
return j.innerHTML;
}
async function exportMarkdown() {
const allBlocks = document.querySelectorAll(SELECTOR);
const nodes = Array.from(allBlocks);
//<code> blocks with leading spaces mess up ExportMD markdown conversion. ex/
// <code ...> import package
//becomes (spaces are moved to the front of the ''' line)):
// '''Python import package
//so we remove whitespace after <code> tags and add <br/> and/or \n
allBlocks.forEach((block) => {
block.innerHTML = block.innerHTML.replace(/(<code[^>]*>)\s*/g, '$1<br\\/>\n'); // Add \n or <br/> after opening code tag
});
const updatedContent = nodes.map((i) => processNode(i, true)).join('');
const data = ExportMD.turndown(updatedContent);
const { id, filename } = getName();
await invoke('save_file', { name: `notes/${id}.md`, content: data });
await invoke('download_list', { pathname: 'chat.notes.json', filename, id, dir: 'notes' });
}
async function downloadThread({ as = Format.PNG } = {}) {
const { startLoading, stopLoading } = new window.__LoadingMask('Exporting in progress...');
startLoading();
const elements = new Elements();
await elements.fixLocation();
const pixelRatio = window.devicePixelRatio;
const minRatio = as === Format.PDF ? 2 : 2.5;
window.devicePixelRatio = Math.max(pixelRatio, minRatio);
html2canvas(elements.thread, {
letterRendering: true,
useCORS: true,
}).then((canvas) => {
elements.restoreLocation();
window.devicePixelRatio = pixelRatio;
const imgData = canvas.toDataURL('image/png');
requestAnimationFrame(async () => {
if (as === Format.PDF) {
await handlePdf(imgData, canvas, pixelRatio);
} else {
await handleImg(imgData);
}
stopLoading();
});
});
}
async function handleImg(imgData) {
const binaryData = atob(imgData.split('base64,')[1]);
const data = [];
for (let i = 0; i < binaryData.length; i++) {
data.push(binaryData.charCodeAt(i));
}
const name = `ChatGPT_${formatDateTime()}.png`;
await invoke('download_file', { name: name, blob: data });
}
async function handlePdf(imgData, canvas, pixelRatio) {
const { jsPDF } = window.jspdf;
const orientation = canvas.width > canvas.height ? 'l' : 'p';
var pdf = new jsPDF(orientation, 'pt', [canvas.width / pixelRatio, canvas.height / pixelRatio]);
var pdfWidth = pdf.internal.pageSize.getWidth();
var pdfHeight = pdf.internal.pageSize.getHeight();
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight, '', 'FAST');
const data = pdf.__private__.getArrayBuffer(pdf.__private__.buildDocument());
const name = `ChatGPT_${formatDateTime()}.pdf`;
await invoke('download_file', { name: name, blob: Array.from(new Uint8Array(data)) });
}
class Elements {
constructor() {
this.init();
}
init() {
this.spacer = document.querySelector("main div[class*='h-'].flex-shrink-0");
this.thread = document.querySelector(
"[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div",
);
// fix: old chat https://github.com/lencx/ChatGPT/issues/185
if (!this.thread) {
this.thread = document.querySelector('main .overflow-y-auto');
}
// h-full overflow-y-auto
this.positionForm = document.querySelector('form').parentNode;
this.scroller = Array.from(document.querySelectorAll('[class*="react-scroll-to"]')).filter(
(el) => el.classList.contains('h-full'),
)[0];
// fix: old chat
if (!this.scroller) {
this.scroller = document.querySelector('main .overflow-y-auto');
}
this.hiddens = Array.from(document.querySelectorAll('.overflow-hidden'));
this.images = Array.from(document.querySelectorAll('img[srcset]'));
this.chatImages = Array.from(document.querySelectorAll('main img[src]'));
}
async fixLocation() {
this.hiddens.forEach((el) => {
el.classList.remove('overflow-hidden');
});
this.spacer.style.display = 'none';
this.thread.style.maxWidth = '960px';
this.thread.style.marginInline = 'auto';
this.positionForm.style.display = 'none';
this.scroller.classList.remove('h-full');
this.scroller.style.minHeight = '100vh';
this.images.forEach((img) => {
const srcset = img.getAttribute('srcset');
img.setAttribute('srcset_old', srcset);
img.setAttribute('srcset', '');
});
const chatImagePromises = this.chatImages.map(async (img) => {
const src = img.getAttribute('src');
if (!/^http/.test(src)) return;
if (['fileserviceuploadsperm.blob.core.windows.net'].includes(new URL(src)?.host)) return;
const data = await invoke('fetch_image', { url: src });
const blob = new Blob([new Uint8Array(data)], { type: 'image/png' });
img.src = URL.createObjectURL(blob);
});
await Promise.all(chatImagePromises);
document.body.style.lineHeight = '0.5';
}
async restoreLocation() {
this.hiddens.forEach((el) => {
el.classList.add('overflow-hidden');
});
this.spacer.style.display = null;
this.thread.style.maxWidth = null;
this.thread.style.marginInline = null;
this.positionForm.style.display = null;
this.scroller.classList.add('h-full');
this.scroller.style.minHeight = null;
}
}
function formatDateTime() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const formattedDateTime = `${year}_${month}_${day}-${hours}${minutes}${seconds}`;
return formattedDateTime;
}
// function sanitizeFilename(filename) {
// if (!filename || filename === '') return '';
// // Replace whitespaces with underscores
// let sanitizedFilename = filename.replace(/\s/g, '_');
// // Replace invalid filename characters with #
// const invalidCharsRegex = /[<>:"/\\|?*\x00-\x1F]/g;
// sanitizedFilename = sanitizedFilename.replace(invalidCharsRegex, '#');
// // Check for filenames ending with period or space (Windows)
// if (sanitizedFilename && /[\s.]$/.test(sanitizedFilename)) {
// sanitizedFilename = sanitizedFilename.slice(0, -1) + '#';
// }
// //console.log(sanitizedFilename);
// return sanitizedFilename;
// }
function btnInit() {
const intervalId = setInterval(function () {
const navActionArea = document.querySelector('nav .border-t > div');
const addArea = document.querySelector('#chatgpt-nav-action-area');
if (!navActionArea || addArea) return;
const cloneNode = document.createElement('div');
cloneNode.id = 'chatgpt-nav-action-area';
cloneNode.classList = `${navActionArea.className} border-b border-white/20 mb-2 pb-2`;
cloneNode.appendChild(addBtn('png'));
cloneNode.appendChild(addBtn('pdf'));
cloneNode.appendChild(addBtn('md'));
cloneNode.appendChild(addBtn('refresh'));
navActionArea.parentNode.insertBefore(cloneNode, navActionArea);
clearInterval(intervalId);
function debounce(func, wait) {
let timeout;
return function () {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
const target = document.querySelector('nav');
const debouncedFunction = debounce(function () {
btnInit();
}, 300);
const observer = new MutationObserver(debouncedFunction);
const config = { attributes: true, childList: true, characterData: true, subtree: true };
observer.observe(target, config);
}, 1000);
}
function addBtn(type) {
const btn = document.createElement('button');
btn.className = `btn dark:text-gray-500 hover:dark:text-gray-300`;
btn.title = {
png: 'Export PNG',
pdf: 'Export PDF',
md: 'Export Markdown',
refresh: 'Refresh the Page',
}[type];
btn.innerHTML = setIcon(type);
btn.onclick = () => {
const content = document.querySelector('main .group');
if (!content && type !== 'refresh') {
alert('Please open a thread first.');
return;
}
switch (type) {
case 'png':
downloadThread();
break;
case 'pdf':
downloadThread({ as: 'pdf' });
break;
case 'md':
exportMarkdown();
break;
case 'refresh':
window.location.reload();
break;
default:
break;
}
};
return btn;
}
function setIcon(type) {
return {
png: `<svg class="chatappico png" viewBox="0 0 1024 1024"><path d="M264.258065 338.580645c16.780387 0 31.281548-6.144 43.536516-18.398968 12.254968-12.221935 18.398968-26.756129 18.398967-43.536516s-6.144-31.281548-18.398967-43.536516A59.524129 59.524129 0 0 0 264.258065 214.709677c-16.780387 0-31.281548 6.144-43.536517 18.398968-12.254968 12.221935-18.398968 26.756129-18.398967 43.536516s6.144 31.281548 18.398967 43.536516c12.221935 12.254968 26.756129 18.398968 43.536517 18.398968zM883.612903 28.903226H140.387097a119.345548 119.345548 0 0 0-87.568516 36.302451A119.345548 119.345548 0 0 0 16.516129 152.774194v743.225806c0 34.188387 12.089806 63.388903 36.302452 87.568516a119.345548 119.345548 0 0 0 87.568516 36.302452h743.225806a119.345548 119.345548 0 0 0 87.568516-36.302452A119.345548 119.345548 0 0 0 1007.483871 896v-743.225806a119.345548 119.345548 0 0 0-36.302452-87.568517A119.345548 119.345548 0 0 0 883.612903 28.903226zM264.258065 152.774194c34.188387 0 63.388903 12.089806 87.568516 36.302451a119.345548 119.345548 0 0 1 36.302451 87.568516 119.345548 119.345548 0 0 1-36.302451 87.568516A119.345548 119.345548 0 0 1 264.258065 400.516129a119.345548 119.345548 0 0 1-87.568517-36.302452A119.345548 119.345548 0 0 1 140.387097 276.645161c0-34.188387 12.089806-63.388903 36.302451-87.568516A119.345548 119.345548 0 0 1 264.258065 152.774194zM140.387097 957.935484c-16.780387 0-31.281548-6.144-43.536516-18.398968a59.524129 59.524129 0 0 1-18.398968-43.536516v-29.035355l245.793032-220.655484L635.870968 957.935484h-495.483871z m805.16129-61.935484c0 16.780387-6.144 31.281548-18.398968 43.536516-12.221935 12.254968-26.756129 18.398968-43.536516 18.398968h-159.677935l-228.385033-231.291871L759.741935 462.451613l185.806452 185.806452v247.741935z" fill="currentColor"></path></svg>`,
pdf: `<svg class="chatappico pdf" viewBox="0 0 1024 1024"><path d="M821.457602 118.382249H205.725895c-48.378584 0-87.959995 39.583368-87.959996 87.963909v615.731707c0 48.378584 39.581411 87.959995 87.959996 87.959996h615.733664c48.380541 0 87.961952-39.581411 87.961952-87.959996V206.346158c-0.001957-48.378584-39.583368-87.963909-87.963909-87.963909zM493.962468 457.544987c-10.112054 32.545237-21.72487 82.872662-38.806571 124.248336-8.806957 22.378397-8.380404 18.480717-15.001764 32.609808l5.71738-1.851007c58.760658-16.443827 99.901532-20.519564 138.162194-27.561607-7.67796-6.06371-14.350194-10.751884-19.631237-15.586807-26.287817-29.101504-35.464584-34.570387-70.440002-111.862636v0.003913z m288.36767 186.413594c-7.476424 8.356924-20.670227 13.191847-40.019704 13.191847-33.427694 0-63.808858-9.229597-107.79277-31.660824-75.648648 8.356924-156.097 17.214754-201.399704 31.729308-2.199293 0.876587-4.832967 1.759043-7.916674 3.077836-54.536215 93.237125-95.031389 132.767663-130.621199 131.19646-11.286054-0.49895-27.694661-7.044-32.973748-10.11988l-6.52157-6.196764-2.29517-4.353583c-3.07588-7.91863-3.954423-15.395054-2.197337-23.751977 4.838837-23.309771 29.907651-60.251638 82.686779-93.237126 8.356924-6.159587 27.430511-15.897917 45.020944-24.25484 13.311204-21.177004 19.45905-34.744531 36.341171-72.259702 19.102937-45.324228 36.505531-99.492589 47.500041-138.191543v-0.44025c-16.267727-53.219378-25.945401-89.310095-9.67376-147.80856 3.958337-16.71189 18.46702-33.864031 34.748444-33.864031h10.552304c10.115967 0 19.791684 3.520043 26.829814 10.552304 29.029107 29.031064 15.39114 103.824649 0.8805 162.323113-0.8805 2.63563-1.322707 4.832967-1.761 6.153717 17.59239 49.697378 45.400538 98.774492 73.108895 121.647926 11.436717 8.791304 22.638634 18.899444 36.71098 26.814161 19.791684-2.20125 37.517128-4.11487 55.547812-4.11487 54.540128 0 87.525615 9.67963 100.279169 30.351814 4.400543 7.034217 6.595923 15.389184 5.281043 24.1844-0.44025 10.996467-4.39663 21.112434-12.31526 29.031064z m-27.796407-36.748157c-4.394673-4.398587-17.024957-16.936907-78.601259-16.936907-3.073923 0-10.622744-0.784623-14.57521 3.612007 32.104987 14.072347 62.830525 24.757704 83.058545 24.757703 3.083707 0 5.72325-0.442207 8.356923-0.876586h1.759044c2.20125-0.8805 3.520043-1.324663 3.960293-5.71738-0.87463-1.324663-1.757087-3.083707-3.958336-4.838837z m-387.124553 63.041845c-9.237424 5.27713-16.71189 10.112054-21.112433 13.634053-31.226444 28.586901-51.018128 57.616008-53.217422 74.331812 19.789727-6.59788 45.737084-35.626987 74.329855-87.961952v-0.003913z m125.574957-297.822284l2.197336-1.761c3.079793-14.072347 5.232127-29.189554 7.87167-38.869184l1.318794-7.036174c4.39663-25.070771 2.71781-39.720334-4.76057-50.272637l-6.59788-2.20125a57.381208 57.381208 0 0 0-3.079794 5.27713c-7.474467 18.47289-7.063567 55.283661 3.0524 94.865072l-0.001956-0.001957z" fill="currentColor"></path></svg>`,
md: `<svg class="chatappico md" viewBox="0 0 1024 1024"><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m170.666667 533.333333v-170.666666l85.333333 85.333333 85.333333-85.333333v170.666666h85.333334v-298.666666h-85.333334l-85.333333 85.333333-85.333333-85.333333H213.333333v298.666666h85.333334z m469.333333-128v-170.666666h-85.333333v170.666666h-85.333334l128 128 128-128h-85.333333z" fill="currentColor"></path></svg>`,
refresh: `<svg class="chatappico refresh" viewBox="0 0 1024 1024"><path d="M512 63.5C264.3 63.5 63.5 264.3 63.5 512S264.3 960.5 512 960.5 960.5 759.7 960.5 512 759.7 63.5 512 63.5zM198 509.6h87.6c0-136.3 102.3-243.4 233.7-238.5 43.8 0 82.8 14.6 121.7 34.1L597.2 349c-24.4-9.8-53.6-19.5-82.8-19.5-92.5 0-170.4 77.9-170.4 180.1h87.6L314.8 631.3 198 509.6z m540.3-0.1c0 131.4-102.2 243.4-228.8 243.4-43.8 0-82.8-19.4-121.7-38.9l43.8-43.8c24.4 9.8 53.6 19.5 82.8 19.5 92.5 0 170.4-77.9 170.4-180.1h-92.5l116.9-121.7L826 509.5h-87.7z" fill="currentColor"></path></svg>`,
}[type];
}
function getName() {
const id = window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36);
const name =
document.querySelector('nav .overflow-y-auto a.hover\\:bg-gray-800')?.innerText?.trim() || '';
// clean_name = sanitizeFilename(name);
return {
id,
filename: name ? name : id,
pathname: 'chat.download.json',
};
}
btnInit();
}
if (document.readyState === 'complete' || document.readyState === 'interactive') {
exportInit();
} else {
document.addEventListener('DOMContentLoaded', exportInit);
}

5
scripts/main.js vendored Normal file
View File

@ -0,0 +1,5 @@
// *** ChatGPT User Script ***
// @github: https://github.com/lencx/ChatGPT
// @path: $HOME/.chatgpt/scripts/main.js
console.log('Hello, ChatGPT!');

36
scripts/manifest.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "ChatGPT Scripts",
"author": "lencx",
"description": "ChatGPT Desktop Application Core Extension Scripts.",
"url": "https://github.com/lencx/ChatGPT/tree/main/scripts",
"scripts": [
{
"name": "chat.js",
"version": "0.1.4"
},
{
"name": "cmd.js",
"version": "0.1.2"
},
{
"name": "core.js",
"version": "0.1.2"
},
{
"name": "dalle2.js",
"version": "0.1.0"
},
{
"name": "export.js",
"version": "0.1.5"
},
{
"name": "markdown.export.js",
"version": "0.1.0"
},
{
"name": "popup.core.js",
"version": "0.1.0"
}
]
}

View File

@ -1,16 +1,24 @@
/**
* @name markdown.export.js
* @version 0.1.0
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/markdown.export.js
*/
var ExportMD = (function () { var ExportMD = (function () {
if (!TurndownService || !turndownPluginGfm) return; if (!TurndownService || !turndownPluginGfm) return;
const hljsREG = /^.*(hljs).*(language-[a-z0-9]+).*$/i; const hljsREG = /^.*(hljs).*(language-[a-z0-9]+).*$/i;
const gfm = turndownPluginGfm.gfm const gfm = turndownPluginGfm.gfm;
const turndownService = new TurndownService() const turndownService = new TurndownService({
hr: '---',
})
.use(gfm) .use(gfm)
.addRule('code', { .addRule('code', {
filter: (node) => { filter(node) {
if (node.nodeName === 'CODE' && hljsREG.test(node.classList.value)) { if (node.nodeName === 'CODE' && hljsREG.test(node.classList.value)) {
return 'code'; return 'code';
} }
}, },
replacement: (content, node) => { replacement(content, node) {
const classStr = node.getAttribute('class'); const classStr = node.getAttribute('class');
if (hljsREG.test(classStr)) { if (hljsREG.test(classStr)) {
const lang = classStr.match(/.*language-(\w+)/)[1]; const lang = classStr.match(/.*language-(\w+)/)[1];
@ -19,18 +27,26 @@ var ExportMD = (function () {
} }
return `\`\`\`\n${content}\n\`\`\``; return `\`\`\`\n${content}\n\`\`\``;
} }
} },
})
.addRule('ignore-text', {
filter: (node) => {
if (node.nodeName === 'DIV' && node.classList.contains('!invisible')) {
return 'ignore-text';
}
},
replacement: () => '',
}) })
.addRule('ignore', { .addRule('ignore', {
filter: ['button', 'img'], filter: ['button', 'img', 'svg'],
replacement: () => '', replacement: () => '',
}) })
.addRule('table', { .addRule('table', {
filter: 'table', filter: 'table',
replacement: function(content, node) { replacement(content, node) {
return `\`\`\`${content}\n\`\`\``; return `\`\`\`${content}\n\`\`\``;
}, },
}); });
return turndownService; return turndownService;
}({})); })({});

View File

@ -1,7 +1,11 @@
// *** Core Script - DALL·E 2 Core *** /**
* @name popup.core.js
* @version 0.1.0
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/popup.core.js
*/
async function init() { async function popupCoreInit() {
const chatConf = await invoke('get_app_conf') || {}; const chatConf = (await invoke('get_app_conf')) || {};
if (!chatConf.popup_search) return; if (!chatConf.popup_search) return;
if (!window.FloatingUIDOM) return; if (!window.FloatingUIDOM) return;
@ -33,13 +37,15 @@ async function init() {
document.body.addEventListener('mousedown', async (e) => { document.body.addEventListener('mousedown', async (e) => {
selectionMenu.style.display = 'none'; selectionMenu.style.display = 'none';
if (e.target.id === 'chagpt-selection-menu') { if (e.target.id === 'chagpt-selection-menu') {
await invoke('dalle2_search_window', { query: encodeURIComponent(window.__DALLE2_CONTENT__) }); await invoke('dalle2_search_window', {
query: encodeURIComponent(window.__DALLE2_CONTENT__),
});
} else { } else {
delete window.__DALLE2_CONTENT__; delete window.__DALLE2_CONTENT__;
} }
}); });
document.body.addEventListener("mouseup", async (e) => { document.body.addEventListener('mouseup', async (e) => {
selectionMenu.style.display = 'none'; selectionMenu.style.display = 'none';
const selection = window.getSelection(); const selection = window.getSelection();
window.__DALLE2_CONTENT__ = selection.toString().trim(); window.__DALLE2_CONTENT__ = selection.toString().trim();
@ -59,12 +65,8 @@ async function init() {
selectionMenu.style.display = 'block'; selectionMenu.style.display = 'block';
computePosition(rootEl, selectionMenu, { computePosition(rootEl, selectionMenu, {
placement: 'top', placement: 'top',
middleware: [ middleware: [flip(), offset(5), shift({ padding: 5 })],
flip(), }).then(({ x, y }) => {
offset(5),
shift({ padding: 5 })
]
}).then(({x, y}) => {
Object.assign(selectionMenu.style, { Object.assign(selectionMenu.style, {
left: `${x}px`, left: `${x}px`,
top: `${y}px`, top: `${y}px`,
@ -74,11 +76,8 @@ async function init() {
}); });
} }
if ( if (document.readyState === 'complete' || document.readyState === 'interactive') {
document.readyState === "complete" || popupCoreInit();
document.readyState === "interactive"
) {
init();
} else { } else {
document.addEventListener("DOMContentLoaded", init); document.addEventListener('DOMContentLoaded', popupCoreInit);
} }

44
sponsor.html Normal file
View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ChatGPT</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin: 0;
padding: 0;
}
p {
margin: 0;
padding: 5px 10px;
font-weight: bold;
text-align: center;
font-size: 12px;
color: #686868;
}
a {
margin: 20px 10px;
cursor: pointer;
}
img {
width: 240px;
}
</style>
</head>
<body>
<p>🙏 Thank you for your support, which can help ChatGPT Free version to develop better!</p>
<p>🙏 感谢您的支持,可以让 ChatGPT 免费版更好的发展!</p>
<a target="_blank" href="https://www.buymeacoffee.com/lencx">
<img style="width: 160px" src="/bmc.png" />
</a>
<img src="/wxp.png" />
</body>
</html>

View File

@ -22,21 +22,22 @@ thiserror = "1.0.38"
walkdir = "2.3.2" walkdir = "2.3.2"
regex = "1.7.0" regex = "1.7.0"
reqwest = "0.11.13" reqwest = "0.11.13"
wry = "0.24.1"
dark-light = "1.0.0" dark-light = "1.0.0"
wry = "0.*"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.23.0", features = ["macros"] } tokio = { version = "1.23.0", features = ["macros"] }
tauri = { version = "1.2.4", features = ["api-all", "devtools", "global-shortcut", "system-tray", "updater"] } tauri = { version = "1.3.0", features = ["devtools", "dialog-all", "fs-create-dir", "fs-exists", "fs-read-dir", "fs-read-file", "fs-remove-dir", "fs-remove-file", "fs-write-file", "global-shortcut", "global-shortcut-all", "os-all", "path-all", "process-all", "shell-all", "shell-open-api", "system-tray", "updater"] }
tauri-plugin-positioner = { version = "1.0.4", features = ["system-tray"] } tauri-plugin-positioner = { git = "https://github.com/lencx/tauri-plugins-workspace", features = ["system-tray"] }
tauri-plugin-log = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev", features = ["colored"] } tauri-plugin-log = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev", features = ["colored"] }
tauri-plugin-autostart = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" } tauri-plugin-autostart = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" }
tauri-plugin-window-state = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" }
# sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite"] } # sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite"] }
[features] [features]
# by default Tauri runs in production mode # by default Tauri runs in production mode
# when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL # when `tauri dev` runs, it is executed with `cargo run --no-default-features` if `devPath` is an URL
default = [ "custom-protocol" ] default = [ "custom-protocol" ]
# this feature is used used for production builds where `devPath` points to the filesystem # this feature is used for production builds where `devPath` points to the filesystem
# DO NOT remove this # DO NOT remove this
custom-protocol = [ "tauri/custom-protocol" ] custom-protocol = [ "tauri/custom-protocol" ]

View File

@ -18,30 +18,31 @@ pub fn fullscreen(app: AppHandle) {
} }
} }
#[command] // #[command]
pub fn download(app: AppHandle, name: String, blob: Vec<u8>) { // pub fn download(app: AppHandle, name: String, blob: Vec<u8>) {
let win = app.app_handle().get_window("core"); // let win = app.app_handle().get_window("core");
let path = utils::app_root().join(PathBuf::from(name)); // let path = utils::app_root().join(PathBuf::from(name));
utils::create_file(&path).unwrap(); // utils::create_file(&path).unwrap();
fs::write(&path, blob).unwrap(); // fs::write(&path, blob).unwrap();
tauri::api::dialog::message( // tauri::api::dialog::message(
win.as_ref(), // win.as_ref(),
"Save File", // "Save File",
format!("PATH: {}", path.display()), // format!("PATH: {}", path.display()),
); // );
} // }
#[command] #[command]
pub fn save_file(app: AppHandle, name: String, content: String) { pub fn save_file(_app: AppHandle, name: String, content: String) {
let win = app.app_handle().get_window("core"); // let win = app.app_handle().get_window("core");
let path = utils::app_root().join(PathBuf::from(name)); let path = utils::app_root().join(PathBuf::from(name));
utils::create_file(&path).unwrap(); utils::create_file(&path).unwrap();
fs::write(&path, content).unwrap(); fs::write(&path, content).unwrap();
tauri::api::dialog::message( utils::open_file(path);
win.as_ref(), // tauri::api::dialog::message(
"Save File", // win.as_ref(),
format!("PATH: {}", path.display()), // "Save File",
); // format!("PATH: {}", path.display()),
// );
} }
#[command] #[command]
@ -59,6 +60,13 @@ pub fn open_file(path: PathBuf) {
utils::open_file(path); utils::open_file(path);
} }
#[command]
pub fn download_file(name: String, blob: Vec<u8>) {
let file = tauri::api::path::download_dir().unwrap().join(name);
fs::write(&file, blob).unwrap();
utils::open_file(file);
}
#[command] #[command]
pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Option<String> { pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Option<String> {
let is_msg = is_msg.unwrap_or(false); let is_msg = is_msg.unwrap_or(false);
@ -72,3 +80,10 @@ pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Opti
None None
}) })
} }
#[tauri::command]
pub async fn fetch_image(url: String) -> Vec<u8> {
let response = reqwest::get(url).await.unwrap();
let bytes = response.bytes().await.unwrap();
bytes.to_vec()
}

View File

@ -10,41 +10,46 @@ use tauri::{api, command, AppHandle, Manager};
use walkdir::WalkDir; use walkdir::WalkDir;
#[command] #[command]
pub fn get_chat_model_cmd() -> serde_json::Value { pub fn get_chat_prompt_cmd() -> serde_json::Value {
let path = utils::app_root().join("chat.model.cmd.json"); let path = utils::app_root().join("chat.prompt.cmd.json");
let content = fs::read_to_string(path).unwrap_or_else(|_| r#"{"data":[]}"#.to_string()); let content = fs::read_to_string(path).unwrap_or_else(|_| r#"{"data":[]}"#.to_string());
serde_json::from_str(&content).unwrap() serde_json::from_str(&content).unwrap()
} }
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PromptRecord { pub struct PromptBaseRecord {
pub cmd: Option<String>, pub cmd: Option<String>,
pub act: String, pub act: String,
pub prompt: String, pub prompt: String,
} }
#[command] #[command]
pub fn parse_prompt(data: String) -> Vec<PromptRecord> { pub fn parse_prompt(data: String) -> Option<Vec<PromptBaseRecord>> {
let mut rdr = csv::Reader::from_reader(data.as_bytes()); let mut rdr = csv::Reader::from_reader(data.as_bytes());
let mut list = vec![]; let mut list = vec![];
for result in rdr.deserialize() {
let record: PromptRecord = result.unwrap_or_else(|err| { for result in rdr.deserialize::<PromptBaseRecord>() {
error!("parse_prompt: {}", err); match result {
PromptRecord { Ok(record) => {
cmd: None, if !record.act.is_empty() {
act: "".to_string(), list.push(record);
prompt: "".to_string(), }
}
Err(err) => {
error!("parse_prompt: {}", err);
} }
});
if !record.act.is_empty() {
list.push(record);
} }
} }
list
if list.is_empty() {
None
} else {
Some(list)
}
} }
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct ModelRecord { pub struct PromptRecord {
pub cmd: String, pub cmd: String,
pub act: String, pub act: String,
pub prompt: String, pub prompt: String,
@ -53,15 +58,15 @@ pub struct ModelRecord {
} }
#[command] #[command]
pub fn cmd_list() -> Vec<ModelRecord> { pub fn cmd_list() -> Vec<PromptRecord> {
let mut list = vec![]; let mut list = vec![];
for entry in WalkDir::new(utils::app_root().join("cache_model")) for entry in WalkDir::new(utils::app_root().join("cache_prompts"))
.into_iter() .into_iter()
.filter_map(|e| e.ok()) .filter_map(|e| e.ok())
{ {
let file = fs::read_to_string(entry.path().display().to_string()); let file = fs::read_to_string(entry.path().display().to_string());
if let Ok(v) = file { if let Ok(v) = file {
let data: Vec<ModelRecord> = serde_json::from_str(&v).unwrap_or_else(|_| vec![]); let data: Vec<PromptRecord> = serde_json::from_str(&v).unwrap_or_else(|_| vec![]);
let enable_list = data.into_iter().filter(|v| v.enable); let enable_list = data.into_iter().filter(|v| v.enable);
list.extend(enable_list) list.extend(enable_list)
} }
@ -159,96 +164,100 @@ pub fn download_list(pathname: &str, dir: &str, filename: Option<String>, id: Op
} }
#[command] #[command]
pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<ModelRecord>> { pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<PromptRecord>> {
let res = utils::get_data(GITHUB_PROMPTS_CSV_URL, Some(&app)) let res = utils::get_data(GITHUB_PROMPTS_CSV_URL, Some(&app))
.await .await
.unwrap(); .unwrap();
if let Some(v) = res { if let Some(v) = res {
let data = parse_prompt(v) if let Some(data) = parse_prompt(v) {
.iter() let transformed_data = data
.map(move |i| ModelRecord { .iter()
cmd: if i.cmd.is_some() { .map(|i| PromptRecord {
i.cmd.clone().unwrap() cmd: if let Some(cmd) = &i.cmd {
} else { cmd.clone()
utils::gen_cmd(i.act.clone()) } else {
}, utils::gen_cmd(i.act.clone())
act: i.act.clone(), },
prompt: i.prompt.clone(), act: i.act.clone(),
tags: vec!["chatgpt-prompts".to_string()], prompt: i.prompt.clone(),
enable: true, tags: vec!["awesome-chatgpt-prompts".to_string()],
}) enable: true,
.collect::<Vec<ModelRecord>>();
let data2 = data.clone();
let model = utils::app_root().join("chat.model.json");
let model_cmd = utils::app_root().join("chat.model.cmd.json");
let chatgpt_prompts = utils::app_root()
.join("cache_model")
.join("chatgpt_prompts.json");
if !utils::exists(&model) {
fs::write(
&model,
serde_json::json!({
"name": "ChatGPT Model",
"link": "https://github.com/lencx/ChatGPT"
}) })
.to_string(), .collect::<Vec<PromptRecord>>();
let prompts = utils::app_root().join("chat.prompt.json");
let prompt_cmd = utils::app_root().join("chat.prompt.cmd.json");
let chatgpt_prompts = utils::app_root()
.join("cache_prompts")
.join("chatgpt_prompts.json");
if !utils::exists(&prompts) {
fs::write(
&prompts,
serde_json::json!({
"name": "ChatGPT Prompts",
"link": "https://github.com/lencx/ChatGPT"
})
.to_string(),
)
.unwrap();
}
// chatgpt_prompts.json
fs::write(
chatgpt_prompts,
serde_json::to_string_pretty(&transformed_data).unwrap(),
) )
.unwrap(); .unwrap();
let cmd_data = cmd_list();
// chat.prompt.cmd.json
fs::write(
prompt_cmd,
serde_json::to_string_pretty(&serde_json::json!({
"name": "ChatGPT CMD",
"last_updated": time,
"data": cmd_data,
}))
.unwrap(),
)
.unwrap();
let mut kv = HashMap::new();
kv.insert(
"sync_prompts".to_string(),
serde_json::json!({ "id": "chatgpt_prompts", "last_updated": time }),
);
let prompts_data = utils::merge(
&serde_json::from_str(&fs::read_to_string(&prompts).unwrap()).unwrap(),
&kv,
);
// chat.prompt.json
fs::write(
prompts,
serde_json::to_string_pretty(&prompts_data).unwrap(),
)
.unwrap();
// refresh window
api::dialog::message(
app.get_window("core").as_ref(),
"Sync Prompts",
"Prompts data has been synchronized!",
);
window::cmd::window_reload(app.clone(), "core");
window::cmd::window_reload(app, "tray");
return Some(transformed_data);
} }
// chatgpt_prompts.json
fs::write(
chatgpt_prompts,
serde_json::to_string_pretty(&data).unwrap(),
)
.unwrap();
let cmd_data = cmd_list();
// chat.model.cmd.json
fs::write(
model_cmd,
serde_json::to_string_pretty(&serde_json::json!({
"name": "ChatGPT CMD",
"last_updated": time,
"data": cmd_data,
}))
.unwrap(),
)
.unwrap();
let mut kv = HashMap::new();
kv.insert(
"sync_prompts".to_string(),
serde_json::json!({ "id": "chatgpt_prompts", "last_updated": time }),
);
let model_data = utils::merge(
&serde_json::from_str(&fs::read_to_string(&model).unwrap()).unwrap(),
&kv,
);
// chat.model.json
fs::write(model, serde_json::to_string_pretty(&model_data).unwrap()).unwrap();
// refresh window
api::dialog::message(
app.get_window("core").as_ref(),
"Sync Prompts",
"ChatGPT Prompts data has been synchronized!",
);
window::cmd::window_reload(app.clone(), "core");
window::cmd::window_reload(app, "tray");
return Some(data2);
} }
None None
} }
#[command] #[command]
pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<ModelRecord>> { pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<PromptRecord>> {
info!("sync_user_prompts: url => {}", url); info!("sync_user_prompts: url => {}", url);
let res = utils::get_data(&url, None).await.unwrap_or_else(|err| { let res = utils::get_data(&url, None).await.unwrap_or_else(|err| {
error!("chatgpt_http: {}", err); error!("chatgpt_http: {}", err);
@ -256,37 +265,40 @@ pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<Mod
}); });
if let Some(v) = res { if let Some(v) = res {
let data; let data: Option<Vec<PromptBaseRecord>> = if data_type == "csv" {
if data_type == "csv" {
info!("chatgpt_http_csv_parse"); info!("chatgpt_http_csv_parse");
data = parse_prompt(v); parse_prompt(v)
} else if data_type == "json" { } else if data_type == "json" {
info!("chatgpt_http_json_parse"); info!("chatgpt_http_json_parse");
data = serde_json::from_str(&v).unwrap_or_else(|err| { match serde_json::from_str::<Vec<PromptBaseRecord>>(&v) {
error!("chatgpt_http_json_parse: {}", err); Ok(parsed) => Some(parsed),
vec![] Err(err) => {
}); error!("chatgpt_http_json_parse: {}", err);
None
}
}
} else { } else {
error!("chatgpt_http_unknown_type"); error!("chatgpt_http_unknown_type");
data = vec![]; None
};
if let Some(base_records) = data {
let data = base_records
.iter()
.map(|i| PromptRecord {
cmd: i
.cmd
.clone()
.unwrap_or_else(|| utils::gen_cmd(i.act.clone())),
act: i.act.clone(),
prompt: i.prompt.clone(),
tags: vec!["user-sync".to_string()],
enable: true,
})
.collect::<Vec<PromptRecord>>();
return Some(data);
} }
let data = data
.iter()
.map(move |i| ModelRecord {
cmd: if i.cmd.is_some() {
i.cmd.clone().unwrap()
} else {
utils::gen_cmd(i.act.clone())
},
act: i.act.clone(),
prompt: i.prompt.clone(),
tags: vec!["user-sync".to_string()],
enable: true,
})
.collect::<Vec<ModelRecord>>();
return Some(data);
} }
None None

View File

@ -22,8 +22,8 @@ pub fn init() -> Menu {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
MenuItem::About(name.into(), AboutMetadata::default()).into(), MenuItem::About(name.into(), AboutMetadata::default()).into(),
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
CustomMenuItem::new("about".to_string(), "About ChatGPT").into(), CustomMenuItem::new("about", "About ChatGPT").into(),
CustomMenuItem::new("check_update".to_string(), "Check for Updates").into(), CustomMenuItem::new("check_update", "Check for Updates").into(),
MenuItem::Services.into(), MenuItem::Services.into(),
MenuItem::Hide.into(), MenuItem::Hide.into(),
MenuItem::HideOthers.into(), MenuItem::HideOthers.into(),
@ -33,25 +33,24 @@ pub fn init() -> Menu {
]), ]),
); );
let stay_on_top = let stay_on_top = CustomMenuItem::new("stay_on_top", "Stay On Top").accelerator("CmdOrCtrl+T");
CustomMenuItem::new("stay_on_top".to_string(), "Stay On Top").accelerator("CmdOrCtrl+T");
let stay_on_top_menu = if app_conf.stay_on_top { let stay_on_top_menu = if app_conf.stay_on_top {
stay_on_top.selected() stay_on_top.selected()
} else { } else {
stay_on_top stay_on_top
}; };
let theme_light = CustomMenuItem::new("theme_light".to_string(), "Light"); let theme_light = CustomMenuItem::new("theme_light", "Light");
let theme_dark = CustomMenuItem::new("theme_dark".to_string(), "Dark"); let theme_dark = CustomMenuItem::new("theme_dark", "Dark");
let theme_system = CustomMenuItem::new("theme_system".to_string(), "System"); let theme_system = CustomMenuItem::new("theme_system", "System");
let is_dark = app_conf.clone().theme_check("dark"); let is_dark = app_conf.clone().theme_check("dark");
let is_system = app_conf.clone().theme_check("system"); let is_system = app_conf.clone().theme_check("system");
let update_prompt = CustomMenuItem::new("update_prompt".to_string(), "Prompt"); let update_prompt = CustomMenuItem::new("update_prompt", "Prompt");
let update_silent = CustomMenuItem::new("update_silent".to_string(), "Silent"); let update_silent = CustomMenuItem::new("update_silent", "Silent");
// let _update_disable = CustomMenuItem::new("update_disable".to_string(), "Disable"); // let _update_disable = CustomMenuItem::new("update_disable", "Disable");
let popup_search = CustomMenuItem::new("popup_search".to_string(), "Pop-up Search"); let popup_search = CustomMenuItem::new("popup_search", "Pop-up Search");
let popup_search_menu = if app_conf.popup_search { let popup_search_menu = if app_conf.popup_search {
popup_search.selected() popup_search.selected()
} else { } else {
@ -59,7 +58,7 @@ pub fn init() -> Menu {
}; };
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let titlebar = CustomMenuItem::new("titlebar".to_string(), "Titlebar").accelerator("CmdOrCtrl+B"); let titlebar = CustomMenuItem::new("titlebar", "Titlebar").accelerator("CmdOrCtrl+B");
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let titlebar_menu = if app_conf.titlebar { let titlebar_menu = if app_conf.titlebar {
titlebar.selected() titlebar.selected()
@ -67,18 +66,24 @@ pub fn init() -> Menu {
titlebar titlebar
}; };
let system_tray = CustomMenuItem::new("system_tray".to_string(), "System Tray"); let system_tray = CustomMenuItem::new("system_tray", "System Tray");
let system_tray_menu = if app_conf.tray { let system_tray_menu = if app_conf.tray {
system_tray.selected() system_tray.selected()
} else { } else {
system_tray system_tray
}; };
let hide_dock_icon = CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon");
let hide_dock_icon_menu = if app_conf.tray {
hide_dock_icon
} else {
hide_dock_icon.disabled()
};
let auto_update = app_conf.get_auto_update(); let auto_update = app_conf.get_auto_update();
let preferences_menu = Submenu::new( let preferences_menu = Submenu::new(
"Preferences", "Preferences",
Menu::with_items([ Menu::with_items([
CustomMenuItem::new("control_center".to_string(), "Control Center") CustomMenuItem::new("control_center", "Control Center")
.accelerator("CmdOrCtrl+Shift+P") .accelerator("CmdOrCtrl+Shift+P")
.into(), .into(),
MenuItem::Separator.into(), MenuItem::Separator.into(),
@ -86,11 +91,8 @@ pub fn init() -> Menu {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
titlebar_menu.into(), titlebar_menu.into(),
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
CustomMenuItem::new("hide_dock_icon".to_string(), "Hide Dock Icon").into(), hide_dock_icon_menu.into(),
system_tray_menu.into(), system_tray_menu.into(),
CustomMenuItem::new("inject_script".to_string(), "Inject Script")
.accelerator("CmdOrCtrl+J")
.into(),
MenuItem::Separator.into(), MenuItem::Separator.into(),
Submenu::new( Submenu::new(
"Theme", "Theme",
@ -133,17 +135,20 @@ pub fn init() -> Menu {
.into(), .into(),
MenuItem::Separator.into(), MenuItem::Separator.into(),
popup_search_menu.into(), popup_search_menu.into(),
CustomMenuItem::new("sync_prompts".to_string(), "Sync Prompts").into(), CustomMenuItem::new("sync_prompts", "Sync Prompts").into(),
MenuItem::Separator.into(), MenuItem::Separator.into(),
CustomMenuItem::new("go_conf".to_string(), "Go to Config") CustomMenuItem::new("go_conf", "Go to Config")
.accelerator("CmdOrCtrl+Shift+G") .accelerator("CmdOrCtrl+Shift+G")
.into(), .into(),
CustomMenuItem::new("restart".to_string(), "Restart ChatGPT") CustomMenuItem::new("restart", "Restart ChatGPT")
.accelerator("CmdOrCtrl+Shift+R") .accelerator("CmdOrCtrl+Shift+R")
.into(), .into(),
CustomMenuItem::new("clear_conf".to_string(), "Clear Config").into(), CustomMenuItem::new("clear_conf", "Clear Config").into(),
MenuItem::Separator.into(), MenuItem::Separator.into(),
CustomMenuItem::new("buy_coffee".to_string(), "Buy lencx a coffee").into(), CustomMenuItem::new("chatgpt_sponsors", "ChatGPT Sponsors").into(),
MenuItem::Separator.into(),
CustomMenuItem::new("nofwl", "NoFWL Desktop Application").into(),
CustomMenuItem::new("sponsor", "Sponsor Author").into(),
]), ]),
); );
@ -162,38 +167,28 @@ pub fn init() -> Menu {
let view_menu = Submenu::new( let view_menu = Submenu::new(
"View", "View",
Menu::new() Menu::new()
.add_item(CustomMenuItem::new("go_back".to_string(), "Go Back").accelerator("CmdOrCtrl+[")) .add_item(CustomMenuItem::new("go_back", "Go Back").accelerator("CmdOrCtrl+["))
.add_item(CustomMenuItem::new("go_forward", "Go Forward").accelerator("CmdOrCtrl+]"))
.add_item( .add_item(
CustomMenuItem::new("go_forward".to_string(), "Go Forward").accelerator("CmdOrCtrl+]"), CustomMenuItem::new("scroll_top", "Scroll to Top of Screen").accelerator("CmdOrCtrl+Up"),
) )
.add_item( .add_item(
CustomMenuItem::new("scroll_top".to_string(), "Scroll to Top of Screen") CustomMenuItem::new("scroll_bottom", "Scroll to Bottom of Screen")
.accelerator("CmdOrCtrl+Up"),
)
.add_item(
CustomMenuItem::new("scroll_bottom".to_string(), "Scroll to Bottom of Screen")
.accelerator("CmdOrCtrl+Down"), .accelerator("CmdOrCtrl+Down"),
) )
.add_native_item(MenuItem::Separator) .add_native_item(MenuItem::Separator)
.add_item( .add_item(CustomMenuItem::new("zoom_0", "Zoom to Actual Size").accelerator("CmdOrCtrl+0"))
CustomMenuItem::new("zoom_0".to_string(), "Zoom to Actual Size").accelerator("CmdOrCtrl+0"), .add_item(CustomMenuItem::new("zoom_out", "Zoom Out").accelerator("CmdOrCtrl+-"))
) .add_item(CustomMenuItem::new("zoom_in", "Zoom In").accelerator("CmdOrCtrl+Plus"))
.add_item(CustomMenuItem::new("zoom_out".to_string(), "Zoom Out").accelerator("CmdOrCtrl+-"))
.add_item(CustomMenuItem::new("zoom_in".to_string(), "Zoom In").accelerator("CmdOrCtrl+Plus"))
.add_native_item(MenuItem::Separator) .add_native_item(MenuItem::Separator)
.add_item( .add_item(CustomMenuItem::new("reload", "Refresh the Screen").accelerator("CmdOrCtrl+R")),
CustomMenuItem::new("reload".to_string(), "Refresh the Screen").accelerator("CmdOrCtrl+R"),
),
); );
let window_menu = Submenu::new( let window_menu = Submenu::new(
"Window", "Window",
Menu::new() Menu::new()
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new("app_website", "ChatGPT User's Guide"))
"app_website".to_string(), .add_item(CustomMenuItem::new("dalle2", "DALL·E 2"))
"ChatGPT User's Guide",
))
.add_item(CustomMenuItem::new("dalle2".to_string(), "DALL·E 2"))
.add_native_item(MenuItem::Separator) .add_native_item(MenuItem::Separator)
.add_native_item(MenuItem::Minimize) .add_native_item(MenuItem::Minimize)
.add_native_item(MenuItem::Zoom), .add_native_item(MenuItem::Zoom),
@ -202,15 +197,11 @@ pub fn init() -> Menu {
let help_menu = Submenu::new( let help_menu = Submenu::new(
"Help", "Help",
Menu::new() Menu::new()
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new("chatgpt_log", "ChatGPT Log"))
"chatgpt_log".to_string(), .add_item(CustomMenuItem::new("update_log", "Update Log"))
"ChatGPT Log", .add_item(CustomMenuItem::new("report_bug", "Report Bug"))
))
.add_item(CustomMenuItem::new("update_log".to_string(), "Update Log"))
.add_item(CustomMenuItem::new("report_bug".to_string(), "Report Bug"))
.add_item( .add_item(
CustomMenuItem::new("dev_tools".to_string(), "Toggle Developer Tools") CustomMenuItem::new("dev_tools", "Toggle Developer Tools").accelerator("CmdOrCtrl+Shift+I"),
.accelerator("CmdOrCtrl+Shift+I"),
), ),
); );
@ -227,7 +218,6 @@ pub fn init() -> Menu {
pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) { pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
let win = Some(event.window()).unwrap(); let win = Some(event.window()).unwrap();
let app = win.app_handle(); let app = win.app_handle();
let script_path = utils::script_path().to_string_lossy().to_string();
let menu_id = event.menu_item_id(); let menu_id = event.menu_item_id();
let menu_handle = win.menu_handle(); let menu_handle = win.menu_handle();
@ -245,9 +235,8 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
utils::run_check_update(app, false, None); utils::run_check_update(app, false, None);
} }
// Preferences // Preferences
"control_center" => window::cmd::control_window(app), "control_center" => window::cmd::control_window(app, "control".into()),
"restart" => tauri::api::process::restart(&app.env()), "restart" => tauri::api::process::restart(&app.env()),
"inject_script" => open(&app, script_path),
"go_conf" => utils::open_file(utils::app_root()), "go_conf" => utils::open_file(utils::app_root()),
"clear_conf" => utils::clear_conf(&app), "clear_conf" => utils::clear_conf(&app),
"app_website" => window::cmd::wa_window( "app_website" => window::cmd::wa_window(
@ -257,7 +246,15 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
conf::APP_WEBSITE.into(), conf::APP_WEBSITE.into(),
None, None,
), ),
"buy_coffee" => open(&app, conf::BUY_COFFEE.to_string()), "nofwl" => open(&app, conf::NOFWL_APP),
"chatgpt_sponsors" => window::cmd::wa_window(
app,
"chatgpt_sponsors".into(),
"Sponsors".into(),
conf::APP_SPONSORS.into(),
None,
),
"sponsor" => window::sponsor_window(app),
"popup_search" => { "popup_search" => {
let app_conf = AppConf::read(); let app_conf = AppConf::read();
let popup_search = !app_conf.popup_search; let popup_search = !app_conf.popup_search;
@ -392,8 +389,8 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
.unwrap(), .unwrap(),
// Help // Help
"chatgpt_log" => utils::open_file(utils::app_root().join("chatgpt.log")), "chatgpt_log" => utils::open_file(utils::app_root().join("chatgpt.log")),
"update_log" => open(&app, conf::UPDATE_LOG_URL.to_string()), "update_log" => open(&app, conf::UPDATE_LOG_URL),
"report_bug" => open(&app, conf::ISSUES_URL.to_string()), "report_bug" => open(&app, conf::ISSUES_URL),
"dev_tools" => { "dev_tools" => {
win.open_devtools(); win.open_devtools();
win.close_devtools(); win.close_devtools();
@ -406,41 +403,29 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
pub fn tray_menu() -> SystemTray { pub fn tray_menu() -> SystemTray {
if cfg!(target_os = "macos") { if cfg!(target_os = "macos") {
let mut tray_menu = SystemTrayMenu::new() let mut tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new("control_center", "Control Center"))
"control_center".to_string(),
"Control Center",
))
.add_native_item(SystemTrayMenuItem::Separator); .add_native_item(SystemTrayMenuItem::Separator);
if AppConf::read().hide_dock_icon { if AppConf::read().hide_dock_icon {
tray_menu = tray_menu.add_item(CustomMenuItem::new( tray_menu = tray_menu.add_item(CustomMenuItem::new("show_dock_icon", "Show Dock Icon"));
"show_dock_icon".to_string(),
"Show Dock Icon",
));
} else { } else {
tray_menu = tray_menu tray_menu = tray_menu
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon"))
"hide_dock_icon".to_string(), .add_item(CustomMenuItem::new("show_core", "Show Window"));
"Hide Dock Icon",
))
.add_item(CustomMenuItem::new("show_core".to_string(), "Show ChatGPT"));
} }
SystemTray::new().with_menu( SystemTray::new().with_menu(
tray_menu tray_menu
.add_native_item(SystemTrayMenuItem::Separator) .add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit".to_string(), "Quit ChatGPT")), .add_item(CustomMenuItem::new("quit", "Quit")),
) )
} else { } else {
SystemTray::new().with_menu( SystemTray::new().with_menu(
SystemTrayMenu::new() SystemTrayMenu::new()
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new("control_center", "Control Center"))
"control_center".to_string(), .add_item(CustomMenuItem::new("show_core", "Show Window"))
"Control Center",
))
.add_item(CustomMenuItem::new("show_core".to_string(), "Show ChatGPT"))
.add_native_item(SystemTrayMenuItem::Separator) .add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit".to_string(), "Quit ChatGPT")), .add_item(CustomMenuItem::new("quit", "Quit")),
) )
} }
} }
@ -462,7 +447,7 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
} }
if let Some(tray_win) = handle.get_window("tray") { if let Some(tray_win) = handle.get_window("tray") {
tray_win.move_window(Position::TrayCenter).unwrap(); tray_win.move_window(Position::TrayFixedCenter).unwrap();
if tray_win.is_visible().unwrap() { if tray_win.is_visible().unwrap() {
tray_win.hide().unwrap(); tray_win.hide().unwrap();
@ -472,7 +457,7 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
} }
} }
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() { SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"control_center" => window::cmd::control_window(app), "control_center" => window::cmd::control_window(app, "control".into()),
"restart" => tauri::api::process::restart(&handle.env()), "restart" => tauri::api::process::restart(&handle.env()),
"show_dock_icon" => { "show_dock_icon" => {
AppConf::read() AppConf::read()
@ -506,6 +491,6 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
} }
} }
pub fn open(app: &AppHandle, path: String) { pub fn open(app: &AppHandle, path: &str) {
tauri::api::shell::open(&app.shell_scope(), path, None).unwrap(); tauri::api::shell::open(&app.shell_scope(), path, None).unwrap();
} }

View File

@ -2,5 +2,7 @@ pub mod cmd;
pub mod fs_extra; pub mod fs_extra;
pub mod gpt; pub mod gpt;
pub mod menu; pub mod menu;
pub mod script;
pub mod setup; pub mod setup;
pub mod template;
pub mod window; pub mod window;

191
src-tauri/src/app/script.rs Normal file
View File

@ -0,0 +1,191 @@
use crate::utils::{app_root, create_file, exists};
use log::error;
use log::info;
use regex::Regex;
use serde_json::{from_str, json, Value};
use std::fs;
use tauri::Manager;
use crate::{conf::SCRIPTS_DIR, window};
pub async fn init_script(app: tauri::AppHandle) -> anyhow::Result<(), reqwest::Error> {
let body = reqwest::get(format!("{}{}", SCRIPTS_DIR, "manifest.json"))
.await?
.text()
.await?;
if exist_scripts("manifest.json".into()) {
let compare = compare_nested_json_objects(
&fs::read_to_string(app_root().join("scripts").join("manifest.json")).unwrap(),
&body,
);
if !compare {
info!("update_scripts_manifest");
create_chatgpt_scripts("manifest.json".into(), body);
if let Some(v) = app.get_window("core") {
tauri::api::dialog::ask(Some(&v), "Scripts Update", "There are new available scripts. Please go to 'Preferences -> Control Center -> Scripts' to check for updates.", |is_ok| {
if is_ok {
info!("update_scripts_manifest_ok");
// TODO: goto scripts page
window::cmd::control_window(app, "scripts".into())
} else {
info!("update_scripts_manifest_cancel");
}
});
}
}
} else {
create_chatgpt_scripts("manifest.json".into(), body);
}
Ok(())
}
pub fn parse_script(name: String) -> Option<serde_json::Value> {
let script_file = app_root().join("scripts").join(name);
let code = match fs::read_to_string(&script_file) {
Ok(content) => content,
Err(_) => {
error!("parse_script_error: {}", script_file.display());
return None;
}
};
// let code = &fs::read_to_string(name).unwrap();
let re_name = Regex::new(r"@name\s+(.*?)\n").unwrap();
let re_version = Regex::new(r"@version\s+(.*?)\n").unwrap();
let re_url = Regex::new(r"@url\s+(.*?)\n").unwrap();
let mut name = String::new();
let mut version = String::new();
let mut url = String::new();
if let Some(capture) = re_name.captures(&code) {
name = capture.get(1).unwrap().as_str().trim().to_owned();
}
if let Some(capture) = re_version.captures(&code) {
version = capture.get(1).unwrap().as_str().trim().to_owned();
}
if let Some(capture) = re_url.captures(&code) {
url = capture.get(1).unwrap().as_str().trim().to_owned();
}
let json_data = json!({
"name": name,
"version": version,
"url": url,
});
Some(json_data)
}
pub fn exist_scripts(file: String) -> bool {
let script_file = app_root().join("scripts").join(file);
exists(&script_file)
}
pub fn create_chatgpt_scripts(file: String, body: String) {
let script_file = app_root().join("scripts").join(file);
match create_file(&script_file) {
Ok(_) => {
info!("script_file: {:?}", script_file);
fs::write(&script_file, body).unwrap();
}
Err(e) => {
error!("create_file, {}: {}", script_file.display(), e);
}
}
}
fn compare_nested_json_objects(json1: &str, json2: &str) -> bool {
let value1: Value = from_str(json1).unwrap_or_else(|err| {
error!("json_parse_1_error: {}", err);
json!({})
});
let value2: Value = from_str(json2).unwrap_or_else(|err| {
error!("json_parse_2_error: {}", err);
json!({})
});
compare_json_objects(&value1, &value2)
}
pub fn compare_json_objects(obj1: &Value, obj2: &Value) -> bool {
match (obj1, obj2) {
(Value::Object(obj1), Value::Object(obj2)) => {
if obj1.len() != obj2.len() {
return false;
}
for (key, value) in obj1 {
if !obj2.contains_key(key) || !compare_json_objects(value, obj2.get(key).unwrap()) {
return false;
}
}
true
}
(Value::Array(arr1), Value::Array(arr2)) => {
if arr1.len() != arr2.len() {
return false;
}
for (value1, value2) in arr1.iter().zip(arr2.iter()) {
if !compare_json_objects(value1, value2) {
return false;
}
}
true
}
_ => obj1 == obj2,
}
}
pub mod cmd {
use super::{create_chatgpt_scripts, parse_script};
use crate::conf::SCRIPTS_DIR;
use log::{error, info};
use tauri::Manager;
#[tauri::command]
pub fn get_script_info(name: String) -> Option<serde_json::Value> {
parse_script(name)
}
#[tauri::command]
pub async fn sync_scripts(app: tauri::AppHandle, name: String) -> bool {
let res = reqwest::get(format!("{}{}", SCRIPTS_DIR, name)).await;
info!("sync_scripts: {}", name);
let body = match res {
Ok(response) => match response.text().await {
Ok(text) => text,
Err(err) => {
error!("sync_scripts_result_error: {}", err);
if let Some(v) = app.get_window("core") {
tauri::api::dialog::message(
Some(&v),
"Sync Scripts Error",
format!("sync_scripts_result_error: {}", err),
);
}
return false;
}
},
Err(err) => {
error!("sync_scripts_response_error: {}", err);
if let Some(v) = app.get_window("core") {
tauri::api::dialog::message(
Some(&v),
"Sync Scripts Error",
format!("sync_scripts_response_error: {}", err),
);
}
return false;
}
};
create_chatgpt_scripts(name, body);
true
}
}

View File

@ -1,18 +1,34 @@
use crate::{app::window, conf::AppConf, utils}; use crate::{
app,
conf::AppConf,
utils::{self, load_script},
};
use log::{error, info}; use log::{error, info};
use tauri::{utils::config::WindowUrl, window::WindowBuilder, App, GlobalShortcutManager, Manager}; use tauri::{utils::config::WindowUrl, window::WindowBuilder, App, GlobalShortcutManager, Manager};
use wry::application::accelerator::Accelerator; use wry::application::accelerator::Accelerator;
pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>> { pub fn init(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
info!("stepup"); info!("stepup");
let app_conf = AppConf::read(); let app_conf = AppConf::read();
let url = app_conf.main_origin.to_string(); let url = app_conf.main_origin.to_string();
let theme = AppConf::theme_mode(); let theme = AppConf::theme_mode();
let handle = app.app_handle();
app::template::Template::new(utils::app_root().join("scripts"));
let handle = app.app_handle();
tauri::async_runtime::spawn(async move {
app::script::init_script(handle)
.await
.unwrap_or_else(|err| {
error!("script_init_error: {}", err);
});
});
let handle = app.app_handle();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
info!("stepup_tray"); info!("stepup_tray");
window::tray_window(&handle); app::window::tray_window(&handle);
}); });
if let Some(v) = app_conf.clone().global_shortcut { if let Some(v) = app_conf.clone().global_shortcut {
@ -52,21 +68,16 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
} else { } else {
let app = app.handle(); let app = app.handle();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let link = if app_conf2.main_dashboard { let url2 = &url;
"index.html" let mut main_win = WindowBuilder::new(&app, "core", WindowUrl::App(url2.into()))
} else {
&url
};
info!("main_window: {}", link);
let mut main_win = WindowBuilder::new(&app, "core", WindowUrl::App(link.into()))
.title("ChatGPT") .title("ChatGPT")
.resizable(true) .resizable(true)
.fullscreen(false) .fullscreen(false)
.inner_size(800.0, 600.0) .inner_size(app_conf2.main_width, app_conf2.main_height)
.theme(Some(theme)) .theme(Some(theme))
.always_on_top(app_conf2.stay_on_top) .always_on_top(app_conf2.stay_on_top)
.initialization_script(&utils::user_script()) .initialization_script(&utils::user_script())
.initialization_script(include_str!("../scripts/core.js")) .initialization_script(&load_script("core.js"))
.user_agent(&app_conf2.ua_window); .user_agent(&app_conf2.ua_window);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -76,7 +87,7 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
.hidden_title(true); .hidden_title(true);
} }
if url == "https://chat.openai.com" && !app_conf2.main_dashboard { if url == "https://chat.openai.com" {
main_win = main_win main_win = main_win
.initialization_script(include_str!("../vendors/floating-ui-core.js")) .initialization_script(include_str!("../vendors/floating-ui-core.js"))
.initialization_script(include_str!("../vendors/floating-ui-dom.js")) .initialization_script(include_str!("../vendors/floating-ui-dom.js"))
@ -84,13 +95,16 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
.initialization_script(include_str!("../vendors/jspdf.js")) .initialization_script(include_str!("../vendors/jspdf.js"))
.initialization_script(include_str!("../vendors/turndown.js")) .initialization_script(include_str!("../vendors/turndown.js"))
.initialization_script(include_str!("../vendors/turndown-plugin-gfm.js")) .initialization_script(include_str!("../vendors/turndown-plugin-gfm.js"))
.initialization_script(include_str!("../scripts/popup.core.js")) .initialization_script(&load_script("popup.core.js"))
.initialization_script(include_str!("../scripts/export.js")) .initialization_script(&load_script("export.js"))
.initialization_script(include_str!("../scripts/markdown.export.js")) .initialization_script(&load_script("markdown.export.js"))
.initialization_script(include_str!("../scripts/cmd.js")) .initialization_script(&load_script("cmd.js"))
.initialization_script(&load_script("chat.js"))
} }
main_win.build().unwrap(); if let Err(err) = main_win.build() {
error!("core_build_error: {}", err);
}
}); });
} }

View File

@ -0,0 +1,110 @@
use anyhow::Result;
use log::{error, info};
use std::{
fs::{self, File},
io::Write,
path::Path,
};
pub static SCRIPT_MAIN: &[u8] = include_bytes!("../../../scripts/main.js");
pub static SCRIPT_CORE: &[u8] = include_bytes!("../../../scripts/core.js");
pub static SCRIPT_CHAT: &[u8] = include_bytes!("../../../scripts/chat.js");
pub static SCRIPT_CMD: &[u8] = include_bytes!("../../../scripts/cmd.js");
pub static SCRIPT_DALLE2: &[u8] = include_bytes!("../../../scripts/dalle2.js");
pub static SCRIPT_EXPORT: &[u8] = include_bytes!("../../../scripts/export.js");
pub static SCRIPT_MD_EXPORT: &[u8] = include_bytes!("../../../scripts/markdown.export.js");
pub static SCRIPT_POPUP_CORE: &[u8] = include_bytes!("../../../scripts/popup.core.js");
pub static SCRIPT_MANIFEST: &[u8] = include_bytes!("../../../scripts/manifest.json");
pub static SCRIPT_README: &[u8] = include_bytes!("../../../scripts/README.md");
#[derive(Debug)]
pub struct Template {
pub main: Vec<u8>,
pub core: Vec<u8>,
pub chat: Vec<u8>,
pub cmd: Vec<u8>,
pub dalle2: Vec<u8>,
pub export: Vec<u8>,
pub markdown_export: Vec<u8>,
pub popup_core: Vec<u8>,
pub manifest: Vec<u8>,
pub readme: Vec<u8>,
}
impl Template {
pub fn new<P: AsRef<Path>>(template_dir: P) -> Self {
let template_dir = template_dir.as_ref();
let mut template = Template::default();
{
let files = vec![
(template_dir.join("main.js"), &mut template.main),
(template_dir.join("core.js"), &mut template.core),
(template_dir.join("chat.js"), &mut template.chat),
(template_dir.join("cmd.js"), &mut template.cmd),
(template_dir.join("dalle2.js"), &mut template.dalle2),
(template_dir.join("export.js"), &mut template.export),
(
template_dir.join("markdown.export.js"),
&mut template.markdown_export,
),
(template_dir.join("popup.core.js"), &mut template.popup_core),
(template_dir.join("README.md"), &mut template.readme),
(template_dir.join("manifest.json"), &mut template.manifest),
];
for (filename, dest) in files {
if !filename.exists() {
match create_dir(&filename) {
Ok(_) => {
if let Err(e) = write_file_contents(&filename, dest) {
error!("write_script, {}: {}", filename.display(), e);
} else {
info!("write_script: {}", filename.display());
}
}
Err(e) => {
error!("create_file, {}: {}", filename.display(), e);
}
}
}
}
}
template
}
}
impl Default for Template {
fn default() -> Template {
Template {
main: Vec::from(SCRIPT_MAIN),
core: Vec::from(SCRIPT_CORE),
chat: Vec::from(SCRIPT_CHAT),
cmd: Vec::from(SCRIPT_CMD),
dalle2: Vec::from(SCRIPT_DALLE2),
export: Vec::from(SCRIPT_EXPORT),
markdown_export: Vec::from(SCRIPT_MD_EXPORT),
popup_core: Vec::from(SCRIPT_POPUP_CORE),
manifest: Vec::from(SCRIPT_MANIFEST),
readme: Vec::from(SCRIPT_README),
}
}
}
fn create_dir<P: AsRef<Path>>(filename: P) -> Result<()> {
let filename = filename.as_ref();
if let Some(parent) = filename.parent() {
if !parent.exists() {
fs::create_dir_all(parent)?;
}
}
Ok(())
}
pub fn write_file_contents<P: AsRef<Path>>(filename: P, data: &[u8]) -> Result<()> {
let filename = filename.as_ref();
let mut file = File::create(filename)?;
file.write_all(data)?;
Ok(())
}

View File

@ -1,4 +1,7 @@
use crate::{conf::AppConf, utils}; use crate::{
conf::AppConf,
utils::{self, load_script},
};
use log::info; use log::info;
use std::time::SystemTime; use std::time::SystemTime;
use tauri::{utils::config::WindowUrl, window::WindowBuilder, Manager}; use tauri::{utils::config::WindowUrl, window::WindowBuilder, Manager};
@ -18,20 +21,21 @@ pub fn tray_window(handle: &tauri::AppHandle) {
.title("ChatGPT") .title("ChatGPT")
.resizable(false) .resizable(false)
.fullscreen(false) .fullscreen(false)
.inner_size(360.0, 540.0) .inner_size(app_conf.tray_width, app_conf.tray_height)
.decorations(false) .decorations(false)
.always_on_top(true) .always_on_top(true)
.theme(Some(theme)) .theme(Some(theme))
.initialization_script(&utils::user_script()) .initialization_script(&utils::user_script())
.initialization_script(include_str!("../scripts/core.js")) .initialization_script(&load_script("core.js"))
.user_agent(&app_conf.ua_tray); .user_agent(&app_conf.ua_tray);
if app_conf.tray_origin == "https://chat.openai.com" && !app_conf.tray_dashboard { if app_conf.tray_origin == "https://chat.openai.com" && !app_conf.tray_dashboard {
tray_win = tray_win tray_win = tray_win
.initialization_script(include_str!("../vendors/floating-ui-core.js")) .initialization_script(include_str!("../vendors/floating-ui-core.js"))
.initialization_script(include_str!("../vendors/floating-ui-dom.js")) .initialization_script(include_str!("../vendors/floating-ui-dom.js"))
.initialization_script(include_str!("../scripts/cmd.js")) .initialization_script(&load_script("cmd.js"))
.initialization_script(include_str!("../scripts/popup.core.js")) .initialization_script(&load_script("chat.js"))
.initialization_script(&load_script("popup.core.js"))
} }
tray_win.build().unwrap().hide().unwrap(); tray_win.build().unwrap().hide().unwrap();
@ -77,9 +81,9 @@ pub fn dalle2_window(
.inner_size(800.0, 600.0) .inner_size(800.0, 600.0)
.always_on_top(false) .always_on_top(false)
.theme(Some(theme)) .theme(Some(theme))
.initialization_script(include_str!("../scripts/core.js")) .initialization_script(&load_script("core.js"))
.initialization_script(&load_script("dalle2.js"))
.initialization_script(&query) .initialization_script(&query)
.initialization_script(include_str!("../scripts/dalle2.js"))
.build() .build()
.unwrap(); .unwrap();
}); });
@ -90,6 +94,23 @@ pub fn dalle2_window(
} }
} }
pub fn sponsor_window(handle: tauri::AppHandle) {
tauri::async_runtime::spawn(async move {
if let Some(win) = handle.get_window("sponsor") {
win.show().unwrap()
} else {
WindowBuilder::new(&handle, "sponsor", WindowUrl::App("sponsor.html".into()))
.title("Sponsor")
.resizable(true)
.fullscreen(false)
.inner_size(600.0, 600.0)
.min_inner_size(600.0, 600.0)
.build()
.unwrap();
}
});
}
pub mod cmd { pub mod cmd {
use super::*; use super::*;
use log::info; use log::info;
@ -106,13 +127,13 @@ pub mod cmd {
} }
#[tauri::command] #[tauri::command]
pub fn control_window(handle: tauri::AppHandle) { pub fn control_window(handle: tauri::AppHandle, win_type: String) {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
if handle.get_window("main").is_none() { if handle.get_window("main").is_none() {
WindowBuilder::new( WindowBuilder::new(
&handle, &handle,
"main", "main",
WindowUrl::App("index.html?type=control".into()), WindowUrl::App(format!("index.html?type={}", win_type).into()),
) )
.title("Control Center") .title("Control Center")
.resizable(true) .resizable(true)
@ -143,15 +164,14 @@ pub mod cmd {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap())) tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap()))
.initialization_script(&script.unwrap_or_default()) .initialization_script(&script.unwrap_or_default())
.initialization_script(include_str!("../scripts/core.js")) .initialization_script(&load_script("core.js"))
.title(title) .title(title)
.inner_size(960.0, 700.0) .inner_size(960.0, 700.0)
.resizable(true) .resizable(true)
.build() .build()
.unwrap(); .unwrap();
}); });
} } else if let Some(v) = win {
if let Some(v) = win {
if !v.is_visible().unwrap() { if !v.is_visible().unwrap() {
v.show().unwrap(); v.show().unwrap();
} }

View File

@ -9,11 +9,14 @@ use tauri::TitleBarStyle;
use crate::utils::{app_root, create_file, exists}; use crate::utils::{app_root, create_file, exists};
pub const APP_WEBSITE: &str = "https://lencx.github.io/app/"; pub const APP_WEBSITE: &str = "https://lencx.github.io/app/";
pub const APP_SPONSORS: &str = "https://lencx.github.io/app/sponsors";
pub const ISSUES_URL: &str = "https://github.com/lencx/ChatGPT/issues"; pub const ISSUES_URL: &str = "https://github.com/lencx/ChatGPT/issues";
pub const NOFWL_APP: &str = "https://github.com/lencx/nofwl";
pub const UPDATE_LOG_URL: &str = "https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md"; pub const UPDATE_LOG_URL: &str = "https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md";
pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx"; // pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx";
pub const GITHUB_PROMPTS_CSV_URL: &str = pub const GITHUB_PROMPTS_CSV_URL: &str =
"https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"; "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv";
pub const SCRIPTS_DIR: &str = "https://raw.githubusercontent.com/lencx/ChatGPT/main/scripts/";
pub const APP_CONF_PATH: &str = "chat.conf.json"; pub const APP_CONF_PATH: &str = "chat.conf.json";
pub const CHATGPT_URL: &str = "https://chat.openai.com"; pub const CHATGPT_URL: &str = "https://chat.openai.com";
@ -35,17 +38,29 @@ pub_struct!(AppConf {
theme: String, theme: String,
// auto update policy: prompt / silent / disable // auto update policy: prompt / silent / disable
auto_update: String, auto_update: String,
tray: bool,
popup_search: bool,
stay_on_top: bool, stay_on_top: bool,
main_dashboard: bool, save_window_state: bool,
tray_dashboard: bool,
main_origin: String,
tray_origin: String,
default_origin: String,
ua_window: String,
ua_tray: String,
global_shortcut: Option<String>, global_shortcut: Option<String>,
default_origin: String,
speech_lang: String,
// Main Window
isinit: bool,
popup_search: bool,
main_close: bool,
main_dashboard: bool,
main_origin: String,
ua_window: String,
main_width: f64,
main_height: f64,
// Tray Window
tray_width: f64,
tray_height: f64,
tray: bool,
tray_dashboard: bool,
tray_origin: String,
ua_tray: String,
}); });
impl AppConf { impl AppConf {
@ -54,13 +69,24 @@ impl AppConf {
Self { Self {
titlebar: !cfg!(target_os = "macos"), titlebar: !cfg!(target_os = "macos"),
hide_dock_icon: false, hide_dock_icon: false,
save_window_state: true,
theme: "light".into(), theme: "light".into(),
auto_update: "prompt".into(), auto_update: "prompt".into(),
#[cfg(target_os = "macos")]
speech_lang: "com.apple.eloquence.en-US.Rocko".into(),
#[cfg(not(target_os = "macos"))]
speech_lang: "".into(),
tray: true, tray: true,
popup_search: false, popup_search: false,
isinit: true,
main_close: false,
stay_on_top: false, stay_on_top: false,
main_dashboard: false, main_dashboard: false,
tray_dashboard: false, tray_dashboard: false,
main_width: 800.0,
main_height: 600.0,
tray_width: 360.0,
tray_height: 540.0,
main_origin: CHATGPT_URL.into(), main_origin: CHATGPT_URL.into(),
tray_origin: CHATGPT_URL.into(), tray_origin: CHATGPT_URL.into(),
default_origin: CHATGPT_URL.into(), default_origin: CHATGPT_URL.into(),
@ -76,7 +102,14 @@ impl AppConf {
pub fn read() -> Self { pub fn read() -> Self {
match std::fs::read_to_string(Self::file_path()) { match std::fs::read_to_string(Self::file_path()) {
Ok(v) => serde_json::from_str::<AppConf>(&v).unwrap(), Ok(v) => {
if let Ok(v2) = serde_json::from_str::<AppConf>(&v) {
v2
} else {
error!("conf_read_parse_error");
Self::default()
}
}
Err(err) => { Err(err) => {
error!("conf_read_error: {}", err); error!("conf_read_error: {}", err);
Self::default() Self::default()

View File

@ -7,7 +7,7 @@ mod app;
mod conf; mod conf;
mod utils; mod utils;
use app::{cmd, fs_extra, gpt, menu, setup, window}; use app::{cmd, fs_extra, gpt, menu, script, setup, window};
use conf::AppConf; use conf::AppConf;
use tauri_plugin_autostart::MacosLauncher; use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_log::{ use tauri_plugin_log::{
@ -55,13 +55,14 @@ async fn main() {
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
cmd::drag_window, cmd::drag_window,
cmd::fullscreen, cmd::fullscreen,
cmd::download,
cmd::save_file, cmd::save_file,
cmd::open_link, cmd::open_link,
cmd::run_check_update, cmd::run_check_update,
cmd::open_file, cmd::open_file,
cmd::download_file,
cmd::get_data, cmd::get_data,
gpt::get_chat_model_cmd, cmd::fetch_image,
gpt::get_chat_prompt_cmd,
gpt::parse_prompt, gpt::parse_prompt,
gpt::sync_prompts, gpt::sync_prompts,
gpt::sync_user_prompts, gpt::sync_user_prompts,
@ -75,6 +76,8 @@ async fn main() {
conf::cmd::form_confirm, conf::cmd::form_confirm,
conf::cmd::form_cancel, conf::cmd::form_cancel,
conf::cmd::form_msg, conf::cmd::form_msg,
script::cmd::sync_scripts,
script::cmd::get_script_info,
window::cmd::wa_window, window::cmd::wa_window,
window::cmd::control_window, window::cmd::control_window,
window::cmd::window_reload, window::cmd::window_reload,
@ -87,16 +90,41 @@ async fn main() {
builder = builder.system_tray(menu::tray_menu()); builder = builder.system_tray(menu::tray_menu());
} }
if app_conf.save_window_state {
builder = builder.plugin(tauri_plugin_window_state::Builder::default().build());
}
builder builder
.on_menu_event(menu::menu_handler) .on_menu_event(menu::menu_handler)
.on_system_tray_event(menu::tray_handler) .on_system_tray_event(menu::tray_handler)
.on_window_event(|event| { .on_window_event(move |event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event.event() { if let tauri::WindowEvent::CloseRequested { api, .. } = event.event() {
let win = event.window(); let win = event.window().clone();
let app_conf = AppConf::read();
if win.label() == "core" { if win.label() == "core" {
event.window().minimize().unwrap(); if app_conf.isinit {
tauri::api::dialog::ask(
Some(event.window()),
"",
"Do you want to exit the application when you click the [x] button?",
move |is_ok| {
app_conf
.amend(serde_json::json!({ "isinit" : false, "main_close": is_ok }))
.write();
if is_ok {
std::process::exit(0);
} else {
win.minimize().unwrap();
}
},
);
} else if app_conf.main_close {
std::process::exit(0);
} else {
win.minimize().unwrap();
}
} else { } else {
win.close().unwrap(); event.window().close().unwrap();
} }
api.prevent_close(); api.prevent_close();
} }

View File

@ -1,300 +0,0 @@
// *** Core Script - CMD ***
function init() {
const styleDom = document.createElement('style');
styleDom.innerHTML = `form {
position: relative;
}
.chat-model-cmd-list {
position: absolute;
bottom: 60px;
max-height: 100px;
overflow: auto;
z-index: 9999;
}
.chat-model-cmd-list>div {
border: solid 2px rgba(80,80,80,.3);
border-radius: 5px;
background-color: #fff;
}
html.dark .chat-model-cmd-list>div {
background-color: #4a4a4a;
}
html.dark .chat-model-cmd-list .cmd-item {
border-color: #666;
}
html.dark .chat-model-cmd-list .cmd-item b {
color: #e8e8e8;
}
html.dark .chat-model-cmd-list .cmd-item i {
color: #999;
}
html.dark .chat-model-cmd-list .cmd-item.selected {
background: rgba(59,130,246,.5);
}
.chat-model-cmd-list .cmd-item {
font-size: 12px;
border-bottom: solid 1px rgba(80,80,80,.2);
padding: 2px 4px;
display: flex;
user-select: none;
cursor: pointer;
}
.chat-model-cmd-list .cmd-item:last-child {
border-bottom: none;
}
.chat-model-cmd-list .cmd-item.selected {
background: rgba(59,130,246,.3);
}
.chat-model-cmd-list .cmd-item b {
display: inline-block;
width: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border-radius: 4px;
margin-right: 10px;
color: #2a2a2a;
}
.chat-model-cmd-list .cmd-item i {
width: 100%;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
color: #888;
}
.chatappico {
width: 20px;
height: 20px;
}
.chatappico.pdf, .chatappico.md {
width: 22px;
height: 22px;
}
.chatappico.copy {
width: 16px;
height: 16px;
}
@media screen and (max-width: 767px) {
#download-png-button, #download-pdf-button, #download-html-button {
display: none;
}
}
`;
document.head.append(styleDom);
if (window.formInterval) {
clearInterval(window.formInterval);
}
window.formInterval = setInterval(() => {
const form = document.querySelector("form textarea");
if (!form) return;
clearInterval(window.formInterval);
cmdTip();
new MutationObserver(function (mutationsList) {
for (const mutation of mutationsList) {
if (mutation.target.getAttribute('id') === '__next') {
initDom();
cmdTip();
}
if (mutation.target.getAttribute('class') === 'chat-model-cmd-list') {
// The `chatgpt prompt` fill can be done by clicking on the event.
const searchDom = document.querySelector("form .chat-model-cmd-list>div");
const searchInput = document.querySelector('form textarea');
if (!searchDom) return;
searchDom.addEventListener('click', (event) => {
const item = event.target.closest("div");
if (item) {
const val = decodeURIComponent(item.getAttribute('data-prompt'));
searchInput.value = val;
document.querySelector('form textarea').focus();
initDom();
}
});
}
}
}).observe(document.body, {
childList: true,
subtree: true,
});
}, 300);
}
async function cmdTip() {
initDom();
const chatModelJson = await invoke('get_chat_model_cmd') || {};
const data = chatModelJson.data;
if (data.length <= 0) return;
let modelDom = document.querySelector('.chat-model-cmd-list');
if (!modelDom) {
const dom = document.createElement('div');
dom.classList.add('chat-model-cmd-list');
document.querySelector('form').appendChild(dom);
modelDom = document.querySelector('.chat-model-cmd-list');
// fix: tray window
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
modelDom.style.bottom = '54px';
}
const itemDom = (v) => `<div class="cmd-item" title="${v.prompt}" data-cmd="${v.cmd}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${v.act}</i></div>`;
const renderList = (v) => {
initDom();
modelDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
window.__CHAT_MODEL_CMD_PROMPT__ = v[0]?.prompt.trim();
window.__CHAT_MODEL_CMD__ = v[0]?.cmd.trim();
window.__cmd_list = modelDom.querySelectorAll('.cmd-item');
window.__cmd_index = 0;
window.__cmd_list[window.__cmd_index].classList.add('selected');
};
const setPrompt = (v = '') => {
if (v.trim()) {
window.__CHAT_MODEL_CMD_PROMPT__ = window.__CHAT_MODEL_CMD_PROMPT__?.replace(/\{([^{}]*)\}/, `{${v.trim()}}`);
}
}
const searchInput = document.querySelector('form textarea');
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
// If more than one command appears in the search results, the first one will be used by default.
function cmdKeydown(event) {
if (!window.__CHAT_MODEL_CMD_PROMPT__) {
return;
}
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
if (event.keyCode === 38 && window.__cmd_index > 0) { // ArrowUp
window.__cmd_list[window.__cmd_index].classList.remove('selected');
window.__cmd_index = window.__cmd_index - 1;
window.__cmd_list[window.__cmd_index].classList.add('selected');
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'));
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
event.preventDefault();
}
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) { // ArrowDown
window.__cmd_list[window.__cmd_index].classList.remove('selected');
window.__cmd_index = window.__cmd_index + 1;
window.__cmd_list[window.__cmd_index].classList.add('selected');
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'));
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
event.preventDefault();
}
const containerHeight = modelDom.offsetHeight;
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
const itemBottom = itemTop + itemHeight;
if (itemTop < modelDom.scrollTop || itemBottom > modelDom.scrollTop + containerHeight) {
modelDom.scrollTop = itemTop;
}
// ------------------ TAB key replaces `{q}` tag content -------------------------------
// feat: https://github.com/lencx/ChatGPT/issues/54
if (event.keyCode === 9 && !window.__CHAT_MODEL_STATUS__) {
const strGroup = window.__CHAT_MODEL_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
if (strGroup[1]) {
searchInput.value = `/${window.__CHAT_MODEL_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
window.__CHAT_MODEL_STATUS__ = 1;
} else {
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
initDom();
}
event.preventDefault();
}
if (window.__CHAT_MODEL_STATUS__ === 1 && event.keyCode === 9) { // TAB
const data = searchInput.value.split('|->');
if (data[1]?.trim()) {
setPrompt(data[1]);
window.__CHAT_MODEL_STATUS__ = 2;
}
event.preventDefault();
}
// input text
if (window.__CHAT_MODEL_STATUS__ === 2 && event.keyCode === 9) { // TAB
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
modelDom.innerHTML = '';
delete window.__CHAT_MODEL_STATUS__;
event.preventDefault();
}
// ------------------ type in a space to complete the fill ------------------------------------
if (event.keyCode === 32) {
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
modelDom.innerHTML = '';
delete window.__CHAT_MODEL_CMD_PROMPT__;
}
// ------------------ send --------------------------------------------------------------------
if (event.keyCode === 13 && window.__CHAT_MODEL_CMD_PROMPT__) { // Enter
const data = searchInput.value.split('|->');
setPrompt(data[1]);
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
initDom();
event.preventDefault();
}
}
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
function cmdInput() {
if (searchInput.value === '') {
initDom();
}
if (window.__CHAT_MODEL_STATUS__) return;
const query = searchInput.value;
if (!query || !/^\//.test(query)) {
initDom();
return;
}
// all cmd result
if (query === '/') {
renderList(data);
return;
}
const result = data.filter(i => new RegExp(query.substring(1)).test(i.cmd));
if (result.length > 0) {
renderList(result);
} else {
initDom();
}
}
searchInput.removeEventListener('input', cmdInput);
searchInput.addEventListener('input', cmdInput);
}
}
function initDom() {
const modelDom = document.querySelector('.chat-model-cmd-list');
if (modelDom) {
modelDom.innerHTML = '';
}
delete window.__CHAT_MODEL_CMD_PROMPT__;
delete window.__CHAT_MODEL_CMD__;
delete window.__CHAT_MODEL_STATUS__;
delete window.__cmd_list;
delete window.__cmd_index;
}
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
init();
} else {
document.addEventListener("DOMContentLoaded", init);
}

View File

@ -1,183 +0,0 @@
// *** Core Script - IPC ***
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
function transformCallback(callback = () => {}, once = false) {
const identifier = uid();
const prop = `_${identifier}`;
Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop);
}
return callback(result)
},
writable: false,
configurable: true,
})
return identifier;
}
async function invoke(cmd, args) {
return new Promise((resolve, reject) => {
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
const callback = transformCallback((e) => {
resolve(e);
Reflect.deleteProperty(window, `_${error}`);
}, true)
const error = transformCallback((e) => {
reject(e);
Reflect.deleteProperty(window, `_${callback}`);
}, true)
window.__TAURI_POST_MESSAGE__({
cmd,
callback,
error,
...args
});
});
}
async function message(message) {
invoke('messageDialog', {
__tauriModule: 'Dialog',
message: {
cmd: 'messageDialog',
message: message.toString(),
title: null,
type: null,
buttonLabel: null
}
});
}
window.uid = uid;
window.invoke = invoke;
window.message = message;
window.transformCallback = transformCallback;
async function init() {
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
}
async function platform() {
return invoke('platform', {
__tauriModule: 'Os',
message: { cmd: 'platform' }
});
}
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
const _platform = await platform();
const chatConf = await invoke('get_app_conf') || {};
if (/darwin/.test(_platform) && !chatConf.titlebar) {
const topStyleDom = document.createElement("style");
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
document.head.appendChild(topStyleDom);
const topDom = document.createElement("div");
topDom.id = "chatgpt-app-window-top";
document.body.appendChild(topDom);
if (window.location.host === 'chat.openai.com') {
const nav = document.body.querySelector('nav');
if (nav) {
const currentPaddingTop = parseInt(window.getComputedStyle(document.querySelector('nav'), null).getPropertyValue('padding-top').replace('px', ''), 10);
const navStyleDom = document.createElement("style");
navStyleDom.innerHTML = `nav{padding-top:${currentPaddingTop + topDom.clientHeight}px !important}`;
document.head.appendChild(navStyleDom);
}
}
topDom.addEventListener("mousedown", () => invoke("drag_window"));
topDom.addEventListener("touchstart", () => invoke("drag_window"));
topDom.addEventListener("dblclick", () => invoke("fullscreen"));
}
}
document.addEventListener("click", (e) => {
const origin = e.target.closest("a");
if (!origin || !origin.target) return;
if (origin && origin.href && origin.target !== '_self') {
invoke('open_link', { url: origin.href });
}
});
if (window.location.host === 'chat.openai.com') {
window.__sync_prompts = async function() {
await invoke('sync_prompts', { time: Date.now() });
}
}
coreZoom();
}
function coreZoom() {
const styleDom = document.createElement('style');
styleDom.innerHTML = `
#ZoomTopTip {
display: none;
position: fixed;
top: 0;
right: 20px;
background: #2a2a2a;
color: #fafafa;
padding: 20px 15px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
font-size: 16px;
font-weight: bold;
z-index: 999999;
box-shadow: 0 2px 2px 2px #d8d8d8;
}
.ZoomTopTipAni {
transition: opacity 200ms, display 200ms;
display: none;
opacity: 0;
}
`;
document.head.append(styleDom);
const zoomTipDom = document.createElement('div');
zoomTipDom.id = 'ZoomTopTip';
document.body.appendChild(zoomTipDom);
function zoom(callback) {
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
const htmlZoom = window.localStorage.getItem("htmlZoom") || "100%";
const html = document.getElementsByTagName("html")[0];
const zoom = callback(htmlZoom);
html.style.zoom = zoom;
window.localStorage.setItem("htmlZoom", zoom);
zoomTipDom.innerHTML = zoom;
zoomTipDom.style.display = 'block';
zoomTipDom.classList.remove('ZoomTopTipAni');
window.zoomSetTimeout = setTimeout(() => {
zoomTipDom.classList.add('ZoomTopTipAni');
}, 2500);
}
function zoomDefault() {
const htmlZoom = window.localStorage.getItem("htmlZoom");
if (htmlZoom) {
document.getElementsByTagName("html")[0].style.zoom = htmlZoom;
}
}
function zoomIn() {
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
}
function zoomOut() {
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
}
function zoom0() {
zoom(() => `100%`);
}
zoomDefault();
window.__zoomIn = zoomIn;
window.__zoomOut = zoomOut;
window.__zoom0 = zoom0;
}
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
init();
} else {
document.addEventListener("DOMContentLoaded", init);
}

View File

@ -1,321 +0,0 @@
// *** Core Script - Export ***
async function init() {
const buttonOuterHTMLFallback = `<button class="btn flex justify-center gap-2 btn-neutral" id="download-png-button">Try Again</button>`;
removeButtons();
if (window.buttonsInterval) {
clearInterval(window.buttonsInterval);
}
if (window.innerWidth < 767) return;
const chatConf = await invoke('get_app_conf') || {};
window.buttonsInterval = setInterval(() => {
const actionsArea = document.querySelector("form>div>div");
if (!actionsArea) {
return;
}
if (shouldAddButtons(actionsArea)) {
let TryAgainButton = actionsArea.querySelector("button");
if (!TryAgainButton) {
const parentNode = document.createElement("div");
parentNode.innerHTML = buttonOuterHTMLFallback;
TryAgainButton = parentNode.querySelector("button");
}
addActionsButtons(actionsArea, TryAgainButton, chatConf);
copyBtns();
} else if (shouldRemoveButtons()) {
removeButtons();
}
}, 1000);
}
window.addEventListener('resize', init);
const Format = {
PNG: "png",
PDF: "pdf",
};
function shouldRemoveButtons() {
const isOpenScreen = document.querySelector("h1.text-4xl");
if(isOpenScreen){
return true;
}
const inConversation = document.querySelector("form button>div");
if(inConversation){
return true;
}
return false;
}
function shouldAddButtons(actionsArea) {
// first, check if there's a "Try Again" button and no other buttons
const buttons = actionsArea.querySelectorAll("button");
const hasTryAgainButton = Array.from(buttons).some((button) => {
return !/download-/.test(button.id);
});
const stopBtn = buttons?.[0]?.innerText;
if (/Stop generating/ig.test(stopBtn)) {
return false;
}
if (buttons.length === 2 && (/Regenerate response/ig.test(stopBtn) || buttons[1].innerText === '')) {
return true;
}
if (hasTryAgainButton && buttons.length === 1) {
return true;
}
// otherwise, check if open screen is not visible
const isOpenScreen = document.querySelector("h1.text-4xl");
if (isOpenScreen) {
return false;
}
// check if the conversation is finished and there are no share buttons
const finishedConversation = document.querySelector("form button>svg");
const hasShareButtons = actionsArea.querySelectorAll("button[share-ext]");
if (finishedConversation && !hasShareButtons.length) {
return true;
}
return false;
}
function removeButtons() {
const downloadButton = document.getElementById("download-png-button");
const downloadPdfButton = document.getElementById("download-pdf-button");
const downloadMdButton = document.getElementById("download-markdown-button");
if (downloadButton) {
downloadButton.remove();
}
if (downloadPdfButton) {
downloadPdfButton.remove();
}
if (downloadPdfButton) {
downloadMdButton.remove();
}
}
function addActionsButtons(actionsArea, TryAgainButton) {
const downloadButton = TryAgainButton.cloneNode(true);
// Export markdown
const exportMd = TryAgainButton.cloneNode(true);
exportMd.id = "download-markdown-button";
downloadButton.setAttribute("share-ext", "true");
exportMd.title = "Export Markdown";
exportMd.innerHTML = setIcon('md');
exportMd.onclick = () => {
exportMarkdown();
};
actionsArea.appendChild(exportMd);
// Generate PNG
downloadButton.id = "download-png-button";
downloadButton.setAttribute("share-ext", "true");
downloadButton.title = "Generate PNG";
downloadButton.innerHTML = setIcon('png');
downloadButton.onclick = () => {
downloadThread();
};
actionsArea.appendChild(downloadButton);
// Generate PDF
const downloadPdfButton = TryAgainButton.cloneNode(true);
downloadPdfButton.id = "download-pdf-button";
downloadButton.setAttribute("share-ext", "true");
downloadPdfButton.title = "Download PDF";
downloadPdfButton.innerHTML = setIcon('pdf');
downloadPdfButton.onclick = () => {
downloadThread({ as: Format.PDF });
};
actionsArea.appendChild(downloadPdfButton);
}
async function exportMarkdown() {
const data = ExportMD.turndown(document.querySelector("main div>div>div").innerHTML);
const { id, filename } = getName();
await invoke('save_file', { name: `notes/${id}.md`, content: data });
await invoke('download_list', { pathname: 'chat.notes.json', filename, id, dir: 'notes' });
}
function downloadThread({ as = Format.PNG } = {}) {
const elements = new Elements();
elements.fixLocation();
const pixelRatio = window.devicePixelRatio;
const minRatio = as === Format.PDF ? 2 : 2.5;
window.devicePixelRatio = Math.max(pixelRatio, minRatio);
html2canvas(elements.thread, {
letterRendering: true,
}).then(async function (canvas) {
elements.restoreLocation();
window.devicePixelRatio = pixelRatio;
const imgData = canvas.toDataURL("image/png");
requestAnimationFrame(() => {
if (as === Format.PDF) {
return handlePdf(imgData, canvas, pixelRatio);
} else {
handleImg(imgData);
}
});
});
}
async function handleImg(imgData) {
const binaryData = atob(imgData.split("base64,")[1]);
const data = [];
for (let i = 0; i < binaryData.length; i++) {
data.push(binaryData.charCodeAt(i));
}
const { pathname, id, filename } = getName();
await invoke('download', { name: `download/img/${id}.png`, blob: data });
await invoke('download_list', { pathname, filename, id, dir: 'download' });
}
async function handlePdf(imgData, canvas, pixelRatio) {
const { jsPDF } = window.jspdf;
const orientation = canvas.width > canvas.height ? "l" : "p";
var pdf = new jsPDF(orientation, "pt", [
canvas.width / pixelRatio,
canvas.height / pixelRatio,
]);
var pdfWidth = pdf.internal.pageSize.getWidth();
var pdfHeight = pdf.internal.pageSize.getHeight();
pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight, '', 'FAST');
const { pathname, id, filename } = getName();
const data = pdf.__private__.getArrayBuffer(pdf.__private__.buildDocument());
await invoke('download', { name: `download/pdf/${id}.pdf`, blob: Array.from(new Uint8Array(data)) });
await invoke('download_list', { pathname, filename, id, dir: 'download' });
}
function getName() {
const id = window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36);
const name = document.querySelector('nav .overflow-y-auto a.hover\\:bg-gray-800')?.innerText?.trim() || '';
return { filename: name ? name : id, id, pathname: 'chat.download.json' };
}
class Elements {
constructor() {
this.init();
}
init() {
// this.threadWrapper = document.querySelector(".cdfdFe");
this.spacer = document.querySelector("[class*='h-48'].w-full.flex-shrink-0");
this.thread = document.querySelector(
"[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div"
);
// fix: old chat https://github.com/lencx/ChatGPT/issues/185
if (!this.thread) {
this.thread = document.querySelector("main .overflow-y-auto");
}
// h-full overflow-y-auto
this.positionForm = document.querySelector("form").parentNode;
// this.styledThread = document.querySelector("main");
// this.threadContent = document.querySelector(".gAnhyd");
this.scroller = Array.from(
document.querySelectorAll('[class*="react-scroll-to"]')
).filter((el) => el.classList.contains("h-full"))[0];
// fix: old chat
if (!this.scroller) {
this.scroller = document.querySelector('main .overflow-y-auto');
}
this.hiddens = Array.from(document.querySelectorAll(".overflow-hidden"));
this.images = Array.from(document.querySelectorAll("img[srcset]"));
}
fixLocation() {
this.hiddens.forEach((el) => {
el.classList.remove("overflow-hidden");
});
this.spacer.style.display = "none";
this.thread.style.maxWidth = "960px";
this.thread.style.marginInline = "auto";
this.positionForm.style.display = "none";
this.scroller.classList.remove("h-full");
this.scroller.style.minHeight = "100vh";
this.images.forEach((img) => {
const srcset = img.getAttribute("srcset");
img.setAttribute("srcset_old", srcset);
img.setAttribute("srcset", "");
});
//Fix to the text shifting down when generating the canvas
document.body.style.lineHeight = "0.5";
}
restoreLocation() {
this.hiddens.forEach((el) => {
el.classList.add("overflow-hidden");
});
this.spacer.style.display = null;
this.thread.style.maxWidth = null;
this.thread.style.marginInline = null;
this.positionForm.style.display = null;
this.scroller.classList.add("h-full");
this.scroller.style.minHeight = null;
this.images.forEach((img) => {
const srcset = img.getAttribute("srcset_old");
img.setAttribute("srcset", srcset);
img.setAttribute("srcset_old", "");
});
document.body.style.lineHeight = null;
}
}
function setIcon(type) {
return {
// link: `<svg class="chatappico" viewBox="0 0 1024 1024"><path d="M1007.382 379.672L655.374 75.702C624.562 49.092 576 70.694 576 112.03v160.106C254.742 275.814 0 340.2 0 644.652c0 122.882 79.162 244.618 166.666 308.264 27.306 19.862 66.222-5.066 56.154-37.262C132.132 625.628 265.834 548.632 576 544.17V720c0 41.4 48.6 62.906 79.374 36.328l352.008-304c22.142-19.124 22.172-53.506 0-72.656z" p-id="8506" fill="currentColor"></path></svg>`,
png: `<svg class="chatappico" viewBox="0 0 1070 1024"><path d="M981.783273 0H85.224727C38.353455 0 0 35.374545 0 83.083636v844.893091c0 47.616 38.353455 86.574545 85.178182 86.574546h903.633454c46.917818 0 81.733818-38.958545 81.733819-86.574546V83.083636C1070.592 35.374545 1028.701091 0 981.783273 0zM335.825455 135.912727c74.193455 0 134.330182 60.974545 134.330181 136.285091 0 75.170909-60.136727 136.192-134.330181 136.192-74.286545 0-134.516364-61.021091-134.516364-136.192 0-75.264 60.229818-136.285091 134.516364-136.285091z m-161.512728 745.937455a41.890909 41.890909 0 0 1-27.648-10.379637 43.752727 43.752727 0 0 1-4.654545-61.067636l198.097454-255.162182a42.123636 42.123636 0 0 1 57.716364-6.702545l116.549818 128.139636 286.906182-352.814545c14.615273-18.711273 90.251636-106.775273 135.866182-6.935273 0.093091-0.093091 0.093091 112.965818 0.232727 247.761455 0.093091 140.8 0.093091 317.067636 0.093091 317.067636-1.024-0.093091-762.740364 0.093091-763.112727 0.093091z" fill="currentColor"></path></svg>`,
pdf: `<svg class="chatappico pdf" viewBox="0 0 1024 1024"><path d="M821.457602 118.382249H205.725895c-48.378584 0-87.959995 39.583368-87.959996 87.963909v615.731707c0 48.378584 39.581411 87.959995 87.959996 87.959996h615.733664c48.380541 0 87.961952-39.581411 87.961952-87.959996V206.346158c-0.001957-48.378584-39.583368-87.963909-87.963909-87.963909zM493.962468 457.544987c-10.112054 32.545237-21.72487 82.872662-38.806571 124.248336-8.806957 22.378397-8.380404 18.480717-15.001764 32.609808l5.71738-1.851007c58.760658-16.443827 99.901532-20.519564 138.162194-27.561607-7.67796-6.06371-14.350194-10.751884-19.631237-15.586807-26.287817-29.101504-35.464584-34.570387-70.440002-111.862636v0.003913z m288.36767 186.413594c-7.476424 8.356924-20.670227 13.191847-40.019704 13.191847-33.427694 0-63.808858-9.229597-107.79277-31.660824-75.648648 8.356924-156.097 17.214754-201.399704 31.729308-2.199293 0.876587-4.832967 1.759043-7.916674 3.077836-54.536215 93.237125-95.031389 132.767663-130.621199 131.19646-11.286054-0.49895-27.694661-7.044-32.973748-10.11988l-6.52157-6.196764-2.29517-4.353583c-3.07588-7.91863-3.954423-15.395054-2.197337-23.751977 4.838837-23.309771 29.907651-60.251638 82.686779-93.237126 8.356924-6.159587 27.430511-15.897917 45.020944-24.25484 13.311204-21.177004 19.45905-34.744531 36.341171-72.259702 19.102937-45.324228 36.505531-99.492589 47.500041-138.191543v-0.44025c-16.267727-53.219378-25.945401-89.310095-9.67376-147.80856 3.958337-16.71189 18.46702-33.864031 34.748444-33.864031h10.552304c10.115967 0 19.791684 3.520043 26.829814 10.552304 29.029107 29.031064 15.39114 103.824649 0.8805 162.323113-0.8805 2.63563-1.322707 4.832967-1.761 6.153717 17.59239 49.697378 45.400538 98.774492 73.108895 121.647926 11.436717 8.791304 22.638634 18.899444 36.71098 26.814161 19.791684-2.20125 37.517128-4.11487 55.547812-4.11487 54.540128 0 87.525615 9.67963 100.279169 30.351814 4.400543 7.034217 6.595923 15.389184 5.281043 24.1844-0.44025 10.996467-4.39663 21.112434-12.31526 29.031064z m-27.796407-36.748157c-4.394673-4.398587-17.024957-16.936907-78.601259-16.936907-3.073923 0-10.622744-0.784623-14.57521 3.612007 32.104987 14.072347 62.830525 24.757704 83.058545 24.757703 3.083707 0 5.72325-0.442207 8.356923-0.876586h1.759044c2.20125-0.8805 3.520043-1.324663 3.960293-5.71738-0.87463-1.324663-1.757087-3.083707-3.958336-4.838837z m-387.124553 63.041845c-9.237424 5.27713-16.71189 10.112054-21.112433 13.634053-31.226444 28.586901-51.018128 57.616008-53.217422 74.331812 19.789727-6.59788 45.737084-35.626987 74.329855-87.961952v-0.003913z m125.574957-297.822284l2.197336-1.761c3.079793-14.072347 5.232127-29.189554 7.87167-38.869184l1.318794-7.036174c4.39663-25.070771 2.71781-39.720334-4.76057-50.272637l-6.59788-2.20125a57.381208 57.381208 0 0 0-3.079794 5.27713c-7.474467 18.47289-7.063567 55.283661 3.0524 94.865072l-0.001956-0.001957z" fill="currentColor"></path></svg>`,
md: `<svg class="chatappico md" viewBox="0 0 1024 1024" width="200" height="200"><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m170.666667 533.333333v-170.666666l85.333333 85.333333 85.333333-85.333333v170.666666h85.333334v-298.666666h-85.333334l-85.333333 85.333333-85.333333-85.333333H213.333333v298.666666h85.333334z m469.333333-128v-170.666666h-85.333333v170.666666h-85.333334l128 128 128-128h-85.333333z" p-id="1381" fill="currentColor"></path></svg>`,
copy: `<svg class="chatappico copy" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`
}[type];
}
function copyBtns() {
Array.from(document.querySelectorAll("main >div>div>div>div>div"))
.forEach(i => {
if (i.querySelector('.chat-item-copy')) return;
if (!i.querySelector('button.rounded-md')) return;
const btn = i.querySelector('button.rounded-md').cloneNode(true);
btn.classList.add('chat-item-copy');
btn.title = 'Copy to clipboard';
btn.innerHTML = setIcon('copy');
i.querySelector('.self-end').appendChild(btn);
btn.onclick = () => {
copyToClipboard(i?.innerText?.trim() || '');
}
})
}
function copyToClipboard(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
} else {
var textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.style.position = 'fixed';
textarea.style.clip = 'rect(0 0 0 0)';
textarea.style.top = '10px';
textarea.value = text;
textarea.select();
document.execCommand('copy', true);
document.body.removeChild(textarea);
}
message('Copied to clipboard');
}
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
init();
} else {
document.addEventListener("DOMContentLoaded", init);
}

View File

@ -4,7 +4,7 @@ use regex::Regex;
use serde_json::Value; use serde_json::Value;
use std::{ use std::{
collections::HashMap, collections::HashMap,
fs::{self, File}, fs,
path::{Path, PathBuf}, path::{Path, PathBuf},
process::Command, process::Command,
}; };
@ -25,46 +25,41 @@ pub fn exists(path: &Path) -> bool {
Path::new(path).exists() Path::new(path).exists()
} }
pub fn create_file(path: &Path) -> Result<File> { pub fn create_file<P: AsRef<Path>>(filename: P) -> Result<()> {
if let Some(p) = path.parent() { let filename = filename.as_ref();
fs::create_dir_all(p)? if let Some(parent) = filename.parent() {
if !parent.exists() {
fs::create_dir_all(parent)?;
}
} }
File::create(path).map_err(Into::into) fs::File::create(filename)?;
Ok(())
} }
pub fn create_chatgpt_prompts() { pub fn create_chatgpt_prompts() {
let sync_file = app_root().join("cache_model").join("chatgpt_prompts.json"); let sync_file = app_root()
.join("cache_prompts")
.join("chatgpt_prompts.json");
if !exists(&sync_file) { if !exists(&sync_file) {
create_file(&sync_file).unwrap(); create_file(&sync_file).unwrap();
fs::write(&sync_file, "[]").unwrap(); fs::write(&sync_file, "[]").unwrap();
} }
} }
pub fn script_path() -> PathBuf {
let script_file = app_root().join("main.js");
if !exists(&script_file) {
create_file(&script_file).unwrap();
fs::write(
&script_file,
format!(
"// *** ChatGPT User Script ***\n// @github: https://github.com/lencx/ChatGPT \n// @path: {}\n\nconsole.log('🤩 Hello ChatGPT!!!');",
&script_file.to_string_lossy()
),
)
.unwrap();
}
script_file
}
pub fn user_script() -> String { pub fn user_script() -> String {
let user_script_content = fs::read_to_string(script_path()).unwrap_or_else(|_| "".to_string()); let user_script_file = app_root().join("scripts").join("main.js");
let user_script_content = fs::read_to_string(user_script_file).unwrap_or_else(|_| "".to_string());
format!( format!(
"window.addEventListener('DOMContentLoaded', function() {{\n{}\n}})", "window.addEventListener('DOMContentLoaded', function() {{\n{}\n}})",
user_script_content user_script_content
) )
} }
pub fn load_script(filename: &str) -> String {
let script_file = app_root().join("scripts").join(filename);
fs::read_to_string(script_file).unwrap_or_else(|_| "".to_string())
}
pub fn open_file(path: PathBuf) { pub fn open_file(path: PathBuf) {
let pathname = convert_path(path.to_str().unwrap()); let pathname = convert_path(path.to_str().unwrap());
info!("open_file: {}", pathname); info!("open_file: {}", pathname);

View File

@ -7,19 +7,45 @@
}, },
"package": { "package": {
"productName": "ChatGPT", "productName": "ChatGPT",
"version": "0.10.2" "version": "1.1.0"
}, },
"tauri": { "tauri": {
"allowlist": { "allowlist": {
"all": true, "all": false,
"globalShortcut": { "globalShortcut": {
"all": true "all": true
}, },
"shell": {
"all": true
},
"fs": { "fs": {
"all": true, "all": false,
"readFile": true,
"writeFile": true,
"readDir": true,
"createDir": true,
"exists": true,
"removeFile": true,
"removeDir": true,
"scope": [ "scope": [
"$HOME/.chatgpt/**" "$HOME/.chatgpt/**",
"$DOWNLOAD/**"
] ]
},
"path": {
"all": true
},
"os": {
"all": true
},
"dialog": {
"all": true
},
"process": {
"all": true,
"exit": true,
"relaunch": true,
"relaunchDangerousAllowSymlinkMacos": true
} }
}, },
"systemTray": { "systemTray": {
@ -64,7 +90,43 @@
} }
}, },
"security": { "security": {
"csp": null "csp": null,
"dangerousRemoteDomainIpcAccess": [
{
"windows": [
"core",
"main",
"tray"
],
"domain": "chat.openai.com",
"enableTauriAPI": true
},
{
"windows": [
"core",
"main"
],
"domain": "labs.openai.com",
"enableTauriAPI": true
},
{
"windows": [
"core",
"main",
"tray"
],
"domain": "openai.com",
"enableTauriAPI": true
},
{
"windows": [
"chatgpt_sponsors",
"app_website"
],
"domain": "app.nofwl.com",
"enableTauriAPI": true
}
]
}, },
"updater": { "updater": {
"active": true, "active": true,

View File

@ -16,7 +16,8 @@ const FilePath: FC<FilePathProps> = ({ className, label = 'PATH', paths = '', ur
const [filePath, setPath] = useState(''); const [filePath, setPath] = useState('');
useEffect(() => { useEffect(() => {
if (!path && !url) return; if (!(paths || url)) return;
(async () => { (async () => {
if (url) { if (url) {
setPath(url); setPath(url);

View File

@ -1,58 +0,0 @@
import { useState, useEffect } from 'react';
import { clone } from 'lodash';
import { invoke } from '@tauri-apps/api';
import { CHAT_MODEL_JSON, CHAT_MODEL_CMD_JSON, readJSON, writeJSON } from '@/utils';
import useInit from '@/hooks/useInit';
export default function useChatModel(key: string, file = CHAT_MODEL_JSON) {
const [modelJson, setModelJson] = useState<Record<string, any>>({});
useInit(async () => {
const data = await readJSON(file, {
defaultVal: { name: 'ChatGPT Model', [key]: null },
});
setModelJson(data);
});
const modelSet = async (data: Record<string, any>[] | Record<string, any>) => {
const oData = clone(modelJson);
oData[key] = data;
await writeJSON(file, oData);
setModelJson(oData);
};
return { modelJson, modelSet, modelData: modelJson?.[key] || [] };
}
export function useCacheModel(file = '') {
const [modelCacheJson, setModelCacheJson] = useState<Record<string, any>[]>([]);
useEffect(() => {
if (!file) return;
(async () => {
const data = await readJSON(file, { isRoot: true, isList: true });
setModelCacheJson(data);
})();
}, [file]);
const modelCacheSet = async (data: Record<string, any>[], newFile = '') => {
await writeJSON(newFile ? newFile : file, data, { isRoot: true });
setModelCacheJson(data);
await modelCacheCmd();
};
const modelCacheCmd = async () => {
// Generate the `chat.model.cmd.json` file and refresh the page for the slash command to take effect.
const list = await invoke('cmd_list');
await writeJSON(CHAT_MODEL_CMD_JSON, {
name: 'ChatGPT CMD',
last_updated: Date.now(),
data: list,
});
await invoke('window_reload', { label: 'core' });
await invoke('window_reload', { label: 'tray' });
};
return { modelCacheJson, modelCacheSet, modelCacheCmd };
}

68
src/hooks/useChatPrompt.ts vendored Normal file
View File

@ -0,0 +1,68 @@
import { useState, useEffect } from 'react';
import { clone } from 'lodash';
import { invoke } from '@tauri-apps/api';
import { CHAT_PROMPT_JSON, CHAT_PROMPT_CMD_JSON, readJSON, writeJSON } from '@/utils';
import useInit from '@/hooks/useInit';
export default function useChatPrompt(key: string, file = CHAT_PROMPT_JSON) {
const [promptJson, setPromptJson] = useState<Record<string, any>>({});
useInit(async () => {
const data = await readJSON(file, {
defaultVal: { name: 'ChatGPT Prompts', [key]: null },
});
setPromptJson(data);
});
const promptSet = async (data: Record<string, any>[] | Record<string, any>) => {
const oData = clone(promptJson);
oData[key] = data;
await writeJSON(file, oData);
setPromptJson(oData);
};
const promptUpdate = async (id: string, field: string, value: any) => {
const oData = clone(promptJson);
const idx = oData[key].findIndex((v: any) => v.id === id);
oData[key][idx][field] = value;
await writeJSON(file, oData);
setPromptJson(oData);
};
return { promptJson, promptSet, promptUpdate, promptData: promptJson?.[key] || [] };
}
export function useCachePrompt(file = '') {
const [promptCacheJson, setPromptCacheJson] = useState<Record<string, any>[]>([]);
useEffect(() => {
if (!file) return;
(async () => {
const data = await readJSON(file, { isRoot: true, isList: true });
setPromptCacheJson(data);
})();
}, [file]);
const promptCacheSet = async (data: Record<string, any>[], newFile = '') => {
await writeJSON(newFile ? newFile : file, data, { isRoot: true });
setPromptCacheJson(data);
await promptCacheCmd();
};
const promptCacheCmd = async () => {
// Generate the `chat.prompt.cmd.json` file and refresh the page for the slash command to take effect.
const list = await invoke('cmd_list');
await writeJSON(CHAT_PROMPT_CMD_JSON, {
name: 'ChatGPT CMD',
last_updated: Date.now(),
data: list,
});
await invoke('window_reload', { label: 'core' });
await invoke('window_reload', { label: 'tray' });
};
return { promptCacheJson, promptCacheSet, promptCacheCmd };
}

View File

@ -74,6 +74,7 @@ export const EditRow: FC<EditRowProps> = ({ rowKey, row, actions }) => {
onChange={handleChange} onChange={handleChange}
{...DISABLE_AUTO_COMPLETE} {...DISABLE_AUTO_COMPLETE}
onPressEnter={handleSave} onPressEnter={handleSave}
onBlur={handleSave}
/> />
) : ( ) : (
<div className="rowedit" onClick={handleEdit}> <div className="rowedit" onClick={handleEdit}>

View File

@ -8,8 +8,8 @@ type rowSelectionOptions = {
key: 'id' | string; key: 'id' | string;
rowType: 'id' | 'row' | 'all'; rowType: 'id' | 'row' | 'all';
}; };
export function useTableRowSelection(options: Partial<rowSelectionOptions> = {}) { export function useTableRowSelection(options?: Partial<rowSelectionOptions>) {
const { key = 'id', rowType = 'id' } = options; const { key = 'id', rowType = 'id' } = options || {};
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const [selectedRowIDs, setSelectedRowIDs] = useState<string[]>([]); const [selectedRowIDs, setSelectedRowIDs] = useState<string[]>([]);
const [selectedRows, setSelectedRows] = useState<Record<string | symbol, any>[]>([]); const [selectedRows, setSelectedRows] = useState<Record<string | symbol, any>[]>([]);

View File

@ -23,8 +23,8 @@ export default function ChatLayout() {
if (location.search === '?type=control') { if (location.search === '?type=control') {
go('/settings'); go('/settings');
} }
if (location.search === '?type=preview') { if (location.search === '?type=scripts') {
go('/?type=preview'); go('/scripts');
} }
setMenuKey(location.pathname); setMenuKey(location.pathname);
setDashboard(location.pathname === '/'); setDashboard(location.pathname === '/');
@ -88,7 +88,7 @@ export default function ChatLayout() {
theme={appInfo.appTheme === 'dark' ? 'dark' : 'light'} theme={appInfo.appTheme === 'dark' ? 'dark' : 'light'}
inlineIndent={12} inlineIndent={12}
items={menuItems} items={menuItems}
// defaultOpenKeys={['/model']} // defaultOpenKeys={['/prompts']}
onClick={(i) => go(i.key)} onClick={(i) => go(i.key)}
/> />
</Sider> </Sider>

31
src/main.scss vendored
View File

@ -73,6 +73,11 @@ body,
} }
} }
.action-btn,
.file-path {
cursor: pointer;
}
.chat-file-path { .chat-file-path {
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
@ -109,3 +114,29 @@ body,
cursor: pointer; cursor: pointer;
} }
} }
.editor-task {
margin-bottom: 5px;
display: flex;
justify-content: space-between;
.ant-breadcrumb-link {
padding: 3px 5px;
transition: all 300ms ease;
border-radius: 4px;
&:hover {
color: rgba(120, 120, 90, 0.88);
background-color: rgba(40, 40, 40, 0.06);
cursor: pointer;
}
}
.editor-btn {
cursor: pointer;
margin-left: 5px;
}
}
.ant-message {
max-width: 500px;
}

44
src/routes.tsx vendored
View File

@ -5,24 +5,22 @@ import {
SyncOutlined, SyncOutlined,
FileSyncOutlined, FileSyncOutlined,
UserOutlined, UserOutlined,
DownloadOutlined,
FormOutlined, FormOutlined,
GlobalOutlined,
InfoCircleOutlined, InfoCircleOutlined,
CodeOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import type { MenuProps } from 'antd'; import type { MenuProps } from 'antd';
import Settings from '@/view/settings'; import Settings from '@/view/settings';
import About from '@/view/about'; import About from '@/view/about';
import Awesome from '@/view/awesome'; import Scripts from '@/view/scripts';
import UserCustom from '@/view/model/UserCustom'; import ScriptsEditor from '@/view/scripts/Editor';
import SyncPrompts from '@/view/model/SyncPrompts'; import UserCustom from '@/view/prompts/UserCustom';
import SyncCustom from '@/view/model/SyncCustom'; import SyncPrompts from '@/view/prompts/SyncPrompts';
import SyncRecord from '@/view/model/SyncRecord'; import SyncCustom from '@/view/prompts/SyncCustom';
import Download from '@/view/download'; import SyncRecord from '@/view/prompts/SyncRecord';
import Notes from '@/view/notes'; import Notes from '@/view/notes';
import Markdown from '@/view/markdown'; import Markdown from '@/view/markdown';
import Dashboard from '@/view/dashboard';
export type ChatRouteMetaObject = { export type ChatRouteMetaObject = {
label: string; label: string;
@ -46,14 +44,6 @@ export const routes: Array<ChatRouteObject> = [
icon: <SettingOutlined />, icon: <SettingOutlined />,
}, },
}, },
{
path: '/awesome',
element: <Awesome />,
meta: {
label: 'Awesome',
icon: <GlobalOutlined />,
},
},
{ {
path: '/notes', path: '/notes',
element: <Notes />, element: <Notes />,
@ -68,9 +58,9 @@ export const routes: Array<ChatRouteObject> = [
hideMenu: true, hideMenu: true,
}, },
{ {
path: '/model', path: '/prompts',
meta: { meta: {
label: 'Language Model', label: 'Prompts',
icon: <BulbOutlined />, icon: <BulbOutlined />,
}, },
children: [ children: [
@ -107,13 +97,18 @@ export const routes: Array<ChatRouteObject> = [
], ],
}, },
{ {
path: '/download', path: '/scripts',
element: <Download />, element: <Scripts />,
meta: { meta: {
label: 'Download', label: 'Scripts',
icon: <DownloadOutlined />, icon: <CodeOutlined />,
}, },
}, },
{
path: '/scripts/:id',
element: <ScriptsEditor />,
hideMenu: true,
},
{ {
path: '/about', path: '/about',
element: <About />, element: <About />,
@ -124,8 +119,7 @@ export const routes: Array<ChatRouteObject> = [
}, },
{ {
path: '/', path: '/',
element: <Dashboard />, element: <Settings />,
hideMenu: true,
}, },
]; ];

12
src/utils.ts vendored
View File

@ -3,8 +3,8 @@ import { homeDir, join, dirname } from '@tauri-apps/api/path';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
export const APP_CONF_JSON = 'chat.conf.json'; export const APP_CONF_JSON = 'chat.conf.json';
export const CHAT_MODEL_JSON = 'chat.model.json'; export const CHAT_PROMPT_JSON = 'chat.prompt.json';
export const CHAT_MODEL_CMD_JSON = 'chat.model.cmd.json'; export const CHAT_PROMPT_CMD_JSON = 'chat.prompt.cmd.json';
export const CHAT_DOWNLOAD_JSON = 'chat.download.json'; export const CHAT_DOWNLOAD_JSON = 'chat.download.json';
export const CHAT_AWESOME_JSON = 'chat.awesome.json'; export const CHAT_AWESOME_JSON = 'chat.awesome.json';
export const CHAT_NOTES_JSON = 'chat.notes.json'; export const CHAT_NOTES_JSON = 'chat.notes.json';
@ -23,8 +23,12 @@ export const chatRoot = async () => {
return join(await homeDir(), '.chatgpt'); return join(await homeDir(), '.chatgpt');
}; };
export const chatModelPath = async (): Promise<string> => { export const scriptRoot = async () => {
return join(await chatRoot(), CHAT_MODEL_JSON); return join(await chatRoot(), 'scripts');
};
export const chatPromptPath = async (): Promise<string> => {
return join(await chatRoot(), CHAT_PROMPT_JSON);
}; };
export const chatPromptsPath = async (): Promise<string> => { export const chatPromptsPath = async (): Promise<string> => {

View File

@ -40,8 +40,7 @@ const AboutChatGPT = () => {
<p> <p>
It is just a wrapper for the It is just a wrapper for the
<a href="https://chat.openai.com" target="_blank" title="https://chat.openai.com"> <a href="https://chat.openai.com" target="_blank" title="https://chat.openai.com">
{' '} OpenAI ChatGPT
OpenAI ChatGPT{' '}
</a> </a>
website, no other data transfer exists (you can check the{' '} website, no other data transfer exists (you can check the{' '}
<a <a
@ -49,25 +48,24 @@ const AboutChatGPT = () => {
target="_blank" target="_blank"
title="https://github.com/lencx/ChatGPT" title="https://github.com/lencx/ChatGPT"
> >
{' '} source code
source code{' '}
</a> </a>
). The development and maintenance of this software has taken up a lot of my time. If it ). The development and maintenance of this software has taken up a lot of my time. If it
helps you, you can buy me a cup of coffee (Chinese users can use WeChat to scan the code), helps you, you can buy me a cup of coffee (Chinese users can use WeChat to scan the code),
thanks! thanks!
</p> </p>
<p className="imgs"> <p className="imgs" style={{ float: 'left' }}>
<a href="https://www.buymeacoffee.com/lencx" target="_blank"> <a href="https://www.buymeacoffee.com/lencx" target="_blank">
<img <img
src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png"
alt="Buy Me A Coffee" alt="Buy Me A Coffee"
/> />
</a>{' '} </a>
<br /> <br />
<img <img
width="200" width="200"
src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png"
></img> />
</p> </p>
</div> </div>
); );

View File

@ -61,8 +61,11 @@ export default function Dashboard() {
No data No data
</div> </div>
<div className="txt"> <div className="txt">
Go to <a onClick={() => invoke('control_window')}>{'Control Center -> Awesome'}</a> to add Go to{' '}
data and make sure they are enabled. <a onClick={() => invoke('control_window', { type: 'control' })}>
{'Control Center -> Awesome'}
</a>{' '}
to add data and make sure they are enabled.
</div> </div>
</div> </div>
); );

View File

@ -1,16 +0,0 @@
.md-task {
margin-bottom: 5px;
display: flex;
justify-content: space-between;
.ant-breadcrumb-link {
padding: 3px 5px;
transition: all 300ms ease;
border-radius: 4px;
&:hover {
color: rgba(0, 0, 0, 0.88);
background-color: rgba(0, 0, 0, 0.06);
cursor: pointer;
}
}
}

View File

@ -8,7 +8,6 @@ import { fs, shell } from '@tauri-apps/api';
import useInit from '@/hooks/useInit'; import useInit from '@/hooks/useInit';
import SplitIcon from '@/icons/SplitIcon'; import SplitIcon from '@/icons/SplitIcon';
import { getPath } from '@/view/notes/config'; import { getPath } from '@/view/notes/config';
import './index.scss';
const modeMap: any = { const modeMap: any = {
0: 'split', 0: 'split',
@ -41,7 +40,7 @@ export default function Markdown() {
return ( return (
<> <>
<div className="md-task"> <div className="editor-task">
<Breadcrumb separator=""> <Breadcrumb separator="">
<Breadcrumb.Item onClick={() => history.go(-1)}> <Breadcrumb.Item onClick={() => history.go(-1)}>
<ArrowLeftOutlined /> <ArrowLeftOutlined />

View File

@ -1,128 +0,0 @@
import {
useEffect,
useState,
ForwardRefRenderFunction,
useImperativeHandle,
forwardRef,
} from 'react';
import { Form, Input, Select, Tooltip } from 'antd';
import { v4 } from 'uuid';
import type { FormProps } from 'antd';
import { DISABLE_AUTO_COMPLETE, chatRoot } from '@/utils';
import useInit from '@/hooks/useInit';
interface SyncFormProps {
record?: Record<string | symbol, any> | null;
type: string;
}
const initFormValue = {
act: '',
enable: true,
tags: [],
prompt: '',
};
const SyncForm: ForwardRefRenderFunction<FormProps, SyncFormProps> = ({ record, type }, ref) => {
const isDisabled = type === 'edit';
const [form] = Form.useForm();
useImperativeHandle(ref, () => ({ form }));
const [root, setRoot] = useState('');
useInit(async () => {
setRoot(await chatRoot());
});
useEffect(() => {
if (record) {
form.setFieldsValue(record);
}
}, [record]);
const pathOptions = (
<Form.Item noStyle name="protocol" initialValue="https">
<Select disabled={isDisabled}>
<Select.Option value="local">{root}</Select.Option>
<Select.Option value="http">http://</Select.Option>
<Select.Option value="https">https://</Select.Option>
</Select>
</Form.Item>
);
const extOptions = (
<Form.Item noStyle name="ext" initialValue="json">
<Select disabled={isDisabled}>
<Select.Option value="csv">.csv</Select.Option>
<Select.Option value="json">.json</Select.Option>
</Select>
</Form.Item>
);
const jsonTip = (
<Tooltip
title={
<pre>
{JSON.stringify(
[
{ cmd: '', act: '', prompt: '' },
{ cmd: '', act: '', prompt: '' },
],
null,
2,
)}
</pre>
}
>
<a>JSON</a>
</Tooltip>
);
const csvTip = (
<Tooltip
title={
<pre>{`"cmd","act","prompt"
"cmd","act","prompt"
"cmd","act","prompt"
"cmd","act","prompt"`}</pre>
}
>
<a>CSV</a>
</Tooltip>
);
return (
<>
<Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
<Form.Item
label="Name"
name="name"
rules={[{ required: true, message: 'Please enter a name!' }]}
>
<Input placeholder="Please enter a name" {...DISABLE_AUTO_COMPLETE} />
</Form.Item>
<Form.Item
label="PATH"
name="path"
rules={[{ required: true, message: 'Please enter the path!' }]}
>
<Input
placeholder="YOUR_PATH"
addonBefore={pathOptions}
addonAfter={extOptions}
{...DISABLE_AUTO_COMPLETE}
/>
</Form.Item>
<Form.Item style={{ display: 'none' }} name="id" initialValue={v4().replace(/-/g, '')}>
<input />
</Form.Item>
</Form>
<div className="tip">
<p>
The file supports only {csvTip} and {jsonTip} formats.
</p>
</div>
</>
);
};
export default forwardRef(SyncForm);

View File

@ -1,155 +0,0 @@
import { useState, useRef, useEffect } from 'react';
import { Table, Modal, Button, message } from 'antd';
import { invoke, path, fs } from '@tauri-apps/api';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import { TABLE_PAGINATION } from '@/hooks/useTable';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
import { CHAT_MODEL_JSON, chatRoot, readJSON, genCmd } from '@/utils';
import { syncColumns, getPath } from './config';
import SyncForm from './Form';
const fmtData = (data: Record<string, any>[] = []) =>
(Array.isArray(data) ? data : []).map((i) => ({
...i,
cmd: i.cmd ? i.cmd : genCmd(i.act),
tags: ['user-sync'],
enable: true,
}));
export default function SyncCustom() {
const [isVisible, setVisible] = useState(false);
const { modelData, modelSet } = useChatModel('sync_custom', CHAT_MODEL_JSON);
const { modelCacheCmd, modelCacheSet } = useCacheModel();
const { opData, opInit, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
const { columns, ...opInfo } = useColumns(syncColumns());
const formRef = useRef<any>(null);
const hide = () => {
setVisible(false);
opInfo.resetRecord();
};
useEffect(() => {
if (modelData.length <= 0) return;
opInit(modelData);
}, [modelData]);
useEffect(() => {
if (!opInfo.opType) return;
if (opInfo.opType === 'sync') {
const filename = `${opInfo?.opRecord?.id}.json`;
handleSync(filename).then((isOk: boolean) => {
opInfo.resetRecord();
if (!isOk) return;
const data = opReplace(opInfo?.opRecord?.[opSafeKey], {
...opInfo?.opRecord,
last_updated: Date.now(),
});
modelSet(data);
opInfo.resetRecord();
});
}
if (['edit', 'new'].includes(opInfo.opType)) {
setVisible(true);
}
if (['delete'].includes(opInfo.opType)) {
(async () => {
try {
const file = await path.join(
await chatRoot(),
'cache_model',
`${opInfo?.opRecord?.id}.json`,
);
await fs.removeFile(file);
} catch (e) {}
const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
modelSet(data);
opInfo.resetRecord();
modelCacheCmd();
})();
}
}, [opInfo.opType, formRef]);
const handleSync = async (filename: string) => {
const record = opInfo?.opRecord;
const isJson = /json$/.test(record?.ext);
const file = await path.join(await chatRoot(), 'cache_model', filename);
const filePath = await getPath(record);
// https or http
if (/^http/.test(record?.protocol)) {
const data = await invoke('sync_user_prompts', { url: filePath, dataType: record?.ext });
if (data) {
await modelCacheSet(data as [], file);
await modelCacheCmd();
message.success('ChatGPT Prompts data has been synchronized!');
return true;
} else {
message.error('ChatGPT Prompts data sync failed, please try again!');
return false;
}
}
// local
if (isJson) {
// parse json
const data = await readJSON(filePath, { isRoot: true });
await modelCacheSet(fmtData(data), file);
} else {
// parse csv
const data = await fs.readTextFile(filePath);
const list: Record<string, string>[] = await invoke('parse_prompt', { data });
await modelCacheSet(fmtData(list), file);
}
await modelCacheCmd();
return true;
};
const handleOk = () => {
formRef.current?.form?.validateFields().then((vals: Record<string, any>) => {
if (opInfo.opType === 'new') {
const data = opAdd(vals);
modelSet(data);
message.success('Data added successfully');
}
if (opInfo.opType === 'edit') {
const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
modelSet(data);
message.success('Data updated successfully');
}
hide();
});
};
return (
<div>
<Button
style={{ marginBottom: 10 }}
className="chat-add-btn"
type="primary"
onClick={opInfo.opNew}
>
Add PATH
</Button>
<Table
key="id"
rowKey="name"
columns={columns}
scroll={{ x: 800 }}
dataSource={opData}
pagination={TABLE_PAGINATION}
/>
<Modal
open={isVisible}
onCancel={hide}
title="Sync PATH"
onOk={handleOk}
destroyOnClose
maskClosable={false}
>
<SyncForm ref={formRef} record={opInfo?.opRecord} type={opInfo.opType} />
</Modal>
</div>
);
}

View File

@ -67,5 +67,5 @@ const RenderPath = ({ row }: any) => {
}; };
export const getPath = async (row: any) => { export const getPath = async (row: any) => {
return (await path.join(await chatRoot(), 'notes', row.id)) + `.${row.ext}`; return await path.join(await chatRoot(), 'notes', `${row.id}.md`);
}; };

166
src/view/prompts/SyncCustom/Form.tsx vendored Normal file
View File

@ -0,0 +1,166 @@
import {
useEffect,
useState,
ForwardRefRenderFunction,
useImperativeHandle,
forwardRef,
} from 'react';
import { Form, Input, Radio, Upload, Tooltip, Button, message } from 'antd';
import { v4 } from 'uuid';
import { UploadOutlined } from '@ant-design/icons';
import type { FormProps, RadioChangeEvent, UploadProps, UploadFile } from 'antd';
import { DISABLE_AUTO_COMPLETE, chatRoot } from '@/utils';
interface SyncFormProps {
record?: Record<string | symbol, any> | null;
}
const initFormValue = {
name: '',
url: '',
file: null,
protocol: 'https',
};
const SyncForm: ForwardRefRenderFunction<FormProps, SyncFormProps> = ({ record }, ref) => {
const [form] = Form.useForm();
useImperativeHandle(ref, () => ({ form }));
const [protocol, setProtocol] = useState('https');
const [fileList, setFileList] = useState<UploadFile[]>([]);
useEffect(() => {
if (record) {
form.setFieldsValue(record);
}
}, [record]);
const jsonTip = (
<Tooltip
title={
<pre>
{JSON.stringify(
[
{ cmd: '', act: '', prompt: '' },
{ cmd: '', act: '', prompt: '' },
],
null,
2,
)}
</pre>
}
>
<a>.json</a>
</Tooltip>
);
const csvTip = (
<Tooltip
title={
<pre>{`"cmd","act","prompt"
"a","aaa","aaa aaa"
"b","bbb","bbb bbb"
"c","ccc","ccc ccc"`}</pre>
}
>
<a>.csv</a>
</Tooltip>
);
const handleType = (e: RadioChangeEvent) => {
setProtocol(e.target.value);
};
const uploadOptions: UploadProps = {
onRemove: () => {
setFileList([]);
},
customRequest: () => {},
beforeUpload: (file) => {
const isCSV = /.csv$/.test(file.name);
const isJSON = /.json$/.test(file.name);
const isOk = isCSV || isJSON;
if (!isOk) {
message.error('You can only upload .json or .csv file!');
} else {
setFileList([file]);
}
return isOk || Upload.LIST_IGNORE;
},
maxCount: 1,
fileList,
};
return (
<>
<Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
<Form.Item
label="Name"
name="name"
rules={[{ required: true, message: 'Please enter a name!' }]}
>
<Input placeholder="Please enter a name" {...DISABLE_AUTO_COMPLETE} />
</Form.Item>
<Form.Item label="Protocol" name="protocol" rules={[{ required: true }]}>
<Radio.Group onChange={handleType} value={protocol}>
<Radio value="https">https</Radio>
<Radio value="http">http</Radio>
<Radio value="local">local</Radio>
</Radio.Group>
</Form.Item>
{['http', 'https'].includes(protocol) && (
<div style={{ height: 180 }}>
<Form.Item
label="URL"
name="url"
rules={[
{ required: true, message: 'Please enter the URL!' },
({ getFieldValue }) => ({
validator(_, value) {
if (!value || /\.json$|\.csv$/.test(getFieldValue('url'))) {
return Promise.resolve();
}
return Promise.reject(
new Error('The file supports only .csv and .json formats'),
);
},
}),
]}
>
<Input
placeholder="your_path/file_name.ext"
addonBefore={`${protocol}://`}
{...DISABLE_AUTO_COMPLETE}
/>
</Form.Item>
<div style={{ marginLeft: 80, color: '#888' }}>
<p>
<b>.ext</b>: only {csvTip} or {jsonTip} file formats are supported.
</p>
</div>
</div>
)}
{protocol === 'local' && (
<Form.Item
name="file"
label="File"
rules={[{ required: true, message: 'Please select a file!' }]}
style={{ height: 168 }}
>
<Upload.Dragger {...uploadOptions}>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
<p className="ant-upload-hint">
Only {csvTip} or {jsonTip} file formats are supported.
</p>
</Upload.Dragger>
</Form.Item>
)}
<Form.Item style={{ display: 'none' }} name="id" initialValue={v4().replace(/-/g, '')}>
<input />
</Form.Item>
</Form>
</>
);
};
export default forwardRef(SyncForm);

View File

@ -4,6 +4,7 @@ import { HistoryOutlined } from '@ant-design/icons';
import { shell, path } from '@tauri-apps/api'; import { shell, path } from '@tauri-apps/api';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { EditRow } from '@/hooks/useColumns';
import useInit from '@/hooks/useInit'; import useInit from '@/hooks/useInit';
import { chatRoot, fmtDate } from '@/utils'; import { chatRoot, fmtDate } from '@/utils';
@ -13,6 +14,9 @@ export const syncColumns = () => [
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
width: 100, width: 100,
render: (_: string, row: any, actions: any) => (
<EditRow rowKey="name" row={row} actions={actions} />
),
}, },
{ {
title: 'Protocol', title: 'Protocol',
@ -47,21 +51,22 @@ export const syncColumns = () => [
render: (_: any, row: any, actions: any) => { render: (_: any, row: any, actions: any) => {
return ( return (
<Space> <Space>
<Popconfirm {row.protocol !== 'local' && (
overlayStyle={{ width: 250 }} <Popconfirm
title="Sync will overwrite the previous data, confirm to sync?" overlayStyle={{ width: 250 }}
onConfirm={() => actions.setRecord(row, 'sync')} title="Sync will overwrite the previous data, confirm to sync?"
okText="Yes" onConfirm={() => actions.setRecord(row, 'sync')}
cancelText="No" okText="Yes"
> cancelText="No"
<a>Sync</a> >
</Popconfirm> <a>Sync</a>
</Popconfirm>
)}
{row.last_updated && ( {row.last_updated && (
<Link to={`${row.id}`} state={row}> <Link to={`${row.id}`} state={row}>
View View
</Link> </Link>
)} )}
<a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
<Popconfirm <Popconfirm
title="Are you sure to delete this path?" title="Are you sure to delete this path?"
onConfirm={() => actions.setRecord(row, 'delete')} onConfirm={() => actions.setRecord(row, 'delete')}
@ -86,8 +91,8 @@ const RenderPath = ({ row }: any) => {
export const getPath = async (row: any) => { export const getPath = async (row: any) => {
if (!/^http/.test(row.protocol)) { if (!/^http/.test(row.protocol)) {
return (await path.join(await chatRoot(), row.path)) + `.${row.ext}`; return await path.join(await chatRoot(), 'cache_prompts', `${row.id}.json`);
} else { } else {
return `${row.protocol}://${row.path}.${row.ext}`; return `${row.protocol}://${row.url}`;
} }
}; };

228
src/view/prompts/SyncCustom/index.tsx vendored Normal file
View File

@ -0,0 +1,228 @@
import { useState, useRef, useEffect } from 'react';
import { Table, Modal, Button, message } from 'antd';
import { invoke, path, fs, shell } from '@tauri-apps/api';
import useData from '@/hooks/useData';
import useInit from '@/hooks/useInit';
import useColumns from '@/hooks/useColumns';
import { TABLE_PAGINATION } from '@/hooks/useTable';
import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
import { CHAT_PROMPT_JSON, chatRoot, genCmd } from '@/utils';
import { syncColumns, getPath } from './config';
import SyncForm from './Form';
const fmtData = (data: Record<string, any>[] = []) =>
(Array.isArray(data) ? data : []).map((i) => ({
...i,
cmd: i.cmd ? i.cmd : genCmd(i.act),
tags: ['user-sync'],
enable: true,
}));
export default function SyncCustom() {
const [logPath, setLogPath] = useState('');
const [isVisible, setVisible] = useState(false);
const { promptData, promptSet, promptUpdate } = useChatPrompt('sync_custom', CHAT_PROMPT_JSON);
const { promptCacheCmd, promptCacheSet } = useCachePrompt();
const { opData, opInit, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
const { columns, ...opInfo } = useColumns(syncColumns());
const formRef = useRef<any>(null);
const hide = () => {
setVisible(false);
opInfo.resetRecord();
};
useInit(async () => {
const filePath = await path.join(await chatRoot(), 'chatgpt.log');
setLogPath(filePath);
});
useEffect(() => {
if (promptData.length <= 0) return;
opInit(promptData);
}, [promptData]);
useEffect(() => {
if (!opInfo.opType) return;
(async () => {
if (opInfo.opType === 'sync') {
handleSync();
}
if (opInfo.opType === 'rowedit') {
await promptUpdate(opInfo?.opRecord?.id, 'name', opInfo?.opRecord?.name);
message.success('Name has been changed');
opInfo.resetRecord();
}
if (['edit', 'new'].includes(opInfo.opType)) {
setVisible(true);
}
if (['delete'].includes(opInfo.opType)) {
try {
const file = await path.join(
await chatRoot(),
'cache_prompts',
`${opInfo?.opRecord?.id}.json`,
);
await fs.removeFile(file);
} catch (e) {}
const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
promptSet(data);
opInfo.resetRecord();
promptCacheCmd();
}
})();
}, [opInfo.opType, formRef]);
const handleSync = async () => {
const filename = `${opInfo?.opRecord?.id}.json`;
const record = opInfo?.opRecord;
// https or http
if (/^http/.test(record?.protocol)) {
const isJson = /json$/.test(record?.url);
const file = await path.join(await chatRoot(), 'cache_prompts', filename);
const filePath = await getPath(record);
const data = await invoke('sync_user_prompts', {
url: filePath,
dataType: isJson ? 'json' : 'csv',
});
if (data) {
await promptCacheSet(data as [], file);
await promptCacheCmd();
message.success('Prompts successfully synchronized');
const data2 = opReplace(opInfo?.opRecord?.[opSafeKey], {
...opInfo?.opRecord,
last_updated: Date.now(),
});
promptSet(data2);
opInfo.resetRecord();
} else {
message.error(
'Prompts synchronization failed, please try again (click to "View Log" for more details)',
);
}
}
opInfo.resetRecord();
};
const parseLocal = async (file: File): Promise<[boolean, any[] | null]> => {
if (file) {
const fileData = await readFile(file);
const isJSON = /json$/.test(file.name);
if (isJSON) {
// parse json
try {
const jsonData = JSON.parse(fileData);
return [true, jsonData];
} catch (e) {
message.error('JSON parse error, please check your file');
return [false, null];
}
} else {
// parse csv
const list: Record<string, string>[] | null = await invoke('parse_prompt', {
data: fileData,
});
if (!list) {
message.error('CSV parse error, please check your file');
return [false, null];
} else {
return [true, list];
}
}
}
message.error('File parsing exception');
return [false, null];
};
const handleOk = () => {
formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
if (opInfo.opType === 'new') {
if (vals.protocol !== 'local') {
// http or https
delete vals.file;
const data = opAdd(vals);
await promptSet(data);
hide();
opInfo.setRecord(data[0], 'sync');
message.success('Data added successfully');
} else {
const file = vals?.file?.file?.originFileObj;
const data = opAdd(vals);
const parseData = await parseLocal(file);
if (parseData[0]) {
const id = data[0].id;
const filePath = await path.join(await chatRoot(), 'cache_prompts', `${id}.json`);
data[0].last_updated = Date.now();
await promptSet(data);
await promptCacheSet(fmtData(parseData[1] as []), filePath);
await promptCacheCmd();
hide();
message.success('Data added successfully');
} else {
opRemove(data?.[0]?.[opSafeKey]);
return;
}
}
}
if (opInfo.opType === 'edit') {
delete vals.file;
const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
promptSet(data);
hide();
message.success('Data updated successfully');
}
});
};
const handleLog = () => {
shell.open(logPath);
};
return (
<div>
<Button
style={{ marginBottom: 10 }}
className="chat-add-btn"
type="primary"
onClick={opInfo.opNew}
>
Add Prompt
</Button>
<Button style={{ marginBottom: 10 }} onClick={handleLog}>
View Log
</Button>
<Table
key="id"
rowKey="id"
columns={columns}
scroll={{ x: 800 }}
dataSource={opData}
pagination={TABLE_PAGINATION}
/>
<Modal
open={isVisible}
onCancel={hide}
title="Add Prompt"
onOk={handleOk}
destroyOnClose
maskClosable={false}
>
<SyncForm ref={formRef} record={opInfo?.opRecord} />
</Modal>
</div>
);
}
function readFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (e: any) => resolve(e.target.result);
reader.onerror = (e: any) => reject(e.target.error);
reader.readAsText(file);
});
}

View File

@ -7,7 +7,6 @@ export const syncColumns = () => [
title: '/{cmd}', title: '/{cmd}',
dataIndex: 'cmd', dataIndex: 'cmd',
fixed: 'left', fixed: 'left',
// width: 120,
key: 'cmd', key: 'cmd',
render: (_: string, row: Record<string, string>) => ( render: (_: string, row: Record<string, string>) => (
<Tag color="#2a2a2a">/{genCmd(row.act)}</Tag> <Tag color="#2a2a2a">/{genCmd(row.act)}</Tag>
@ -17,20 +16,17 @@ export const syncColumns = () => [
title: 'Act', title: 'Act',
dataIndex: 'act', dataIndex: 'act',
key: 'act', key: 'act',
// width: 200,
}, },
{ {
title: 'Tags', title: 'Tags',
dataIndex: 'tags', dataIndex: 'tags',
key: 'tags', key: 'tags',
// width: 150, render: () => <Tag>built-in</Tag>,
render: () => <Tag>chatgpt-prompts</Tag>,
}, },
{ {
title: 'Enable', title: 'Enable',
dataIndex: 'enable', dataIndex: 'enable',
key: 'enable', key: 'enable',
// width: 80,
render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => ( render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
<Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} /> <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
), ),
@ -40,7 +36,6 @@ export const syncColumns = () => [
title: 'Prompt', title: 'Prompt',
dataIndex: 'prompt', dataIndex: 'prompt',
key: 'prompt', key: 'prompt',
// width: 300,
render: (v: string) => <span className="chat-prompts-val">{v}</span>, render: (v: string) => <span className="chat-prompts-val">{v}</span>,
}, },
]; ];

View File

@ -6,38 +6,39 @@ import useInit from '@/hooks/useInit';
import useData from '@/hooks/useData'; import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns'; import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath'; import FilePath from '@/components/FilePath';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel'; import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable'; import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { fmtDate, chatRoot } from '@/utils'; import { fmtDate, chatRoot } from '@/utils';
import { syncColumns } from './config'; import { syncColumns } from './config';
import './index.scss'; import './index.scss';
const promptsURL = 'https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv'; // const promptsURL = 'https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv';
const promptsURL = 'https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv';
export default function SyncPrompts() { export default function SyncPrompts() {
const { rowSelection, selectedRowIDs } = useTableRowSelection(); const { rowSelection, selectedRowIDs } = useTableRowSelection();
const [jsonPath, setJsonPath] = useState(''); const [jsonPath, setJsonPath] = useState('');
const { modelJson, modelSet } = useChatModel('sync_prompts'); const { promptJson, promptSet } = useChatPrompt('sync_prompts');
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath); const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]); const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
const { columns, ...opInfo } = useColumns(syncColumns()); const { columns, ...opInfo } = useColumns(syncColumns());
const lastUpdated = modelJson?.sync_prompts?.last_updated; const lastUpdated = promptJson?.sync_prompts?.last_updated;
const selectedItems = rowSelection.selectedRowKeys || []; const selectedItems = rowSelection.selectedRowKeys || [];
useInit(async () => { useInit(async () => {
setJsonPath(await path.join(await chatRoot(), 'cache_model', 'chatgpt_prompts.json')); setJsonPath(await path.join(await chatRoot(), 'cache_prompts', 'chatgpt_prompts.json'));
}); });
useEffect(() => { useEffect(() => {
if (modelCacheJson.length <= 0) return; if (promptCacheJson.length <= 0) return;
opInit(modelCacheJson); opInit(promptCacheJson);
}, [modelCacheJson.length]); }, [promptCacheJson.length]);
const handleSync = async () => { const handleSync = async () => {
const data = await invoke('sync_prompts', { time: Date.now() }); const data = await invoke('sync_prompts', { time: Date.now() });
if (data) { if (data) {
opInit(data as any[]); opInit(data as any[]);
modelSet({ promptSet({
id: 'chatgpt_prompts', id: 'chatgpt_prompts',
last_updated: Date.now(), last_updated: Date.now(),
}); });
@ -47,13 +48,13 @@ export default function SyncPrompts() {
useEffect(() => { useEffect(() => {
if (opInfo.opType === 'enable') { if (opInfo.opType === 'enable') {
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord); const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
modelCacheSet(data); promptCacheSet(data);
} }
}, [opInfo.opTime]); }, [opInfo.opTime]);
const handleEnable = (isEnable: boolean) => { const handleEnable = (isEnable: boolean) => {
const data = opReplaceItems(selectedRowIDs, { enable: isEnable }); const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
modelCacheSet(data); promptCacheSet(data);
}; };
return ( return (
@ -83,8 +84,8 @@ export default function SyncPrompts() {
</div> </div>
<div className="chat-table-tip"> <div className="chat-table-tip">
<div className="chat-sync-path"> <div className="chat-sync-path">
<FilePath url={promptsURL} content="f/awesome-chatgpt-prompts/prompts.csv" /> <FilePath label="URL" url={promptsURL} content="f/awesome-chatgpt-prompts/prompts.csv" />
<FilePath label="CACHE" paths="cache_model/chatgpt_prompts.json" /> <FilePath label="CACHE" paths="cache_prompts/chatgpt_prompts.json" />
</div> </div>
{lastUpdated && ( {lastUpdated && (
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}> <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>

View File

@ -7,7 +7,6 @@ export const syncColumns = () => [
title: '/{cmd}', title: '/{cmd}',
dataIndex: 'cmd', dataIndex: 'cmd',
fixed: 'left', fixed: 'left',
// width: 120,
key: 'cmd', key: 'cmd',
render: (_: string, row: Record<string, string>) => ( render: (_: string, row: Record<string, string>) => (
<Tag color="#2a2a2a">/{row.cmd ? row.cmd : genCmd(row.act)}</Tag> <Tag color="#2a2a2a">/{row.cmd ? row.cmd : genCmd(row.act)}</Tag>
@ -17,13 +16,11 @@ export const syncColumns = () => [
title: 'Act', title: 'Act',
dataIndex: 'act', dataIndex: 'act',
key: 'act', key: 'act',
// width: 200,
}, },
{ {
title: 'Tags', title: 'Tags',
dataIndex: 'tags', dataIndex: 'tags',
key: 'tags', key: 'tags',
// width: 150,
render: (v: string[]) => ( render: (v: string[]) => (
<span className="chat-prompts-tags"> <span className="chat-prompts-tags">
{v?.map((i) => ( {v?.map((i) => (
@ -36,7 +33,6 @@ export const syncColumns = () => [
title: 'Enable', title: 'Enable',
dataIndex: 'enable', dataIndex: 'enable',
key: 'enable', key: 'enable',
// width: 80,
render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => ( render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
<Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} /> <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
), ),
@ -46,7 +42,6 @@ export const syncColumns = () => [
title: 'Prompt', title: 'Prompt',
dataIndex: 'prompt', dataIndex: 'prompt',
key: 'prompt', key: 'prompt',
// width: 300,
render: (v: string) => <span className="chat-prompts-val">{v}</span>, render: (v: string) => <span className="chat-prompts-val">{v}</span>,
}, },
]; ];

View File

@ -7,9 +7,9 @@ import { path } from '@tauri-apps/api';
import useData from '@/hooks/useData'; import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns'; import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath'; import FilePath from '@/components/FilePath';
import { useCacheModel } from '@/hooks/useChatModel'; import { useCachePrompt } from '@/hooks/useChatPrompt';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable'; import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { getPath } from '@/view/model/SyncCustom/config'; import { getPath } from '@/view/prompts/SyncCustom/config';
import { fmtDate, chatRoot } from '@/utils'; import { fmtDate, chatRoot } from '@/utils';
import { syncColumns } from './config'; import { syncColumns } from './config';
import useInit from '@/hooks/useInit'; import useInit from '@/hooks/useInit';
@ -21,32 +21,36 @@ export default function SyncRecord() {
const state = location?.state; const state = location?.state;
const { rowSelection, selectedRowIDs } = useTableRowSelection(); const { rowSelection, selectedRowIDs } = useTableRowSelection();
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath); const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]); const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
const { columns, ...opInfo } = useColumns(syncColumns()); const { columns, ...opInfo } = useColumns(syncColumns());
const selectedItems = rowSelection.selectedRowKeys || []; const selectedItems = rowSelection.selectedRowKeys || [];
useInit(async () => { useInit(async () => {
setFilePath(await getPath(state)); if (state.protocol === 'local') {
setJsonPath(await path.join(await chatRoot(), 'cache_model', `${state?.id}.json`)); setFilePath('');
} else {
setFilePath(await getPath(state));
}
setJsonPath(await path.join(await chatRoot(), 'cache_prompts', `${state?.id}.json`));
}); });
useEffect(() => { useEffect(() => {
if (modelCacheJson.length <= 0) return; if (promptCacheJson.length <= 0) return;
opInit(modelCacheJson); opInit(promptCacheJson);
}, [modelCacheJson.length]); }, [promptCacheJson.length]);
useEffect(() => { useEffect(() => {
if (opInfo.opType === 'enable') { if (opInfo.opType === 'enable') {
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord); const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
modelCacheSet(data); promptCacheSet(data);
} }
}, [opInfo.opTime]); }, [opInfo.opTime]);
const handleEnable = (isEnable: boolean) => { const handleEnable = (isEnable: boolean) => {
const data = opReplaceItems(selectedRowIDs, { enable: isEnable }); const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
modelCacheSet(data); promptCacheSet(data);
}; };
return ( return (
@ -69,8 +73,8 @@ export default function SyncRecord() {
</div> </div>
<div className="chat-table-tip"> <div className="chat-table-tip">
<div className="chat-sync-path"> <div className="chat-sync-path">
<FilePath url={filePath} /> {filePath && <FilePath label="URL" url={filePath} />}
<FilePath label="CACHE" paths={`cache_model/${state?.id}.json`} /> <FilePath label="CACHE" paths={`cache_prompts/${state?.id}.json`} />
</div> </div>
{state?.last_updated && ( {state?.last_updated && (
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}> <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>

View File

@ -45,12 +45,6 @@ const UserCustomForm: ForwardRefRenderFunction<FormProps, UserCustomFormProps> =
> >
<Input placeholder="Please enter the Act" {...DISABLE_AUTO_COMPLETE} /> <Input placeholder="Please enter the Act" {...DISABLE_AUTO_COMPLETE} />
</Form.Item> </Form.Item>
<Form.Item label="Tags" name="tags">
<Tags value={record?.tags} />
</Form.Item>
<Form.Item label="Enable" name="enable" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item <Form.Item
label="Prompt" label="Prompt"
name="prompt" name="prompt"
@ -58,6 +52,12 @@ const UserCustomForm: ForwardRefRenderFunction<FormProps, UserCustomFormProps> =
> >
<Input.TextArea rows={4} placeholder="Please enter a prompt" {...DISABLE_AUTO_COMPLETE} /> <Input.TextArea rows={4} placeholder="Please enter a prompt" {...DISABLE_AUTO_COMPLETE} />
</Form.Item> </Form.Item>
<Form.Item label="Enable" name="enable" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item label="Tags" name="tags">
<Tags value={record?.tags} />
</Form.Item>
</Form> </Form>
); );
}; };

View File

@ -1,6 +1,6 @@
import { Tag, Switch, Space, Popconfirm, Table } from 'antd'; import { Tag, Switch, Space, Popconfirm, Table } from 'antd';
export const modelColumns = () => [ export const promptColumns = () => [
{ {
title: '/{cmd}', title: '/{cmd}',
dataIndex: 'cmd', dataIndex: 'cmd',
@ -54,7 +54,7 @@ export const modelColumns = () => [
<Space size="middle"> <Space size="middle">
<a onClick={() => actions.setRecord(row, 'edit')}>Edit</a> <a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
<Popconfirm <Popconfirm
title="Are you sure to delete this model?" title="Are you sure to delete this prompt?"
onConfirm={() => actions.setRecord(row, 'delete')} onConfirm={() => actions.setRecord(row, 'delete')}
okText="Yes" okText="Yes"
cancelText="No" cancelText="No"

View File

@ -6,32 +6,32 @@ import useInit from '@/hooks/useInit';
import useData from '@/hooks/useData'; import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns'; import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath'; import FilePath from '@/components/FilePath';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel'; import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable'; import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { chatRoot, fmtDate } from '@/utils'; import { chatRoot, fmtDate } from '@/utils';
import { modelColumns } from './config'; import { promptColumns } from './config';
import UserCustomForm from './Form'; import UserCustomForm from './Form';
export default function UserCustom() { export default function UserCustom() {
const { rowSelection, selectedRowIDs } = useTableRowSelection(); const { rowSelection, selectedRowIDs } = useTableRowSelection();
const [isVisible, setVisible] = useState(false); const [isVisible, setVisible] = useState(false);
const [jsonPath, setJsonPath] = useState(''); const [jsonPath, setJsonPath] = useState('');
const { modelJson, modelSet } = useChatModel('user_custom'); const { promptJson, promptSet } = useChatPrompt('user_custom');
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath); const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
const { opData, opInit, opReplaceItems, opAdd, opRemove, opReplace, opSafeKey } = useData([]); const { opData, opInit, opReplaceItems, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
const { columns, ...opInfo } = useColumns(modelColumns()); const { columns, ...opInfo } = useColumns(promptColumns());
const lastUpdated = modelJson?.user_custom?.last_updated; const lastUpdated = promptJson?.user_custom?.last_updated;
const selectedItems = rowSelection.selectedRowKeys || []; const selectedItems = rowSelection.selectedRowKeys || [];
const formRef = useRef<any>(null); const formRef = useRef<any>(null);
useInit(async () => { useInit(async () => {
setJsonPath(await path.join(await chatRoot(), 'cache_model', 'user_custom.json')); setJsonPath(await path.join(await chatRoot(), 'cache_prompts', 'user_custom.json'));
}); });
useEffect(() => { useEffect(() => {
if (modelCacheJson.length <= 0) return; if (promptCacheJson.length <= 0) return;
opInit(modelCacheJson); opInit(promptCacheJson);
}, [modelCacheJson.length]); }, [promptCacheJson.length]);
useEffect(() => { useEffect(() => {
if (!opInfo.opType) return; if (!opInfo.opType) return;
@ -40,7 +40,7 @@ export default function UserCustom() {
} }
if (['delete'].includes(opInfo.opType)) { if (['delete'].includes(opInfo.opType)) {
const data = opRemove(opInfo?.opRecord?.[opSafeKey]); const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
modelCacheSet(data); promptCacheSet(data);
opInfo.resetRecord(); opInfo.resetRecord();
} }
}, [opInfo.opType, formRef]); }, [opInfo.opType, formRef]);
@ -48,13 +48,13 @@ export default function UserCustom() {
useEffect(() => { useEffect(() => {
if (opInfo.opType === 'enable') { if (opInfo.opType === 'enable') {
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord); const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
modelCacheSet(data); promptCacheSet(data);
} }
}, [opInfo.opTime]); }, [opInfo.opTime]);
const handleEnable = (isEnable: boolean) => { const handleEnable = (isEnable: boolean) => {
const data = opReplaceItems(selectedRowIDs, { enable: isEnable }); const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
modelCacheSet(data); promptCacheSet(data);
}; };
const hide = () => { const hide = () => {
@ -65,7 +65,7 @@ export default function UserCustom() {
const handleOk = () => { const handleOk = () => {
formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => { formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
if ( if (
modelCacheJson.map((i: any) => i.cmd).includes(vals.cmd) && promptCacheJson.map((i: any) => i.cmd).includes(vals.cmd) &&
opInfo?.opRecord?.cmd !== vals.cmd opInfo?.opRecord?.cmd !== vals.cmd
) { ) {
message.warning( message.warning(
@ -84,9 +84,9 @@ export default function UserCustom() {
default: default:
break; break;
} }
await modelCacheSet(data); await promptCacheSet(data);
opInit(data); opInit(data);
modelSet({ promptSet({
id: 'user_custom', id: 'user_custom',
last_updated: Date.now(), last_updated: Date.now(),
}); });
@ -94,13 +94,13 @@ export default function UserCustom() {
}); });
}; };
const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} Model`; const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} Prompt`;
return ( return (
<div> <div>
<div className="chat-table-btns"> <div className="chat-table-btns">
<Button className="chat-add-btn" type="primary" onClick={opInfo.opNew}> <Button className="chat-add-btn" type="primary" onClick={opInfo.opNew}>
Add Model Add Prompt
</Button> </Button>
<div> <div>
{selectedItems.length > 0 && ( {selectedItems.length > 0 && (
@ -115,7 +115,7 @@ export default function UserCustom() {
</div> </div>
</div> </div>
<div className="chat-table-tip"> <div className="chat-table-tip">
<FilePath label="CACHE" paths="cache_model/user_custom.json" /> <FilePath label="CACHE" paths="cache_prompts/user_custom.json" />
{lastUpdated && ( {lastUpdated && (
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}> <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
Last updated on {fmtDate(lastUpdated)} Last updated on {fmtDate(lastUpdated)}

76
src/view/scripts/Editor.tsx vendored Normal file
View File

@ -0,0 +1,76 @@
import { FC, useState } from 'react';
import { useLocation } from 'react-router-dom';
import Editor from '@monaco-editor/react';
import { Breadcrumb, Tag, Popconfirm } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { fs, shell, dialog, process } from '@tauri-apps/api';
import useInit from '@/hooks/useInit';
import { getPath } from './config';
interface ScriptEditorProps {
onChange?: (v: string) => void;
}
const ScriptEditor: FC<ScriptEditorProps> = ({ onChange }) => {
const [filePath, setFilePath] = useState('');
const [source, setSource] = useState('// write your script here\n');
const location = useLocation();
const state = location?.state;
useInit(async () => {
const file = await getPath(state);
setFilePath(file);
setSource(await fs.readTextFile(file));
});
const handleEdit = (e: any) => {
setSource(e);
onChange && onChange(e);
};
const handleSave = async () => {
await fs.writeTextFile(filePath, source);
const isOk = await dialog.ask(
'The script will take effect after the application is restarted. Do you want to restart now?',
{
title: 'Script saved successfully',
},
);
if (isOk) {
process.relaunch();
}
};
const handleReset = async () => {
setSource(await fs.readTextFile(filePath));
};
return (
<div className="script-editor">
<Breadcrumb className="editor-task" separator="">
<Breadcrumb.Item onClick={() => history.go(-1)}>
<ArrowLeftOutlined />
</Breadcrumb.Item>
<Popconfirm
placement="topRight"
title="Are you sure you want to save the changes? It is a risky operation, but you can restore it through the sync button."
onConfirm={handleSave}
onCancel={handleReset}
okText="Yes"
cancelText="No"
overlayStyle={{ width: 300 }}
>
<Tag className="editor-btn" color="#108ee9">
Save
</Tag>
</Popconfirm>
<Breadcrumb.Item onClick={() => shell.open(filePath)}>{filePath}</Breadcrumb.Item>
</Breadcrumb>
<Editor height="80vh" language="javascript" value={source} onChange={handleEdit} />
</div>
);
};
export default ScriptEditor;

94
src/view/scripts/config.tsx vendored Normal file
View File

@ -0,0 +1,94 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Tag, Space, Popconfirm } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import { path, shell } from '@tauri-apps/api';
import useInit from '@/hooks/useInit';
import { fmtDate, chatRoot } from '@/utils';
export const scriptColumns = ({ scriptsMap }: any) => [
{
title: 'File Name',
dataIndex: 'name',
key: 'name',
fixed: 'left',
width: 160,
render: (v: string) => <Tag color={v === 'main.js' ? 'green' : 'default'}>{v}</Tag>,
},
{
title: 'Version',
width: 200,
render: (_: string, row: any) => {
const next = scriptsMap?.[row.name]?.next_version;
const curr = scriptsMap?.[row.name]?.curr_version;
return (
row.name !== 'main.js' && (
<Space>
{curr && <Tag style={{ marginRight: 0 }}>{curr}</Tag>}
{next && next !== curr && <ArrowRightOutlined style={{ color: '#989898' }} />}
{next && next !== curr && <Tag color="green-inverse">{next}</Tag>}
</Space>
)
);
},
},
{
title: 'Path',
dataIndex: 'path',
key: 'path',
width: 200,
render: (_: string, row: any) => <RenderPath row={row} />,
},
{
title: 'Remote File',
width: 200,
render: (_: string, row: any) => {
const uri = `https://raw.githubusercontent.com/lencx/ChatGPT/main/scripts/${row.name}`;
return <a onClick={() => shell.open(uri)}>{uri}</a>;
},
},
{
title: 'Action',
fixed: 'right',
width: 100,
render: (_: any, row: any, actions: any) => {
const isExternal = row.name === 'main.js';
return (
<Space>
<Link
to={`/scripts/${row.id}`}
state={row}
style={{ color: !isExternal ? '#ff4d4f' : '' }}
>
Edit
</Link>
{!isExternal && (
<Popconfirm
placement="topLeft"
title="Are you sure you want to synchronize? It will overwrite all previous modifications made to this file."
onConfirm={() => actions.setRecord(row, 'sync')}
okText="Yes"
cancelText="No"
overlayStyle={{ width: 300 }}
>
<a>Sync</a>
</Popconfirm>
)}
</Space>
);
},
},
];
export const RenderPath = ({ row }: any) => {
const [filePath, setFilePath] = useState('');
useInit(async () => {
setFilePath(await getPath(row));
});
return <a onClick={() => shell.open(filePath)}>{filePath}</a>;
};
export const getPath = async (row: any) => {
return await path.join(await chatRoot(), 'scripts', `${row.name}`);
};

80
src/view/scripts/index.tsx vendored Normal file
View File

@ -0,0 +1,80 @@
import { useEffect, useState } from 'react';
import { Table, message } from 'antd';
import { path, fs, invoke } from '@tauri-apps/api';
import useInit from '@/hooks/useInit';
import useColumns from '@/hooks/useColumns';
import { TABLE_PAGINATION } from '@/hooks/useTable';
import { scriptRoot } from '@/utils';
import { scriptColumns } from './config';
const SCRIPTS = [
'main.js',
'core.js',
'chat.js',
'cmd.js',
'dalle2.js',
'export.js',
'markdown.export.js',
'popup.core.js',
];
export default function Scripts() {
const [scriptsMap, setScriptsMap] = useState({});
const { columns, ...opInfo } = useColumns(scriptColumns({ scriptsMap }));
const handleInit = async () => {
try {
const manifestPath = await path.join(await scriptRoot(), 'manifest.json');
const data = await fs.readTextFile(manifestPath);
const { scripts } = JSON.parse(data);
const infoMap: Record<string, any> = {};
for (const script of scripts) {
const scriptInfo: any = await invoke('get_script_info', { name: script.name });
infoMap[script.name] = {
curr_version: scriptInfo?.version,
next_version: script.version,
};
}
setScriptsMap(infoMap);
} catch (error) {
console.error(error);
}
};
useInit(handleInit);
useEffect(() => {
if (!opInfo.opType) return;
(async () => {
if (opInfo.opType === 'sync') {
const isOk = await invoke('sync_scripts', { name: opInfo?.opRecord?.name });
if (isOk) {
await handleInit();
opInfo.resetRecord();
message.success(
`The ${opInfo?.opRecord?.name} script has been synchronized successfully`,
);
} else {
message.error(
`The ${opInfo?.opRecord?.name} script synchronization failed. You can try editing the script and click the Remote File link to copy the source code.`,
);
}
}
})();
}, [opInfo.opType]);
return (
<div className="chatgpt-script">
<Table
rowKey="name"
scroll={{ x: 800 }}
columns={columns}
dataSource={SCRIPTS.map((i) => ({ name: i }))}
{...TABLE_PAGINATION}
pagination={false}
/>
</div>
);
}

View File

@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { Form, Radio, Switch, Input, Tooltip } from 'antd'; import { Form, Radio, Switch, Input, Tooltip, Select, Tag } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons'; import { QuestionCircleOutlined } from '@ant-design/icons';
import { platform } from '@tauri-apps/api/os'; import { platform } from '@tauri-apps/api/os';
@ -8,9 +8,16 @@ import { DISABLE_AUTO_COMPLETE } from '@/utils';
export default function General() { export default function General() {
const [platformInfo, setPlatform] = useState(''); const [platformInfo, setPlatform] = useState('');
const [vlist, setVoices] = useState<any[]>([]);
useInit(async () => { useInit(async () => {
setPlatform(await platform()); setPlatform(await platform());
speechSynthesis.addEventListener('voiceschanged', () => {
const voices = speechSynthesis.getVoices();
console.log(voices);
setVoices(voices);
});
setVoices(speechSynthesis.getVoices());
}); });
return ( return (
@ -18,16 +25,19 @@ export default function General() {
<Form.Item label="Stay On Top" name="stay_on_top" valuePropName="checked"> <Form.Item label="Stay On Top" name="stay_on_top" valuePropName="checked">
<Switch /> <Switch />
</Form.Item> </Form.Item>
{/* <Form.Item label="Save Window State" name="save_window_state" valuePropName="checked">
<Switch />
</Form.Item> */}
{platformInfo === 'darwin' && ( {platformInfo === 'darwin' && (
<Form.Item label="Titlebar" name="titlebar" valuePropName="checked"> <Form.Item label="Titlebar" name="titlebar" valuePropName="checked">
<Switch /> <Switch />
</Form.Item> </Form.Item>
)} )}
{platformInfo === 'darwin' && ( {/* {platformInfo === 'darwin' && (
<Form.Item label="Hide Dock Icon" name="hide_dock_icon" valuePropName="checked"> <Form.Item label="Hide Dock Icon" name="hide_dock_icon" valuePropName="checked">
<Switch /> <Switch />
</Form.Item> </Form.Item>
)} )} */}
<Form.Item label="Theme" name="theme"> <Form.Item label="Theme" name="theme">
<Radio.Group> <Radio.Group>
<Radio value="light">Light</Radio> <Radio value="light">Light</Radio>
@ -45,6 +55,18 @@ export default function General() {
<Form.Item label={<GlobalShortcutLabel />} name="global_shortcut"> <Form.Item label={<GlobalShortcutLabel />} name="global_shortcut">
<Input placeholder="CmdOrCtrl+Shift+O" {...DISABLE_AUTO_COMPLETE} /> <Input placeholder="CmdOrCtrl+Shift+O" {...DISABLE_AUTO_COMPLETE} />
</Form.Item> </Form.Item>
<Form.Item label="Set Speech Language" name="speech_lang">
<Select>
{vlist.map((voice: any) => {
return (
<Select.Option key={voice.voiceURI} value={voice.voiceURI}>
{voice.name} {': '}
<Tag>{voice.lang}</Tag>
</Select.Option>
);
})}
</Select>
</Form.Item>
</> </>
); );
} }

View File

@ -1,7 +1,7 @@
import { Form, Switch, Input, Tooltip } from 'antd'; import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons'; import { QuestionCircleOutlined } from '@ant-design/icons';
import SwitchOrigin from '@/components/SwitchOrigin'; // import SwitchOrigin from '@/components/SwitchOrigin';
import { DISABLE_AUTO_COMPLETE } from '@/utils'; import { DISABLE_AUTO_COMPLETE } from '@/utils';
const PopupSearchLabel = () => { const PopupSearchLabel = () => {
@ -30,13 +30,33 @@ const PopupSearchLabel = () => {
); );
}; };
const MainCloseLabel = () => {
return (
<span>
Close Exit{' '}
<Tooltip title="Click the close button whether to exit directly, the default minimized.">
<QuestionCircleOutlined style={{ color: '#1677ff' }} />
</Tooltip>
</span>
);
};
export default function MainWindow() { export default function MainWindow() {
return ( return (
<> <>
<Form.Item label={<PopupSearchLabel />} name="popup_search" valuePropName="checked"> <Form.Item label={<PopupSearchLabel />} name="popup_search" valuePropName="checked">
<Switch /> <Switch />
</Form.Item> </Form.Item>
<SwitchOrigin name="main" /> <Form.Item label={<MainCloseLabel />} name="main_close" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item label="Default Width" name="main_width">
<InputNumber />
</Form.Item>
<Form.Item label="Default Height" name="main_height">
<InputNumber />
</Form.Item>
{/* <SwitchOrigin name="main" /> */}
<Form.Item label="User Agent (Main)" name="ua_window"> <Form.Item label="User Agent (Main)" name="ua_window">
<Input.TextArea <Input.TextArea
autoSize={{ minRows: 4, maxRows: 4 }} autoSize={{ minRows: 4, maxRows: 4 }}

View File

@ -1,8 +1,8 @@
import { Form, Switch, Input, Tooltip } from 'antd'; import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons'; import { QuestionCircleOutlined } from '@ant-design/icons';
import { DISABLE_AUTO_COMPLETE } from '@/utils'; import { DISABLE_AUTO_COMPLETE } from '@/utils';
import SwitchOrigin from '@/components/SwitchOrigin'; // import SwitchOrigin from '@/components/SwitchOrigin';
const UALabel = () => { const UALabel = () => {
return ( return (
@ -23,7 +23,13 @@ export default function TrayWindow() {
<Form.Item label="Enable SystemTray" name="tray" valuePropName="checked"> <Form.Item label="Enable SystemTray" name="tray" valuePropName="checked">
<Switch /> <Switch />
</Form.Item> </Form.Item>
<SwitchOrigin name="tray" /> <Form.Item label="Default Width" name="tray_width">
<InputNumber />
</Form.Item>
<Form.Item label="Default Height" name="tray_height">
<InputNumber />
</Form.Item>
{/* <SwitchOrigin name="tray" /> */}
<Form.Item label={<UALabel />} name="ua_tray"> <Form.Item label={<UALabel />} name="ua_tray">
<Input.TextArea <Input.TextArea
autoSize={{ minRows: 4, maxRows: 4 }} autoSize={{ minRows: 4, maxRows: 4 }}

View File

@ -39,7 +39,7 @@ export default function Settings() {
const onReset = async () => { const onReset = async () => {
const chatData = await invoke('reset_app_conf'); const chatData = await invoke('reset_app_conf');
setChatConf(chatData); setChatConf(chatData);
const isOk = await dialog.ask(`Configuration reset successfully, whether to restart?`, { const isOk = await dialog.ask(`Configuration reset successfully, do you want to restart?`, {
title: 'ChatGPT Preferences', title: 'ChatGPT Preferences',
}); });
if (isOk) { if (isOk) {
@ -52,7 +52,7 @@ export default function Settings() {
const onFinish = async (values: any) => { const onFinish = async (values: any) => {
if (!isEqual(omit(chatConf, ['default_origin']), values)) { if (!isEqual(omit(chatConf, ['default_origin']), values)) {
await invoke('form_confirm', { data: values, label: 'main' }); await invoke('form_confirm', { data: values, label: 'main' });
const isOk = await dialog.ask(`Configuration saved successfully, whether to restart?`, { const isOk = await dialog.ask(`Configuration saved successfully, do you want to restart?`, {
title: 'ChatGPT Preferences', title: 'ChatGPT Preferences',
}); });
if (isOk) { if (isOk) {

View File

@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ESNext", "target": "ES2015",
"useDefineForClassFields": true, "useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"], "lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false, "allowJs": false,

View File

@ -24,5 +24,19 @@ export default defineConfig({
minify: !process.env.TAURI_DEBUG ? 'esbuild' : false, minify: !process.env.TAURI_DEBUG ? 'esbuild' : false,
// produce sourcemaps for debug builds // produce sourcemaps for debug builds
sourcemap: !!process.env.TAURI_DEBUG, sourcemap: !!process.env.TAURI_DEBUG,
rollupOptions: {
output: {
manualChunks: {
ant: ['antd'],
antico: ['@ant-design/icons'],
editor: ['@monaco-editor/react'],
utils: ['lodash', 'uuid', 'dayjs', 'clsx'],
rrr: ['react', 'react-dom', 'react-router-dom'],
rm: ['react-markdown'],
rsh: ['react-syntax-highlighter'],
md: ['github-markdown-css', 'rehype-raw', 'remark-comment-config', 'remark-gfm'],
},
},
},
}, },
}); });