A Neovim plugin enabling you to solve LeetCode problems.
| 1 | local path = require("plenary.path") |
| 2 | local log = require("leetcode.logger") |
| 3 | |
| 4 | local config = require("leetcode.config") |
| 5 | ---@type Path |
| 6 | local file = config.storage.cache:joinpath(("cookie%s"):format(config.is_cn and "_cn" or "")) |
| 7 | |
| 8 | local 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 |
| 16 | local Cookie = {} |
| 17 | |
| 18 | ---@param str string |
| 19 | --- |
| 20 | ---@return string|nil |
| 21 | |
| 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 |
| 34 | end |
| 35 | |
| 36 | ---@return boolean |
| 37 | |
| 38 | if not file:exists() then |
| 39 | return false |
| 40 | end |
| 41 | return pcall(path.rm, file) |
| 42 | end |
| 43 | |
| 44 | ---@return string|nil |
| 45 | |
| 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")) |
| 53 | end |
| 54 | |
| 55 | ---@return lc.cache.Cookie | nil |
| 56 | |
| 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 |
| 83 | end |
| 84 | |
| 85 | ---@param str string |
| 86 | --- |
| 87 | ---@return lc.cache.Cookie|nil, string|nil |
| 88 | |
| 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 } |
| 100 | end |
| 101 | |
| 102 | return Cookie |