|
| 1 | +const CACHED = { |
| 2 | + fb_dtsg: null, |
| 3 | +}; |
| 4 | + |
| 5 | +export async function fetchGraphQl(params, url) { |
| 6 | + let query = ""; |
| 7 | + if (typeof params === "string") query = "&q=" + encodeURIComponent(params); |
| 8 | + else |
| 9 | + query = wrapGraphQlParams({ |
| 10 | + dpr: 1, |
| 11 | + __a: 1, |
| 12 | + __aaid: 0, |
| 13 | + __ccg: "GOOD", |
| 14 | + server_timestamps: true, |
| 15 | + ...params, |
| 16 | + }); |
| 17 | + |
| 18 | + const res = await fetch(url || "https://www.facebook.com/api/graphql/", { |
| 19 | + body: query + "&fb_dtsg=" + (await getFbDtsg()), |
| 20 | + method: "POST", |
| 21 | + headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| 22 | + credentials: "include", |
| 23 | + }); |
| 24 | + const text = await res.text(); |
| 25 | + |
| 26 | + // check error response |
| 27 | + try { |
| 28 | + const json = JSON.parse(text); |
| 29 | + if (json.errors) { |
| 30 | + const { summary, message, description_raw } = json.errors[0]; |
| 31 | + if (summary) { |
| 32 | + console.log(json); |
| 33 | + |
| 34 | + const div = document.createElement("div"); |
| 35 | + div.innerHTML = description_raw?.__html; |
| 36 | + const description = div.innerText; |
| 37 | + |
| 38 | + // notification.error({ |
| 39 | + // message: i18n.t("Facebook response Error"), |
| 40 | + // description: summary + ". " + message + ". " + description, |
| 41 | + // duration: 0, |
| 42 | + // }); |
| 43 | + } |
| 44 | + } |
| 45 | + } catch (e) {} |
| 46 | + |
| 47 | + return text; |
| 48 | +} |
| 49 | + |
| 50 | +export function wrapGraphQlParams(params = {}) { |
| 51 | + const formBody = []; |
| 52 | + for (const property in params) { |
| 53 | + const encodedKey = encodeURIComponent(property); |
| 54 | + const value = |
| 55 | + typeof params[property] === "string" |
| 56 | + ? params[property] |
| 57 | + : JSON.stringify(params[property]); |
| 58 | + const encodedValue = encodeURIComponent(value); |
| 59 | + formBody.push(encodedKey + "=" + encodedValue); |
| 60 | + } |
| 61 | + return formBody.join("&"); |
| 62 | +} |
| 63 | + |
| 64 | +export async function getFbDtsg() { |
| 65 | + if (CACHED.fb_dtsg) return CACHED.fb_dtsg; |
| 66 | + let res = await fetch("https://mbasic.facebook.com/photos/upload/"); |
| 67 | + let text = await res.text(); |
| 68 | + let dtsg = RegExp(/name="fb_dtsg" value="(.*?)"/).exec(text)?.[1]; |
| 69 | + if (!dtsg) { |
| 70 | + res = await fetch("https://m.facebook.com/home.php", { |
| 71 | + headers: { |
| 72 | + Accept: "text/html", |
| 73 | + }, |
| 74 | + }); |
| 75 | + text = res.text(); |
| 76 | + dtsg = |
| 77 | + RegExp(/"dtsg":{"token":"([^"]+)"/).exec(text)?.[1] || |
| 78 | + RegExp(/"name":"fb_dtsg","value":"([^"]+)/).exec(text)?.[1]; |
| 79 | + } |
| 80 | + CACHED.fb_dtsg = dtsg || null; |
| 81 | + return CACHED.fb_dtsg; |
| 82 | +} |
0 commit comments