From db33da9d564c4b479907a63a2fa7b0919eed4744 Mon Sep 17 00:00:00 2001 From: lartsch Date: Wed, 14 Dec 2022 05:44:01 -0500 Subject: [PATCH] add loggedin check, fix bug with v3, improve v3 support, disable log --- firefox/manifest.json | 2 +- manifest.json | 2 +- src/inject.js | 50 ++++++++++++++++++++++++++++++++++------ src/inject.min.js | 2 +- src/nodeinserted.css | 3 ++- src/nodeinserted.min.css | 2 +- 6 files changed, 49 insertions(+), 12 deletions(-) diff --git a/firefox/manifest.json b/firefox/manifest.json index 2051f63..ae6cb46 100644 --- a/firefox/manifest.json +++ b/firefox/manifest.json @@ -1,6 +1,6 @@ { "name": "FediAct", - "version": "0.9.6.1", + "version": "0.9.6.2", "description": "Simplifies interactions on other Mastodon instances than your own. Visit https://github.com/lartsch/FediAct for more.", "manifest_version": 2, "content_scripts": [ diff --git a/manifest.json b/manifest.json index 8f21237..7e2ca1d 100644 --- a/manifest.json +++ b/manifest.json @@ -1,6 +1,6 @@ { "name": "FediAct", - "version": "0.9.6.1", + "version": "0.9.6.2", "description": "Simplifies interactions on other Mastodon instances than your own. Visit https://github.com/lartsch/FediAct for more.", "manifest_version": 3, "content_scripts": [ diff --git a/src/inject.js b/src/inject.js index d4abce0..32b853d 100644 --- a/src/inject.js +++ b/src/inject.js @@ -7,7 +7,7 @@ const profileNamePaths = ["div.account__header__tabs__name small", "div.public-a const domainRegex = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/ const handleExtractUrlRegex = /^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})?\/?@(?\w+)(?:@(?(?:[\w-]+\.)+?\w+))?(?:\/(?\d+))?\/?$/ const handleExtractUriRegex = /^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})(?:\/users\/)(?\w+)(?:(?:\/statuses\/)(?\d+))?\/?$/ -const enableConsoleLog = true +const enableConsoleLog = false const logPrepend = "[FediAct]" const instanceApi = "/api/v1/instance" const statusApi = "/api/v1/statuses" @@ -75,6 +75,28 @@ function log(text) { jQuery.fn.onAppear = jQuery.fn.DOMNodeAppear })(jQuery) +// for checking if logged in on an external instance +function isLoggedIn() { + return new Promise(function(resolve) { + if ($(document).find("script#initial-state").length) { + var initialState = $(document).find("script#initial-state").first() + var stateJson = JSON.parse($(initialState).text()) + if (stateJson.meta.access_token) { + resolve(true) + } + } else { + $(document).DOMNodeAppear(function(e) { + var initialState = $(e.target) + var stateJson = JSON.parse($(initialState).text()) + if (stateJson.meta.access_token) { + resolve(true) + } + }, "script#initial-state") + } + resolve(false) + }) +} + // extract given url parameter value var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), @@ -505,6 +527,16 @@ async function processToots() { // otherwise do the same for any closest article or div with the data-id attribute } else if ($(el).closest("article[data-id], div[data-id]").length) { return $(el).closest("article[data-id], div[data-id]").first().attr("data-id").split("-").slice(-1)[0] + } else if ($(el).find("a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").length) { + var hrefEl = $(el).find("a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").first() + if ($(hrefEl).attr("href")) { + var hrefAttr = $(hrefEl).attr("href") + if (~hrefAttr.indexOf("interact/")) { + var splitted = hrefAttr.split("?")[0].split("/") + var lastpart = splitted.pop() || splitted.pop() + return lastpart + } + } } } // check elements that can contain an href (either resolved external link or internal reference) @@ -517,6 +549,7 @@ async function processToots() { } else if ($(el).find("a.modal-button").length) { return tootHrefCheck($(el).find("a.modal-button").first().attr("href").split("?")[0]) } + return [false,undefined] } // check toot author, mentions and toot prepend mentions for applying mutes function processMutes(el, tootAuthor) { @@ -534,7 +567,7 @@ async function processToots() { hrefs.push($(this).find("a").attr("href").split("?")[0]) }) var processedHrefs = [] - for (href of hrefs) { + for (var href of hrefs) { var splitted = href.split("/") var lastpart = splitted.pop() || splitted.pop() lastpart = lastpart.slice(1) @@ -562,7 +595,7 @@ async function processToots() { // main function to process each detected toot element async function process(el) { // extra step for detailed status elements to select the correct parent - if ($(el).is("div.detailed-status")) { + if ($(el).is("div.detailed-status") && $(el).closest("div.focusable").length) { el = $(el).closest("div.focusable") } // get toot data @@ -582,8 +615,8 @@ async function processToots() { // check if id is already cached var cacheIndex = isInProcessedToots(internalIdentifier) // get all button elements of this toot - var favButton = $(el).find("button:has(i.fa-star), a.icon-button:has(i.fa-star)").first() - var boostButton = $(el).find("button:has(i.fa-retweet), a.icon-button:has(i.fa-retweet)").first() + var favButton = $(el).find("button:has(i.fa-star), a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").first() + var boostButton = $(el).find("button:has(i.fa-retweet), a.icon-button:has(i.fa-retweet), a.detailed-status__link:has(i.fa-retweet)").first() var bookmarkButton = $(el).find("button:has(i.fa-bookmark)").first() var replyButton = $(el).find("button:has(i.fa-reply), button:has(i.fa-reply-all), a.icon-button:has(i.fa-reply), a.icon-button:has(i.fa-reply-all)").first() // handles process when a button is clicked @@ -1067,10 +1100,13 @@ async function checkSite() { } else { settings.fediact_exturi = uri } - return true + if (await isLoggedIn()) { + log("Already logged in to this external instance.") + } else { + return true + } } } - log("Does not look like a Mastodon instance.") return false } diff --git a/src/inject.min.js b/src/inject.min.js index fe0d571..d07e7b7 100644 --- a/src/inject.min.js +++ b/src/inject.min.js @@ -1 +1 @@ -const a=["div.account__header button.logo-button","div.public-account-header a.logo-button","div.account-card a.logo-button","div.directory-card a.icon-button","div.detailed-status a.logo-button","button.remote-button","div.account__header button.button--follow"],c=["div.account__header__tabs__name small","div.public-account-header__tabs__name small","div.detailed-status span.display-name__account","div.display-name > span","a.user-screen-name","div.profile-info-panel small"],i=/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/,D=/^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})?\/?@(?\w+)(?:@(?(?:[\w-]+\.)+?\w+))?(?:\/(?\d+))?\/?$/,N=/^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})(?:\/users\/)(?\w+)(?:(?:\/statuses\/)(?\d+))?\/?$/,e=!0,n="[FediAct]",o="/api/v1/instance",r="/api/v1/statuses",s="/api/v2/search",d="/api/v1/accounts",l=500,u=200;var browser,chrome,f,h,I={};const t={fediact_homeinstance:null,fediact_alert:!1,fediact_mode:"blacklist",fediact_whitelist:null,fediact_blacklist:null,fediact_target:"_self",fediact_autoaction:!0,fediact_token:null,fediact_showfollows:!0,fediact_redirects:!0,fediact_enabledelay:!0,fediact_hidemuted:!1,fediact_mutesblocks:[],fediact_domainblocks:[]};var[M,p,m]=[[],[],[]];function P(t){e&&console.log(n+" "+t)}!function(i){i.fn.DOMNodeAppear=function(e,a){if(!a)return!1;i(document).on("animationstart webkitAnimationStart oanimationstart MSAnimationStart",function(t){"nodeInserted"==t.originalEvent.animationName&&i(t.target).is(a)&&"function"==typeof e&&e(t)})},jQuery.fn.onAppear=jQuery.fn.DOMNodeAppear}(jQuery);var g=function(t){for(var e,a=window.location.search.substring(1).split("&"),i=0;i{setTimeout(function(){t()},l-e)}),f=t),new Promise(function(t){let e=new XMLHttpRequest;if(e.open(i,n),e.timeout=3e3,o)for(var a in o)e.setRequestHeader(a,o[a]);e.onload=function(){200<=this.status&&this.status<300?t(e.responseText):t(!1)},e.onerror=function(){P("Request to "+n+" failed."),t(!1)},e.send()})}function b(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(t,e,a){return t.replace(new RegExp(b(e),"g"),a)}function S(t){var e;I.fediact_redirects?(I.fediact_alert&&alert("Redirecting..."),e=window.open(t,I.fediact_target),P("Redirected to "+t),e?e.focus():P("Could not open new window. Please allow popups for this website.")):P("Redirects disabled.")}async function z(t,e){var a,i;switch(e){case"follow":a="https://"+I.fediact_homeinstance+d+"/"+t+"/follow",i=function(t){return t.following||t.requested};break;case"boost":a="https://"+I.fediact_homeinstance+r+"/"+t+"/reblog",i=function(t){return t.reblogged};break;case"favourite":a="https://"+I.fediact_homeinstance+r+"/"+t+"/favourite",i=function(t){return t.favourited};break;case"bookmark":a="https://"+I.fediact_homeinstance+r+"/"+t+"/bookmark",i=function(t){return t.bookmarked};break;case"unfollow":a="https://"+I.fediact_homeinstance+d+"/"+t+"/unfollow",i=function(t){return!t.following&&!t.requested};break;case"unboost":a="https://"+I.fediact_homeinstance+r+"/"+t+"/unreblog",i=function(t){return!t.reblogged};break;case"unfavourite":a="https://"+I.fediact_homeinstance+r+"/"+t+"/unfavourite",i=function(t){return!t.favourited};break;case"unbookmark":a="https://"+I.fediact_homeinstance+r+"/"+t+"/unbookmark",i=function(t){return!t.bookmarked};break;default:P("No valid action specified.")}if(a){var n=await v("POST",a,I.tokenheader);if(n&&i(JSON.parse(n)))return!0}P(e+" action failed.")}async function w(t){var e="https://"+I.fediact_homeinstance+d+"/relationships?";for(const o of t)e+="id[]="+o.toString()+"&";var a=await v("GET",e,I.tokenheader),i=Array(t.length).fill(!1);if(a)for(var a=JSON.parse(a),n=0;nI.fediact_mutesblocks.includes(t))||q(e)||n.some(t=>I.fediact_domainblocks.includes(t.split("@")[1]))?($(t).hide(),a&&$(a).hide(),1):void 0}}(e,t)){i=$(e);var a=$(i).is(".detailed-status__wrapper")?(a=window.location.href.split("?")[0].split("/")).pop()||a.pop():$(i).attr("data-id")?$(i).attr("data-id").split("-").slice(-1)[0]:$(i).closest("article[data-id], div[data-id]").length?$(i).closest("article[data-id], div[data-id]").first().attr("data-id").split("-").slice(-1)[0]:void 0,[i,n]=(i=$(e),$(i).find("a.status__relative-time").length?R($(i).find("a.status__relative-time").first().attr("href").split("?")[0]):$(i).find("a.detailed-status__datetime").length?R($(i).find("a.detailed-status__datetime").first().attr("href").split("?")[0]):$(i).find("a.modal-button").length?R($(i).find("a.modal-button").first().attr("href").split("?")[0]):void 0),o=a||n;if(o){var r=[],s=L(o),c=$(e).find("button:has(i.fa-star), a.icon-button:has(i.fa-star)").first(),d=$(e).find("button:has(i.fa-retweet), a.icon-button:has(i.fa-retweet)").first(),l=$(e).find("button:has(i.fa-bookmark)").first(),u=$(e).find("button:has(i.fa-reply), button:has(i.fa-reply-all), a.icon-button:has(i.fa-reply), a.icon-button:has(i.fa-reply-all)").first();async function f(t,e){if(!I.fediact_autoaction)return P("Auto-action disabled."),!0;i=e,a=!1,$(i.currentTarget).children("i.fa-retweet").length?a=$(i.currentTarget).children("i.fa-retweet").hasClass("fediactive")?"unboost":"boost":$(i.currentTarget).children("i.fa-star").length?a=$(i.currentTarget).hasClass("fediactive")?"unfavourite":"favourite":$(i.currentTarget).children("i.fa-bookmark").length?a=$(i.currentTarget).hasClass("fediactive")?"unbookmark":"bookmark":$(i.currentTarget).attr("href")&&(~$(i.currentTarget).attr("href").indexOf("type=reblog")?a=$(i.currentTarget).hasClass("fediactive")?"unboost":"boost":~$(i.currentTarget).attr("href").indexOf("type=favourite")&&(a=$(i.currentTarget).hasClass("fediactive")?"unfavourite":"favourite"));var a,i=a;if(i){if(await z(t,i))return"boost"==i||"unboost"==i?(U($(e.currentTarget),[["color","!remove","rgb(140, 141, 255)"]],"fediactive"),U($(e.currentTarget).find("i"),[["transition-duration","!remove","0.9s"],["background-position","!remove","0px 100%"]],"fediactive"),s&&(M[s][3]=!M[s][3])):"favourite"==i||"unfavourite"==i?(U($(e.currentTarget),[["color","!remove","rgb(202, 143, 4)"]],"fediactive"),U($(e.currentTarget).find("i"),[["animation","spring-rotate-out 1s linear","spring-rotate-in 1s linear"]],"fediactive"),s&&(M[s][4]=!M[s][4])):(U($(e.currentTarget),[["color","!remove","rgb(255, 80, 80)"]],"fediactive"),s&&(M[s][5]=!M[s][5])),!0;P("Could not execute action on home instance.")}else P("Could not determine action.")}function h(t){$(e).find(".feditriggered").remove(),t[1]?($(l).removeClass("disabled").removeAttr("disabled"),t[4]&&!$(c).hasClass("fediactive")&&(U($(c),[["color","!remove","rgb(202, 143, 4)"]],"fediactive"),U($(c).find("i"),[["animation","spring-rotate-out 1s linear","spring-rotate-in 1s linear"]],"fediactive")),t[3]&&!$(d).find("i.fediactive").length&&(U($(d),[["color","!remove","rgb(140, 141, 255)"]],"fediactive"),U($(d).find("i"),[["transition-duration","!remove","0.9s"],["background-position","!remove","0px 100%"]],"fediactive")),t[5]&&!$(l).hasClass("fediactive")&&U($(l),[["color","!remove","rgb(255, 80, 80)"]],"fediactive")):$("Unresolved").insertAfter($(c))}function p(i){$(u).on("click",function(t){t.preventDefault(),t.stopImmediatePropagation(),S(i[6]+"?fedireply")}),$([c,d,l]).each(function(){var e,a=0;$(this).on("click",async function(t){t.preventDefault(),t.stopImmediatePropagation(),1==++a?e=setTimeout(async function(){await f(i[2],t)||P("Action failed."),a=0},350):(clearTimeout(e),await f(i[2],t)?S(i[6]):P("Action failed."),a=0)}).on("dblclick",function(t){t.preventDefault(),t.stopImmediatePropagation()})})}if(s){var m=M[s];h(m),m[1]&&p(m)}else{if(i&&r.push(n),t){var g,v,b,_=t.match(D),[w,k]=[!1,!1],y=(!_.groups.handledomain||~location.hostname.indexOf(_.groups.handledomain)||(w=!0),[a]);i||y.push(n);for(g of y=y.filter((t,e)=>void 0!==t&&y.indexOf(t)==e))w?k||((v=await J(location.protocol+"//"+location.hostname+"/"+t+"/"+g))&&(k=!0,r.push(v),N.test(v)?(b=v.match(N)).groups.handle&&b.groups.tootid&&b.groups.domain&&r.push(b.groups.domain+"/@"+b.groups.handle+"/"+b.groups.tootid):D.test(v)&&(b=v.match(D)).groups.handle&&b.groups.tootid&&b.groups.domain&&r.push(b.groups.domain+"/users/"+b.groups.handle+"/statuses/"+b.groups.tootid)),r.push(location.protocol+"//"+location.hostname+"/"+t+"/"+g)):(r.push(location.protocol+"//"+location.hostname+"/users/"+_.groups.handle+"/statuses/"+g),r.push(location.protocol+"//"+location.hostname+"/@"+_.groups.handle+"/"+g))}if(r.length){var x,T,A,C,O=!1;for(x of r=r.filter((t,e)=>r.indexOf(t)==e))O||(T=await W(x))&&(O=!0,A="https://"+I.fediact_homeinstance+"/@"+T[0]+"/"+T[1],C=[o,...T,A,!0]);O?(s=E(C),h(C),p(C)):(P("Failed to resolve: "+r),s=E([o,!1]),h([o,!1]))}else P("Could not identify a post URI for home resolving."),s=E([o,!1]),h([o,!1])}}else P("Could not get toot data.")}}$(document).DOMNodeAppear(async function(t){m.includes($(t.target).get(0))||(m.push($(t.target).get(0)),e($(t.target)))},"div.status, div.detailed-status"),$(document).find("div.status, div.detailed-status").each(function(){m.includes($(this).get(0))||(m.push($(this).get(0)),e($(this)))})}async function C(){async function e(i){var t,n,o,r,e="follow";async function s(t){return I.fediact_autoaction?(t=await z(t,e),"follow"==e&&t?($(i).text("Unfollow"),e="unfollow",!0):"unfollow"==e&&t?($(i).text("Follow"),e="follow",!0):void 0):(P("Auto-action disabled."),!0)}if($(i).closest("div.account-card").length)t=$(i).closest("div.account-card").find("div.display-name > span").text().trim();else for(const a of c)if($(a).length){(t=$(a).text().trim()).split("@").length-1==1&&(t=t+"@"+I.fediact_exturi);break}t&&!p.includes(t)&&((n=await k(t))?(p.push(t),I.fediact_showfollows&&(await w([n[0]]))[0]&&($(i).text("Unfollow"),e="unfollow"),o=0,$(i).on("click",async function(t){var e,a;t.preventDefault(),t.stopImmediatePropagation(),1==++o?r=setTimeout(async function(){s(n[0]),o=0},350):(clearTimeout(r),await s(n[0])?(e=$(i).text(),a="https://"+I.fediact_homeinstance+"/@"+n[1],$(i).text("Redirecting..."),setTimeout(function(){S(a),$(i).text(e)},1e3)):P("Action failed."),o=0)}).on("dblclick",function(t){t.preventDefault(),t.stopImmediatePropagation()})):P("Could not resolve user home ID."))}var t=a.join(",");$(document).DOMNodeAppear(async function(t){m.includes($(t.target).get(0))||(m.push($(t.target).get(0)),e($(t.target)))},t),$(document).find(t).each(function(){m.includes($(this).get(0))||(m.push($(this).get(0)),e($(this)))})}function y(t){var e,a=[];for(e of t.split(/\r?\n/))(e=e.trim()).length&&(i.test(e)?a.push(e):P("Removed invalid domain "+e+" from blacklist/whitelist."));return[...new Set(a)]}function O(){if(null==I.fediact_homeinstance||!I.fediact_homeinstance)return P("Mastodon home instance is not set."),!1;if(!I.fediact_token)return P("No API token available. Are you logged in to your home instance? If yes, wait for 1-2 minutes and reload page."),!1;if(I.tokenheader={Authorization:"Bearer "+I.fediact_token},!i.test(I.fediact_homeinstance))return P("Instance setting is not a valid domain name."),!1;if("whitelist"==I.fediact_mode){if(I.fediact_whitelist=y(I.fediact_whitelist),I.fediact_whitelist.length<1)return P("Whitelist is empty or invalid."),!1}else I.fediact_blacklist=y(I.fediact_blacklist);return!0}async function R(){if(location.hostname!=I.fediact_homeinstance||(h=g("fedireply"))){if("whitelist"==I.fediact_mode){if($.inArray(location.hostname,I.fediact_whitelist)<0)return P("Current site is not in whitelist."),!1}else if(-1<$.inArray(location.hostname,I.fediact_blacklist))return P("Current site is in blacklist."),!1;var t=await v("GET",location.protocol+"//"+location.hostname+o,null);if(t){t=JSON.parse(t).uri;if(t)return t.startsWith("http")?(t=new URL(t),I.fediact_exturi=t.hostname):I.fediact_exturi=t,!0}P("Does not look like a Mastodon instance.")}else P("Current site is your home instance.");return!1}async function j(){chrome.runtime.onMessage.addListener(async function(t,e,a){t.urlchanged&&(M=[],p=[],m=[],await x()||location.reload()),t.updatedfedisettings&&location.reload()});try{return await chrome.runtime.sendMessage({running:!0}),!0}catch(t){P(t)}return!1}function x(){return new Promise(async function(e){try{I=await(browser||chrome).storage.local.get(t)}catch(t){P(t),e(!1)}I&&O()?e(!0):e(!1)})}async function F(){await x()?await R()?h?T():j()?(C(),A()):P("Failed to initialize background script."):P("Will not process this site."):P("Could not load settings.")}F(); \ No newline at end of file +const a=["div.account__header button.logo-button","div.public-account-header a.logo-button","div.account-card a.logo-button","div.directory-card a.icon-button","div.detailed-status a.logo-button","button.remote-button","div.account__header button.button--follow"],c=["div.account__header__tabs__name small","div.public-account-header__tabs__name small","div.detailed-status span.display-name__account","div.display-name > span","a.user-screen-name","div.profile-info-panel small"],i=/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/,R=/^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})?\/?@(?\w+)(?:@(?(?:[\w-]+\.)+?\w+))?(?:\/(?\d+))?\/?$/,D=/^(?https?:\/\/(?:\.?[a-z0-9-]+)+(?:\.[a-z]+){1})(?:\/users\/)(?\w+)(?:(?:\/statuses\/)(?\d+))?\/?$/,e=!1,n="[FediAct]",o="/api/v1/instance",r="/api/v1/statuses",s="/api/v2/search",d="/api/v1/accounts",l=500,u=200;var browser,chrome,f,h,P={};const t={fediact_homeinstance:null,fediact_alert:!1,fediact_mode:"blacklist",fediact_whitelist:null,fediact_blacklist:null,fediact_target:"_self",fediact_autoaction:!0,fediact_token:null,fediact_showfollows:!0,fediact_redirects:!0,fediact_enabledelay:!0,fediact_hidemuted:!1,fediact_mutesblocks:[],fediact_domainblocks:[]};var[S,p,m]=[[],[],[]];function I(t){e&&console.log(n+" "+t)}function g(){return new Promise(function(e){var t;$(document).find("script#initial-state").length?(t=$(document).find("script#initial-state").first(),JSON.parse($(t).text()).meta.access_token&&e(!0)):$(document).DOMNodeAppear(function(t){t=$(t.target);JSON.parse($(t).text()).meta.access_token&&e(!0)},"script#initial-state"),e(!1)})}!function(i){i.fn.DOMNodeAppear=function(e,a){if(!a)return!1;i(document).on("animationstart webkitAnimationStart oanimationstart MSAnimationStart",function(t){"nodeInserted"==t.originalEvent.animationName&&i(t.target).is(a)&&"function"==typeof e&&e(t)})},jQuery.fn.onAppear=jQuery.fn.DOMNodeAppear}(jQuery);var v=function(t){for(var e,a=window.location.search.substring(1).split("&"),i=0;i{setTimeout(function(){t()},l-e)}),f=t),new Promise(function(t){let e=new XMLHttpRequest;if(e.open(i,n),e.timeout=3e3,o)for(var a in o)e.setRequestHeader(a,o[a]);e.onload=function(){200<=this.status&&this.status<300?t(e.responseText):t(!1)},e.onerror=function(){I("Request to "+n+" failed."),t(!1)},e.send()})}function b(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function w(t,e,a){return t.replace(new RegExp(b(e),"g"),a)}function M(t){var e;P.fediact_redirects?(P.fediact_alert&&alert("Redirecting..."),e=window.open(t,P.fediact_target),I("Redirected to "+t),e?e.focus():I("Could not open new window. Please allow popups for this website.")):I("Redirects disabled.")}async function z(t,e){var a,i;switch(e){case"follow":a="https://"+P.fediact_homeinstance+d+"/"+t+"/follow",i=function(t){return t.following||t.requested};break;case"boost":a="https://"+P.fediact_homeinstance+r+"/"+t+"/reblog",i=function(t){return t.reblogged};break;case"favourite":a="https://"+P.fediact_homeinstance+r+"/"+t+"/favourite",i=function(t){return t.favourited};break;case"bookmark":a="https://"+P.fediact_homeinstance+r+"/"+t+"/bookmark",i=function(t){return t.bookmarked};break;case"unfollow":a="https://"+P.fediact_homeinstance+d+"/"+t+"/unfollow",i=function(t){return!t.following&&!t.requested};break;case"unboost":a="https://"+P.fediact_homeinstance+r+"/"+t+"/unreblog",i=function(t){return!t.reblogged};break;case"unfavourite":a="https://"+P.fediact_homeinstance+r+"/"+t+"/unfavourite",i=function(t){return!t.favourited};break;case"unbookmark":a="https://"+P.fediact_homeinstance+r+"/"+t+"/unbookmark",i=function(t){return!t.bookmarked};break;default:I("No valid action specified.")}if(a){var n=await _("POST",a,P.tokenheader);if(n&&i(JSON.parse(n)))return!0}I(e+" action failed.")}async function k(t){var e="https://"+P.fediact_homeinstance+d+"/relationships?";for(const o of t)e+="id[]="+o.toString()+"&";var a=await _("GET",e,P.tokenheader),i=Array(t.length).fill(!1);if(a)for(var a=JSON.parse(a),n=0;nP.fediact_mutesblocks.includes(t))||q(e)||o.some(t=>P.fediact_domainblocks.includes(t.split("@")[1]))?($(t).hide(),a&&$(a).hide(),1):void 0}}(e,t)){var a=function(t){if($(t).is(".detailed-status__wrapper"))return(e=window.location.href.split("?")[0].split("/")).pop()||e.pop();if($(t).attr("data-id"))return $(t).attr("data-id").split("-").slice(-1)[0];if($(t).closest("article[data-id], div[data-id]").length)return $(t).closest("article[data-id], div[data-id]").first().attr("data-id").split("-").slice(-1)[0];if($(t).find("a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").length){var e=$(t).find("a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").first();if($(e).attr("href")){t=$(e).attr("href");if(~t.indexOf("interact/"))return(e=t.split("?")[0].split("/")).pop()||e.pop()}}}($(e)),[i,n]=(i=$(e),$(i).find("a.status__relative-time").length?N($(i).find("a.status__relative-time").first().attr("href").split("?")[0]):$(i).find("a.detailed-status__datetime").length?N($(i).find("a.detailed-status__datetime").first().attr("href").split("?")[0]):$(i).find("a.modal-button").length?N($(i).find("a.modal-button").first().attr("href").split("?")[0]):[!1,void 0]),o=a||n;if(o){var r=[],s=L(o),c=$(e).find("button:has(i.fa-star), a.icon-button:has(i.fa-star), a.detailed-status__link:has(i.fa-star)").first(),d=$(e).find("button:has(i.fa-retweet), a.icon-button:has(i.fa-retweet), a.detailed-status__link:has(i.fa-retweet)").first(),l=$(e).find("button:has(i.fa-bookmark)").first(),u=$(e).find("button:has(i.fa-reply), button:has(i.fa-reply-all), a.icon-button:has(i.fa-reply), a.icon-button:has(i.fa-reply-all)").first();async function f(t,e){if(!P.fediact_autoaction)return I("Auto-action disabled."),!0;i=e,a=!1,$(i.currentTarget).children("i.fa-retweet").length?a=$(i.currentTarget).children("i.fa-retweet").hasClass("fediactive")?"unboost":"boost":$(i.currentTarget).children("i.fa-star").length?a=$(i.currentTarget).hasClass("fediactive")?"unfavourite":"favourite":$(i.currentTarget).children("i.fa-bookmark").length?a=$(i.currentTarget).hasClass("fediactive")?"unbookmark":"bookmark":$(i.currentTarget).attr("href")&&(~$(i.currentTarget).attr("href").indexOf("type=reblog")?a=$(i.currentTarget).hasClass("fediactive")?"unboost":"boost":~$(i.currentTarget).attr("href").indexOf("type=favourite")&&(a=$(i.currentTarget).hasClass("fediactive")?"unfavourite":"favourite"));var a,i=a;if(i){if(await z(t,i))return"boost"==i||"unboost"==i?(U($(e.currentTarget),[["color","!remove","rgb(140, 141, 255)"]],"fediactive"),U($(e.currentTarget).find("i"),[["transition-duration","!remove","0.9s"],["background-position","!remove","0px 100%"]],"fediactive"),s&&(S[s][3]=!S[s][3])):"favourite"==i||"unfavourite"==i?(U($(e.currentTarget),[["color","!remove","rgb(202, 143, 4)"]],"fediactive"),U($(e.currentTarget).find("i"),[["animation","spring-rotate-out 1s linear","spring-rotate-in 1s linear"]],"fediactive"),s&&(S[s][4]=!S[s][4])):(U($(e.currentTarget),[["color","!remove","rgb(255, 80, 80)"]],"fediactive"),s&&(S[s][5]=!S[s][5])),!0;I("Could not execute action on home instance.")}else I("Could not determine action.")}function h(t){$(e).find(".feditriggered").remove(),t[1]?($(l).removeClass("disabled").removeAttr("disabled"),t[4]&&!$(c).hasClass("fediactive")&&(U($(c),[["color","!remove","rgb(202, 143, 4)"]],"fediactive"),U($(c).find("i"),[["animation","spring-rotate-out 1s linear","spring-rotate-in 1s linear"]],"fediactive")),t[3]&&!$(d).find("i.fediactive").length&&(U($(d),[["color","!remove","rgb(140, 141, 255)"]],"fediactive"),U($(d).find("i"),[["transition-duration","!remove","0.9s"],["background-position","!remove","0px 100%"]],"fediactive")),t[5]&&!$(l).hasClass("fediactive")&&U($(l),[["color","!remove","rgb(255, 80, 80)"]],"fediactive")):$("Unresolved").insertAfter($(c))}function p(i){$(u).on("click",function(t){t.preventDefault(),t.stopImmediatePropagation(),M(i[6]+"?fedireply")}),$([c,d,l]).each(function(){var e,a=0;$(this).on("click",async function(t){t.preventDefault(),t.stopImmediatePropagation(),1==++a?e=setTimeout(async function(){await f(i[2],t)||I("Action failed."),a=0},350):(clearTimeout(e),await f(i[2],t)?M(i[6]):I("Action failed."),a=0)}).on("dblclick",function(t){t.preventDefault(),t.stopImmediatePropagation()})})}if(s){var m=S[s];h(m),m[1]&&p(m)}else{if(i&&r.push(n),t){var g,v,_,b=t.match(R),[w,k]=[!1,!1],y=(!b.groups.handledomain||~location.hostname.indexOf(b.groups.handledomain)||(w=!0),[a]);i||y.push(n);for(g of y=y.filter((t,e)=>void 0!==t&&y.indexOf(t)==e))w?k||((v=await W(location.protocol+"//"+location.hostname+"/"+t+"/"+g))&&(k=!0,r.push(v),D.test(v)?(_=v.match(D)).groups.handle&&_.groups.tootid&&_.groups.domain&&r.push(_.groups.domain+"/@"+_.groups.handle+"/"+_.groups.tootid):R.test(v)&&(_=v.match(R)).groups.handle&&_.groups.tootid&&_.groups.domain&&r.push(_.groups.domain+"/users/"+_.groups.handle+"/statuses/"+_.groups.tootid)),r.push(location.protocol+"//"+location.hostname+"/"+t+"/"+g)):(r.push(location.protocol+"//"+location.hostname+"/users/"+b.groups.handle+"/statuses/"+g),r.push(location.protocol+"//"+location.hostname+"/@"+b.groups.handle+"/"+g))}if(r.length){var x,T,A,C,O=!1;for(x of r=r.filter((t,e)=>r.indexOf(t)==e))O||(T=await E(x))&&(O=!0,A="https://"+P.fediact_homeinstance+"/@"+T[0]+"/"+T[1],C=[o,...T,A,!0]);O?(s=J(C),h(C),p(C)):(I("Failed to resolve: "+r),s=J([o,!1]),h([o,!1]))}else I("Could not identify a post URI for home resolving."),s=J([o,!1]),h([o,!1])}}else I("Could not get toot data.")}}$(document).DOMNodeAppear(async function(t){m.includes($(t.target).get(0))||(m.push($(t.target).get(0)),e($(t.target)))},"div.status, div.detailed-status"),$(document).find("div.status, div.detailed-status").each(function(){m.includes($(this).get(0))||(m.push($(this).get(0)),e($(this)))})}async function O(){async function e(i){var t,n,o,r,e="follow";async function s(t){return P.fediact_autoaction?(t=await z(t,e),"follow"==e&&t?($(i).text("Unfollow"),e="unfollow",!0):"unfollow"==e&&t?($(i).text("Follow"),e="follow",!0):void 0):(I("Auto-action disabled."),!0)}if($(i).closest("div.account-card").length)t=$(i).closest("div.account-card").find("div.display-name > span").text().trim();else for(const a of c)if($(a).length){(t=$(a).text().trim()).split("@").length-1==1&&(t=t+"@"+P.fediact_exturi);break}t&&!p.includes(t)&&((n=await T(t))?(p.push(t),P.fediact_showfollows&&(await k([n[0]]))[0]&&($(i).text("Unfollow"),e="unfollow"),o=0,$(i).on("click",async function(t){var e,a;t.preventDefault(),t.stopImmediatePropagation(),1==++o?r=setTimeout(async function(){s(n[0]),o=0},350):(clearTimeout(r),await s(n[0])?(e=$(i).text(),a="https://"+P.fediact_homeinstance+"/@"+n[1],$(i).text("Redirecting..."),setTimeout(function(){M(a),$(i).text(e)},1e3)):I("Action failed."),o=0)}).on("dblclick",function(t){t.preventDefault(),t.stopImmediatePropagation()})):I("Could not resolve user home ID."))}var t=a.join(",");$(document).DOMNodeAppear(async function(t){m.includes($(t.target).get(0))||(m.push($(t.target).get(0)),e($(t.target)))},t),$(document).find(t).each(function(){m.includes($(this).get(0))||(m.push($(this).get(0)),e($(this)))})}function y(t){var e,a=[];for(e of t.split(/\r?\n/))(e=e.trim()).length&&(i.test(e)?a.push(e):I("Removed invalid domain "+e+" from blacklist/whitelist."));return[...new Set(a)]}function N(){if(null==P.fediact_homeinstance||!P.fediact_homeinstance)return I("Mastodon home instance is not set."),!1;if(!P.fediact_token)return I("No API token available. Are you logged in to your home instance? If yes, wait for 1-2 minutes and reload page."),!1;if(P.tokenheader={Authorization:"Bearer "+P.fediact_token},!i.test(P.fediact_homeinstance))return I("Instance setting is not a valid domain name."),!1;if("whitelist"==P.fediact_mode){if(P.fediact_whitelist=y(P.fediact_whitelist),P.fediact_whitelist.length<1)return I("Whitelist is empty or invalid."),!1}else P.fediact_blacklist=y(P.fediact_blacklist);return!0}async function j(){if(location.hostname!=P.fediact_homeinstance||(h=v("fedireply"))){if("whitelist"==P.fediact_mode){if($.inArray(location.hostname,P.fediact_whitelist)<0)return I("Current site is not in whitelist."),!1}else if(-1<$.inArray(location.hostname,P.fediact_blacklist))return I("Current site is in blacklist."),!1;var t=await _("GET",location.protocol+"//"+location.hostname+o,null);if(t){t=JSON.parse(t).uri;if(t){if(t.startsWith("http")?(t=new URL(t),P.fediact_exturi=t.hostname):P.fediact_exturi=t,!await g())return!0;I("Already logged in to this external instance.")}}}else I("Current site is your home instance.");return!1}async function F(){chrome.runtime.onMessage.addListener(async function(t,e,a){t.urlchanged&&(S=[],p=[],m=[],await x()||location.reload()),t.updatedfedisettings&&location.reload()});try{return await chrome.runtime.sendMessage({running:!0}),!0}catch(t){I(t)}return!1}function x(){return new Promise(async function(e){try{P=await(browser||chrome).storage.local.get(t)}catch(t){I(t),e(!1)}P&&N()?e(!0):e(!1)})}async function G(){await x()?await j()?h?A():F()?(O(),C()):I("Failed to initialize background script."):I("Will not process this site."):I("Could not load settings.")}G(); \ No newline at end of file diff --git a/src/nodeinserted.css b/src/nodeinserted.css index 0c3f6d8..60d2816 100644 --- a/src/nodeinserted.css +++ b/src/nodeinserted.css @@ -48,7 +48,8 @@ div.public-account-header a.logo-button, div.account-card a.logo-button, div.directory-card a.icon-button, div.detailed-status a.logo-button, -button.remote-button { +button.remote-button, +script#initial-state { -webkit-animation-name: nodeInserted !important; -webkit-animation-duration: 0.001s !important; -ms-animation-name: nodeInserted !important; diff --git a/src/nodeinserted.min.css b/src/nodeinserted.min.css index b7a2a88..8e2b8de 100644 --- a/src/nodeinserted.min.css +++ b/src/nodeinserted.min.css @@ -1 +1 @@ -@-moz-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-webkit-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-ms-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-o-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@keyframes nodeInserted{from{opacity:1}to{opacity:1}}div.status,div.detailed-status,div.detailed-status__action-bar,div.account__header button.logo-button,div.account__header button.button--follow,div.public-account-header a.logo-button,div.account-card a.logo-button,div.directory-card a.icon-button,div.detailed-status a.logo-button,button.remote-button{-webkit-animation-name:nodeInserted !important;-webkit-animation-duration:.001s !important;-ms-animation-name:nodeInserted !important;-ms-animation-duration:.001s !important;-moz-animation-name:nodeInserted !important;-moz-animation-duration:.001s !important;-o-animation-name:nodeInserted !important;-o-animation-duration:.001s !important;animation-name:nodeInserted !important;animation-duration:.001s !important} +@-moz-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-webkit-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-ms-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@-o-keyframes nodeInserted{from{opacity:1}to{opacity:1}}@keyframes nodeInserted{from{opacity:1}to{opacity:1}}div.status,div.detailed-status,div.detailed-status__action-bar,div.account__header button.logo-button,div.account__header button.button--follow,div.public-account-header a.logo-button,div.account-card a.logo-button,div.directory-card a.icon-button,div.detailed-status a.logo-button,button.remote-button,script#initial-state{-webkit-animation-name:nodeInserted !important;-webkit-animation-duration:.001s !important;-ms-animation-name:nodeInserted !important;-ms-animation-duration:.001s !important;-moz-animation-name:nodeInserted !important;-moz-animation-duration:.001s !important;-o-animation-name:nodeInserted !important;-o-animation-duration:.001s !important;animation-name:nodeInserted !important;animation-duration:.001s !important}