diff --git a/bun.lockb b/bun.lockb index e4c6d7d..782352a 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index b3ad55e..31db37c 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "module": "src/main.ts", "devDependencies": { "@tsconfig/node18": "^18.2.2", + "@types/tough-cookie": "^4.0.3", "@typescript-eslint/eslint-plugin": "^6.7.2", "@typescript-eslint/parser": "^6.7.2", "bun-types": "^1.0.2", @@ -44,6 +45,8 @@ }, "dependencies": { "fp-ts": "^2.16.1", + "http-cookie-agent": "^5.0.4", + "tough-cookie": "^4.1.3", "undici": "^5.25.3" } } diff --git a/src/loans.ts b/src/loans.ts index 3adab57..aab27e3 100644 --- a/src/loans.ts +++ b/src/loans.ts @@ -1,6 +1,8 @@ import { pipe } from "fp-ts/function"; import * as TE from "fp-ts/TaskEither"; -import { Dispatcher, request } from "undici"; +import { CookieAgent } from "http-cookie-agent/undici"; +import { CookieJar } from "tough-cookie"; +import { Dispatcher, FormData, request } from "undici"; // type Loans = { // username: string; @@ -10,15 +12,42 @@ import { Dispatcher, request } from "undici"; // } export const listLoans = (): TE.TaskEither => { - const post = (url: string) => - TE.tryCatch( - () => request(url), - (reason) => new Error(`Unable to fetch loans: ${String(reason)}`), - ); - const parseJson = TE.tryCatchK( - (resp) => resp.body.text(), - (reason) => new Error(`Unable to : ${String(reason)}`), + return pipe( + authenticate( + "http://www.mediathequederoubaix.fr", + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + process.env.USERNAME!, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + process.env.PASSWORD!, + ), + TE.chain(getText), ); - - return pipe(post("http://www.mediathequederoubaix.fr"), TE.chain(parseJson)); }; + +const authenticate = (url: string, user: string, pass: string) => + TE.tryCatch( + () => { + const cookieJar = new CookieJar(); + const agent = new CookieAgent({ cookies: { jar: cookieJar } }); + + const data = new FormData(); + data.set("name", user); + data.set("pass", pass); + data.set("form_id", "user_login"); + + return request(url, { + method: "POST", + body: data, + dispatcher: agent, + }); + }, + (reason) => new Error(`Unable to authenticate: ${String(reason)}`), + ); +const getText = TE.tryCatchK( + async (resp) => { + const text = await resp.body.text(); + console.log("text", text); + return text; + }, + (reason) => new Error(`Unable to : ${String(reason)}`), +); diff --git a/src/test.ts b/src/test.ts new file mode 100644 index 0000000..9988220 --- /dev/null +++ b/src/test.ts @@ -0,0 +1,15 @@ +import { FormData, request } from "undici"; + +const data = new FormData(); +data.set("name", "X0002412030"); +data.set("pass", "03/11/1980"); +data.set("form_id", "user_login"); + +const resp = await request("http://www.mediathequederoubaix.fr", { + method: "POST", + body: data, +}); + +const text = await resp.body.text(); + +console.log("text", text);