Merge branch 'main' into add-fedibird-support

# Conflicts:
#	index.html
This commit is contained in:
Natty 2023-09-01 18:26:16 +02:00
commit 618a256002
No known key found for this signature in database
GPG key ID: BF6CB659ADEE60EC
6 changed files with 323 additions and 125 deletions

BIN
background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 559 KiB

View file

@ -12,6 +12,13 @@ async function apiRequest(url, options = null)
} }
return await fetch(url, options ?? {}) return await fetch(url, options ?? {})
.then(response => {
if (response.ok) {
return response;
}
throw new Error(`Error fetching ${url}: ${response.status} ${response.statusText}`);
})
.then(response => response.json()) .then(response => response.json())
.catch(error => { .catch(error => {
console.error(`Error fetching ${url}: ${error}`); console.error(`Error fetching ${url}: ${error}`);
@ -19,12 +26,99 @@ async function apiRequest(url, options = null)
}); });
} }
function Handle(name, instance) {
let handleObj = Object.create(Handle.prototype);
handleObj.name = name;
handleObj.instance = instance;
handleObj._baseInstance = null;
handleObj._apiInstance = null;
handleObj.profileUrl = null;
return handleObj;
}
Object.defineProperty(Handle.prototype, "baseInstance", {
get: function () {
return this._baseInstance || this.instance;
}
});
Object.defineProperty(Handle.prototype, "apiInstance", {
get: function () {
return this._apiInstance || this.instance;
}
});
Object.defineProperty(Handle.prototype, "baseHandle", {
get: function () {
return this.name + "@" + this.baseInstance;
}
});
Handle.prototype.toString = function () {
return this.name + "@" + this.instance;
};
/** /**
* @typedef {{ * @returns {Promise<Handle>} The handle WebFingered, or the original on fail
* name: string,
* instance: string,
* }} Handle
*/ */
Handle.prototype.webFinger = async function () {
if (this._baseInstance) {
return this;
}
let url = `https://${this.instance}/.well-known/webfinger?` + new URLSearchParams({
resource: `acct:${this}`
});
let webFinger = await apiRequest(url);
if (!webFinger)
return this;
let acct = webFinger["subject"];
if (typeof acct !== "string")
return this;
if (acct.startsWith("acct:")) {
acct = acct.substring("acct:".length);
}
let baseHandle = parseHandle(acct);
baseHandle._baseInstance = baseHandle.instance;
baseHandle.instance = this.instance;
const links = webFinger["links"];
if (!Array.isArray(links)) {
return baseHandle;
}
const selfLink = links.find(link => link["rel"] === "self");
if (!selfLink) {
return baseHandle;
}
try {
const url = new URL(selfLink["href"])
baseHandle._apiInstance = url.hostname;
} catch (e) {
console.error(`Error parsing WebFinger self link ${selfLink["href"]}: ${e}`);
}
const profileLink = links.find(link => link["rel"] === "http://webfinger.net/rel/profile-page");
if (profileLink?.["href"]) {
try {
baseHandle.profileUrl = new URL(profileLink["href"]);
} catch (e) {
console.error(`Error parsing WebFinger profile page link ${profileLink["href"]}: ${e}`);
}
}
return baseHandle;
};
/** /**
* @typedef {{ * @typedef {{
@ -36,6 +130,10 @@ async function apiRequest(url, options = null)
* }} FediUser * }} FediUser
*/ */
/**
* @typedef {FediUser & {conStrength: number}} RatedUser
*/
/** /**
* @typedef {{ * @typedef {{
* id: string, * id: string,
@ -195,8 +293,13 @@ class MastodonApiClient extends ApiClient {
} }
async getUserIdFromHandle(handle) { async getUserIdFromHandle(handle) {
const url = `https://${this._instance}/api/v1/accounts/lookup?acct=${handle.name}@${handle.instance}`; const url = `https://${this._instance}/api/v1/accounts/lookup?acct=${handle.baseHandle}`;
const response = await apiRequest(url, null); let response = await apiRequest(url, null);
if (!response) {
const url = `https://${this._instance}/api/v1/accounts/lookup?acct=${handle}`;
response = await apiRequest(url, null);
}
if (!response) { if (!response) {
return null; return null;
@ -433,8 +536,11 @@ class MisskeyApiClient extends ApiClient {
let id = null; let id = null;
for (const user of Array.isArray(lookup) ? lookup : []) { for (const user of Array.isArray(lookup) ? lookup : []) {
if ((user["host"] === handle.instance || this._instance === handle.instance && user["host"] === null) const isLocal = user?.["host"] === handle.instance ||
&& user["username"] === handle.name) { user?.["host"] === handle.baseInstance ||
this._instance === handle.apiInstance && user?.["host"] === null;
if (isLocal && user?.["username"] === handle.name && user["id"]) {
id = user["id"]; id = user["id"];
break; break;
} }
@ -590,7 +696,7 @@ class MisskeyApiClient extends ApiClient {
} }
} }
/** @type Map<string, ApiClient> */ /** @type {Map<string, ApiClient>} */
let instanceTypeCache = new Map(); let instanceTypeCache = new Map();
/** /**
@ -606,16 +712,9 @@ function parseHandle(fediHandle, fallbackInstance = "") {
fediHandle = fediHandle.replaceAll(" ", ""); fediHandle = fediHandle.replaceAll(" ", "");
const [name, instance] = fediHandle.split("@", 2); const [name, instance] = fediHandle.split("@", 2);
return { return new Handle(name, instance || fallbackInstance);
name: name,
instance: instance || fallbackInstance,
};
} }
/**
* @typedef {FediUser & {conStrength: number}} RatedUser
*/
async function circleMain() { async function circleMain() {
let progress = document.getElementById("outInfo"); let progress = document.getElementById("outInfo");
@ -624,7 +723,7 @@ async function circleMain() {
generateBtn.style.display = "none"; generateBtn.style.display = "none";
let fediHandle = document.getElementById("txt_mastodon_handle"); let fediHandle = document.getElementById("txt_mastodon_handle");
const selfUser = parseHandle(fediHandle.value); const selfUser = await parseHandle(fediHandle.value).webFinger();
let form = document.getElementById("generateForm"); let form = document.getElementById("generateForm");
let backend = form.backend; let backend = form.backend;
@ -637,20 +736,20 @@ async function circleMain() {
let client; let client;
switch (backend.value) { switch (backend.value) {
case "mastodon": case "mastodon":
client = new MastodonApiClient(selfUser.instance); client = new MastodonApiClient(selfUser.apiInstance);
break; break;
case "pleroma": case "pleroma":
client = new PleromaApiClient(selfUser.instance, true); client = new PleromaApiClient(selfUser.apiInstance, true);
break; break;
case "misskey": case "misskey":
client = new MisskeyApiClient(selfUser.instance); client = new MisskeyApiClient(selfUser.apiInstance);
break; break;
case "fedibird": case "fedibird":
client = new FedibirdApiClient(selfUser.instance, true); client = new FedibirdApiClient(selfUser.instance, true);
break; break;
default: default:
progress.innerText = "Detecting instance..."; progress.innerText = "Detecting instance...";
client = await ApiClient.getClient(selfUser.instance); client = await ApiClient.getClient(selfUser.apiInstance);
backend.value = client.getClientName(); backend.value = client.getClientName();
break; break;
} }
@ -704,8 +803,6 @@ async function processNotes(client, connectionList, notes) {
await evaluateNote(client, connectionList, note); await evaluateNote(client, connectionList, note);
counter++; counter++;
} }
progress.innerText = "Done :3";
} }
/** /**
@ -778,8 +875,6 @@ function showConnections(localUser, connectionList) {
// Sort dict into Array items // Sort dict into Array items
const items = [...connectionList.values()].sort((first, second) => second.conStrength - first.conStrength); const items = [...connectionList.values()].sort((first, second) => second.conStrength - first.conStrength);
console.log(items);
// Also export the Username List // Also export the Username List
let usersDivs = [ let usersDivs = [
document.getElementById("ud1"), document.getElementById("ud1"),
@ -788,12 +883,41 @@ function showConnections(localUser, connectionList) {
]; ];
usersDivs.forEach((div) => div.innerHTML = "") usersDivs.forEach((div) => div.innerHTML = "")
for (let i=0; i < items.length; i++) {
let newUser = document.createElement("p");
newUser.innerText = "@" + items[i].handle.name + "@" + items[i].handle.instance;
createUserObj(items[i]); const [inner, middle, outer] = usersDivs;
inner.innerHTML = "<div><h3>Inner Circle</h3></div>";
middle.innerHTML = "<div><h3>Middle Circle</h3></div>";
outer.innerHTML = "<div><h3>Outer Circle</h3></div>";
for (let i= 0; i < items.length; i++) {
const newUser = document.createElement("a");
newUser.className = "userItem";
newUser.innerText = items[i].handle.name;
newUser.title = items[i].name;
// I'm so sorry
newUser.href = "javascript:void(0)";
const handle = items[i].handle;
newUser.onclick = async () => {
const fingeredHandle = await handle.webFinger();
if (fingeredHandle.profileUrl)
window.open(fingeredHandle.profileUrl, "_blank");
else
alert("Could not fetch the profile URL for " + fingeredHandle.baseHandle);
};
const newUserHost = document.createElement("span");
newUserHost.className = "userHost";
newUserHost.innerText = "@" + items[i].handle.instance;
newUser.appendChild(newUserHost);
const newUserImg = document.createElement("img");
newUserImg.src = items[i].avatar;
newUserImg.alt = "";
newUserImg.className = "userImg";
newUserImg.onload = () => {
newUserImg.title = newUserImg.alt = stripName(items[i].name || items[i].handle.name) + "'s avatar";
};
newUser.prepend(newUserImg);
let udNum = 0; let udNum = 0;
if (i > numb[0]) udNum = 1; if (i > numb[0]) udNum = 1;
@ -801,15 +925,22 @@ function showConnections(localUser, connectionList) {
usersDivs[udNum].appendChild(newUser); usersDivs[udNum].appendChild(newUser);
} }
usersDivs.forEach((div) => {
const items = div.querySelectorAll(".userItem");
for (let i = 0; i < items.length - 1; i++) {
const item = items[i];
item.appendChild(document.createTextNode(", "));
}
});
const outDiv = document.getElementById("outDiv");
outDiv.style.display = "block";
document.getElementById("outSelfUser").innerText = stripName(localUser.name || localUser.handle.name);
render(items, localUser); render(items, localUser);
} }
/** function stripName(name) {
* @param {FediUser} usr return name.replaceAll(/:[a-zA-Z0-9_]+:/g, "").trim();
*/ }
function createUserObj(usr) {
let usrElement = document.createElement("div");
usrElement.innerHTML = `<img src="${usr.avatar}" width="20px">&nbsp;&nbsp;&nbsp;<b>${usr.name}</b>&nbsp;&nbsp;`;
document.getElementById("outDiv").appendChild(usrElement);
}

