fix: cookie manager
This commit is contained in:
parent
6ca7256a1e
commit
e23952abe3
@ -1,33 +1,57 @@
|
|||||||
import { ICookieManager } from "../types/cookieManager"
|
import fs from "fs"
|
||||||
|
import path from "path"
|
||||||
|
|
||||||
export class CookieManager implements ICookieManager {
|
export class CookieManager {
|
||||||
private cookieName: string
|
private cookieFile: string
|
||||||
|
private cookieData: { [key: string]: string }
|
||||||
|
|
||||||
constructor(cookieName: string) {
|
constructor(name: string) {
|
||||||
this.cookieName = cookieName
|
// Create cookies directory in user's home directory
|
||||||
|
const homeDir = process.env.HOME || process.env.USERPROFILE
|
||||||
|
const cookieDir = path.join(homeDir!, ".tiktok-api")
|
||||||
|
|
||||||
|
if (!fs.existsSync(cookieDir)) {
|
||||||
|
fs.mkdirSync(cookieDir, { recursive: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cookieFile = path.join(cookieDir, "cookies.json")
|
||||||
|
this.cookieData = this.loadCookies()
|
||||||
}
|
}
|
||||||
|
|
||||||
public getCookie(): string | null {
|
private loadCookies(): { [key: string]: string } {
|
||||||
if (typeof window === "undefined") return null
|
try {
|
||||||
const cookies = document.cookie.split(";")
|
if (fs.existsSync(this.cookieFile)) {
|
||||||
const cookie = cookies.find((c) =>
|
const data = fs.readFileSync(this.cookieFile, "utf8")
|
||||||
c.trim().startsWith(`${this.cookieName}=`)
|
return JSON.parse(data)
|
||||||
)
|
}
|
||||||
if (!cookie) return null
|
} catch (error) {
|
||||||
return decodeURIComponent(cookie.split("=")[1])
|
console.error("Error loading cookies:", error)
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private saveCookies(): void {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(
|
||||||
|
this.cookieFile,
|
||||||
|
JSON.stringify(this.cookieData, null, 2)
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error saving cookies:", error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public setCookie(value: string): void {
|
public setCookie(value: string): void {
|
||||||
if (typeof window === "undefined") return
|
this.cookieData["tiktok"] = value
|
||||||
const date = new Date()
|
this.saveCookies()
|
||||||
date.setTime(date.getTime() + 30 * 24 * 60 * 60 * 1000) // 30 days
|
}
|
||||||
document.cookie = `${this.cookieName}=${encodeURIComponent(
|
|
||||||
value
|
public getCookie(): string | null {
|
||||||
)}; expires=${date.toUTCString()}; path=/`
|
return this.cookieData["tiktok"] || null
|
||||||
}
|
}
|
||||||
|
|
||||||
public deleteCookie(): void {
|
public deleteCookie(): void {
|
||||||
if (typeof window === "undefined") return
|
delete this.cookieData["tiktok"]
|
||||||
document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`
|
this.saveCookies()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user