Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More โ†’
Socket
Sign inDemoInstall
Socket

threads-api

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

threads-api - npm Package Compare versions

Comparing version 1.4.3 to 1.4.4

2

build/threads-api.d.ts

@@ -228,3 +228,3 @@ /// <reference types="node" />

getUserFollowers: PaginationAndSearchUserIDQuerier<GetUserProfileFollowPaginatedResponse>;
getUserFollowing: PaginationAndSearchUserIDQuerier<GetUserProfileFollowPaginatedResponse>;
getUserFollowings: PaginationAndSearchUserIDQuerier<GetUserProfileFollowPaginatedResponse>;
getPostIDfromThreadID: (threadID: string) => string;

@@ -231,0 +231,0 @@ getPostIDfromURL: (postURL: string) => string;

@@ -1,1 +0,1 @@

"use strict";!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{DEFAULT_DEVICE:function(){return d},ThreadsAPI:function(){return h}});var e=require("axios"),t=require("crypto");require("dotenv/config");var r=require("mrmime"),n=require("uuid"),s=require("./constants"),o=require("./dynamic-data");function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function u(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function a(e){i(o,n,s,a,u,"next",e)}function u(e){i(o,n,s,a,u,"throw",e)}a(void 0)})}}function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function c(e,t){var r,n,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(o){return function(i){return function(o){if(r)throw TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&o[0]?n.return:o[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,o[1])).done)return s;switch(n=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(s=(s=a.trys).length>0&&s[s.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{r=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,i])}}}var d={manufacturer:"OnePlus",model:"ONEPLUS+A3010",os_version:25,os_release:"7.1.1"},h=function(){"use strict";function i(i){var h,p,f,g,v=this;this.verbose=!1,this.token=void 0,this.fbLSDToken=s.DEFAULT_LSD_TOKEN,this.noUpdateToken=!1,this.noUpdateLSD=!1,this.device=d,this.userID=void 0,this.locale=void 0,this.maxRetries=1;var _=this;this.syncLoginExperiments=u(function(){var t,r,o;return c(this,function(a){switch(a.label){case 0:r={id:t=(0,n.v4)(),experiments:s.LOGIN_EXPERIMENTS},a.label=1;case 1:return a.trys.push([1,3,,4]),[4,e.default.post(""+s.BASE_API_URL+"/api/v1/qe/sync/",_.sign(r),{headers:l({},_._getAppHeaders(),{Authorization:void 0,"Sec-Fetch-Site":"same-origin","X-DEVICE-ID":t})})];case 2:return[2,a.sent()];case 3:throw o=a.sent(),_.verbose&&console.log("[SYNC LOGIN EXPERIMENT FAILED]",o.response.data),Error("Sync login experiment failed");case 4:return[2]}})});var b=this;this.encryptPassword=u(function(e){var r,n,s,o,a,i,u,l,d,h,p;return c(this,function(c){switch(c.label){case 0:return r=t.randomBytes(32),n=t.randomBytes(12),[4,b.syncLoginExperiments()];case 1:return s=c.sent().headers,b.verbose&&console.log("[SYNC LOGIN EXPERIMENT HEADERS]",JSON.stringify(s)),o=s["ig-set-password-encryption-key-id"],a=s["ig-set-password-encryption-pub-key"],i=t.publicEncrypt({key:Buffer.from(a||"","base64").toString(),padding:t.constants.RSA_PKCS1_PADDING},r),u=t.createCipheriv("aes-256-gcm",r,n),l=Math.floor(Date.now()/1e3).toString(),u.setAAD(Buffer.from(l)),d=Buffer.concat([u.update(e,"utf8"),u.final()]),(h=Buffer.alloc(2,0)).writeInt16LE(i.byteLength,0),p=u.getAuthTag(),[2,{time:l,password:Buffer.concat([Buffer.from([1,o||0]),n,h,i,p,d]).toString("base64")}]}})});var m=this;this.login=u(function(){var t,r,n,o;return c(this,function(a){switch(a.label){case 0:t=function(){var e;return c(this,function(t){switch(t.label){case 0:return t.trys.push([0,1,,3]),[2,{v:n()}];case 1:return t.sent(),m.verbose&&console.error("[LOGIN] Failed to login, retrying... ("+(r+1)+"/"+m.maxRetries+")"),e=1e3*Math.pow(2,r),[4,new Promise(function(t){return setTimeout(t,e)})];case 2:return t.sent(),r++,[3,3];case 3:return[2]}})},r=0,n=u(function(){var t,r,n,o,a,i,u,l;return c(this,function(c){switch(c.label){case 0:return m.verbose&&console.log("[LOGIN] Logging in..."),[4,m.encryptPassword(m.password)];case 1:return r=encodeURIComponent(JSON.stringify({client_input_params:{password:"#PWD_INSTAGRAM:4:"+(t=c.sent()).time+":"+t.password,contact_point:m.username,device_id:m.deviceID},server_params:{credential_type:"password",device_id:m.deviceID}})),n=encodeURIComponent(JSON.stringify({bloks_version:s.BLOKS_VERSION,styles_id:"instagram"})),o={method:"POST",headers:m._getAppHeaders(),responseType:"text",data:"params="+r+"&bk_client_context="+n+"&bloks_versioning_id="+s.BLOKS_VERSION},[4,(0,e.default)(""+s.BASE_API_URL+"/api/v1/bloks/apps/com.bloks.www.bloks.caa.login.async.send_login_request/",o)];case 2:a=JSON.stringify((a=c.sent().data).replaceAll("\\","")),m.verbose&&console.log("[LOGIN] Cleaned output",a);try{return u=a.split("Bearer IGT:2:")[1].split('"')[0].replaceAll("\\",""),l=null==(i=a.match(/pk_id":"(\d+)/))?void 0:i[1],m.noUpdateToken||(m.verbose&&console.debug("[token] UPDATED",u),m.token=u),m.userID=l,m.verbose&&console.debug("[userID] UPDATED",m.userID),[2,{token:u,userID:l}]}catch(e){throw m.verbose&&console.error("[LOGIN] Failed to login",e),Error("Login Failed")}return[2]}})}),a.label=1;case 1:if(!(r<m.maxRetries))return[3,3];return[5,function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t())];case 2:var i;if("object"==((i=o=a.sent())&&"undefined"!=typeof Symbol&&i.constructor===Symbol?"symbol":typeof i))return[2,o.v];return[3,1];case 3:throw Error("[LOGIN] Failed to login after "+m.maxRetries+" retries")}})}),this._getAppHeaders=function(){return l({"User-Agent":"Barcelona "+o.LATEST_ANDROID_APP_VERSION+" Android","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},v.token&&{Authorization:"Bearer IGT:2:"+v.token})},this._getInstaHeaders=function(){return l({},v._getAppHeaders(),{"X-Bloks-Is-Layout-Rtl":"false","X-Bloks-Version-Id":s.BLOKS_VERSION,"X-Ig-Android-Id":v.deviceID,"X-Ig-App-Id":s.IG_APP_ID,"Accept-Language":v.locale||"en-US"},v.userID&&{"Ig-U-Ds-User-Id":v.userID,"Ig-Intended-User-Id":v.userID},v.locale&&{"X-Ig-App-Locale":v.locale.replace("-","_"),"X-Ig-Device-Locale":v.locale.replace("-","_"),"X-Ig-Mapped-Locale":v.locale.replace("-","_")})},this._getDefaultHeaders=function(e){return l({},v._getAppHeaders(),{authority:"www.threads.net",accept:"*/*","accept-language":v.locale,"cache-control":"no-cache",origin:"https://www.threads.net",pragma:"no-cache","Sec-Fetch-Site":"same-origin","x-asbd-id":"129477","x-fb-lsd":v.fbLSDToken,"x-ig-app-id":"238260118697367"},e?{referer:"https://www.threads.net/@"+e}:void 0)};var I=this;this.getProfilePage=u(function(t,r,n){return c(this,function(s){switch(s.label){case 0:return[4,e.default.get(""+t+r,l({},n,{httpAgent:I.httpAgent,httpsAgent:I.httpsAgent,headers:l({},I._getDefaultHeaders(r),{accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","accept-language":"ko,en;q=0.9,ko-KR;q=0.8,ja;q=0.7",Authorization:void 0,referer:"https://www.instagram.com/","sec-fetch-dest":"document","sec-fetch-mode":"navigate","sec-fetch-site":"cross-site","sec-fetch-user":"?1","upgrade-insecure-requests":"1","x-asbd-id":void 0,"x-fb-lsd":void 0,"x-ig-app-id":void 0})}))];case 1:return[2,(0,s.sent().data).replace(/\s/g,"").replace(/\n/g,"")]}})});var D=this;this.getUserIDfromUsernameWithInstagram=u(function(e,t){var r,n,s,o,a;return c(this,function(i){switch(i.label){case 0:return[4,D.getProfilePage("https://www.instagram.com/",e,t)];case 1:return o=null==(r=(s=i.sent()).match(/"user_id":"(\d+)",/))?void 0:r[1],a=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!D.noUpdateLSD&&a&&(D.fbLSDToken=a,D.verbose&&console.debug("[fbLSDToken] UPDATED",D.fbLSDToken)),[2,o]}})});var S=this;this.getUserIDfromUsername=u(function(e,t){var r,n,s,o,a;return c(this,function(i){switch(i.label){case 0:return[4,S.getProfilePage("https://www.threads.net/@",e,t)];case 1:if(o=null==(r=(s=i.sent()).match(/"user_id":"(\d+)"/))?void 0:r[1],a=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!o)return[2,S.getUserIDfromUsernameWithInstagram(e,t)];return!S.noUpdateLSD&&a&&(S.fbLSDToken=a,S.verbose&&console.debug("[fbLSDToken] UPDATED",S.fbLSDToken)),[2,o]}})});var y=this;this.getCurrentUserID=u(function(e){var t;return c(this,function(r){switch(r.label){case 0:if(y.userID)return y.verbose&&console.debug("[userID] USING",y.userID),[2,y.userID];if(!y.username)throw Error("username is not defined");r.label=1;case 1:return r.trys.push([1,3,,5]),[4,y.getUserIDfromUsername(y.username,e)];case 2:return y.userID=r.sent(),y.verbose&&console.debug("[userID] UPDATED",y.userID),[2,y.userID];case 3:return t=r.sent(),y.verbose&&console.error("[userID] Failed to fetch userID, Fallbacking to login",t),[4,y.login()];case 4:return[2,r.sent().userID];case 5:return[2]}})}),this._requestQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultHeaders()},n))},this._destructureFromUserIDQuerier=function(e){var t,r;return"string"==typeof e[0]&&"string"==typeof e[1]?(t=e[1],r=e[2]):(t=e[0],r=e[1]),{userID:t,options:r}};var w=this;this.getUserProfile=u(function(){var e,t,r,n,s,o,a=arguments;return c(this,function(i){switch(i.label){case 0:for(t=Array(e=a.length),r=0;r<e;r++)t[r]=a[r];return s=(n=w._destructureFromUserIDQuerier(t)).userID,o=n.options,w.verbose&&console.debug("[fbLSDToken] USING",w.fbLSDToken),[4,w._requestQuery("https://www.threads.net/api/graphql",{lsd:w.fbLSDToken,variables:JSON.stringify({userID:s}),doc_id:"23996318473300828"},o)];case 1:return[2,i.sent().data.data.userData.user]}})});var A=this;this.getUserProfileThreads=u(function(){var e,t,r,n,s,o,a,i,u=arguments;return c(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return a=(o=A._destructureFromUserIDQuerier(t)).userID,i=o.options,A.verbose&&console.debug("[fbLSDToken] USING",A.fbLSDToken),[4,A._requestQuery("https://www.threads.net/api/graphql",{lsd:A.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6232751443445612"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var E=this;this.getUserProfileThreadsLoggedIn=u(function(t,r,n){var o,a,i,u;return c(this,function(c){switch(c.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),E.token)return[3,2];return[4,E.getToken()];case 1:c.sent(),c.label=2;case 2:if(!E.token)throw Error("Token not found");a=void 0,c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get(s.BASE_API_URL+"/api/v1/text_feed/"+t+"/profile/"+(r&&"?max_id="+r),l({},n,{headers:l({},E._getInstaHeaders(),null==(i=n)?void 0:i.headers)}))];case 4:return a=c.sent().data,[3,6];case 5:return a=null==(u=c.sent().response)?void 0:u.data,[3,6];case 6:if((null==(o=a)?void 0:o.status)!=="ok")throw E.verbose&&console.log("[USER FEED] Failed to fetch",a),Error("Failed to fetch user feed: "+JSON.stringify(a));return[2,a]}})});var k=this;this.getUserProfileReplies=u(function(){var e,t,r,n,s,o,a,i,u=arguments;return c(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return a=(o=k._destructureFromUserIDQuerier(t)).userID,i=o.options,k.verbose&&console.debug("[fbLSDToken] USING",k.fbLSDToken),[4,k._requestQuery("https://www.threads.net/api/graphql",{lsd:k.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6684830921547925"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var L=this;this.getUserProfileRepliesLoggedIn=u(function(t,r,n){var s,o,a,i;return c(this,function(u){switch(u.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),L.token)return[3,2];return[4,L.getToken()];case 1:u.sent(),u.label=2;case 2:if(!L.token)throw Error("Token not found");o=void 0,u.label=3;case 3:return u.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/text_feed/"+t+"/profile/replies/"+(r&&"?max_id="+r),l({},n,{headers:l({},L._getInstaHeaders(),null==(a=n)?void 0:a.headers)}))];case 4:return o=u.sent().data,[3,6];case 5:return o=null==(i=u.sent().response)?void 0:i.data,[3,6];case 6:if((null==(s=o)?void 0:s.status)!=="ok")throw L.verbose&&console.log("[USER FEED] Failed to fetch",o),Error("Failed to fetch user feed: "+JSON.stringify(o));return[2,o]}})});var T=this;this.getUserFollowers=u(function(t,r,n){var o,a,i,u,d,h,p,f;return c(this,function(c){switch(c.label){case 0:if(a=(o=void 0===r?{}:r).maxID,i=o.query,T.token)return[3,2];return[4,T.getToken()];case 1:c.sent(),c.label=2;case 2:if(!T.token)throw Error("Token not found");d=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),a&&h.append("max_id",a),i&&h.append("query",i),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/followers/?"+h.toString(),l({},n,{headers:l({},T._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return d=c.sent().data,[3,6];case 5:return d=null==(f=c.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=d)?void 0:u.status)!=="ok")throw T.verbose&&console.log("[USER FOLLOWERS] Failed to fetch",d),Error("Failed to fetch user followers: "+JSON.stringify(d));return[2,d]}})});var U=this;this.getUserFollowing=u(function(t,r,n){var o,a,i,u,d,h,p,f;return c(this,function(c){switch(c.label){case 0:if(a=(o=void 0===r?{}:r).maxID,i=o.query,U.token)return[3,2];return[4,U.getToken()];case 1:c.sent(),c.label=2;case 2:if(!U.token)throw Error("Token not found");d=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),a&&h.append("max_id",a),i&&h.append("query",i),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/following/?"+h.toString(),l({},n,{headers:l({},U._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return d=c.sent().data,[3,6];case 5:return d=null==(f=c.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=d)?void 0:u.status)!=="ok")throw U.verbose&&console.log("[USER FOLLOWING] Failed to fetch",d),Error("Failed to fetch user following: "+JSON.stringify(d));return[2,d]}})}),this.getPostIDfromThreadID=function(e){e=(e=(e=e.split("?")[0]).replace(/\s/g,"")).replace(/\//g,"");for(var t,r=0n,n=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return a(e,t)}}(e))){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(t=n()).done;){var s=t.value;r=64n*r+BigInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(s))}return r.toString()},this.getPostIDfromURL=function(e){var t,r,n=null==e?void 0:e.split("?")[0];return(null==(t=n)?void 0:t.endsWith("/"))&&(n=n.slice(0,-1)),n=(null==(r=n)?void 0:r.split("/").pop())||"",v.getPostIDfromThreadID(n||"")};var P=this;this.getThreads=u(function(e,t){return c(this,function(r){switch(r.label){case 0:return P.verbose&&console.debug("[fbLSDToken] USING",P.fbLSDToken),[4,P._requestQuery("https://www.threads.net/api/graphql",{lsd:P.fbLSDToken,variables:JSON.stringify({postID:e}),doc_id:"5587632691339264"},t)];case 1:return[2,r.sent().data.data.data]}})});var O=this;this.getThreadLikers=u(function(e,t){return c(this,function(r){switch(r.label){case 0:return O.verbose&&console.debug("[fbLSDToken] USING",O.fbLSDToken),[4,O._requestQuery("https://www.threads.net/api/graphql",{lsd:O.fbLSDToken,variables:JSON.stringify({mediaID:e}),doc_id:"9360915773983802"},t)];case 1:return[2,r.sent().data.data.likers]}})});var R=this;this.getTimeline=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:if(void 0===e&&(e=""),!R.token&&(!R.username||!R.password))throw Error("Username or password not set");return[4,R.getToken()];case 1:if(!n.sent())throw Error("Token not found");n.label=2;case 2:return n.trys.push([2,4,,5]),[4,R._requestQuery(""+s.BASE_API_URL+"/api/v1/feed/text_post_app_timeline/",{pagination_source:"text_post_feed_threads",max_id:e||void 0},l({},t,{headers:R._getAppHeaders()}))];case 3:return[2,n.sent().data];case 4:throw r=n.sent(),R.verbose&&console.log("[TIMELINE FETCH FAILED]",r.response.data),Error("Failed to fetch timeline");case 5:return[2]}})});var N=this;this._toggleAuthPostRequest=u(function(t,r,n){return c(this,function(s){switch(s.label){case 0:return[4,N.getToken()];case 1:if(!s.sent())throw Error("Token not found");return[4,e.default.post(t,r?new URLSearchParams(r):void 0,l({},n,{httpAgent:N.httpAgent,httpsAgent:N.httpsAgent,headers:N._getDefaultHeaders()}))];case 2:return[2,s.sent()]}})});var x=this;this.like=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,x.getCurrentUserID()];case 1:return r=n.sent(),[4,x._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/like/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var q=this;this.unlike=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,q.getCurrentUserID()];case 1:return r=n.sent(),[4,q._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/unlike/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var F=this;this.follow=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,F._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/create/"+e+"/",void 0,t)];case 1:return r=n.sent(),F.verbose&&console.debug("[FOLLOW]",r.data),[2,r.data]}})});var B=this;this.unfollow=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,B._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/destroy/"+e+"/",void 0,t)];case 1:return r=n.sent(),B.verbose&&console.debug("[UNFOLLOW]",r.data),[2,r.data]}})});var G=this;this.repost=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,G._toggleAuthPostRequest(""+s.BASE_API_URL+"api/v1/repost/create_repost/",{media_id:e},t)];case 1:return r=n.sent(),G.verbose&&console.debug("[REPOST]",r.data),[2,r.data]}})});var H=this;this.unrepost=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,H._toggleAuthPostRequest(""+s.BASE_API_URL+"/api/v1/repost/delete_text_app_repost/",{original_media_id:e},t)];case 1:return r=n.sent(),H.verbose&&console.debug("[UNREPOST]",r.data),[2,r.data]}})});var C=this;this.getToken=u(function(){return c(this,function(e){switch(e.label){case 0:if(C.token)return C.verbose&&console.debug("[token] USING",C.token),[2,C.token];if(!C.username||!C.password)throw Error("Username and password are required");return[4,C.login()];case 1:return e.sent(),[2,C.token]}})});var J=this;this.publish=u(function(t){var r,n,o,a,i,u,l;return c(this,function(c){switch(c.label){case 0:if(r="string"==typeof t?{text:t}:t,!J.token&&(!J.username||!J.password))throw Error("Username or password not set");return[4,J.getCurrentUserID()];case 1:if(!(n=c.sent()))throw Error("User ID not found");return[4,J.getToken()];case 2:if(!c.sent())throw Error("Token not found");if(a={text_post_app_info:{reply_control:0},timezone_offset:(-(60*(o=new Date).getTimezoneOffset())).toString(),source_type:"4",_uid:n,device_id:J.deviceID,caption:r.text||"",upload_id:o.getTime(),device:J.device},i=s.POST_URL,!("image"in r&&r.image))return[3,4];return i=s.POST_WITH_IMAGE_URL,[4,J.uploadImage(r.image)];case 3:return a.upload_id=c.sent().upload_id,a.scene_capture_type="",[3,5];case 4:"url"in r&&r.url&&(a.text_post_app_info.link_attachment_url=r.url),c.label=5;case 5:return r.parentPostID&&(a.text_post_app_info.reply_id=r.parentPostID),r.quotedPostID&&(a.text_post_app_info.quoted_post_id=r.quotedPostID),r.image||(a.publish_mode="text_post"),u="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify(a)),[4,e.default.post(i,u,{httpAgent:J.httpAgent,httpsAgent:J.httpsAgent,headers:J._getAppHeaders(),timeout:6e4})];case 6:if(l=c.sent(),J.verbose&&console.debug("[PUBLISH]",l.data),"ok"===l.data.status)return[2,l.data.media.id];return[2,void 0]}})});var M=this;this.delete=u(function(t,r){var n,o;return c(this,function(a){switch(a.label){case 0:return n=s.BASE_API_URL+"/api/v1/media/"+t+"/delete/",o="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify({media_id:t,_uid:M.userID,_uuid:M.deviceID})),[4,e.default.post(n,o,l({httpAgent:M.httpAgent,httpsAgent:M.httpsAgent,headers:M._getAppHeaders(),timeout:6e4},r))];case 1:if("ok"===a.sent().data.status)return[2,!0];return[2,!1]}})});var X=this;this.publishWithImage=u(function(e,t){return c(this,function(r){return[2,X.publish({text:e,image:t})]})});var W=this;if(this.uploadImage=u(function(t){var s,o,a,i,u,d,h,p,f,g,v,_;return c(this,function(c){switch(c.label){case 0:if(a="https://www.instagram.com/rupload_igphoto/"+(o=(s=Date.now().toString())+"_0_"+Math.floor(9e9*Math.random()+1e9)),!("string"==typeof t||"path"in t))return[3,6];if((d="string"==typeof t?t:t.path).startsWith("http"))return[3,3];return[4,Promise.resolve().then(function(){return require("fs")})];case 1:return[4,c.sent().promises.readFile(d)];case 2:return i=c.sent(),u=r.default.lookup(d)||"application/octet-stream",[3,5];case 3:return[4,e.default.get(d,{responseType:"arraybuffer"})];case 4:h=c.sent(),i=Buffer.from(h.data,"binary"),u=h.headers["content-type"],c.label=5;case 5:return[3,7];case 6:i=t.data,u=(t.type.includes("/")?t.type:r.default.lookup(t.type))||"application/octet-stream",c.label=7;case 7:p={upload_id:s,media_type:"1",sticker_burnin_params:JSON.stringify([]),image_compression:JSON.stringify({lib_name:"moz",lib_version:"3.1.m",quality:"80"}),xsharing_user_ids:JSON.stringify([]),retry_context:JSON.stringify({num_step_auto_retry:"0",num_reupload:"0",num_step_manual_retry:"0"}),"IG-FB-Xpost-entry-point-v2":"feed"},f=i.length,g=l({},W._getDefaultHeaders(),{"Content-Type":"application/octet-stream",X_FB_PHOTO_WATERFALL_ID:(0,n.v4)(),"X-Entity-Type":void 0!==u?"image/"+u:"image/jpeg",Offset:"0","X-Instagram-Rupload-Params":JSON.stringify(p),"X-Entity-Name":o,"X-Entity-Length":f.toString(),"Content-Length":f.toString(),"Accept-Encoding":"gzip"}),W.verbose&&console.log("[UPLOAD_IMAGE] Uploading "+f.toLocaleString()+"b as "+s+"..."),c.label=8;case 8:return c.trys.push([8,10,,11]),[4,e.default.post(a,i,{httpAgent:W.httpAgent,headers:g,timeout:6e4})];case 9:return v=c.sent().data,W.verbose&&console.log("[UPLOAD_IMAGE] SUCCESS",v),[2,v];case 10:throw _=c.sent(),W.verbose&&console.log("[UPLOAD_IMAGE] FAILED",_.response.data),Error("Upload image failed");case 11:return[2]}})}),(null==i?void 0:i.token)&&(this.token=i.token),(null==i?void 0:i.fbLSDToken)&&(this.fbLSDToken=i.fbLSDToken),this.noUpdateToken=!!(null==i?void 0:i.noUpdateToken),this.noUpdateLSD=!!(null==i?void 0:i.noUpdateLSD),this.verbose=(null==i?void 0:i.verbose)||!1,this.httpAgent=null==i?void 0:i.httpAgent,this.httpsAgent=null==i?void 0:i.httpsAgent,this.username=null!=(h=null==i?void 0:i.username)?h:process.env.THREADS_USERNAME,this.password=null!=(p=null==i?void 0:i.password)?p:process.env.THREADS_PASSWORD,this.deviceID=null!=(g=null!=(f=null==i?void 0:i.deviceID)?f:process.env.THREADS_DEVICE_ID)?g:"",this.deviceID||(this.deviceID="android-"+(1e24*Math.random()).toString(36),console.warn("โš ๏ธ WARNING: deviceID not provided, automatically generating device id '"+this.deviceID+"'","Please save this device id and use it for future uses to prevent login issues.","You can provide this device id by passing it to the constructor or setting the THREADS_DEVICE_ID environment variable (.env file)")),this.device=null==i?void 0:i.device,this.userID=null==i?void 0:i.userID,null==i?void 0:i.locale)this.locale=i.locale;else{var j=Intl.DateTimeFormat().resolvedOptions().locale;this.locale=j}this.maxRetries=(null==i?void 0:i.maxRetries)||this.maxRetries}return i.prototype.sign=function(e){var r="object"==typeof e?JSON.stringify(e):e;return{ig_sig_key_version:4,signed_body:t.createHmac("sha256",s.SIGNATURE_KEY).update(r).digest("hex")+"."+r}},i}();
"use strict";!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{DEFAULT_DEVICE:function(){return d},ThreadsAPI:function(){return h}});var e=require("axios"),t=require("crypto");require("dotenv/config");var r=require("mrmime"),n=require("uuid"),s=require("./constants"),o=require("./dynamic-data");function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function u(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function a(e){i(o,n,s,a,u,"next",e)}function u(e){i(o,n,s,a,u,"throw",e)}a(void 0)})}}function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function c(e,t){var r,n,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(o){return function(i){return function(o){if(r)throw TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&o[0]?n.return:o[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,o[1])).done)return s;switch(n=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(s=(s=a.trys).length>0&&s[s.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{r=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,i])}}}var d={manufacturer:"OnePlus",model:"ONEPLUS+A3010",os_version:25,os_release:"7.1.1"},h=function(){"use strict";function i(i){var h,p,f,g,v=this;this.verbose=!1,this.token=void 0,this.fbLSDToken=s.DEFAULT_LSD_TOKEN,this.noUpdateToken=!1,this.noUpdateLSD=!1,this.device=d,this.userID=void 0,this.locale=void 0,this.maxRetries=1;var _=this;this.syncLoginExperiments=u(function(){var t,r,o;return c(this,function(a){switch(a.label){case 0:r={id:t=(0,n.v4)(),experiments:s.LOGIN_EXPERIMENTS},a.label=1;case 1:return a.trys.push([1,3,,4]),[4,e.default.post(""+s.BASE_API_URL+"/api/v1/qe/sync/",_.sign(r),{headers:l({},_._getAppHeaders(),{Authorization:void 0,"Sec-Fetch-Site":"same-origin","X-DEVICE-ID":t})})];case 2:return[2,a.sent()];case 3:throw o=a.sent(),_.verbose&&console.log("[SYNC LOGIN EXPERIMENT FAILED]",o.response.data),Error("Sync login experiment failed");case 4:return[2]}})});var b=this;this.encryptPassword=u(function(e){var r,n,s,o,a,i,u,l,d,h,p;return c(this,function(c){switch(c.label){case 0:return r=t.randomBytes(32),n=t.randomBytes(12),[4,b.syncLoginExperiments()];case 1:return s=c.sent().headers,b.verbose&&console.log("[SYNC LOGIN EXPERIMENT HEADERS]",JSON.stringify(s)),o=s["ig-set-password-encryption-key-id"],a=s["ig-set-password-encryption-pub-key"],i=t.publicEncrypt({key:Buffer.from(a||"","base64").toString(),padding:t.constants.RSA_PKCS1_PADDING},r),u=t.createCipheriv("aes-256-gcm",r,n),l=Math.floor(Date.now()/1e3).toString(),u.setAAD(Buffer.from(l)),d=Buffer.concat([u.update(e,"utf8"),u.final()]),(h=Buffer.alloc(2,0)).writeInt16LE(i.byteLength,0),p=u.getAuthTag(),[2,{time:l,password:Buffer.concat([Buffer.from([1,o||0]),n,h,i,p,d]).toString("base64")}]}})});var m=this;this.login=u(function(){var t,r,n,o;return c(this,function(a){switch(a.label){case 0:t=function(){var e;return c(this,function(t){switch(t.label){case 0:return t.trys.push([0,1,,3]),[2,{v:n()}];case 1:return t.sent(),m.verbose&&console.error("[LOGIN] Failed to login, retrying... ("+(r+1)+"/"+m.maxRetries+")"),e=1e3*Math.pow(2,r),[4,new Promise(function(t){return setTimeout(t,e)})];case 2:return t.sent(),r++,[3,3];case 3:return[2]}})},r=0,n=u(function(){var t,r,n,o,a,i,u,l;return c(this,function(c){switch(c.label){case 0:return m.verbose&&console.log("[LOGIN] Logging in..."),[4,m.encryptPassword(m.password)];case 1:return r=encodeURIComponent(JSON.stringify({client_input_params:{password:"#PWD_INSTAGRAM:4:"+(t=c.sent()).time+":"+t.password,contact_point:m.username,device_id:m.deviceID},server_params:{credential_type:"password",device_id:m.deviceID}})),n=encodeURIComponent(JSON.stringify({bloks_version:s.BLOKS_VERSION,styles_id:"instagram"})),o={method:"POST",headers:m._getAppHeaders(),responseType:"text",data:"params="+r+"&bk_client_context="+n+"&bloks_versioning_id="+s.BLOKS_VERSION},[4,(0,e.default)(""+s.BASE_API_URL+"/api/v1/bloks/apps/com.bloks.www.bloks.caa.login.async.send_login_request/",o)];case 2:a=JSON.stringify((a=c.sent().data).replaceAll("\\","")),m.verbose&&console.log("[LOGIN] Cleaned output",a);try{return u=a.split("Bearer IGT:2:")[1].split('"')[0].replaceAll("\\",""),l=null==(i=a.match(/pk_id":"(\d+)/))?void 0:i[1],m.noUpdateToken||(m.verbose&&console.debug("[token] UPDATED",u),m.token=u),m.userID=l,m.verbose&&console.debug("[userID] UPDATED",m.userID),[2,{token:u,userID:l}]}catch(e){throw m.verbose&&console.error("[LOGIN] Failed to login",e),Error("Login Failed")}return[2]}})}),a.label=1;case 1:if(!(r<m.maxRetries))return[3,3];return[5,function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t())];case 2:var i;if("object"==((i=o=a.sent())&&"undefined"!=typeof Symbol&&i.constructor===Symbol?"symbol":typeof i))return[2,o.v];return[3,1];case 3:throw Error("[LOGIN] Failed to login after "+m.maxRetries+" retries")}})}),this._getAppHeaders=function(){return l({"User-Agent":"Barcelona "+o.LATEST_ANDROID_APP_VERSION+" Android","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},v.token&&{Authorization:"Bearer IGT:2:"+v.token})},this._getInstaHeaders=function(){return l({},v._getAppHeaders(),{"X-Bloks-Is-Layout-Rtl":"false","X-Bloks-Version-Id":s.BLOKS_VERSION,"X-Ig-Android-Id":v.deviceID,"X-Ig-App-Id":s.IG_APP_ID,"Accept-Language":v.locale||"en-US"},v.userID&&{"Ig-U-Ds-User-Id":v.userID,"Ig-Intended-User-Id":v.userID},v.locale&&{"X-Ig-App-Locale":v.locale.replace("-","_"),"X-Ig-Device-Locale":v.locale.replace("-","_"),"X-Ig-Mapped-Locale":v.locale.replace("-","_")})},this._getDefaultHeaders=function(e){return l({},v._getAppHeaders(),{authority:"www.threads.net",accept:"*/*","accept-language":v.locale,"cache-control":"no-cache",origin:"https://www.threads.net",pragma:"no-cache","Sec-Fetch-Site":"same-origin","x-asbd-id":"129477","x-fb-lsd":v.fbLSDToken,"x-ig-app-id":"238260118697367"},e?{referer:"https://www.threads.net/@"+e}:void 0)};var I=this;this.getProfilePage=u(function(t,r,n){return c(this,function(s){switch(s.label){case 0:return[4,e.default.get(""+t+r,l({},n,{httpAgent:I.httpAgent,httpsAgent:I.httpsAgent,headers:l({},I._getDefaultHeaders(r),{accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","accept-language":"ko,en;q=0.9,ko-KR;q=0.8,ja;q=0.7",Authorization:void 0,referer:"https://www.instagram.com/","sec-fetch-dest":"document","sec-fetch-mode":"navigate","sec-fetch-site":"cross-site","sec-fetch-user":"?1","upgrade-insecure-requests":"1","x-asbd-id":void 0,"x-fb-lsd":void 0,"x-ig-app-id":void 0})}))];case 1:return[2,(0,s.sent().data).replace(/\s/g,"").replace(/\n/g,"")]}})});var D=this;this.getUserIDfromUsernameWithInstagram=u(function(e,t){var r,n,s,o,a;return c(this,function(i){switch(i.label){case 0:return[4,D.getProfilePage("https://www.instagram.com/",e,t)];case 1:return o=null==(r=(s=i.sent()).match(/"user_id":"(\d+)",/))?void 0:r[1],a=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!D.noUpdateLSD&&a&&(D.fbLSDToken=a,D.verbose&&console.debug("[fbLSDToken] UPDATED",D.fbLSDToken)),[2,o]}})});var S=this;this.getUserIDfromUsername=u(function(e,t){var r,n,s,o,a;return c(this,function(i){switch(i.label){case 0:return[4,S.getProfilePage("https://www.threads.net/@",e,t)];case 1:if(o=null==(r=(s=i.sent()).match(/"user_id":"(\d+)"/))?void 0:r[1],a=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!o)return[2,S.getUserIDfromUsernameWithInstagram(e,t)];return!S.noUpdateLSD&&a&&(S.fbLSDToken=a,S.verbose&&console.debug("[fbLSDToken] UPDATED",S.fbLSDToken)),[2,o]}})});var y=this;this.getCurrentUserID=u(function(e){var t;return c(this,function(r){switch(r.label){case 0:if(y.userID)return y.verbose&&console.debug("[userID] USING",y.userID),[2,y.userID];if(!y.username)throw Error("username is not defined");r.label=1;case 1:return r.trys.push([1,3,,5]),[4,y.getUserIDfromUsername(y.username,e)];case 2:return y.userID=r.sent(),y.verbose&&console.debug("[userID] UPDATED",y.userID),[2,y.userID];case 3:return t=r.sent(),y.verbose&&console.error("[userID] Failed to fetch userID, Fallbacking to login",t),[4,y.login()];case 4:return[2,r.sent().userID];case 5:return[2]}})}),this._requestQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultHeaders()},n))},this._destructureFromUserIDQuerier=function(e){var t,r;return"string"==typeof e[0]&&"string"==typeof e[1]?(t=e[1],r=e[2]):(t=e[0],r=e[1]),{userID:t,options:r}};var w=this;this.getUserProfile=u(function(){var e,t,r,n,s,o,a=arguments;return c(this,function(i){switch(i.label){case 0:for(t=Array(e=a.length),r=0;r<e;r++)t[r]=a[r];return s=(n=w._destructureFromUserIDQuerier(t)).userID,o=n.options,w.verbose&&console.debug("[fbLSDToken] USING",w.fbLSDToken),[4,w._requestQuery("https://www.threads.net/api/graphql",{lsd:w.fbLSDToken,variables:JSON.stringify({userID:s}),doc_id:"23996318473300828"},o)];case 1:return[2,i.sent().data.data.userData.user]}})});var A=this;this.getUserProfileThreads=u(function(){var e,t,r,n,s,o,a,i,u=arguments;return c(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return a=(o=A._destructureFromUserIDQuerier(t)).userID,i=o.options,A.verbose&&console.debug("[fbLSDToken] USING",A.fbLSDToken),[4,A._requestQuery("https://www.threads.net/api/graphql",{lsd:A.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6232751443445612"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var E=this;this.getUserProfileThreadsLoggedIn=u(function(t,r,n){var o,a,i,u;return c(this,function(c){switch(c.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),E.token)return[3,2];return[4,E.getToken()];case 1:c.sent(),c.label=2;case 2:if(!E.token)throw Error("Token not found");a=void 0,c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get(s.BASE_API_URL+"/api/v1/text_feed/"+t+"/profile/"+(r&&"?max_id="+r),l({},n,{headers:l({},E._getInstaHeaders(),null==(i=n)?void 0:i.headers)}))];case 4:return a=c.sent().data,[3,6];case 5:return a=null==(u=c.sent().response)?void 0:u.data,[3,6];case 6:if((null==(o=a)?void 0:o.status)!=="ok")throw E.verbose&&console.log("[USER FEED] Failed to fetch",a),Error("Failed to fetch user feed: "+JSON.stringify(a));return[2,a]}})});var k=this;this.getUserProfileReplies=u(function(){var e,t,r,n,s,o,a,i,u=arguments;return c(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return a=(o=k._destructureFromUserIDQuerier(t)).userID,i=o.options,k.verbose&&console.debug("[fbLSDToken] USING",k.fbLSDToken),[4,k._requestQuery("https://www.threads.net/api/graphql",{lsd:k.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6684830921547925"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var L=this;this.getUserProfileRepliesLoggedIn=u(function(t,r,n){var s,o,a,i;return c(this,function(u){switch(u.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),L.token)return[3,2];return[4,L.getToken()];case 1:u.sent(),u.label=2;case 2:if(!L.token)throw Error("Token not found");o=void 0,u.label=3;case 3:return u.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/text_feed/"+t+"/profile/replies/"+(r&&"?max_id="+r),l({},n,{headers:l({},L._getInstaHeaders(),null==(a=n)?void 0:a.headers)}))];case 4:return o=u.sent().data,[3,6];case 5:return o=null==(i=u.sent().response)?void 0:i.data,[3,6];case 6:if((null==(s=o)?void 0:s.status)!=="ok")throw L.verbose&&console.log("[USER FEED] Failed to fetch",o),Error("Failed to fetch user feed: "+JSON.stringify(o));return[2,o]}})});var T=this;this.getUserFollowers=u(function(t,r,n){var o,a,i,u,d,h,p,f;return c(this,function(c){switch(c.label){case 0:if(a=(o=void 0===r?{}:r).maxID,i=o.query,T.token)return[3,2];return[4,T.getToken()];case 1:c.sent(),c.label=2;case 2:if(!T.token)throw Error("Token not found");d=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),a&&h.append("max_id",a),i&&h.append("query",i),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/followers/?"+h.toString(),l({},n,{headers:l({},T._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return d=c.sent().data,[3,6];case 5:return d=null==(f=c.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=d)?void 0:u.status)!=="ok")throw T.verbose&&console.log("[USER FOLLOWERS] Failed to fetch",d),Error("Failed to fetch user followers: "+JSON.stringify(d));return[2,d]}})});var U=this;this.getUserFollowings=u(function(t,r,n){var o,a,i,u,d,h,p,f;return c(this,function(c){switch(c.label){case 0:if(a=(o=void 0===r?{}:r).maxID,i=o.query,U.token)return[3,2];return[4,U.getToken()];case 1:c.sent(),c.label=2;case 2:if(!U.token)throw Error("Token not found");d=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),a&&h.append("max_id",a),i&&h.append("query",i),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/following/?"+h.toString(),l({},n,{headers:l({},U._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return d=c.sent().data,[3,6];case 5:return d=null==(f=c.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=d)?void 0:u.status)!=="ok")throw U.verbose&&console.log("[USER FOLLOWING] Failed to fetch",d),Error("Failed to fetch user following: "+JSON.stringify(d));return[2,d]}})}),this.getPostIDfromThreadID=function(e){e=(e=(e=e.split("?")[0]).replace(/\s/g,"")).replace(/\//g,"");for(var t,r=0n,n=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return a(e,t)}}(e))){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(t=n()).done;){var s=t.value;r=64n*r+BigInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(s))}return r.toString()},this.getPostIDfromURL=function(e){var t,r,n=null==e?void 0:e.split("?")[0];return(null==(t=n)?void 0:t.endsWith("/"))&&(n=n.slice(0,-1)),n=(null==(r=n)?void 0:r.split("/").pop())||"",v.getPostIDfromThreadID(n||"")};var P=this;this.getThreads=u(function(e,t){return c(this,function(r){switch(r.label){case 0:return P.verbose&&console.debug("[fbLSDToken] USING",P.fbLSDToken),[4,P._requestQuery("https://www.threads.net/api/graphql",{lsd:P.fbLSDToken,variables:JSON.stringify({postID:e}),doc_id:"5587632691339264"},t)];case 1:return[2,r.sent().data.data.data]}})});var O=this;this.getThreadLikers=u(function(e,t){return c(this,function(r){switch(r.label){case 0:return O.verbose&&console.debug("[fbLSDToken] USING",O.fbLSDToken),[4,O._requestQuery("https://www.threads.net/api/graphql",{lsd:O.fbLSDToken,variables:JSON.stringify({mediaID:e}),doc_id:"9360915773983802"},t)];case 1:return[2,r.sent().data.data.likers]}})});var R=this;this.getTimeline=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:if(void 0===e&&(e=""),!R.token&&(!R.username||!R.password))throw Error("Username or password not set");return[4,R.getToken()];case 1:if(!n.sent())throw Error("Token not found");n.label=2;case 2:return n.trys.push([2,4,,5]),[4,R._requestQuery(""+s.BASE_API_URL+"/api/v1/feed/text_post_app_timeline/",{pagination_source:"text_post_feed_threads",max_id:e||void 0},l({},t,{headers:R._getAppHeaders()}))];case 3:return[2,n.sent().data];case 4:throw r=n.sent(),R.verbose&&console.log("[TIMELINE FETCH FAILED]",r.response.data),Error("Failed to fetch timeline");case 5:return[2]}})});var N=this;this._toggleAuthPostRequest=u(function(t,r,n){return c(this,function(s){switch(s.label){case 0:return[4,N.getToken()];case 1:if(!s.sent())throw Error("Token not found");return[4,e.default.post(t,r?new URLSearchParams(r):void 0,l({},n,{httpAgent:N.httpAgent,httpsAgent:N.httpsAgent,headers:N._getDefaultHeaders()}))];case 2:return[2,s.sent()]}})});var x=this;this.like=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,x.getCurrentUserID()];case 1:return r=n.sent(),[4,x._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/like/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var q=this;this.unlike=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,q.getCurrentUserID()];case 1:return r=n.sent(),[4,q._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/unlike/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var F=this;this.follow=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,F._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/create/"+e+"/",void 0,t)];case 1:return r=n.sent(),F.verbose&&console.debug("[FOLLOW]",r.data),[2,r.data]}})});var B=this;this.unfollow=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,B._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/destroy/"+e+"/",void 0,t)];case 1:return r=n.sent(),B.verbose&&console.debug("[UNFOLLOW]",r.data),[2,r.data]}})});var G=this;this.repost=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,G._toggleAuthPostRequest(""+s.BASE_API_URL+"api/v1/repost/create_repost/",{media_id:e},t)];case 1:return r=n.sent(),G.verbose&&console.debug("[REPOST]",r.data),[2,r.data]}})});var H=this;this.unrepost=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,H._toggleAuthPostRequest(""+s.BASE_API_URL+"/api/v1/repost/delete_text_app_repost/",{original_media_id:e},t)];case 1:return r=n.sent(),H.verbose&&console.debug("[UNREPOST]",r.data),[2,r.data]}})});var C=this;this.getToken=u(function(){return c(this,function(e){switch(e.label){case 0:if(C.token)return C.verbose&&console.debug("[token] USING",C.token),[2,C.token];if(!C.username||!C.password)throw Error("Username and password are required");return[4,C.login()];case 1:return e.sent(),[2,C.token]}})});var J=this;this.publish=u(function(t){var r,n,o,a,i,u,l;return c(this,function(c){switch(c.label){case 0:if(r="string"==typeof t?{text:t}:t,!J.token&&(!J.username||!J.password))throw Error("Username or password not set");return[4,J.getCurrentUserID()];case 1:if(!(n=c.sent()))throw Error("User ID not found");return[4,J.getToken()];case 2:if(!c.sent())throw Error("Token not found");if(a={text_post_app_info:{reply_control:0},timezone_offset:(-(60*(o=new Date).getTimezoneOffset())).toString(),source_type:"4",_uid:n,device_id:J.deviceID,caption:r.text||"",upload_id:o.getTime(),device:J.device},i=s.POST_URL,!("image"in r&&r.image))return[3,4];return i=s.POST_WITH_IMAGE_URL,[4,J.uploadImage(r.image)];case 3:return a.upload_id=c.sent().upload_id,a.scene_capture_type="",[3,5];case 4:"url"in r&&r.url&&(a.text_post_app_info.link_attachment_url=r.url),c.label=5;case 5:return r.parentPostID&&(a.text_post_app_info.reply_id=r.parentPostID),r.quotedPostID&&(a.text_post_app_info.quoted_post_id=r.quotedPostID),r.image||(a.publish_mode="text_post"),u="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify(a)),[4,e.default.post(i,u,{httpAgent:J.httpAgent,httpsAgent:J.httpsAgent,headers:J._getAppHeaders(),timeout:6e4})];case 6:if(l=c.sent(),J.verbose&&console.debug("[PUBLISH]",l.data),"ok"===l.data.status)return[2,l.data.media.id];return[2,void 0]}})});var M=this;this.delete=u(function(t,r){var n,o;return c(this,function(a){switch(a.label){case 0:return n=s.BASE_API_URL+"/api/v1/media/"+t+"/delete/",o="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify({media_id:t,_uid:M.userID,_uuid:M.deviceID})),[4,e.default.post(n,o,l({httpAgent:M.httpAgent,httpsAgent:M.httpsAgent,headers:M._getAppHeaders(),timeout:6e4},r))];case 1:if("ok"===a.sent().data.status)return[2,!0];return[2,!1]}})});var X=this;this.publishWithImage=u(function(e,t){return c(this,function(r){return[2,X.publish({text:e,image:t})]})});var W=this;if(this.uploadImage=u(function(t){var s,o,a,i,u,d,h,p,f,g,v,_;return c(this,function(c){switch(c.label){case 0:if(a="https://www.instagram.com/rupload_igphoto/"+(o=(s=Date.now().toString())+"_0_"+Math.floor(9e9*Math.random()+1e9)),!("string"==typeof t||"path"in t))return[3,6];if((d="string"==typeof t?t:t.path).startsWith("http"))return[3,3];return[4,Promise.resolve().then(function(){return require("fs")})];case 1:return[4,c.sent().promises.readFile(d)];case 2:return i=c.sent(),u=r.default.lookup(d)||"application/octet-stream",[3,5];case 3:return[4,e.default.get(d,{responseType:"arraybuffer"})];case 4:h=c.sent(),i=Buffer.from(h.data,"binary"),u=h.headers["content-type"],c.label=5;case 5:return[3,7];case 6:i=t.data,u=(t.type.includes("/")?t.type:r.default.lookup(t.type))||"application/octet-stream",c.label=7;case 7:p={upload_id:s,media_type:"1",sticker_burnin_params:JSON.stringify([]),image_compression:JSON.stringify({lib_name:"moz",lib_version:"3.1.m",quality:"80"}),xsharing_user_ids:JSON.stringify([]),retry_context:JSON.stringify({num_step_auto_retry:"0",num_reupload:"0",num_step_manual_retry:"0"}),"IG-FB-Xpost-entry-point-v2":"feed"},f=i.length,g=l({},W._getDefaultHeaders(),{"Content-Type":"application/octet-stream",X_FB_PHOTO_WATERFALL_ID:(0,n.v4)(),"X-Entity-Type":void 0!==u?"image/"+u:"image/jpeg",Offset:"0","X-Instagram-Rupload-Params":JSON.stringify(p),"X-Entity-Name":o,"X-Entity-Length":f.toString(),"Content-Length":f.toString(),"Accept-Encoding":"gzip"}),W.verbose&&console.log("[UPLOAD_IMAGE] Uploading "+f.toLocaleString()+"b as "+s+"..."),c.label=8;case 8:return c.trys.push([8,10,,11]),[4,e.default.post(a,i,{httpAgent:W.httpAgent,headers:g,timeout:6e4})];case 9:return v=c.sent().data,W.verbose&&console.log("[UPLOAD_IMAGE] SUCCESS",v),[2,v];case 10:throw _=c.sent(),W.verbose&&console.log("[UPLOAD_IMAGE] FAILED",_.response.data),Error("Upload image failed");case 11:return[2]}})}),(null==i?void 0:i.token)&&(this.token=i.token),(null==i?void 0:i.fbLSDToken)&&(this.fbLSDToken=i.fbLSDToken),this.noUpdateToken=!!(null==i?void 0:i.noUpdateToken),this.noUpdateLSD=!!(null==i?void 0:i.noUpdateLSD),this.verbose=(null==i?void 0:i.verbose)||!1,this.httpAgent=null==i?void 0:i.httpAgent,this.httpsAgent=null==i?void 0:i.httpsAgent,this.username=null!=(h=null==i?void 0:i.username)?h:process.env.THREADS_USERNAME,this.password=null!=(p=null==i?void 0:i.password)?p:process.env.THREADS_PASSWORD,this.deviceID=null!=(g=null!=(f=null==i?void 0:i.deviceID)?f:process.env.THREADS_DEVICE_ID)?g:"",this.deviceID||(this.deviceID="android-"+(1e24*Math.random()).toString(36),console.warn("โš ๏ธ WARNING: deviceID not provided, automatically generating device id '"+this.deviceID+"'","Please save this device id and use it for future uses to prevent login issues.","You can provide this device id by passing it to the constructor or setting the THREADS_DEVICE_ID environment variable (.env file)")),this.device=null==i?void 0:i.device,this.userID=null==i?void 0:i.userID,null==i?void 0:i.locale)this.locale=i.locale;else{var j=Intl.DateTimeFormat().resolvedOptions().locale;this.locale=j}this.maxRetries=(null==i?void 0:i.maxRetries)||this.maxRetries}return i.prototype.sign=function(e){var r="object"==typeof e?JSON.stringify(e):e;return{ig_sig_key_version:4,signed_body:t.createHmac("sha256",s.SIGNATURE_KEY).update(r).digest("hex")+"."+r}},i}();
{
"name": "threads-api",
"version": "1.4.3",
"version": "1.4.4",
"description": "Unofficial, Reverse-Engineered Node.js/TypeScript client for Meta's [Threads](https://threads.net).",

@@ -5,0 +5,0 @@ "author": "Junho Yeo <i@junho.io>",

@@ -70,3 +70,3 @@ # [<img src="https://github.com/junhoyeo/threads-api/raw/main/.github/logo.jpg" width="36" height="36" />](https://github.com/junhoyeo) Threads API

##### ๐Ÿ’ก Get Threads/Replies from User (with pagination)
##### ๐Ÿ’ก Get Threads/Replies from a User (with pagination)

@@ -83,2 +83,14 @@ ```ts

##### ๐Ÿ’ก Get Followers/Followings of a User (with Pagination)
```ts
const { users, next_max_id: cursor } = await threadsAPI.getUserFollowers(userID);
console.log(JSON.stringify(users));
```
```ts
const { users, next_max_id: cursor } = await threadsAPI.getUserFollowings(userID);
console.log(JSON.stringify(users));
```
### ๐Ÿš€ Usage (Write)

@@ -265,11 +277,13 @@

- [x] โœ… Fetch UserID(`314216`) via username(`zuck`)
- [x] โœ… Read timeline feed
- [x] โœ… Read User Profile Info
- [x] โœ… Read list of User Threads
- [x] โœ… With Pagination (If auth provided)
- [x] โœ… Read list of User Replies
- [x] โœ… With Pagination (If auth provided)
- [x] โœ… Fetch PostID(`3140957200974444958`) via PostID(`CuW6-7KyXme`) or PostURL(`https://www.threads.net/t/CuW6-7KyXme`)
- [x] โœ… Read Threads via PostID
- [x] โœ… Read Likers in Thread via PostID
- [ ] ๐Ÿšง Read User Followers
- [ ] ๐Ÿšง Read User Followings
- [ ] ๐Ÿšง Read private data
- [x] โœ… Read User Followers
- [x] โœ… Read User Followings
- [x] โœ… Write data (i.e. write automated Threads)

@@ -279,3 +293,3 @@ - [x] โœ… Create new Thread with text

- [x] โœ… Create new Thread with a single image
- [ ] ๐Ÿšง Create new Thread with a multiple images
- [ ] ๐Ÿšง Create new Thread with multiple images
- [x] โœ… Reply to existing Thread

@@ -282,0 +296,0 @@ - [x] โœ… Delete Thread

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with โšก๏ธ by Socket Inc