111
image.js
View file

@ -2,9 +2,10 @@ const toRad = (x) => x * (Math.PI / 180);
const dist = [200, 330, 450]; const dist = [200, 330, 450];
const numb = [8, 15, 26]; const numb = [8, 15, 26];
const radius = [64,58,50]; const radius = [64, 58, 50];
let userNum = 0; let userNum = 0;
let remainingImg = 0; let remainingImg = 0;
let totalImg = 0;
function render(users, selfUser) { function render(users, selfUser) {
userNum = 0; userNum = 0;
@ -12,28 +13,34 @@ function render(users, selfUser) {
const canvas = document.getElementById("canvas"); const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
const width = canvas.width; const width = canvas.width;
const height = canvas.height; const height = canvas.height;
// fill the background // fill the background
const bg_image = document.getElementById("mieke_bg"); const bg_image = document.getElementById("mieke_bg");
ctx.drawImage(bg_image, 0, 0, 1000, 1000); ctx.drawImage(bg_image, 0, 0, 1000, 1000);
loadImage(ctx, selfUser.avatar, (width/2)-110, (height/2)-110, 110, "@" + selfUser.handle.name + "@" + selfUser.handle.instance); const tasks = [];
loadImage(ctx,
selfUser.avatar,
(width / 2) - 110,
(height / 2) - 110,
110,
"@" + selfUser.handle,
tasks);
// loop over the layers // loop over the layers
for (var layerIndex=0; layerIndex<3; layerIndex++) { for (let layerIndex= 0; layerIndex < 3; layerIndex++) {
//let layerIndex = get_layer(num);
const angleSize = 360 / numb[layerIndex]; const angleSize = 360 / numb[layerIndex];
// loop over each circle of the layer // loop over each circle of the layer
for (let i = 0; i < numb[layerIndex]; i++) { for (let i = 0; i < numb[layerIndex]; i++) {
remainingImg += 1; remainingImg += 1;
// if we are trying to render a circle but we ran out of users, just exit the loop. We are done. // if we are trying to render a circle, but we ran out of users, just exit the loop. We are done.
if (userNum>=users.length) break; if (userNum >= users.length) break;
// We need an offset or the first circle will always on the same line and it looks weird // We need an offset or the first circle will always on the same line, and it looks weird
// Try removing this to see what happens // Try removing this to see what happens
const offset = layerIndex * 30; const offset = layerIndex * 30;
@ -44,34 +51,33 @@ function render(users, selfUser) {
const centerX = Math.cos(r) * dist[layerIndex] + width / 2; const centerX = Math.cos(r) * dist[layerIndex] + width / 2;
const centerY = Math.sin(r) * dist[layerIndex] + height / 2; const centerY = Math.sin(r) * dist[layerIndex] + height / 2;
loadImage( loadImage(
ctx, ctx,
users[userNum].avatar, users[userNum].avatar,
centerX - radius[layerIndex], centerX - radius[layerIndex],
centerY - radius[layerIndex], centerY - radius[layerIndex],
radius[layerIndex], radius[layerIndex],
"@" + users[userNum].handle.name + "@" + users[userNum].handle.instance "@" + users[userNum].handle,
tasks
); );
userNum++; userNum++;
} }
} }
ctx.fillStyle = "#0505AA"; totalImg = remainingImg;
ctx.fillText("Be gay do crime uwu", 10, 15);
ctx.fillStyle = "#666666";
ctx.fillText("https://data.natty.sh/fedi-circles", width-120, height-15, 110)
//ctx.fillText("@sonnenbrandi@mieke.club mit lieben Grüßen an Duiker101", width-300, height-15, 290)
};
function get_layer(i) { ctx.font = "12px sans-serif";
if (i<numb[0]) return 0; ctx.fillStyle = "silver";
if (i<numb[0]+numb[1]) return 1; ctx.fillText("Be gay do crime uwu", 10, 15);
return 2; ctx.fillStyle = "black";
ctx.fillText("https://data.natty.sh/fedi-circles", width - 170, height - 15, 160);
} }
// Load the image from the URL and draw it in a circle // Load the image from the URL and draw it in a circle
function loadImage(ctx, url, x, y, r, name) { function loadImage(ctx, url, x, y, r, name, tasks) {
let progress = document.getElementById("outInfo");
const addText = () => { const addText = () => {
ctx.font = "bold 11px sans-serif"; ctx.font = "bold 11px sans-serif";
const textWidth = ctx.measureText(name).width; const textWidth = ctx.measureText(name).width;
@ -91,33 +97,40 @@ function loadImage(ctx, url, x, y, r, name) {
} }
}; };
const img = new Image; tasks.push(addText);
img.onload = function(){
ctx.save();
ctx.beginPath();
ctx.arc(x+r, y+r, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(img,x,y,r*2,r*2);
ctx.beginPath();
ctx.arc(x+r, y+r, r, 0, Math.PI * 2, true);
ctx.clip();
ctx.closePath();
ctx.restore();
addText();
const decrementRemaining = () => {
remainingImg -= 1; remainingImg -= 1;
progress.innerText = `Loading avatars: ${totalImg - remainingImg}/${totalImg}`;
if (remainingImg <= 0) { if (remainingImg <= 0) {
document.getElementById("btn_download").href = document.getElementById("canvas").toDataURL("image/png"); progress.innerText = "Done :3";
document.getElementById("btn_download").style.display = "inline"; tasks.forEach((task) => task());
} }
};
img.onerror = function() {
addText();
}; };
img.src = url; const img = new Image();
img.onload = function(){
ctx.save();
ctx.beginPath();
ctx.arc(x + r, y + r, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(img, x, y, r * 2, r * 2);
ctx.beginPath();
ctx.arc(x + r, y + r, r, 0, Math.PI * 2, true);
ctx.clip();
ctx.closePath();
ctx.restore();
decrementRemaining();
};
img.onerror = function() {
decrementRemaining();
};
img.src = url;
} }

View file

@ -1,19 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="de"> <html lang="en">
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Fedi Circle Creator</title> <title>Fedi Circle Creator</title>
<meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<style>
</style>
<script src=""></script>
<body> <body>
<script src="create-circle.js"></script> <script src="create-circle.js"></script>
<script src="image.js"></script> <script src="image.js"></script>
<h1>Trötpty</h1> <h1>&#11093; Fedi Circle Creator</h1>
<h3><span style="text-decoration: line-through" aria-hidden="true">Mastodon</span> Fedi Circle Creator</h3>
<!-- TODO Logo? -->
<form id="generateForm" onsubmit="(async () => await circleMain())(); return false;"> <form id="generateForm" onsubmit="(async () => await circleMain())(); return false;">
<input id="txt_mastodon_handle" type="text" placeholder="@sonnenbrandi@mieke.club"> <input id="txt_mastodon_handle" type="text" placeholder="@sonnenbrandi@mieke.club">
<br><br> <br><br>
@ -22,34 +16,35 @@
<label><input type="radio" name="backend" value="mastodon" autocomplete="off"> Mastodon API</label> <label><input type="radio" name="backend" value="mastodon" autocomplete="off"> Mastodon API</label>
<label><input type="radio" name="backend" value="misskey" autocomplete="off"> Misskey API</label> <label><input type="radio" name="backend" value="misskey" autocomplete="off"> Misskey API</label>
<label><input type="radio" name="backend" value="pleroma" autocomplete="off"> Pleroma API</label> <label><input type="radio" name="backend" value="pleroma" autocomplete="off"> Pleroma API</label>
<label><input type="radio" name="backend" value="fedibird" autocomplete="off"> Fedibird API</label>
</span> </span>
<br> <br>
<button type="submit" id="generateButton">Generate circle</button> <button type="submit" id="generateButton">Generate circle</button>
</form> </form>
<span id="outInfo"></span> <span id="outInfo"></span>
<a href="" id="btn_download" class="button" download="mastodon-circle.png" style="display: none;">DOWNLOAD (klappt wsl nicht)</a>
<!-- <button id="btn_download" onClick="downloadImage()" style="display: none;">DOWNLOAD</button> -->
<br><br> <br><br>
<!-- Canvas for the final Image --> <!-- Canvas for the final Image -->
<canvas id="canvas" width="1000" height="1000"></canvas> <canvas id="canvas" width="1000" height="1000" style="background-color: gray">
</canvas>
<br> <br>
<!-- List of all people in Circle --> <!-- List of all people in Circle -->
<div id="usersDiv"> <div id="outDiv">
<div id="ud1" class="userSubDiv"></div> <em>Click a user below to visit their profile.</em>
<div id="ud2" class="userSubDiv"></div> <h2><span id="outSelfUser"></span>'s Fedi Circle</h2>
<div id="ud3" class="userSubDiv"></div>
<div id="usersDiv">
<div id="ud1" class="userSubDiv"></div>
<div id="ud2" class="userSubDiv"></div>
<div id="ud3" class="userSubDiv"></div>
</div>
</div> </div>
<br><br><br> <br><br><br>
<div id="credits" style="width: 100%;"> <div id="credits" style="width: 100%;">
<p>Added Fedibird support by <a href="https://github.com/noellabo/Mastodon-Circles">noellabo</a> </p> <p>Contribute on <a href="https://github.com/AMNatty/Mastodon-Circles">GitHub: AMNatty/Mastodon-Circles</a></p>
<p>Contribute on <a href="https://github.com/AMNatty/Mastodon-Circles">Github</a> </p> <p>Fedibird support by <a href="https://github.com/noellabo/Mastodon-Circles">noellabo</a></p>
<p>Thanks to <a href="https://twitter.com/duiker101">Duiker101</a> for creating chirpty for Twitter</p> <p>Based on <a href="https://github.com/andigandhi/Mastodon-Circles">andigandhi/Mastodon-Circles</a> </p>
<p>Original on <a href="https://github.com/andigandhi/Mastodon-Circles">Github</a> </p>
</div> </div>
<!-- output for further projects ;) -->
<div id="outDiv" style="display: none;"></div>
<!-- Preload the background image --> <!-- Preload the background image -->
<div style="display:none;"><img id="mieke_bg" src="mieke_bg.jpg" width="1000" height="1000" /></div> <div style="display:none;"><img id="mieke_bg" src="background.png" width="1000" height="1000" /></div>
</body> </body>
</html> </html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

View file

@ -1,12 +1,26 @@
body { body {
background-color: #191b22; font-family: sans-serif;
color: #d9e1e8;
font-size: 20px; font-size: 20px;
line-height: 200%; line-height: 200%;
padding-top: 75px; padding-top: 75px;
text-align: center; text-align: center;
} }
@media (prefers-color-scheme: dark) {
body {
background-color: #191b22;
color: #d9e1e8;
}
a:link {
color: #aaa0ff;
}
a:visited {
color: #dd87ff;
}
}
input[type="text"] input[type="text"]
{ {
font-size: 110%; font-size: 110%;
@ -20,28 +34,73 @@ button {
canvas { canvas {
max-width: 1000px; max-width: 1000px;
width: 90%; width: 90%;
image-rendering: smooth;
} }
a { a:hover {
text-decoration: none; text-decoration: none;
color: #AAAAAA; }
a:active {
color: #ff6200;
} }
#outDiv { #outDiv {
font-size: 20%; display: none;
margin-top: 30px;
}
#outInfo {
font-style: italic;
} }
#usersDiv { #usersDiv {
margin-top: 30px; line-height: 150%;
line-height: 100%;
font-size: 100%; font-size: 100%;
} display: flex;
justify-content: center;
#credits { gap: 2em;
min-width: 90%; flex-wrap: wrap;
} }
.userSubDiv { .userSubDiv {
min-width: 400px; min-width: 400px;
max-width: 90%; max-width: 90%;
} display: flex;
flex-wrap: wrap;
flex-direction: column;
align-items: start;
}
.userItem {
display: inline;
text-align: left;
}
.userItem {
text-decoration: underline 1px;
text-decoration-style: dotted;
}
.userItem:hover {
text-decoration-style: solid;
}
.userHost {
opacity: 0.75;
}
.userImg {
border-radius: 50%;
width: 1em;
height: 1em;
vertical-align: middle;
user-select: none;
-webkit-user-select: none;
margin-right: 0.5em;
}
#credits {
min-width: 90%;
}