irongit

A Neovim plugin enabling you to solve LeetCode problems.

102 lines2.1 KBLua
1local path = require("plenary.path")
2local log = require("leetcode.logger")
3
4local config = require("leetcode.config")
5---@type Path
6local file = config.storage.cache:joinpath(("cookie%s"):format(config.is_cn and "_cn" or ""))
7
8local hist = {}
9
10---@class lc.cache.Cookie
11---@field csrftoken string
12---@field leetcode_session string
13---@field str string
14
15---@class lc.Cookie
16local Cookie = {}
17
18---@param str string
19---
20---@return string|nil
21function Cookie.set(str)
22 local _, cerr = Cookie.parse(str)
23 if cerr then
24 return cerr
25 end
26
27 file:write(str, "w")
28 local auth_api = require("leetcode.api.auth")
29 local _, aerr = auth_api.user()
30
31 if aerr then
32 return aerr.msg
33 end
34end
35
36---@return boolean
37function Cookie.delete()
38 if not file:exists() then
39 return false
40 end
41 return pcall(path.rm, file)
42end
43
44---@return string|nil
45function Cookie.read()
46 local contents = file:read()
47
48 if not contents or type(contents) ~= "string" then
49 return
50 end
51
52 return select(1, contents:gsub("^%s*(.-)%s*$", "%1"))
53end
54
55---@return lc.cache.Cookie | nil
56function Cookie.get()
57 if not file:exists() then
58 return
59 end
60
61 local fstats = file:_stat()
62 local ftime = fstats.mtime.sec
63
64 local hcookie = hist[ftime]
65 if hcookie then
66 return hcookie
67 end
68
69 local contents = Cookie.read()
70 if not contents then
71 require("leetcode.command").delete_cookie()
72 return
73 end
74
75 local cookie = Cookie.parse(contents)
76 if not cookie then
77 require("leetcode.command").delete_cookie()
78 return
79 end
80
81 hist[ftime] = cookie
82 return cookie
83end
84
85---@param str string
86---
87---@return lc.cache.Cookie|nil, string|nil
88function Cookie.parse(str)
89 local csrf = str:match("csrftoken=([^;]+)")
90 if not csrf or csrf == "" then
91 return nil, "Bad csrf token format"
92 end
93
94 local ls = str:match("LEETCODE_SESSION=([^;]+)")
95 if not ls or ls == "" then
96 return nil, "Bad leetcode session token format"
97 end
98
99 return { csrftoken = csrf, leetcode_session = ls, str = str }
100end
101
102return Cookie