threads-api
Advanced tools
Comparing version 1.4.5 to 1.4.6
@@ -118,4 +118,6 @@ /// <reference types="node" /> | ||
}; | ||
export type ThreadsAPIPostReplyControl = 'everyone' | 'accounts_you_follow' | 'mentioned_only'; | ||
export type ThreadsAPIPublishOptions = { | ||
text?: string; | ||
replyControl?: ThreadsAPIPostReplyControl; | ||
parentPostID?: string; | ||
@@ -122,0 +124,0 @@ quotedPostID?: 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.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}(); | ||
"use strict";!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{DEFAULT_DEVICE:function(){return h},ThreadsAPI:function(){return p}});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={everyone:0,accounts_you_follow:1,mentioned_only:2},h={manufacturer:"OnePlus",model:"ONEPLUS+A3010",os_version:25,os_release:"7.1.1"},p=function(){"use strict";function i(i){var 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=h,this.userID=void 0,this.locale=void 0,this.maxRetries=1;var b=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/",b.sign(r),{headers:l({},b._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(),b.verbose&&console.log("[SYNC LOGIN EXPERIMENT FAILED]",o.response.data),Error("Sync login experiment failed");case 4:return[2]}})});var m=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,m.syncLoginExperiments()];case 1:return s=c.sent().headers,m.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 I=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(),I.verbose&&console.error("[LOGIN] Failed to login, retrying... ("+(r+1)+"/"+I.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 I.verbose&&console.log("[LOGIN] Logging in..."),[4,I.encryptPassword(I.password)];case 1:return r=encodeURIComponent(JSON.stringify({client_input_params:{password:"#PWD_INSTAGRAM:4:"+(t=c.sent()).time+":"+t.password,contact_point:I.username,device_id:I.deviceID},server_params:{credential_type:"password",device_id:I.deviceID}})),n=encodeURIComponent(JSON.stringify({bloks_version:s.BLOKS_VERSION,styles_id:"instagram"})),o={method:"POST",headers:I._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("\\","")),I.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],I.noUpdateToken||(I.verbose&&console.debug("[token] UPDATED",u),I.token=u),I.userID=l,I.verbose&&console.debug("[userID] UPDATED",I.userID),[2,{token:u,userID:l}]}catch(e){throw I.verbose&&console.error("[LOGIN] Failed to login",e),Error("Login Failed")}return[2]}})}),a.label=1;case 1:if(!(r<I.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 "+I.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"},_.token&&{Authorization:"Bearer IGT:2:"+_.token})},this._getInstaHeaders=function(){return l({},_._getAppHeaders(),{"X-Bloks-Is-Layout-Rtl":"false","X-Bloks-Version-Id":s.BLOKS_VERSION,"X-Ig-Android-Id":_.deviceID,"X-Ig-App-Id":s.IG_APP_ID,"Accept-Language":_.locale||"en-US"},_.userID&&{"Ig-U-Ds-User-Id":_.userID,"Ig-Intended-User-Id":_.userID},_.locale&&{"X-Ig-App-Locale":_.locale.replace("-","_"),"X-Ig-Device-Locale":_.locale.replace("-","_"),"X-Ig-Mapped-Locale":_.locale.replace("-","_")})},this._getDefaultHeaders=function(e){return l({},_._getAppHeaders(),{authority:"www.threads.net",accept:"*/*","accept-language":_.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":_.fbLSDToken,"x-ig-app-id":"238260118697367"},e?{referer:"https://www.threads.net/@"+e}:void 0)};var D=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:D.httpAgent,httpsAgent:D.httpsAgent,headers:l({},D._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 y=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,y.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],!y.noUpdateLSD&&a&&(y.fbLSDToken=a,y.verbose&&console.debug("[fbLSDToken] UPDATED",y.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 w=this;this.getCurrentUserID=u(function(e){var t;return c(this,function(r){switch(r.label){case 0:if(w.userID)return w.verbose&&console.debug("[userID] USING",w.userID),[2,w.userID];if(!w.username)throw Error("username is not defined");r.label=1;case 1:return r.trys.push([1,3,,5]),[4,w.getUserIDfromUsername(w.username,e)];case 2:return w.userID=r.sent(),w.verbose&&console.debug("[userID] UPDATED",w.userID),[2,w.userID];case 3:return t=r.sent(),w.verbose&&console.error("[userID] Failed to fetch userID, Fallbacking to login",t),[4,w.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:_.httpAgent,httpsAgent:_.httpsAgent,headers:_._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 A=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=A._destructureFromUserIDQuerier(t)).userID,o=n.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:s}),doc_id:"23996318473300828"},o)];case 1:return[2,i.sent().data.data.userData.user]}})});var E=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=E._destructureFromUserIDQuerier(t)).userID,i=o.options,E.verbose&&console.debug("[fbLSDToken] USING",E.fbLSDToken),[4,E._requestQuery("https://www.threads.net/api/graphql",{lsd:E.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 k=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={}),k.token)return[3,2];return[4,k.getToken()];case 1:c.sent(),c.label=2;case 2:if(!k.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({},k._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 k.verbose&&console.log("[USER FEED] Failed to fetch",a),Error("Failed to fetch user feed: "+JSON.stringify(a));return[2,a]}})});var L=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=L._destructureFromUserIDQuerier(t)).userID,i=o.options,L.verbose&&console.debug("[fbLSDToken] USING",L.fbLSDToken),[4,L._requestQuery("https://www.threads.net/api/graphql",{lsd:L.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 T=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={}),T.token)return[3,2];return[4,T.getToken()];case 1:u.sent(),u.label=2;case 2:if(!T.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({},T._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 T.verbose&&console.log("[USER FEED] Failed to fetch",o),Error("Failed to fetch user feed: "+JSON.stringify(o));return[2,o]}})});var U=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,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+"/followers/?"+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 FOLLOWERS] Failed to fetch",d),Error("Failed to fetch user followers: "+JSON.stringify(d));return[2,d]}})});var P=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,P.token)return[3,2];return[4,P.getToken()];case 1:c.sent(),c.label=2;case 2:if(!P.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({},P._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 P.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())||"",_.getPostIDfromThreadID(n||"")};var O=this;this.getThreads=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({postID:e}),doc_id:"5587632691339264"},t)];case 1:return[2,r.sent().data.data.data]}})});var R=this;this.getThreadLikers=u(function(e,t){return c(this,function(r){switch(r.label){case 0:return R.verbose&&console.debug("[fbLSDToken] USING",R.fbLSDToken),[4,R._requestQuery("https://www.threads.net/api/graphql",{lsd:R.fbLSDToken,variables:JSON.stringify({mediaID:e}),doc_id:"9360915773983802"},t)];case 1:return[2,r.sent().data.data.likers]}})});var N=this;this.getTimeline=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:if(void 0===e&&(e=""),!N.token&&(!N.username||!N.password))throw Error("Username or password not set");return[4,N.getToken()];case 1:if(!n.sent())throw Error("Token not found");n.label=2;case 2:return n.trys.push([2,4,,5]),[4,N._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:N._getAppHeaders()}))];case 3:return[2,n.sent().data];case 4:throw r=n.sent(),N.verbose&&console.log("[TIMELINE FETCH FAILED]",r.response.data),Error("Failed to fetch timeline");case 5:return[2]}})});var x=this;this._toggleAuthPostRequest=u(function(t,r,n){return c(this,function(s){switch(s.label){case 0:return[4,x.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:x.httpAgent,httpsAgent:x.httpsAgent,headers:x._getDefaultHeaders()}))];case 2:return[2,s.sent()]}})});var q=this;this.like=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+"/like/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var F=this;this.unlike=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,F.getCurrentUserID()];case 1:return r=n.sent(),[4,F._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/unlike/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var B=this;this.follow=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/create/"+e+"/",void 0,t)];case 1:return r=n.sent(),B.verbose&&console.debug("[FOLLOW]",r.data),[2,r.data]}})});var G=this;this.unfollow=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/friendships/destroy/"+e+"/",void 0,t)];case 1:return r=n.sent(),G.verbose&&console.debug("[UNFOLLOW]",r.data),[2,r.data]}})});var H=this;this.repost=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/create_repost/",{media_id:e},t)];case 1:return r=n.sent(),H.verbose&&console.debug("[REPOST]",r.data),[2,r.data]}})});var C=this;this.unrepost=u(function(e,t){var r;return c(this,function(n){switch(n.label){case 0:return[4,C._toggleAuthPostRequest(""+s.BASE_API_URL+"/api/v1/repost/delete_text_app_repost/",{original_media_id:e},t)];case 1:return r=n.sent(),C.verbose&&console.debug("[UNREPOST]",r.data),[2,r.data]}})});var J=this;this.getToken=u(function(){return c(this,function(e){switch(e.label){case 0:if(J.token)return J.verbose&&console.debug("[token] USING",J.token),[2,J.token];if(!J.username||!J.password)throw Error("Username and password are required");return[4,J.login()];case 1:return e.sent(),[2,J.token]}})});var M=this;this.publish=u(function(t){var r,n,o,a,i,u,l,h,p;return c(this,function(c){switch(c.label){case 0:if(r="string"==typeof t?{text:t}:t,!M.token&&(!M.username||!M.password))throw Error("Username or password not set");return[4,M.getCurrentUserID()];case 1:if(!(n=c.sent()))throw Error("User ID not found");return[4,M.getToken()];case 2:if(!c.sent())throw Error("Token not found");if(a=-(60*(o=new Date).getTimezoneOffset()),u={text_post_app_info:{reply_control:d[null!=(i=r.replyControl)?i:"everyone"]},timezone_offset:a.toString(),source_type:"4",_uid:n,device_id:M.deviceID,caption:r.text||"",upload_id:o.getTime(),device:M.device},l=s.POST_URL,!("image"in r&&r.image))return[3,4];return l=s.POST_WITH_IMAGE_URL,[4,M.uploadImage(r.image)];case 3:return u.upload_id=c.sent().upload_id,u.scene_capture_type="",[3,5];case 4:"url"in r&&r.url&&(u.text_post_app_info.link_attachment_url=r.url),c.label=5;case 5:return r.parentPostID&&(u.text_post_app_info.reply_id=r.parentPostID.replace(/_\d+$/,"")),r.quotedPostID&&(u.text_post_app_info.quoted_post_id=r.quotedPostID.replace(/_\d+$/,"")),r.image||(u.publish_mode="text_post"),h="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify(u)),[4,e.default.post(l,h,{httpAgent:M.httpAgent,httpsAgent:M.httpsAgent,headers:M._getAppHeaders(),timeout:6e4})];case 6:if(p=c.sent(),M.verbose&&console.debug("[PUBLISH]",p.data),"ok"===p.data.status)return[2,p.data.media.id];return[2,void 0]}})});var X=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:X.userID,_uuid:X.deviceID})),[4,e.default.post(n,o,l({httpAgent:X.httpAgent,httpsAgent:X.httpsAgent,headers:X._getAppHeaders(),timeout:6e4},r))];case 1:if("ok"===a.sent().data.status)return[2,!0];return[2,!1]}})});var W=this;this.publishWithImage=u(function(e,t){return c(this,function(r){return[2,W.publish({text:e,image:t})]})});var j=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.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.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({},j._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"}),j.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:j.httpAgent,headers:g,timeout:6e4})];case 9:return v=c.sent().data,j.verbose&&console.log("[UPLOAD_IMAGE] SUCCESS",v),[2,v];case 10:throw _=c.sent(),j.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!=(p=null==i?void 0:i.username)?p:process.env.THREADS_USERNAME,this.password=null!=(f=null==i?void 0:i.password)?f:process.env.THREADS_PASSWORD,this.deviceID=null!=(v=null!=(g=null==i?void 0:i.deviceID)?g:process.env.THREADS_DEVICE_ID)?v:"",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 Q=Intl.DateTimeFormat().resolvedOptions().locale;this.locale=Q}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.5", | ||
"version": "1.4.6", | ||
"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>", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
68819
430