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 ?? {})
.then(response => {
if (response.ok) {
return response;
}
throw new Error(`Error fetching ${url}: ${response.status} ${response.statusText}`);
})
.then(response => response.json())
.catch(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 {{
* name: string,
* instance: string,
* }} Handle
* @returns {Promise<Handle>} The handle WebFingered, or the original on fail
*/
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 {{
@ -36,6 +130,10 @@ async function apiRequest(url, options = null)
* }} FediUser
*/
/**
* @typedef {FediUser & {conStrength: number}} RatedUser
*/
/**
* @typedef {{
* id: string,
@ -195,8 +293,13 @@ class MastodonApiClient extends ApiClient {
}
async getUserIdFromHandle(handle) {
const url = `https://${this._instance}/api/v1/accounts/lookup?acct=${handle.name}@${handle.instance}`;
const response = await apiRequest(url, null);
const url = `https://${this._instance}/api/v1/accounts/lookup?acct=${handle.baseHandle}`;
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) {
return null;
@ -433,8 +536,11 @@ class MisskeyApiClient extends ApiClient {
let id = null;
for (const user of Array.isArray(lookup) ? lookup : []) {
if ((user["host"] === handle.instance || this._instance === handle.instance && user["host"] === null)
&& user["username"] === handle.name) {
const isLocal = user?.["host"] === handle.instance ||
user?.["host"] === handle.baseInstance ||
this._instance === handle.apiInstance && user?.["host"] === null;
if (isLocal && user?.["username"] === handle.name && user["id"]) {
id = user["id"];
break;
}
@ -590,7 +696,7 @@ class MisskeyApiClient extends ApiClient {
}
}
/** @type Map<string, ApiClient> */
/** @type {Map<string, ApiClient>} */
let instanceTypeCache = new Map();
/**
@ -606,16 +712,9 @@ function parseHandle(fediHandle, fallbackInstance = "") {
fediHandle = fediHandle.replaceAll(" ", "");
const [name, instance] = fediHandle.split("@", 2);
return {
name: name,
instance: instance || fallbackInstance,
};
return new Handle(name, instance || fallbackInstance);
}
/**
* @typedef {FediUser & {conStrength: number}} RatedUser
*/
async function circleMain() {
let progress = document.getElementById("outInfo");
@ -624,7 +723,7 @@ async function circleMain() {
generateBtn.style.display = "none";
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 backend = form.backend;
@ -637,20 +736,20 @@ async function circleMain() {
let client;
switch (backend.value) {
case "mastodon":
client = new MastodonApiClient(selfUser.instance);
client = new MastodonApiClient(selfUser.apiInstance);
break;
case "pleroma":
client = new PleromaApiClient(selfUser.instance, true);
client = new PleromaApiClient(selfUser.apiInstance, true);
break;
case "misskey":
client = new MisskeyApiClient(selfUser.instance);
client = new MisskeyApiClient(selfUser.apiInstance);
break;
case "fedibird":
client = new FedibirdApiClient(selfUser.instance, true);
break;
default:
progress.innerText = "Detecting instance...";
client = await ApiClient.getClient(selfUser.instance);
client = await ApiClient.getClient(selfUser.apiInstance);
backend.value = client.getClientName();
break;
}
@ -704,8 +803,6 @@ async function processNotes(client, connectionList, notes) {
await evaluateNote(client, connectionList, note);
counter++;
}
progress.innerText = "Done :3";
}
/**
@ -778,8 +875,6 @@ function showConnections(localUser, connectionList) {
// Sort dict into Array items
const items = [...connectionList.values()].sort((first, second) => second.conStrength - first.conStrength);
console.log(items);
// Also export the Username List
let usersDivs = [
document.getElementById("ud1"),
@ -789,11 +884,40 @@ function showConnections(localUser, connectionList) {
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;
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>";
createUserObj(items[i]);
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;
if (i > numb[0]) udNum = 1;
@ -801,15 +925,22 @@ function showConnections(localUser, connectionList) {
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);
}
/**
* @param {FediUser} usr
*/
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);
function stripName(name) {
return name.replaceAll(/:[a-zA-Z0-9_]+:/g, "").trim();
}

View file

@ -2,9 +2,10 @@ const toRad = (x) => x * (Math.PI / 180);
const dist = [200, 330, 450];
const numb = [8, 15, 26];
const radius = [64,58,50];
const radius = [64, 58, 50];
let userNum = 0;
let remainingImg = 0;
let totalImg = 0;
function render(users, selfUser) {
userNum = 0;
@ -20,20 +21,26 @@ function render(users, selfUser) {
const bg_image = document.getElementById("mieke_bg");
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
for (var layerIndex=0; layerIndex<3; layerIndex++) {
//let layerIndex = get_layer(num);
for (let layerIndex= 0; layerIndex < 3; layerIndex++) {
const angleSize = 360 / numb[layerIndex];
// loop over each circle of the layer
for (let i = 0; i < numb[layerIndex]; i++) {
remainingImg += 1;
// 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;
// We need an offset or the first circle will always on the same line and it looks weird
// 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;
// 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
const offset = layerIndex * 30;
@ -50,28 +57,27 @@ function render(users, selfUser) {
centerX - radius[layerIndex],
centerY - radius[layerIndex],
radius[layerIndex],
"@" + users[userNum].handle.name + "@" + users[userNum].handle.instance
"@" + users[userNum].handle,
tasks
);
userNum++;
}
}
ctx.fillStyle = "#0505AA";
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)
};
totalImg = remainingImg;
function get_layer(i) {
if (i<numb[0]) return 0;
if (i<numb[0]+numb[1]) return 1;
return 2;
ctx.font = "12px sans-serif";
ctx.fillStyle = "silver";
ctx.fillText("Be gay do crime uwu", 10, 15);
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
function loadImage(ctx, url, x, y, r, name) {
function loadImage(ctx, url, x, y, r, name, tasks) {
let progress = document.getElementById("outInfo");
const addText = () => {
ctx.font = "bold 11px sans-serif";
const textWidth = ctx.measureText(name).width;
@ -91,32 +97,39 @@ function loadImage(ctx, url, x, y, r, name) {
}
};
const img = new Image;
tasks.push(addText);
const decrementRemaining = () => {
remainingImg -= 1;
progress.innerText = `Loading avatars: ${totalImg - remainingImg}/${totalImg}`;
if (remainingImg <= 0) {
progress.innerText = "Done :3";
tasks.forEach((task) => task());
}
};
const img = new Image();
img.onload = function(){
ctx.save();
ctx.beginPath();
ctx.arc(x+r, y+r, r, 0, Math.PI * 2, true);
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.drawImage(img, x, y, r * 2, r * 2);
ctx.beginPath();
ctx.arc(x+r, y+r, r, 0, Math.PI * 2, true);
ctx.arc(x + r, y + r, r, 0, Math.PI * 2, true);
ctx.clip();
ctx.closePath();
ctx.restore();
addText();
remainingImg -= 1;
if (remainingImg <= 0) {
document.getElementById("btn_download").href = document.getElementById("canvas").toDataURL("image/png");
document.getElementById("btn_download").style.display = "inline";
}
decrementRemaining();
};
img.onerror = function() {
addText();
decrementRemaining();
};
img.src = url;

View file

@ -1,19 +1,13 @@
<!DOCTYPE html>
<html lang="de">
<html lang="en">
<meta charset="UTF-8">
<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">
<style>
</style>
<script src=""></script>
<body>
<script src="create-circle.js"></script>
<script src="image.js"></script>
<h1>Trötpty</h1>
<h3><span style="text-decoration: line-through" aria-hidden="true">Mastodon</span> Fedi Circle Creator</h3>
<!-- TODO Logo? -->
<h1>&#11093; Fedi Circle Creator</h1>
<form id="generateForm" onsubmit="(async () => await circleMain())(); return false;">
<input id="txt_mastodon_handle" type="text" placeholder="@sonnenbrandi@mieke.club">
<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="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="fedibird" autocomplete="off"> Fedibird API</label>
</span>
<br>
<button type="submit" id="generateButton">Generate circle</button>
</form>
<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>
<!-- 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>
<!-- List of all people in Circle -->
<div id="outDiv">
<em>Click a user below to visit their profile.</em>
<h2><span id="outSelfUser"></span>'s Fedi Circle</h2>
<div id="usersDiv">
<div id="ud1" class="userSubDiv"></div>
<div id="ud2" class="userSubDiv"></div>
<div id="ud3" class="userSubDiv"></div>
</div>
</div>
<br><br><br>
<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</a> </p>
<p>Thanks to <a href="https://twitter.com/duiker101">Duiker101</a> for creating chirpty for Twitter</p>
<p>Original on <a href="https://github.com/andigandhi/Mastodon-Circles">Github</a> </p>
<p>Contribute on <a href="https://github.com/AMNatty/Mastodon-Circles">GitHub: AMNatty/Mastodon-Circles</a></p>
<p>Fedibird support by <a href="https://github.com/noellabo/Mastodon-Circles">noellabo</a></p>
<p>Based on <a href="https://github.com/andigandhi/Mastodon-Circles">andigandhi/Mastodon-Circles</a> </p>
</div>
<!-- output for further projects ;) -->
<div id="outDiv" style="display: none;"></div>
<!-- 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>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

View file

@ -1,12 +1,26 @@
body {
background-color: #191b22;
color: #d9e1e8;
font-family: sans-serif;
font-size: 20px;
line-height: 200%;
padding-top: 75px;
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"]
{
font-size: 110%;
@ -20,28 +34,73 @@ button {
canvas {
max-width: 1000px;
width: 90%;
image-rendering: smooth;
}
a {
a:hover {
text-decoration: none;
color: #AAAAAA;
}
a:active {
color: #ff6200;
}
#outDiv {
font-size: 20%;
display: none;
margin-top: 30px;
}
#outInfo {
font-style: italic;
}
#usersDiv {
margin-top: 30px;
line-height: 100%;
line-height: 150%;
font-size: 100%;
}
#credits {
min-width: 90%;
display: flex;
justify-content: center;
gap: 2em;
flex-wrap: wrap;
}
.userSubDiv {
min-width: 400px;
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%;
}