git » sdk » commit f0f7afc

Generate default avatars

author Stephen Paul Weber
2023-09-13 14:31:52 UTC
committer Stephen Paul Weber
2023-09-13 15:13:07 UTC
parent 316705bdf22caa94d64643bc96a226a548f7c8db

Generate default avatars

xmpp/Chat.hx +5 -0
xmpp/Color.hx +27 -0

diff --git a/xmpp/Chat.hx b/xmpp/Chat.hx
index 116a263..c365e05 100644
--- a/xmpp/Chat.hx
+++ b/xmpp/Chat.hx
@@ -5,6 +5,7 @@ import xmpp.ChatMessage;
 import xmpp.Chat;
 import xmpp.GenericStream;
 import xmpp.queries.MAMQuery;
+import xmpp.Color;
 
 enum ChatType {
 	ChatTypeDirect;
@@ -76,4 +77,8 @@ class DirectChat extends Chat {
 		client.chatActivity(this);
 		client.sendStanza(message.asStanza());
 	}
+
+	public function getPhoto(callback:(String)->Void) {
+		callback(Color.defaultPhoto(chatId, chatId.charAt(0)));
+	}
 }
diff --git a/xmpp/Color.hx b/xmpp/Color.hx
new file mode 100644
index 0000000..3a93586
--- /dev/null
+++ b/xmpp/Color.hx
@@ -0,0 +1,27 @@
+package xmpp;
+
+import hsluv.Hsluv;
+import haxe.io.Bytes;
+import haxe.crypto.Sha1;
+
+class Color {
+	public static function forString(s:String) {
+		var hash = Sha1.make(Bytes.ofString(s));
+		var hue = (hash.getUInt16(0) / 65536.0) * 360;
+		var color = new Hsluv();
+		color.hsluv_h = hue;
+		color.hsluv_s = 100;
+		color.hsluv_l = 50;
+		color.hsluvToHex();
+		return color.hex;
+	}
+
+	public static function defaultPhoto(input:String, letter:String) {
+		var hex = forString(input).substr(1);
+		return
+			'data:image/svg+xml,<svg%20xmlns="http://www.w3.org/2000/svg"%20version="1.1"%20width="15"%20height="15"%20viewBox="0%200%2015%2015">' +
+			'<rect%20style="fill:%23' + hex + ';"%20width="15"%20height="15"%20x="0"%20y="0"%20/>' +
+			'<text%20style="fill:%23ffffff;font-size:8px;font-family:sans-serif;"%20text-anchor="middle"%20dominant-baseline="central"%20x="50%25"%20y="50%25">' + letter + '</text>' +
+			'</svg>';
+	}
+}