forked from emacs-grammarly/lsp-grammarly-un
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsp-grammarly-un.el
456 lines (388 loc) · 17.2 KB
/
lsp-grammarly-un.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
;;; lsp-grammarly-un.el --- LSP Clients for Grammarly (Unofficial) -*- lexical-binding: t; -*-
;; Copyright (C) 2021-2022 Shen, Jen-Chieh
;; Created date 2021-02-19 23:48:37
;; Author: Shen, Jen-Chieh <[email protected]>
;; Description: LSP Clients for Unofficial Grammarly.
;; Keywords: convenience lsp grammarly checker
;; Version: 0.2.2
;; Package-Requires: ((emacs "27.1") (lsp-mode "6.1") (grammarly "0.3.0") (request "0.3.0") (s "1.12.0") (ht "2.3"))
;; URL: https://github.com/emacs-grammarly/lsp-grammarly-un
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU 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 General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; LSP server implementation for Grammarly (Unofficial)
;;
;;; Code:
(require 'subr-x)
(require 'lsp-mode)
(require 'grammarly)
(require 'request)
(require 's)
(require 'ht)
(require 'json)
(unless (require 'keytar nil t)
(warn "`keytar' is required for login into Grammarly account"))
(defgroup lsp-grammarly-un nil
"Settings for the Grammarly Language Server (Unofficial).
Link: https://github.com/emacs-grammarly/unofficial-grammarly-language-server."
:group 'lsp-mode
:link '(url-link "https://github.com/emacs-grammarly/lsp-grammarly-un"))
(defcustom lsp-grammarly-un-server-path nil
"Path points for Grammarly LSP.
This is only for development use."
:type 'string
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-active-modes
'(text-mode latex-mode org-mode markdown-mode)
"List of major mode that work with Grammarly."
:type 'list
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-auto-activate t
"Enable Grammarly service when a supported document is opened."
:type 'boolean
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-audience "knowledgeable"
"Sets the default audience for every document."
:type '(choice (const "general")
(const "knowledgeable")
(const "expert"))
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-dialect "american"
"Sets the default dialect for every document."
:type '(choice (const "american")
(const "australian")
(const "british")
(const "canadian"))
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-domain "general"
"Sets the default domain for every document."
:type '(choice (const "academic")
(const "business")
(const "general")
(const "technical")
(const "casual")
(const "creative"))
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-emotions '()
"Experimental: How do you want to sound."
:type 'list
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-goals '()
"Experimental: What are you trying to do."
:type 'list
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-user-words '()
"A list of words as a local dictionary."
:type 'list
:group 'lsp-grammarly-un)
(defcustom lsp-grammarly-un-override '()
"Per document override for audience, dialect, domain, emotions and goals."
:type 'list
:group 'lsp-grammarly-un)
(defvar lsp-grammarly-un--show-debug-message nil
"Flag to see if we show debug messages.")
;;
;; (@* "External" )
;;
(declare-function keytar--check "ext:keytar.el")
(declare-function keytar-set-password "ext:keytar.el")
(declare-function keytar-get-password "ext:keytar.el")
(declare-function keytar-delete-password "ext:keytar.el")
;;
;; (@* "Util" )
;;
(defun lsp-grammarly-un--message (fmt &rest args)
"Debug message like function `message' with same argument FMT and ARGS."
(when lsp-grammarly-un--show-debug-message (apply 'message fmt args)))
(defun lsp-grammarly-un--scale-100 (score)
"Convert SCORE to the scale of 100 instead of scale of 1."
(ignore-errors (* score 100)))
(defun lsp-grammarly-un--random-bytes (n)
"Return random bytes up to N."
(let* ((charset "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
(baseCount (length charset)))
(with-temp-buffer
(dotimes (_ n) (insert (elt charset (random baseCount))))
(buffer-string))))
(defun lsp-grammarly-un--json-encode (obj)
"Wrap function `json-encode' to convert OBJ for keytar password."
(s-replace "\"" "\\\"" (json-encode obj)))
(defun lsp-grammarly-un--json-read (string)
"Ensure read JSON STRING avoid bad string format."
(let ((output (or (ignore-errors (json-read-from-string string))
(ignore-errors (json-read-from-string (concat "\"" string "\""))))))
;; After avoiding bad string format, we need to read json once again.
(when (stringp output)
(setq output (ignore-errors (json-read-from-string output))))
output))
;;
;; (@* "Login" )
;;
(defconst lsp-grammarly-un--cookie-key "vscode-grammarly-cookie"
"Key to store credentials.")
(defconst lsp-grammarly-un--account "default"
"Key that Grammarly LSP default to.")
(defvar lsp-grammarly-un--password-string nil
"Encrypted password in string.")
(defvar lsp-grammarly-un--password nil
"Encrypted password in alist.")
(defun lsp-grammarly-un-login-p ()
"Return non-nil if currently logged in to Grammarly.com."
lsp-grammarly-un--password)
(defun lsp-grammarly-un--username ()
"Return the currently login username."
(when lsp-grammarly-un--password
(or (ignore-errors (cdr (assoc 'username lsp-grammarly-un--password)))
(ignore-errors (ht-get lsp-grammarly-un--password "username")))))
(defun lsp-grammarly-un--get-credentials (_workspace _uri callback &rest _)
"Return the credentials from native password manager.
For argument CALLBACK, see object `lsp--client' description."
(funcall callback nil))
(defun lsp-grammarly-un--get-token (_workspace _uri callback &rest _)
"Return the token from variable `lsp-grammarly-un--password'.
For argument CALLBACK, see object `lsp--client' description."
(funcall callback lsp-grammarly-un--password))
(defun lsp-grammarly-un--store-token (_workspace _uri _callback &rest _)
"Save the token once."
(keytar-set-password
lsp-grammarly-un--cookie-key lsp-grammarly-un--account lsp-grammarly-un--password-string))
(defun lsp-grammarly-un--init (&rest _)
"Get Grammarly API ready."
(unless (lsp-grammarly-un-login-p)
(let ((pass (ignore-errors
(keytar-get-password lsp-grammarly-un--cookie-key lsp-grammarly-un--account))))
(when pass
(setq lsp-grammarly-un--password-string pass
lsp-grammarly-un--password (lsp-grammarly-un--json-read pass))))
(if (lsp-grammarly-un-login-p)
(message "[INFO] Logged in as, %s" (lsp-grammarly-un--username))
(message "[INFO] Visited as, anonymous"))))
(defun lsp-grammarly-un--show-error (_workspace _uri callback &rest _)
"Show error from language server.
For argument CALLBACK, see object `lsp--client' description."
;; TODO: This only shows credentials error but we have it resolve
;; on our side.
(funcall callback))
(defun lsp-grammarly-un--update-document-state (_workspace _uri _callback &rest _)
"Update the document status from current document."
;; TODO: this is where you get the document state to update modeline
;; information for this plugin.
;;
;; Currently, this does nothing.
)
;;
;; (@* "Server" )
;;
(defun lsp-grammarly-un--server-command ()
"Generate startup command for Grammarly language server."
(or (and lsp-grammarly-un-server-path
(list lsp-grammarly-un-server-path "--stdio"))
(list (lsp-package-path 'grammarly-ls) "--stdio")))
(lsp-register-custom-settings
'(("grammarly.autoActivate" lsp-grammarly-un-auto-activate t)
("grammarly.audience" lsp-grammarly-un-audience)
("grammarly.dialect" lsp-grammarly-un-dialect)
("grammarly.domain" lsp-grammarly-un-domain)
("grammarly.emotions" lsp-grammarly-un-emotions)
("grammarly.goals" lsp-grammarly-un-goals)
("grammarly.userWords" lsp-grammarly-un-user-words)
("grammarly.overrides" lsp-grammarly-un-override)))
(lsp-dependency 'grammarly-ls
'(:system "grammarly-ls")
'(:npm :package "@emacs-grammarly/unofficial-grammarly-language-server"
:path "unofficial-grammarly-language-server"))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection #'lsp-grammarly-un--server-command)
:activation-fn (lambda (&rest _) (apply #'derived-mode-p lsp-grammarly-un-active-modes))
:priority -1
:add-on? t
:server-id 'grammarly-ls
:download-server-fn (lambda (_client callback error-callback _update?)
(lsp-package-ensure 'grammarly-ls callback error-callback))
:after-open-fn #'lsp-grammarly-un--init
:async-request-handlers
(ht ("$/getCredentials" #'lsp-grammarly-un--get-credentials)
("$/getToken" #'lsp-grammarly-un--get-token)
("$/storeToken" #'lsp-grammarly-un--store-token)
("$/showError" #'lsp-grammarly-un--show-error)
("$/updateDocumentState" #'lsp-grammarly-un--update-document-state))))
;;
;; (@* "Commands" )
;;
(defun lsp-grammarly-un-check-grammar ()
"Start the Grammarly checker."
(interactive)
(lsp-request-async
"$/checkGrammar" `(:uri ,(lsp--buffer-uri))
(lambda (_) (message "Start Grammarly checker..."))))
(defun lsp-grammarly-un-stop ()
"Stop the Grammarly checker."
(interactive)
(lsp-request-async
"$/stop" `(:uri ,(lsp--buffer-uri))
(lambda (_) (message "Stop Grammarly checker..."))))
(defun lsp-grammarly-un-stats ()
"Return document state."
(interactive)
(lsp-request-async
"$/getDocumentState" `(:uri ,(lsp--buffer-uri))
(lambda (state)
(message
(concat
(let* ((user (ht-get state "user"))
(is-premium (ht-get user "isPremium"))
(_is-anonymous (ht-get user "isAnonymous"))
(username (ht-get user "username")))
(format "[User] %s (%s)" username (if is-premium "Premium" "Free")))
(when-let ((score (ht-get state "score")))
(format "\n[Text Score] %s out of 100" score))
(when-let* ((text-info (ht-get state "textInfo"))
(chars-count (ht-get text-info "charsCount"))
(words-count (ht-get text-info "wordsCount"))
(readability-score (ht-get text-info "readabilityScore")))
(format "\n[Text-Info] Readability: %s, C: %s, W: %s"
readability-score chars-count words-count))
(when-let* ((scores (ht-get state "scores"))
(clarity (ht-get scores "Clarity"))
(tone (ht-get scores "Tone"))
(correctness (ht-get scores "Correctness"))
(general-score (ht-get scores "GeneralScore"))
(engagement (ht-get scores "Engagement")))
(format "\nClarity: %s, Tone: %s, Correctness: %s, GeneralScore: %s, Engagement: %s"
(lsp-grammarly-un--scale-100 clarity)
(lsp-grammarly-un--scale-100 tone)
(lsp-grammarly-un--scale-100 correctness)
(lsp-grammarly-un--scale-100 general-score)
(lsp-grammarly-un--scale-100 engagement))))))))
;;
;; (@* "Login" )
;;
(defvar lsp-grammarly-un--code-verifier nil "Login information, code verifier.")
(defvar lsp-grammarly-un--challenge nil "Login information, challenge.")
(defconst lsp-grammarly-un-client-id "extensionVSCode"
"Key for URI scheme.")
(defun lsp-grammarly-un--resolve-uri (uri)
"Handle URI for authentication."
(let ((prefix "vscode://znck.grammarly/auth/callback?") query)
(if (not (string-prefix-p prefix uri))
(user-error "[WARNING] An URL should start with prefix: %s" prefix)
(setq uri (s-replace prefix "" uri)
query (url-parse-query-string uri))
(nth 1 (assoc "code" query)))))
(defun lsp-grammarly-un--update-cookie ()
"Refresh the Grammarly.com cookie once."
(grammarly--form-cookie)
`((csrf-token . ,(grammarly--get-cookie-by-name "csrf-token"))
(grauth . ,(grammarly--get-cookie-by-name "grauth"))
(gnar-containerId . ,(grammarly--get-cookie-by-name "gnar_containerId"))
(tdi . ,(grammarly--get-cookie-by-name "tdi"))))
(defun lsp-grammarly-un--uri-callback ()
"Callback after resolving URI.
Argument CODE is the query string from URI."
(let* ((uri (read-string "[Grammarly Authentication] code: "))
(code (lsp-grammarly-un--resolve-uri uri))
cookie csrf-token grauth gnar-containerId tdi)
(request
(format "https://auth.grammarly.com/v3/user/oranonymous?app=%s" lsp-grammarly-un-client-id)
:type "GET"
:headers
`(("x-client-type". ,lsp-grammarly-un-client-id)
("x-client-version" . "0.0.0"))
:success
(cl-function
(lambda (&key _response _data &allow-other-keys)
(setq cookie (lsp-grammarly-un--update-cookie)
csrf-token (cdr (assoc 'csrf-token cookie))
grauth (cdr (assoc 'grauth cookie))
gnar-containerId (cdr (assoc 'gnar-containerId cookie)))
(request
"https://auth.grammarly.com/v3/api/unified-login/code/exchange"
:type "POST"
:headers
`(("Accept" . "application/json")
("Content-Type" . "application/json")
("x-client-type" . ,lsp-grammarly-un-client-id)
("x-client-version" . "0.0.0")
("x-csrf-token" . ,csrf-token)
("x-container-id" . ,gnar-containerId)
("cookie" . ,(format "grauth=%s; csrf-token=%s" grauth csrf-token)))
:data
(json-encode
`(("client_id" . ,lsp-grammarly-un-client-id)
("code" . ,code)
("code_verifier" . ,lsp-grammarly-un--code-verifier)))
:success
(cl-function
(lambda (&key _response data &allow-other-keys)
(setq cookie (lsp-grammarly-un--update-cookie)
csrf-token (cdr (assoc 'csrf-token cookie))
grauth (cdr (assoc 'grauth cookie))
gnar-containerId (cdr (assoc 'gnar-containerId cookie))
tdi (cdr (assoc 'tdi cookie)))
(let* ((all-data (lsp-grammarly-un--json-read data))
(user (nth 0 all-data))
(premium (string= "Premium" (cdr (assoc 'type user))))
(name (cdr (assoc 'name user)))
(email (cdr (assoc 'email user)))
(token (format "grauth=%s;csrf-token=%s;tdi=%s;" grauth csrf-token tdi))
(auth-info `(("isAnonymous" . :json-false)
("isPremium" . ,premium)
("token" . ,token)
("username" . ,email))))
(keytar-set-password
lsp-grammarly-un--cookie-key lsp-grammarly-un--account
(lsp-grammarly-un--json-encode auth-info))
;; TODO: This is slow, need to improve the performance for better
;; user experience.
(ignore-errors (lsp-workspace-restart nil))
(message "[INFO] Logged in as `%s`" name))))
:error
(cl-function
(lambda (&rest args &key _error-thrown &allow-other-keys)
(lsp-grammarly-un--message "[ERROR] Error while authenticating login: %s" args))))))
:error
(cl-function
(lambda (&rest args &key _error-thrown &allow-other-keys)
(lsp-grammarly-un--message "[ERROR] Error while getting cookie: %s" args))))))
(defun lsp-grammarly-un-login ()
"Login to Grammarly.com."
(interactive)
(keytar--check)
(if (lsp-grammarly-un-login-p)
(message "[INFO] You are already logged in with `%s`" (lsp-grammarly-un--username))
(setq lsp-grammarly-un--code-verifier
(base64url-encode-string (lsp-grammarly-un--random-bytes 96) t)
lsp-grammarly-un--challenge
(base64url-encode-string (secure-hash 'sha256 lsp-grammarly-un--code-verifier nil nil t) t))
(browse-url (format
"https://grammarly.com/signin/app?client_id=%s&code_challenge=%s"
lsp-grammarly-un-client-id lsp-grammarly-un--challenge))
(lsp-grammarly-un--uri-callback)))
(defun lsp-grammarly-un-logout ()
"Logout from Grammarly.com."
(interactive)
(keytar--check)
(if (not (lsp-grammarly-un-login-p))
(message "[INFO] You are already logout from Grammarly.com")
(if (keytar-delete-password lsp-grammarly-un--cookie-key lsp-grammarly-un--account)
(progn
(setq lsp-grammarly-un--password nil
lsp-grammarly-un--password-string nil)
;; TODO: This is slow, need to improve the performance for better
;; user experience.
(ignore-errors (lsp-workspace-restart nil))
(message "[INFO] Logged out of Grammarly.com"))
(message "[ERROR] Failed to logout from Grammarly.com"))))
(provide 'lsp-grammarly-un)
;;; lsp-grammarly-un.el ends here