Skip to content

Commit

Permalink
instagram: add fetching using bearer token (imputnet#487)
Browse files Browse the repository at this point in the history
for total of SEVEN methods of getting post info, i cannot bear this anymore

also prevent repetitive oembed pulling
  • Loading branch information
wukko authored May 3, 2024
1 parent 182e32d commit 6403cc8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
3 changes: 3 additions & 0 deletions docs/examples/cookies.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
"instagram": [
"mid=<replace>; ig_did=<with>; csrftoken=<your>; ds_user_id=<own>; sessionid=<cookies>"
],
"instagram_bearer": [
"token=<token_with_no_bearer_in_front>", "token=IGT:2:<looks_like_this>"
],
"reddit": [
"client_id=<replace_this>; client_secret=<replace_this>; refresh_token=<replace_this>"
],
Expand Down
25 changes: 19 additions & 6 deletions src/modules/processing/services/instagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,26 @@ async function request(url, cookie, method = 'GET', requestData) {
updateCookie(cookie, data.headers);
return data.json();
}

async function requestMobileApi(id, cookie) {
async function getMediaId(id, { cookie, token } = {}) {
const oembedURL = new URL('https://i.instagram.com/api/v1/oembed/');
oembedURL.searchParams.set('url', `https://www.instagram.com/p/${id}/`);

const oembed = await fetch(oembedURL, {
headers: {
...mobileHeaders,
...( token && { authorization: `Bearer ${token}` } ),
cookie
}
}).then(r => r.json()).catch(() => {});

const mediaId = oembed?.media_id;
if (!mediaId) return false;
return oembed?.media_id;
}

async function requestMobileApi(mediaId, { cookie, token } = {}) {
const mediaInfo = await fetch(`https://i.instagram.com/api/v1/media/${mediaId}/info/`, {
headers: {
...mobileHeaders,
...( token && { authorization: `Bearer ${token}` } ),
cookie
}
}).then(r => r.json()).catch(() => {});
Expand Down Expand Up @@ -236,10 +238,21 @@ async function getPost(id) {
let data, result;
try {
const cookie = getCookie('instagram');

const bearer = getCookie('instagram_bearer');
const token = bearer?.values()?.token;

// get media_id for mobile api, three methods
let media_id = await getMediaId(id);
if (!media_id && token) media_id = await getMediaId(id, { token });
if (!media_id && cookie) media_id = await getMediaId(id, { cookie });

// mobile api (bearer)
if (media_id && token) data = await requestMobileApi(id, { token });

// mobile api (no cookie, cookie)
data = await requestMobileApi(id);
if (!data && cookie) data = await requestMobileApi(id, cookie);
if (!data && media_id) data = await requestMobileApi(id);
if (!data && media_id && cookie) data = await requestMobileApi(id, { cookie });

// html embed (no cookie, cookie)
if (!data) data = await requestHTML(id);
Expand Down

0 comments on commit 6403cc8

Please sign in to comment.