Add native NeoUI SIP, Email, IRCv3, Tox, and Kopher SmallWeb plugins
This commit is contained in:
1 parent
0656042f7f
commit
be9ec9af0b
45 files changed
+6544
-13
No files matched your search
@@ -503,12 +503,19 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
statusNoticeUntilMs = nowMs() + 2000;
|
||||
};
|
||||
|
||||
auto isVoipCallId = [&](const std::string& cid) -> bool {
|
||||
return cid.rfind("sip:", 0) == 0 || cid.rfind("tox:", 0) == 0;
|
||||
};
|
||||
|
||||
auto setSpeakerRoute = [&](bool toSpeaker) {
|
||||
speakerOn = toSpeaker;
|
||||
bool jackPlugged = (readIntFile("/tmp/sxmo_jack_plugged", 0) == 1);
|
||||
long hwVol = pctToHwVol(callVolumePct, toSpeaker, !toSpeaker && jackPlugged);
|
||||
alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", true);
|
||||
alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !micMuted);
|
||||
bool voip = isVoipCallId(callId);
|
||||
if (!voip) {
|
||||
alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", true);
|
||||
alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !micMuted);
|
||||
}
|
||||
alsa.setEnum("CIC1 MUX", 0);
|
||||
if (!micMuted) {
|
||||
alsa.setEnum("DEC1 MUX", savedMicMux > 0 ? savedMicMux : 1);
|
||||
@@ -760,9 +767,14 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
XftColor* stateCol = &colBlue;
|
||||
unsigned long stateAccentPx = theme.spec.accent;
|
||||
|
||||
std::string simTag = (activeSimSlot == 1 || activeSimSlot == 2)
|
||||
? (" [SIM " + std::to_string(activeSimSlot) + "]")
|
||||
: "";
|
||||
std::string simTag;
|
||||
if (activeSimSlot == 3 || callId.rfind("sip:", 0) == 0) {
|
||||
simTag = " [SIP]";
|
||||
} else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) {
|
||||
simTag = " [TOX]";
|
||||
} else if (activeSimSlot == 1 || activeSimSlot == 2) {
|
||||
simTag = " [SIM " + std::to_string(activeSimSlot) + "]";
|
||||
}
|
||||
if (callState == CallState::SelectSim) {
|
||||
stateIcon = kIconOutCall;
|
||||
stateBadge = "SELECT SIM CARD";
|
||||
@@ -1233,7 +1245,11 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
setSpeakerRoute(false);
|
||||
render();
|
||||
|
||||
if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
if (cid.rfind("sip:", 0) == 0) {
|
||||
sendPluginCommand("sip", "CALL_ACCEPT " + cid);
|
||||
} else if (cid.rfind("tox:", 0) == 0) {
|
||||
sendPluginCommand("tox", "CALL_ACCEPT " + cid);
|
||||
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str());
|
||||
}
|
||||
};
|
||||
@@ -1245,7 +1261,11 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
ringMuted = true;
|
||||
stopRingingJobs();
|
||||
std::string cid = resolveActiveModemCallId();
|
||||
if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
if (cid.rfind("sip:", 0) == 0) {
|
||||
sendPluginCommand("sip", "CALL_MUTE_RING " + cid);
|
||||
} else if (cid.rfind("tox:", 0) == 0) {
|
||||
sendPluginCommand("tox", "CALL_MUTE_RING " + cid);
|
||||
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str());
|
||||
}
|
||||
statusNotice = "Ringtone silenced";
|
||||
@@ -1289,7 +1309,11 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
std::string cid = resolveActiveModemCallId();
|
||||
bool wasIncoming = (callState == CallState::Incoming);
|
||||
stopRingingJobs();
|
||||
if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
if (cid.rfind("sip:", 0) == 0) {
|
||||
sendPluginCommand("sip", "CALL_HANGUP " + cid);
|
||||
} else if (cid.rfind("tox:", 0) == 0) {
|
||||
sendPluginCommand("tox", "CALL_HANGUP " + cid);
|
||||
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
runAsyncArgv("sxmo_modemcall.sh", "hangup", cid.c_str());
|
||||
} else {
|
||||
runAsyncCmd("mmcli -m any --voice-hangup-all >/dev/null 2>&1");
|
||||
@@ -1303,7 +1327,10 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
dtmfSent.erase(0, dtmfSent.size() - 16);
|
||||
}
|
||||
std::string cid = resolveActiveModemCallId();
|
||||
if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
|
||||
if (cid.rfind("sip:", 0) == 0) {
|
||||
sendPluginCommand("sip", std::string("CALL_DTMF ") + ch);
|
||||
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" &&
|
||||
cid.rfind("tox:", 0) != 0) {
|
||||
if (cid.rfind("sub", 0) == 0) {
|
||||
char cmd[160];
|
||||
std::snprintf(cmd, sizeof(cmd),
|
||||
@@ -1473,7 +1500,7 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
};
|
||||
|
||||
auto syncModemCalls = [&]() {
|
||||
if (callId == "sim" || callId == "test") {
|
||||
if (callId == "sim" || callId == "test" || isVoipCallId(callId)) {
|
||||
return;
|
||||
}
|
||||
std::string foundId;
|
||||
@@ -1690,6 +1717,14 @@ int callscreen_run_main(int argc, char** argv) {
|
||||
}
|
||||
|
||||
auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) {
|
||||
if (tagStr == "SIP" || cidStr.rfind("sip:", 0) == 0) {
|
||||
activeSimSlot = 3;
|
||||
return;
|
||||
}
|
||||
if (tagStr == "TOX" || cidStr.rfind("tox:", 0) == 0) {
|
||||
activeSimSlot = 4;
|
||||
return;
|
||||
}
|
||||
simInfo = queryDualSimInfo();
|
||||
if (tagStr == "SIM1") {
|
||||
activeSimSlot = 1;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2067,8 +2067,7 @@ int runFilesApp(int argc, char** argv) {
|
||||
drawUI();
|
||||
} else {
|
||||
editLastTapDigit = -1;
|
||||
int lineLen =
|
||||
static_cast<int>(editLines[editCursorRow].size());
|
||||
size_t lineLen = editLines[editCursorRow].size();
|
||||
if (editCursorCol < lineLen) {
|
||||
editCursorCol =
|
||||
nextUtf8Pos(editLines[editCursorRow], editCursorCol);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,738 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-only
|
||||
// Shared C++20 TCP / OpenSSL TLS / STARTTLS / Digest / MIME / HTTPS helpers
|
||||
// for Bananarchy NeoUI DWM plugins (SIP, Email, IRC, SmallWeb, GPS/OSM).
|
||||
|
||||
#ifndef DWM_PLUGINS_NET_TLS_H
|
||||
#define DWM_PLUGINS_NET_TLS_H
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "phone_data.h"
|
||||
|
||||
namespace bananarchy {
|
||||
|
||||
inline void ensureOpenSslInit() {
|
||||
static bool initialized = false;
|
||||
if (!initialized) {
|
||||
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
|
||||
OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
|
||||
nullptr);
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
inline std::string md5Hex(const std::string& input) {
|
||||
ensureOpenSslInit();
|
||||
unsigned char digest[EVP_MAX_MD_SIZE];
|
||||
unsigned int digestLen = 0;
|
||||
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
|
||||
if (!ctx) {
|
||||
return "";
|
||||
}
|
||||
if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) != 1 ||
|
||||
EVP_DigestUpdate(ctx, input.data(), input.size()) != 1 ||
|
||||
EVP_DigestFinal_ex(ctx, digest, &digestLen) != 1) {
|
||||
EVP_MD_CTX_free(ctx);
|
||||
return "";
|
||||
}
|
||||
EVP_MD_CTX_free(ctx);
|
||||
char hex[64];
|
||||
for (unsigned int i = 0; i < digestLen && i < 16; ++i) {
|
||||
std::snprintf(hex + i * 2, 3, "%02x", digest[i]);
|
||||
}
|
||||
hex[digestLen * 2] = '\0';
|
||||
return std::string(hex);
|
||||
}
|
||||
|
||||
inline std::string randomHexToken(size_t numBytes = 8) {
|
||||
ensureOpenSslInit();
|
||||
std::vector<unsigned char> buf(numBytes);
|
||||
if (RAND_bytes(buf.data(), static_cast<int>(numBytes)) != 1) {
|
||||
uint64_t t = static_cast<uint64_t>(nowMs()) ^
|
||||
(static_cast<uint64_t>(::getpid()) << 16);
|
||||
for (size_t i = 0; i < numBytes; ++i) {
|
||||
buf[i] = static_cast<unsigned char>((t >> ((i % 8) * 8)) & 0xff);
|
||||
t = t * 6364136223846793005ULL + 1442695040888963407ULL;
|
||||
}
|
||||
}
|
||||
std::string out;
|
||||
out.reserve(numBytes * 2);
|
||||
char tmp[4];
|
||||
for (size_t i = 0; i < numBytes; ++i) {
|
||||
std::snprintf(tmp, sizeof(tmp), "%02x", buf[i]);
|
||||
out += tmp;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string base64Encode(const void* rawData, size_t len) {
|
||||
static constexpr char kTable[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
const auto* in = static_cast<const unsigned char*>(rawData);
|
||||
std::string out;
|
||||
out.reserve(((len + 2) / 3) * 4);
|
||||
for (size_t i = 0; i < len; i += 3) {
|
||||
uint32_t v = static_cast<uint32_t>(in[i]) << 16;
|
||||
if (i + 1 < len) v |= static_cast<uint32_t>(in[i + 1]) << 8;
|
||||
if (i + 2 < len) v |= static_cast<uint32_t>(in[i + 2]);
|
||||
out.push_back(kTable[(v >> 18) & 0x3f]);
|
||||
out.push_back(kTable[(v >> 12) & 0x3f]);
|
||||
out.push_back((i + 1 < len) ? kTable[(v >> 6) & 0x3f] : '=');
|
||||
out.push_back((i + 2 < len) ? kTable[v & 0x3f] : '=');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string base64EncodeStr(const std::string& s) {
|
||||
return base64Encode(s.data(), s.size());
|
||||
}
|
||||
|
||||
inline std::string base64Decode(const std::string& input) {
|
||||
std::string out;
|
||||
out.reserve((input.size() * 3) / 4);
|
||||
uint32_t val = 0;
|
||||
int valb = -8;
|
||||
for (unsigned char c : input) {
|
||||
int d = -1;
|
||||
if (c >= 'A' && c <= 'Z') d = c - 'A';
|
||||
else if (c >= 'a' && c <= 'z') d = c - 'a' + 26;
|
||||
else if (c >= '0' && c <= '9') d = c - '0' + 52;
|
||||
else if (c == '+') d = 62;
|
||||
else if (c == '/') d = 63;
|
||||
else if (c == '=') break;
|
||||
else continue;
|
||||
val = (val << 6) + static_cast<uint32_t>(d);
|
||||
valb += 6;
|
||||
if (valb >= 0) {
|
||||
out.push_back(static_cast<char>((val >> valb) & 0xff));
|
||||
valb -= 8;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string decodeQuotedPrintable(const std::string& input,
|
||||
bool underscoreAsSpace = false) {
|
||||
std::string out;
|
||||
out.reserve(input.size());
|
||||
for (size_t i = 0; i < input.size(); ++i) {
|
||||
if (input[i] == '=' && i + 1 < input.size()) {
|
||||
if (input[i + 1] == '\r' && i + 2 < input.size() && input[i + 2] == '\n') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (input[i + 1] == '\n') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (i + 2 < input.size()) {
|
||||
int hi = themeHexNibble(input[i + 1]);
|
||||
int lo = themeHexNibble(input[i + 2]);
|
||||
if (hi >= 0 && lo >= 0) {
|
||||
out.push_back(static_cast<char>((hi << 4) | lo));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else if (underscoreAsSpace && input[i] == '_') {
|
||||
out.push_back(' ');
|
||||
continue;
|
||||
}
|
||||
out.push_back(input[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Decode RFC 2047 encoded words (=?utf-8?B?...?= or =?utf-8?Q?...?=)
|
||||
inline std::string decodeMimeHeader(const std::string& raw) {
|
||||
std::string out;
|
||||
size_t pos = 0;
|
||||
while (pos < raw.size()) {
|
||||
size_t start = raw.find("=?", pos);
|
||||
if (start == std::string::npos) {
|
||||
out.append(raw.substr(pos));
|
||||
break;
|
||||
}
|
||||
std::string between = raw.substr(pos, start - pos);
|
||||
bool onlySpace = !out.empty();
|
||||
for (char c : between) {
|
||||
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
|
||||
onlySpace = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!onlySpace) {
|
||||
out.append(between);
|
||||
}
|
||||
size_t q1 = raw.find('?', start + 2);
|
||||
if (q1 == std::string::npos || q1 + 3 >= raw.size() || raw[q1 + 2] != '?') {
|
||||
out.append(raw.substr(start, 2));
|
||||
pos = start + 2;
|
||||
continue;
|
||||
}
|
||||
char enc = static_cast<char>(std::toupper(static_cast<unsigned char>(raw[q1 + 1])));
|
||||
size_t end = raw.find("?=", q1 + 3);
|
||||
if (end == std::string::npos) {
|
||||
out.append(raw.substr(start));
|
||||
break;
|
||||
}
|
||||
std::string payload = raw.substr(q1 + 3, end - (q1 + 3));
|
||||
if (enc == 'B') {
|
||||
out.append(base64Decode(payload));
|
||||
} else if (enc == 'Q') {
|
||||
out.append(decodeQuotedPrintable(payload, true));
|
||||
} else {
|
||||
out.append(payload);
|
||||
}
|
||||
pos = end + 2;
|
||||
}
|
||||
// Strip CR/LF in single-line headers
|
||||
std::string clean;
|
||||
clean.reserve(out.size());
|
||||
for (char c : out) {
|
||||
if (c == '\r' || c == '\n') {
|
||||
if (!clean.empty() && clean.back() != ' ') {
|
||||
clean.push_back(' ');
|
||||
}
|
||||
} else {
|
||||
clean.push_back(c);
|
||||
}
|
||||
}
|
||||
return trimStr(clean);
|
||||
}
|
||||
|
||||
inline std::string stripHtmlTags(const std::string& html) {
|
||||
std::string out;
|
||||
out.reserve(html.size());
|
||||
bool inTag = false;
|
||||
bool inStyleOrScript = false;
|
||||
std::string tagName;
|
||||
for (size_t i = 0; i < html.size(); ++i) {
|
||||
char c = html[i];
|
||||
if (c == '<') {
|
||||
inTag = true;
|
||||
tagName.clear();
|
||||
continue;
|
||||
}
|
||||
if (c == '>') {
|
||||
inTag = false;
|
||||
std::string low = toLowerStr(trimStr(tagName));
|
||||
if (low.rfind("script", 0) == 0 || low.rfind("style", 0) == 0) {
|
||||
inStyleOrScript = true;
|
||||
} else if (low.rfind("/script", 0) == 0 || low.rfind("/style", 0) == 0) {
|
||||
inStyleOrScript = false;
|
||||
} else if (low == "br" || low == "br/" || low == "p" || low == "/p" ||
|
||||
low == "div" || low == "/div" || low == "li" || low == "tr") {
|
||||
if (!out.empty() && out.back() != '\n') {
|
||||
out.push_back('\n');
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (inTag) {
|
||||
if (tagName.size() < 24) {
|
||||
tagName.push_back(c);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (inStyleOrScript) {
|
||||
continue;
|
||||
}
|
||||
if (c == '&') {
|
||||
size_t semi = html.find(';', i + 1);
|
||||
if (semi != std::string::npos && semi - i <= 10) {
|
||||
std::string ent = toLowerStr(html.substr(i + 1, semi - i - 1));
|
||||
if (ent == "amp") { out.push_back('&'); i = semi; continue; }
|
||||
if (ent == "lt") { out.push_back('<'); i = semi; continue; }
|
||||
if (ent == "gt") { out.push_back('>'); i = semi; continue; }
|
||||
if (ent == "quot") { out.push_back('"'); i = semi; continue; }
|
||||
if (ent == "apos" || ent == "#39") { out.push_back('\''); i = semi; continue; }
|
||||
if (ent == "nbsp") { out.push_back(' '); i = semi; continue; }
|
||||
}
|
||||
}
|
||||
out.push_back(c);
|
||||
}
|
||||
return trimStr(out);
|
||||
}
|
||||
|
||||
class NetStream {
|
||||
public:
|
||||
NetStream() = default;
|
||||
~NetStream() { close(); }
|
||||
|
||||
NetStream(const NetStream&) = delete;
|
||||
NetStream& operator=(const NetStream&) = delete;
|
||||
|
||||
int fd() const { return fd_; }
|
||||
bool isConnected() const { return fd_ >= 0; }
|
||||
bool isTls() const { return ssl_ != nullptr; }
|
||||
const std::string& lastError() const { return lastErr_; }
|
||||
|
||||
void close() {
|
||||
if (ssl_) {
|
||||
SSL_shutdown(ssl_);
|
||||
SSL_free(ssl_);
|
||||
ssl_ = nullptr;
|
||||
}
|
||||
if (ctx_) {
|
||||
SSL_CTX_free(ctx_);
|
||||
ctx_ = nullptr;
|
||||
}
|
||||
if (fd_ >= 0) {
|
||||
::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
rxBuf_.clear();
|
||||
}
|
||||
|
||||
bool connectTcp(const std::string& host, int port, int timeoutMs = 6000) {
|
||||
close();
|
||||
struct addrinfo hints {};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
struct addrinfo* res = nullptr;
|
||||
char portStr[16];
|
||||
std::snprintf(portStr, sizeof(portStr), "%d", port);
|
||||
int rc = ::getaddrinfo(host.c_str(), portStr, &hints, &res);
|
||||
if (rc != 0 || !res) {
|
||||
lastErr_ = std::string("DNS failed: ") + host;
|
||||
return false;
|
||||
}
|
||||
|
||||
int sock = -1;
|
||||
for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) {
|
||||
sock = ::socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC,
|
||||
p->ai_protocol);
|
||||
if (sock < 0) continue;
|
||||
int one = 1;
|
||||
::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
|
||||
int c = ::connect(sock, p->ai_addr, p->ai_addrlen);
|
||||
if (c == 0) {
|
||||
break;
|
||||
}
|
||||
if (errno == EINPROGRESS) {
|
||||
struct pollfd pfd { sock, POLLOUT, 0 };
|
||||
if (::poll(&pfd, 1, timeoutMs) > 0 && (pfd.revents & POLLOUT)) {
|
||||
int soErr = 0;
|
||||
socklen_t sl = sizeof(soErr);
|
||||
if (::getsockopt(sock, SOL_SOCKET, SO_ERROR, &soErr, &sl) == 0 &&
|
||||
soErr == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
::close(sock);
|
||||
sock = -1;
|
||||
}
|
||||
::freeaddrinfo(res);
|
||||
|
||||
if (sock < 0) {
|
||||
lastErr_ = "Connection failed to " + host + ":" + portStr;
|
||||
return false;
|
||||
}
|
||||
fd_ = sock;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool startTls(const std::string& serverName, int timeoutMs = 6000) {
|
||||
if (fd_ < 0) {
|
||||
lastErr_ = "Socket not connected";
|
||||
return false;
|
||||
}
|
||||
ensureOpenSslInit();
|
||||
ctx_ = SSL_CTX_new(TLS_client_method());
|
||||
if (!ctx_) {
|
||||
lastErr_ = "SSL_CTX_new failed";
|
||||
return false;
|
||||
}
|
||||
SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
|
||||
SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
|
||||
|
||||
ssl_ = SSL_new(ctx_);
|
||||
if (!ssl_) {
|
||||
lastErr_ = "SSL_new failed";
|
||||
return false;
|
||||
}
|
||||
if (!serverName.empty()) {
|
||||
SSL_set_tlsext_host_name(ssl_, serverName.c_str());
|
||||
}
|
||||
SSL_set_fd(ssl_, fd_);
|
||||
|
||||
int64_t deadline = nowMs() + timeoutMs;
|
||||
while (nowMs() < deadline) {
|
||||
int r = SSL_connect(ssl_);
|
||||
if (r == 1) {
|
||||
return true;
|
||||
}
|
||||
int err = SSL_get_error(ssl_, r);
|
||||
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||
struct pollfd pfd {
|
||||
fd_, static_cast<short>(err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT), 0
|
||||
};
|
||||
int waitMs = static_cast<int>(std::max<int64_t>(10, deadline - nowMs()));
|
||||
if (::poll(&pfd, 1, std::min(waitMs, 250)) < 0 && errno != EINTR) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
lastErr_ = "TLS handshake failed with " + serverName;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool sendAll(const void* data, size_t len, int timeoutMs = 5000) {
|
||||
if (fd_ < 0) return false;
|
||||
const auto* ptr = static_cast<const char*>(data);
|
||||
size_t sent = 0;
|
||||
int64_t deadline = nowMs() + timeoutMs;
|
||||
while (sent < len && nowMs() < deadline) {
|
||||
if (ssl_) {
|
||||
int w = SSL_write(ssl_, ptr + sent, static_cast<int>(len - sent));
|
||||
if (w > 0) {
|
||||
sent += static_cast<size_t>(w);
|
||||
continue;
|
||||
}
|
||||
int err = SSL_get_error(ssl_, w);
|
||||
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||
struct pollfd pfd {
|
||||
fd_, static_cast<short>(err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT), 0
|
||||
};
|
||||
::poll(&pfd, 1, 100);
|
||||
continue;
|
||||
}
|
||||
lastErr_ = "TLS write failed";
|
||||
return false;
|
||||
} else {
|
||||
ssize_t w = ::send(fd_, ptr + sent, len - sent, MSG_NOSIGNAL);
|
||||
if (w > 0) {
|
||||
sent += static_cast<size_t>(w);
|
||||
continue;
|
||||
}
|
||||
if (w < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
|
||||
struct pollfd pfd { fd_, POLLOUT, 0 };
|
||||
::poll(&pfd, 1, 100);
|
||||
continue;
|
||||
}
|
||||
lastErr_ = "Socket write failed";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return sent == len;
|
||||
}
|
||||
|
||||
bool sendStr(const std::string& s, int timeoutMs = 5000) {
|
||||
return sendAll(s.data(), s.size(), timeoutMs);
|
||||
}
|
||||
|
||||
// Pump non-blocking incoming bytes into rxBuf_. Returns <0 on EOF/error.
|
||||
int pumpRx(int waitMs = 0) {
|
||||
if (fd_ < 0) return -1;
|
||||
if (waitMs > 0 && (!ssl_ || SSL_pending(ssl_) == 0)) {
|
||||
struct pollfd pfd { fd_, POLLIN, 0 };
|
||||
int pr = ::poll(&pfd, 1, waitMs);
|
||||
if (pr == 0) return 0;
|
||||
if (pr < 0) return (errno == EINTR) ? 0 : -1;
|
||||
}
|
||||
int totalAdded = 0;
|
||||
char buf[4096];
|
||||
while (true) {
|
||||
if (ssl_) {
|
||||
int n = SSL_read(ssl_, buf, sizeof(buf));
|
||||
if (n > 0) {
|
||||
rxBuf_.append(buf, static_cast<size_t>(n));
|
||||
totalAdded += n;
|
||||
continue;
|
||||
}
|
||||
int err = SSL_get_error(ssl_, n);
|
||||
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||
break;
|
||||
}
|
||||
return totalAdded > 0 ? totalAdded : -1;
|
||||
} else {
|
||||
ssize_t n = ::recv(fd_, buf, sizeof(buf), 0);
|
||||
if (n > 0) {
|
||||
rxBuf_.append(buf, static_cast<size_t>(n));
|
||||
totalAdded += static_cast<int>(n);
|
||||
continue;
|
||||
}
|
||||
if (n == 0) {
|
||||
return totalAdded > 0 ? totalAdded : -1;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
|
||||
break;
|
||||
}
|
||||
return totalAdded > 0 ? totalAdded : -1;
|
||||
}
|
||||
}
|
||||
return totalAdded;
|
||||
}
|
||||
|
||||
bool popLine(std::string& outLine) {
|
||||
size_t nl = rxBuf_.find('\n');
|
||||
if (nl == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
outLine = rxBuf_.substr(0, nl);
|
||||
if (!outLine.empty() && outLine.back() == '\r') {
|
||||
outLine.pop_back();
|
||||
}
|
||||
rxBuf_.erase(0, nl + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readLine(std::string& outLine, int timeoutMs = 5000) {
|
||||
if (popLine(outLine)) {
|
||||
return true;
|
||||
}
|
||||
int64_t deadline = nowMs() + timeoutMs;
|
||||
while (nowMs() < deadline) {
|
||||
int waitMs = static_cast<int>(std::min<int64_t>(150, deadline - nowMs()));
|
||||
int r = pumpRx(std::max(1, waitMs));
|
||||
if (popLine(outLine)) {
|
||||
return true;
|
||||
}
|
||||
if (r < 0) {
|
||||
if (!rxBuf_.empty()) {
|
||||
outLine = rxBuf_;
|
||||
if (!outLine.empty() && outLine.back() == '\r') outLine.pop_back();
|
||||
rxBuf_.clear();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return popLine(outLine);
|
||||
}
|
||||
|
||||
bool readUntilClose(std::string& outData, size_t maxBytes = 2 * 1024 * 1024,
|
||||
int timeoutMs = 8000) {
|
||||
int64_t deadline = nowMs() + timeoutMs;
|
||||
while (nowMs() < deadline && rxBuf_.size() < maxBytes) {
|
||||
int waitMs = static_cast<int>(std::min<int64_t>(200, deadline - nowMs()));
|
||||
int r = pumpRx(std::max(1, waitMs));
|
||||
if (r < 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
outData = std::move(rxBuf_);
|
||||
rxBuf_.clear();
|
||||
return !outData.empty();
|
||||
}
|
||||
|
||||
std::string& rxBuffer() { return rxBuf_; }
|
||||
|
||||
private:
|
||||
int fd_ = -1;
|
||||
SSL_CTX* ctx_ = nullptr;
|
||||
SSL* ssl_ = nullptr;
|
||||
std::string rxBuf_;
|
||||
std::string lastErr_;
|
||||
};
|
||||
|
||||
struct ParsedUrl {
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
int port = 0;
|
||||
std::string path;
|
||||
char gopherType = '1';
|
||||
std::string gopherSelector;
|
||||
};
|
||||
|
||||
inline ParsedUrl parseUrl(const std::string& rawUrl,
|
||||
const std::string& defaultScheme = "gopher") {
|
||||
ParsedUrl u;
|
||||
std::string s = trimStr(rawUrl);
|
||||
size_t schemeEnd = s.find("://");
|
||||
std::string rest;
|
||||
if (schemeEnd != std::string::npos) {
|
||||
u.scheme = toLowerStr(s.substr(0, schemeEnd));
|
||||
rest = s.substr(schemeEnd + 3);
|
||||
} else {
|
||||
u.scheme = toLowerStr(defaultScheme);
|
||||
rest = s;
|
||||
}
|
||||
|
||||
size_t slash = rest.find('/');
|
||||
std::string hostPort = (slash == std::string::npos) ? rest : rest.substr(0, slash);
|
||||
u.path = (slash == std::string::npos) ? "/" : rest.substr(slash);
|
||||
|
||||
if (!hostPort.empty() && hostPort.front() == '[') {
|
||||
size_t rb = hostPort.find(']');
|
||||
if (rb != std::string::npos) {
|
||||
u.host = hostPort.substr(1, rb - 1);
|
||||
if (rb + 1 < hostPort.size() && hostPort[rb + 1] == ':') {
|
||||
u.port = std::atoi(hostPort.substr(rb + 2).c_str());
|
||||
}
|
||||
} else {
|
||||
u.host = hostPort;
|
||||
}
|
||||
} else {
|
||||
size_t colon = hostPort.rfind(':');
|
||||
if (colon != std::string::npos) {
|
||||
u.host = hostPort.substr(0, colon);
|
||||
u.port = std::atoi(hostPort.substr(colon + 1).c_str());
|
||||
} else {
|
||||
u.host = hostPort;
|
||||
}
|
||||
}
|
||||
|
||||
if (u.port <= 0) {
|
||||
if (u.scheme == "gopher" || u.scheme == "gophers") u.port = 70;
|
||||
else if (u.scheme == "gemini") u.port = 1965;
|
||||
else if (u.scheme == "spartan") u.port = 300;
|
||||
else if (u.scheme == "nex") u.port = 1900;
|
||||
else if (u.scheme == "https") u.port = 443;
|
||||
else if (u.scheme == "http") u.port = 80;
|
||||
else u.port = 70;
|
||||
}
|
||||
|
||||
if (u.scheme == "gopher" || u.scheme == "gophers") {
|
||||
if (u.path.size() >= 2 && u.path[0] == '/') {
|
||||
u.gopherType = u.path[1];
|
||||
u.gopherSelector = u.path.substr(2);
|
||||
} else {
|
||||
u.gopherType = '1';
|
||||
u.gopherSelector = "";
|
||||
}
|
||||
}
|
||||
return u;
|
||||
}
|
||||
|
||||
// Minimal HTTP/1.1 + HTTPS GET client (handles Content-Length, chunked, redirects)
|
||||
inline bool httpGet(const std::string& url, std::string& outBody,
|
||||
std::string* outContentType = nullptr,
|
||||
int timeoutMs = 7000,
|
||||
const std::string& userAgent = "Bananarchy/1.0 (Linux armv7)") {
|
||||
std::string currentUrl = url;
|
||||
for (int redirects = 0; redirects < 4; ++redirects) {
|
||||
ParsedUrl u = parseUrl(currentUrl, "https");
|
||||
if (u.host.empty()) return false;
|
||||
NetStream net;
|
||||
if (!net.connectTcp(u.host, u.port, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
if (u.scheme == "https" && !net.startTls(u.host, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
std::ostringstream req;
|
||||
req << "GET " << (u.path.empty() ? "/" : u.path) << " HTTP/1.1\r\n"
|
||||
<< "Host: " << u.host << "\r\n"
|
||||
<< "User-Agent: " << userAgent << "\r\n"
|
||||
<< "Accept: */*\r\n"
|
||||
<< "Connection: close\r\n\r\n";
|
||||
if (!net.sendStr(req.str(), timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
std::string raw;
|
||||
if (!net.readUntilClose(raw, 4 * 1024 * 1024, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
size_t hdrEnd = raw.find("\r\n\r\n");
|
||||
size_t sepLen = 4;
|
||||
if (hdrEnd == std::string::npos) {
|
||||
hdrEnd = raw.find("\n\n");
|
||||
sepLen = 2;
|
||||
}
|
||||
if (hdrEnd == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
std::string hdrs = raw.substr(0, hdrEnd);
|
||||
std::string body = raw.substr(hdrEnd + sepLen);
|
||||
|
||||
int statusCode = 0;
|
||||
{
|
||||
std::istringstream hss(hdrs);
|
||||
std::string httpVer;
|
||||
hss >> httpVer >> statusCode;
|
||||
}
|
||||
|
||||
bool chunked = false;
|
||||
std::string location;
|
||||
std::istringstream lss(hdrs);
|
||||
std::string line;
|
||||
while (std::getline(lss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
size_t colon = line.find(':');
|
||||
if (colon == std::string::npos) continue;
|
||||
std::string k = toLowerStr(trimStr(line.substr(0, colon)));
|
||||
std::string v = trimStr(line.substr(colon + 1));
|
||||
if (k == "transfer-encoding" && toLowerStr(v).find("chunked") != std::string::npos) {
|
||||
chunked = true;
|
||||
} else if (k == "location") {
|
||||
location = v;
|
||||
} else if (k == "content-type" && outContentType) {
|
||||
*outContentType = v;
|
||||
}
|
||||
}
|
||||
|
||||
if ((statusCode == 301 || statusCode == 302 || statusCode == 303 ||
|
||||
statusCode == 307 || statusCode == 308) && !location.empty()) {
|
||||
if (location.rfind("http://", 0) == 0 || location.rfind("https://", 0) == 0) {
|
||||
currentUrl = location;
|
||||
} else if (!location.empty() && location[0] == '/') {
|
||||
currentUrl = u.scheme + "://" + u.host + location;
|
||||
} else {
|
||||
currentUrl = u.scheme + "://" + u.host + "/" + location;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (chunked) {
|
||||
std::string unchunked;
|
||||
size_t pos = 0;
|
||||
while (pos < body.size()) {
|
||||
size_t crlf = body.find("\r\n", pos);
|
||||
if (crlf == std::string::npos) break;
|
||||
std::string hexLen = trimStr(body.substr(pos, crlf - pos));
|
||||
size_t semi = hexLen.find(';');
|
||||
if (semi != std::string::npos) hexLen = hexLen.substr(0, semi);
|
||||
unsigned long chunkLen = std::strtoul(hexLen.c_str(), nullptr, 16);
|
||||
pos = crlf + 2;
|
||||
if (chunkLen == 0) break;
|
||||
if (pos + chunkLen > body.size()) {
|
||||
unchunked.append(body.substr(pos));
|
||||
break;
|
||||
}
|
||||
unchunked.append(body.substr(pos, chunkLen));
|
||||
pos += chunkLen + 2;
|
||||
}
|
||||
outBody = std::move(unchunked);
|
||||
} else {
|
||||
outBody = std::move(body);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace bananarchy
|
||||
|
||||
#endif // DWM_PLUGINS_NET_TLS_H
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,967 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-only
|
||||
// Tox / Trifa P2P Messenger & VoIP DWM Plugin (tox.so / xtox) for Bananarchy (240x320)
|
||||
// Built on c-toxcore (libtoxcore / tox.h + toxav.h) with:
|
||||
// - Persistent Tox profile (~/.local/share/sxmo/tox/profile.tox)
|
||||
// - DHT + TCP relay bootstrap with standby background mode
|
||||
// - Friend requests, P2P encrypted messaging, and per-friend chat logs
|
||||
// - ToxAV Opus audio calls integrated with CallScreen (callscreen.so)
|
||||
|
||||
#include "../sxmo-dwm/dwm_plugin.h"
|
||||
#include "phone_data.h"
|
||||
|
||||
#include <tox/tox.h>
|
||||
#include <tox/toxav.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace bananarchy;
|
||||
|
||||
volatile sig_atomic_t gRunning = 1;
|
||||
|
||||
void handleSignal(int) {
|
||||
gRunning = 0;
|
||||
}
|
||||
|
||||
std::string bytesToHexUpper(const uint8_t* data, size_t len) {
|
||||
std::string out;
|
||||
out.reserve(len * 2);
|
||||
char buf[4];
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
std::snprintf(buf, sizeof(buf), "%02X", data[i]);
|
||||
out += buf;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool hexToBytes(const std::string& hex, uint8_t* out, size_t expectedBytes) {
|
||||
std::string clean;
|
||||
for (char c : hex) {
|
||||
if (!std::isspace(static_cast<unsigned char>(c))) {
|
||||
clean.push_back(c);
|
||||
}
|
||||
}
|
||||
if (clean.size() != expectedBytes * 2) return false;
|
||||
for (size_t i = 0; i < expectedBytes; ++i) {
|
||||
int hi = themeHexNibble(clean[i * 2]);
|
||||
int lo = themeHexNibble(clean[i * 2 + 1]);
|
||||
if (hi < 0 || lo < 0) return false;
|
||||
out[i] = static_cast<uint8_t>((hi << 4) | lo);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string getToxDataDir() {
|
||||
std::string dir = getHomeDirPath() + "/.local/share/sxmo/tox";
|
||||
ContactBook::ensureParentDir(dir + "/profile.tox");
|
||||
return dir;
|
||||
}
|
||||
|
||||
std::string getToxProfilePath() {
|
||||
return getToxDataDir() + "/profile.tox";
|
||||
}
|
||||
|
||||
struct ToxChatEntry {
|
||||
std::string timeStr;
|
||||
bool outgoing = false;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct PendingFriendReq {
|
||||
uint8_t pubKey[TOX_PUBLIC_KEY_SIZE] {};
|
||||
std::string pubKeyHex;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct ToxRuntimeContext {
|
||||
Tox* tox = nullptr;
|
||||
ToxAV* toxav = nullptr;
|
||||
bool dhtConnected = false;
|
||||
std::string connBadge = "OFFLINE";
|
||||
std::vector<PendingFriendReq> pendingReqs;
|
||||
|
||||
// Active ToxAV call state
|
||||
bool inCall = false;
|
||||
bool callIncoming = false;
|
||||
bool callActive = false;
|
||||
uint32_t callFriendNum = UINT32_MAX;
|
||||
FILE* playPipe = nullptr;
|
||||
FILE* capPipe = nullptr;
|
||||
int capFd = -1;
|
||||
std::mutex audioMtx;
|
||||
bool uiDirty = false;
|
||||
};
|
||||
|
||||
std::string getFriendChatLogPath(const std::string& pubKeyHex) {
|
||||
return getToxDataDir() + "/chat_" + pubKeyHex.substr(0, 16) + ".tsv";
|
||||
}
|
||||
|
||||
std::vector<ToxChatEntry> loadFriendChat(const std::string& pubKeyHex) {
|
||||
std::vector<ToxChatEntry> list;
|
||||
std::ifstream in(getFriendChatLogPath(pubKeyHex));
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
if (line.empty()) continue;
|
||||
size_t t1 = line.find('\t');
|
||||
size_t t2 = (t1 == std::string::npos) ? std::string::npos : line.find('\t', t1 + 1);
|
||||
if (t1 != std::string::npos && t2 != std::string::npos) {
|
||||
ToxChatEntry e;
|
||||
e.timeStr = line.substr(0, t1);
|
||||
e.outgoing = (line.substr(t1 + 1, t2 - t1 - 1) == "OUT");
|
||||
e.text = line.substr(t2 + 1);
|
||||
list.push_back(std::move(e));
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
void appendFriendChat(const std::string& pubKeyHex, bool outgoing,
|
||||
const std::string& text) {
|
||||
time_t now = ::time(nullptr);
|
||||
struct tm tmNow {};
|
||||
localtime_r(&now, &tmNow);
|
||||
char ts[16];
|
||||
std::strftime(ts, sizeof(ts), "%H:%M", &tmNow);
|
||||
std::string clean = text;
|
||||
for (char& c : clean) {
|
||||
if (c == '\r' || c == '\n' || c == '\t') c = ' ';
|
||||
}
|
||||
std::ofstream out(getFriendChatLogPath(pubKeyHex), std::ios::app);
|
||||
if (out.is_open()) {
|
||||
out << ts << "\t" << (outgoing ? "OUT" : "IN") << "\t" << clean << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void saveToxProfile(Tox* tox) {
|
||||
if (!tox) return;
|
||||
size_t sz = tox_get_savedata_size(tox);
|
||||
if (sz == 0) return;
|
||||
std::vector<uint8_t> buf(sz);
|
||||
tox_get_savedata(tox, buf.data());
|
||||
std::string path = getToxProfilePath();
|
||||
std::ofstream out(path, std::ios::binary | std::ios::trunc);
|
||||
if (out.is_open()) {
|
||||
out.write(reinterpret_cast<const char*>(buf.data()),
|
||||
static_cast<std::streamsize>(buf.size()));
|
||||
}
|
||||
}
|
||||
|
||||
std::string getFriendDisplayName(Tox* tox, uint32_t friendNum) {
|
||||
Tox_Err_Friend_Query err;
|
||||
size_t sz = tox_friend_get_name_size(tox, friendNum, &err);
|
||||
if (err == TOX_ERR_FRIEND_QUERY_OK && sz > 0 && sz < 256) {
|
||||
std::vector<uint8_t> buf(sz);
|
||||
if (tox_friend_get_name(tox, friendNum, buf.data(), &err)) {
|
||||
std::string name(reinterpret_cast<const char*>(buf.data()), sz);
|
||||
if (!trimStr(name).empty()) return trimStr(name);
|
||||
}
|
||||
}
|
||||
uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0};
|
||||
if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) {
|
||||
return "Tox:" + bytesToHexUpper(pk, 4);
|
||||
}
|
||||
return "Friend #" + std::to_string(friendNum);
|
||||
}
|
||||
|
||||
std::string getFriendPubKeyHex(Tox* tox, uint32_t friendNum) {
|
||||
uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0};
|
||||
if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) {
|
||||
return bytesToHexUpper(pk, TOX_PUBLIC_KEY_SIZE);
|
||||
}
|
||||
return "0000000000000000";
|
||||
}
|
||||
|
||||
void startToxAvAudioPipes(ToxRuntimeContext* ctx) {
|
||||
std::lock_guard<std::mutex> lk(ctx->audioMtx);
|
||||
if (!ctx->playPipe) {
|
||||
ctx->playPipe = ::popen("aplay -q -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "w");
|
||||
}
|
||||
if (!ctx->capPipe) {
|
||||
ctx->capPipe = ::popen("arecord -q -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "r");
|
||||
if (ctx->capPipe) {
|
||||
ctx->capFd = ::fileno(ctx->capPipe);
|
||||
int fl = ::fcntl(ctx->capFd, F_GETFL, 0);
|
||||
::fcntl(ctx->capFd, F_SETFL, fl | O_NONBLOCK);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void stopToxAvAudioPipes(ToxRuntimeContext* ctx) {
|
||||
std::lock_guard<std::mutex> lk(ctx->audioMtx);
|
||||
if (ctx->capPipe) {
|
||||
::pclose(ctx->capPipe);
|
||||
ctx->capPipe = nullptr;
|
||||
ctx->capFd = -1;
|
||||
}
|
||||
if (ctx->playPipe) {
|
||||
::pclose(ctx->playPipe);
|
||||
ctx->playPipe = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// c-toxcore callbacks
|
||||
void onSelfConnectionStatus(Tox*, Tox_Connection status, void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
if (status == TOX_CONNECTION_UDP) {
|
||||
ctx->dhtConnected = true;
|
||||
ctx->connBadge = "DHT(UDP)";
|
||||
} else if (status == TOX_CONNECTION_TCP) {
|
||||
ctx->dhtConnected = true;
|
||||
ctx->connBadge = "DHT(TCP)";
|
||||
} else {
|
||||
ctx->dhtConnected = false;
|
||||
ctx->connBadge = "SEARCHING";
|
||||
}
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onFriendRequest(Tox*, const Tox_Public_Key publicKey,
|
||||
const uint8_t message[], size_t length, void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
std::string hex = bytesToHexUpper(publicKey, TOX_PUBLIC_KEY_SIZE);
|
||||
for (const auto& r : ctx->pendingReqs) {
|
||||
if (r.pubKeyHex == hex) return;
|
||||
}
|
||||
PendingFriendReq req;
|
||||
std::memcpy(req.pubKey, publicKey, TOX_PUBLIC_KEY_SIZE);
|
||||
req.pubKeyHex = hex;
|
||||
req.message.assign(reinterpret_cast<const char*>(message), length);
|
||||
ctx->pendingReqs.push_back(std::move(req));
|
||||
neoui_vibrate(70);
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onFriendMessage(Tox* tox, Tox_Friend_Number friendNum,
|
||||
Tox_Message_Type, const uint8_t message[],
|
||||
size_t length, void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
std::string pkHex = getFriendPubKeyHex(tox, friendNum);
|
||||
std::string txt(reinterpret_cast<const char*>(message), length);
|
||||
appendFriendChat(pkHex, false, txt);
|
||||
neoui_vibrate(60);
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onFriendName(Tox* tox, Tox_Friend_Number, const uint8_t[], size_t,
|
||||
void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
saveToxProfile(tox);
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onFriendConnectionStatus(Tox*, Tox_Friend_Number, Tox_Connection,
|
||||
void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onToxAvCall(ToxAV*, Tox_Friend_Number friendNum, bool, bool,
|
||||
void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
if (ctx->inCall) {
|
||||
toxav_call_control(ctx->toxav, friendNum, TOXAV_CALL_CONTROL_CANCEL, nullptr);
|
||||
return;
|
||||
}
|
||||
ctx->inCall = true;
|
||||
ctx->callIncoming = true;
|
||||
ctx->callActive = false;
|
||||
ctx->callFriendNum = friendNum;
|
||||
|
||||
std::string caller = getFriendDisplayName(ctx->tox, friendNum);
|
||||
for (char& c : caller) {
|
||||
if (c == ' ') c = '_';
|
||||
}
|
||||
std::string cid = "tox:" + std::to_string(friendNum);
|
||||
writeIntFile("/tmp/sxmo_call_ringing", 1);
|
||||
runAsyncCmd("sxmo_jobs.sh start ringing sxmo_hook_ring.sh >/dev/null 2>&1");
|
||||
if (!sendPluginCommand("callscreen", "INCOMING " + cid + " " + caller + " TOX")) {
|
||||
runAsyncArgv("xcallscreen", "incoming", cid.c_str(), caller.c_str());
|
||||
}
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
|
||||
void onToxAvCallState(ToxAV*, Tox_Friend_Number friendNum, uint32_t state,
|
||||
void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
if (friendNum != ctx->callFriendNum) return;
|
||||
|
||||
if (state & (TOXAV_FRIEND_CALL_STATE_FINISHED | TOXAV_FRIEND_CALL_STATE_ERROR)) {
|
||||
stopToxAvAudioPipes(ctx);
|
||||
ctx->inCall = false;
|
||||
ctx->callIncoming = false;
|
||||
ctx->callActive = false;
|
||||
ctx->callFriendNum = UINT32_MAX;
|
||||
::unlink("/tmp/sxmo_call_ringing");
|
||||
runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
|
||||
"pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1");
|
||||
sendPluginCommand("callscreen", "ENDED TOX CALL ENDED");
|
||||
ctx->uiDirty = true;
|
||||
} else if (state & (TOXAV_FRIEND_CALL_STATE_SENDING_A |
|
||||
TOXAV_FRIEND_CALL_STATE_ACCEPTING_A)) {
|
||||
if (!ctx->callActive) {
|
||||
ctx->callActive = true;
|
||||
ctx->callIncoming = false;
|
||||
::unlink("/tmp/sxmo_call_ringing");
|
||||
runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
|
||||
"pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1");
|
||||
startToxAvAudioPipes(ctx);
|
||||
std::string caller = getFriendDisplayName(ctx->tox, friendNum);
|
||||
for (char& c : caller) {
|
||||
if (c == ' ') c = '_';
|
||||
}
|
||||
sendPluginCommand("callscreen",
|
||||
"ACTIVE tox:" + std::to_string(friendNum) + " " + caller + " TOX");
|
||||
ctx->uiDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void onToxAvAudioReceiveFrame(ToxAV*, Tox_Friend_Number, const int16_t pcm[],
|
||||
size_t sampleCount, uint8_t channels,
|
||||
uint32_t, void* userData) {
|
||||
auto* ctx = static_cast<ToxRuntimeContext*>(userData);
|
||||
std::lock_guard<std::mutex> lk(ctx->audioMtx);
|
||||
if (!ctx->playPipe || !pcm || sampleCount == 0) return;
|
||||
if (channels == 1) {
|
||||
std::fwrite(pcm, sizeof(int16_t), sampleCount, ctx->playPipe);
|
||||
} else {
|
||||
std::vector<int16_t> mono(sampleCount);
|
||||
for (size_t i = 0; i < sampleCount; ++i) {
|
||||
mono[i] = pcm[i * channels];
|
||||
}
|
||||
std::fwrite(mono.data(), sizeof(int16_t), sampleCount, ctx->playPipe);
|
||||
}
|
||||
std::fflush(ctx->playPipe);
|
||||
}
|
||||
|
||||
void bootstrapToxDht(Tox* tox) {
|
||||
struct BootstrapNode {
|
||||
const char* host;
|
||||
uint16_t port;
|
||||
const char* pubKeyHex;
|
||||
};
|
||||
static const BootstrapNode kNodes[] = {
|
||||
{"114.35.245.150", 33445,
|
||||
"3F0A45A268367C1BEA652F258C85F4A66DA76BCAA667A49E770BCC4917AB6A25"},
|
||||
{"24.87.200.32", 33445,
|
||||
"10C00EB250C3233E343E2AEBA07115A5C28920E9C8D29492F6D00B29049EDC7E"},
|
||||
{"144.217.167.73", 33445,
|
||||
"7E5668E0EE09E19F320AD47902419331FFEE147BB3606769CFBE921A2A2FD34C"}
|
||||
};
|
||||
for (const auto& n : kNodes) {
|
||||
uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0};
|
||||
if (hexToBytes(n.pubKeyHex, pk, TOX_PUBLIC_KEY_SIZE)) {
|
||||
tox_bootstrap(tox, n.host, n.port, pk, nullptr);
|
||||
tox_add_tcp_relay(tox, n.host, n.port, pk, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int tox_run_main(int argc, char** argv) {
|
||||
gRunning = 1;
|
||||
bool isPreload = false;
|
||||
std::string initCmd;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (!argv[i] || !argv[i][0]) continue;
|
||||
if (std::strcmp(argv[i], "--preload") == 0) isPreload = true;
|
||||
else {
|
||||
if (!initCmd.empty()) initCmd.push_back(' ');
|
||||
initCmd += argv[i];
|
||||
}
|
||||
}
|
||||
|
||||
std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd));
|
||||
if (sendPluginCommand("tox", forwarded)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string daemonPidPath = getPluginDaemonPidPath("tox");
|
||||
std::string activePidPath = getRuntimeFile("xtox.pid");
|
||||
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
|
||||
int fifoFd = setupPluginDaemonFifo("tox");
|
||||
|
||||
struct sigaction sa {};
|
||||
sa.sa_handler = handleSignal;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGTERM, &sa, nullptr);
|
||||
sigaction(SIGINT, &sa, nullptr);
|
||||
|
||||
NeoWindow neo;
|
||||
if (!neo.create("xtox", "XTox", "Tox Messenger")) {
|
||||
if (fifoFd >= 0) ::close(fifoFd);
|
||||
::unlink(daemonPidPath.c_str());
|
||||
return 1;
|
||||
}
|
||||
neo.bindAsActiveContext();
|
||||
|
||||
// Initialize c-toxcore instance from savedata or fresh profile
|
||||
Tox_Options* opts = tox_options_new(nullptr);
|
||||
tox_options_set_ipv6_enabled(opts, false);
|
||||
tox_options_set_udp_enabled(opts, true);
|
||||
tox_options_set_local_discovery_enabled(opts, true);
|
||||
|
||||
std::vector<uint8_t> savedData;
|
||||
{
|
||||
std::ifstream in(getToxProfilePath(), std::ios::binary);
|
||||
if (in.is_open()) {
|
||||
savedData.assign(std::istreambuf_iterator<char>(in),
|
||||
std::istreambuf_iterator<char>());
|
||||
if (!savedData.empty()) {
|
||||
tox_options_set_savedata_type(opts, TOX_SAVEDATA_TYPE_TOX_SAVE);
|
||||
tox_options_set_savedata_data(opts, savedData.data(), savedData.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Tox_Err_New newErr = TOX_ERR_NEW_OK;
|
||||
Tox* tox = tox_new(opts, &newErr);
|
||||
tox_options_free(opts);
|
||||
if (!tox) {
|
||||
tox = tox_new(nullptr, &newErr);
|
||||
}
|
||||
|
||||
ToxRuntimeContext ctx;
|
||||
ctx.tox = tox;
|
||||
if (tox) {
|
||||
if (tox_self_get_name_size(tox) == 0) {
|
||||
const char* defName = "Bananarchy";
|
||||
tox_self_set_name(tox, reinterpret_cast<const uint8_t*>(defName),
|
||||
std::strlen(defName), nullptr);
|
||||
const char* defStatus = "On Bananarchy Linux";
|
||||
tox_self_set_status_message(tox, reinterpret_cast<const uint8_t*>(defStatus),
|
||||
std::strlen(defStatus), nullptr);
|
||||
}
|
||||
saveToxProfile(tox);
|
||||
|
||||
tox_callback_self_connection_status(tox, onSelfConnectionStatus);
|
||||
tox_callback_friend_request(tox, onFriendRequest);
|
||||
tox_callback_friend_message(tox, onFriendMessage);
|
||||
tox_callback_friend_name(tox, onFriendName);
|
||||
tox_callback_friend_connection_status(tox, onFriendConnectionStatus);
|
||||
|
||||
ctx.toxav = toxav_new(tox, nullptr);
|
||||
if (ctx.toxav) {
|
||||
toxav_callback_call(ctx.toxav, onToxAvCall, &ctx);
|
||||
toxav_callback_call_state(ctx.toxav, onToxAvCallState, &ctx);
|
||||
toxav_callback_audio_receive_frame(ctx.toxav, onToxAvAudioReceiveFrame, &ctx);
|
||||
}
|
||||
}
|
||||
|
||||
// Export Tox ID to /tmp/tox_id.txt for easy sharing
|
||||
std::string selfToxIdHex;
|
||||
if (tox) {
|
||||
uint8_t addr[TOX_ADDRESS_SIZE] = {0};
|
||||
tox_self_get_address(tox, addr);
|
||||
selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE);
|
||||
std::ofstream idOut("/tmp/tox_id.txt", std::ios::trunc);
|
||||
if (idOut.is_open()) {
|
||||
idOut << selfToxIdHex << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
bool networkActive = false;
|
||||
int64_t lastBootstrapMs = 0;
|
||||
|
||||
bool visible = false;
|
||||
int activeTab = 0; // 0=Friends, 1=Chat, 2=My Tox ID
|
||||
int selectedRow = 0;
|
||||
int scrollOffset = 0;
|
||||
uint32_t activeFriendNum = 0;
|
||||
bool hasActiveFriend = false;
|
||||
int chatScrollBack = 0;
|
||||
std::string chatInput;
|
||||
bool menuOpen = false;
|
||||
int menuSel = 0;
|
||||
|
||||
// Add friend modal
|
||||
bool addModalOpen = false;
|
||||
std::string addToxIdStr;
|
||||
|
||||
auto getFriendList = [&]() -> std::vector<uint32_t> {
|
||||
std::vector<uint32_t> list;
|
||||
if (!tox) return list;
|
||||
size_t cnt = tox_self_get_friend_list_size(tox);
|
||||
if (cnt > 0) {
|
||||
list.resize(cnt);
|
||||
tox_self_get_friend_list(tox, list.data());
|
||||
}
|
||||
return list;
|
||||
};
|
||||
|
||||
auto ensureNetworkStarted = [&]() {
|
||||
if (!tox) return;
|
||||
if (!networkActive) {
|
||||
networkActive = true;
|
||||
ctx.connBadge = "CONNECTING";
|
||||
bootstrapToxDht(tox);
|
||||
lastBootstrapMs = nowMs();
|
||||
}
|
||||
};
|
||||
|
||||
auto render = [&]() {
|
||||
if (!visible) return;
|
||||
neo.bindAsActiveContext();
|
||||
neoui_begin_frame();
|
||||
|
||||
neoui_draw_header(kIconShield, ctx.dhtConnected ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW,
|
||||
"Tox / Trifa", ctx.connBadge.c_str());
|
||||
neoui_draw_tabs("Friends|Chat|Tox ID", activeTab, 34, 24);
|
||||
|
||||
constexpr int kBodyY = 58;
|
||||
constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H;
|
||||
std::vector<uint32_t> friends = getFriendList();
|
||||
|
||||
if (activeTab == 0) {
|
||||
int totalItems = static_cast<int>(ctx.pendingReqs.size() + friends.size());
|
||||
int rowH = 42;
|
||||
int maxVis = kBodyH / rowH;
|
||||
if (totalItems == 0) {
|
||||
neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 55,
|
||||
240, 24, "No Tox Friends Yet");
|
||||
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 82,
|
||||
240, 20, "Press OK or Menu -> Add Friend");
|
||||
} else {
|
||||
selectedRow = std::clamp(selectedRow, 0, totalItems - 1);
|
||||
if (selectedRow < scrollOffset) scrollOffset = selectedRow;
|
||||
if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1;
|
||||
for (int i = 0; i < maxVis && (scrollOffset + i) < totalItems; ++i) {
|
||||
int idx = scrollOffset + i;
|
||||
if (idx < static_cast<int>(ctx.pendingReqs.size())) {
|
||||
const auto& r = ctx.pendingReqs[idx];
|
||||
std::string title = "Req: " + r.pubKeyHex.substr(0, 12) + "...";
|
||||
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
|
||||
kIconPlus, NEO_TEXT_YELLOW, title.c_str(),
|
||||
r.message.c_str(), "ACCEPT");
|
||||
} else {
|
||||
uint32_t fnum = friends[idx - static_cast<int>(ctx.pendingReqs.size())];
|
||||
std::string name = getFriendDisplayName(tox, fnum);
|
||||
std::string pkHex = getFriendPubKeyHex(tox, fnum).substr(0, 16);
|
||||
Tox_Connection cstat = tox_friend_get_connection_status(tox, fnum, nullptr);
|
||||
const char* badge = (cstat == TOX_CONNECTION_UDP) ? "UDP"
|
||||
: ((cstat == TOX_CONNECTION_TCP) ? "TCP" : "OFF");
|
||||
int col = (cstat != TOX_CONNECTION_NONE) ? NEO_TEXT_GREEN : NEO_TEXT_MUTED;
|
||||
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
|
||||
kIconUser, col, name.c_str(), pkHex.c_str(), badge);
|
||||
}
|
||||
}
|
||||
neoui_draw_scrollbar(236, kBodyY, kBodyH, totalItems, maxVis, scrollOffset);
|
||||
}
|
||||
neoui_draw_softkeys("Menu", totalItems == 0 ? "ADD" : "CHAT", "Close");
|
||||
} else if (activeTab == 1) {
|
||||
if (!hasActiveFriend && !friends.empty()) {
|
||||
activeFriendNum = friends[0];
|
||||
hasActiveFriend = true;
|
||||
}
|
||||
if (!hasActiveFriend) {
|
||||
neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 70,
|
||||
240, 24, "Select a friend first");
|
||||
neoui_draw_softkeys("Menu", "FRIENDS", "Back");
|
||||
} else {
|
||||
std::string pkHex = getFriendPubKeyHex(tox, activeFriendNum);
|
||||
std::vector<ToxChatEntry> chat = loadFriendChat(pkHex);
|
||||
int msgAreaH = kBodyH - 48;
|
||||
int lineH = 18;
|
||||
int maxLines = msgAreaH / lineH;
|
||||
int total = static_cast<int>(chat.size());
|
||||
chatScrollBack = std::clamp(chatScrollBack, 0, std::max(0, total - maxLines));
|
||||
int startIdx = std::max(0, total - maxLines - chatScrollBack);
|
||||
|
||||
for (int i = 0; i < maxLines && (startIdx + i) < total; ++i) {
|
||||
const auto& m = chat[startIdx + i];
|
||||
std::string line = m.timeStr + (m.outgoing ? " Me: " : " Peer: ") + m.text;
|
||||
neoui_draw_text(NEO_FONT_SMALL,
|
||||
m.outgoing ? NEO_TEXT_GREEN : NEO_TEXT_WHITE,
|
||||
6, kBodyY + 2 + i * lineH, lineH, line.c_str(), 228);
|
||||
}
|
||||
neoui_draw_input_box(4, kBodyY + msgAreaH, 232, 26, 1, "",
|
||||
neoui_input_get_text(), "Encrypted Tox message...", 0);
|
||||
neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20,
|
||||
"[OK] Send [Call] Voice Call [*] Mode");
|
||||
neoui_draw_softkeys("Menu", "SEND", "Back");
|
||||
}
|
||||
} else {
|
||||
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 4, 18,
|
||||
"Your 76-char Tox ID (saved in /tmp/tox_id.txt):", 224);
|
||||
// Display 76 hex chars across 4 clean lines of 19 chars
|
||||
for (int row = 0; row < 4; ++row) {
|
||||
size_t pos = static_cast<size_t>(row * 19);
|
||||
if (pos < selfToxIdHex.size()) {
|
||||
std::string chunk = selfToxIdHex.substr(pos, 19);
|
||||
neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, 12,
|
||||
kBodyY + 26 + row * 22, 20, chunk.c_str(), 216);
|
||||
}
|
||||
}
|
||||
neoui_draw_button(12, kBodyY + 124, 216, 32, 1, 0, kIconPlus,
|
||||
"Add Friend by Tox ID");
|
||||
neoui_draw_softkeys("Menu", "ADD FRIEND", "Back");
|
||||
}
|
||||
|
||||
if (addModalOpen) {
|
||||
neoui_draw_modal_box(6, 48, 228, 170, kIconPlus, NEO_TEXT_YELLOW,
|
||||
"Add Friend (76-hex Tox ID)");
|
||||
neoui_draw_input_box(12, 82, 216, 48, 1, "Tox ID:",
|
||||
neoui_input_get_text(), "76 hex chars...", 0);
|
||||
neoui_draw_multitap_bar(12, 140, 216, 22, "[*] Mode [Left Soft] Add");
|
||||
neoui_draw_softkeys("Add", "PASTE /TMP", "Cancel");
|
||||
} else if (menuOpen) {
|
||||
neoui_draw_menu_popup(
|
||||
"Add Friend by Tox ID|Start Voice Call|Bootstrap DHT Now|Rotate NoSpam|Delete Friend",
|
||||
nullptr, menuSel, 5);
|
||||
}
|
||||
|
||||
neoui_end_frame();
|
||||
};
|
||||
|
||||
auto startOutgoingToxCall = [&](uint32_t friendNum) {
|
||||
if (!ctx.toxav || ctx.inCall) return;
|
||||
Toxav_Err_Call err;
|
||||
if (toxav_call(ctx.toxav, friendNum, 32, 0, &err)) {
|
||||
ctx.inCall = true;
|
||||
ctx.callIncoming = false;
|
||||
ctx.callActive = false;
|
||||
ctx.callFriendNum = friendNum;
|
||||
std::string name = getFriendDisplayName(tox, friendNum);
|
||||
for (char& c : name) {
|
||||
if (c == ' ') c = '_';
|
||||
}
|
||||
sendPluginCommand("callscreen",
|
||||
"OUTGOING tox:" + std::to_string(friendNum) + " " + name + " TOX");
|
||||
} else {
|
||||
neoui_show_toast("Friend is offline or busy", 2000);
|
||||
}
|
||||
};
|
||||
|
||||
auto openWindow = [&]() {
|
||||
if (isPhonePasscodeLocked()) return;
|
||||
writeIntFile(activePidPath, static_cast<int>(::getpid()));
|
||||
closeOtherPlugins("tox");
|
||||
visible = true;
|
||||
neoui_show();
|
||||
neoui_input_reset(chatInput.c_str());
|
||||
render();
|
||||
ensureNetworkStarted();
|
||||
};
|
||||
|
||||
auto closeWindow = [&]() {
|
||||
if (!visible) return;
|
||||
visible = false;
|
||||
addModalOpen = false;
|
||||
menuOpen = false;
|
||||
neoui_hide();
|
||||
::unlink(activePidPath.c_str());
|
||||
};
|
||||
|
||||
if (!isPreload) {
|
||||
openWindow();
|
||||
}
|
||||
|
||||
while (gRunning) {
|
||||
for (const std::string& cmd : readFifoLines(fifoFd)) {
|
||||
if (cmd == "NOP") continue;
|
||||
if (cmd == "CLOSE") closeWindow();
|
||||
else if (cmd == "RELOAD_THEME") {
|
||||
neo.reloadTheme();
|
||||
if (visible) render();
|
||||
} else if (cmd.rfind("CALL_ACCEPT", 0) == 0) {
|
||||
if (ctx.inCall && ctx.callIncoming && ctx.toxav) {
|
||||
if (toxav_answer(ctx.toxav, ctx.callFriendNum, 32, 0, nullptr)) {
|
||||
ctx.callActive = true;
|
||||
ctx.callIncoming = false;
|
||||
::unlink("/tmp/sxmo_call_ringing");
|
||||
runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
|
||||
"pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1");
|
||||
startToxAvAudioPipes(&ctx);
|
||||
std::string caller = getFriendDisplayName(tox, ctx.callFriendNum);
|
||||
for (char& c : caller) {
|
||||
if (c == ' ') c = '_';
|
||||
}
|
||||
sendPluginCommand("callscreen",
|
||||
"ACTIVE tox:" + std::to_string(ctx.callFriendNum) +
|
||||
" " + caller + " TOX");
|
||||
}
|
||||
}
|
||||
} else if (cmd.rfind("CALL_HANGUP", 0) == 0) {
|
||||
if (ctx.inCall && ctx.toxav) {
|
||||
toxav_call_control(ctx.toxav, ctx.callFriendNum,
|
||||
TOXAV_CALL_CONTROL_CANCEL, nullptr);
|
||||
stopToxAvAudioPipes(&ctx);
|
||||
ctx.inCall = false;
|
||||
ctx.callIncoming = false;
|
||||
ctx.callActive = false;
|
||||
ctx.callFriendNum = UINT32_MAX;
|
||||
}
|
||||
} else if (cmd.rfind("CALL_MUTE_RING", 0) == 0) {
|
||||
::unlink("/tmp/sxmo_call_ringing");
|
||||
runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
|
||||
"pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1");
|
||||
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
|
||||
openWindow();
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate Tox and ToxAV when visible, in a call, or when friends are configured
|
||||
bool shouldIterateTox =
|
||||
networkActive && tox &&
|
||||
(visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0);
|
||||
if (shouldIterateTox) {
|
||||
tox_iterate(tox, &ctx);
|
||||
if (ctx.toxav) {
|
||||
toxav_iterate(ctx.toxav);
|
||||
}
|
||||
if (ctx.inCall && ctx.callActive && ctx.capFd >= 0 && ctx.toxav) {
|
||||
// Send 20ms (960 samples @ 48kHz) audio frames when available
|
||||
int16_t pcmFrame[960];
|
||||
ssize_t r = ::read(ctx.capFd, pcmFrame, sizeof(pcmFrame));
|
||||
if (r == sizeof(pcmFrame)) {
|
||||
toxav_audio_send_frame(ctx.toxav, ctx.callFriendNum, pcmFrame, 960, 1,
|
||||
48000, nullptr);
|
||||
}
|
||||
}
|
||||
if (!ctx.dhtConnected && nowMs() - lastBootstrapMs >= 30000) {
|
||||
bootstrapToxDht(tox);
|
||||
lastBootstrapMs = nowMs();
|
||||
}
|
||||
if (ctx.uiDirty && visible) {
|
||||
ctx.uiDirty = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
if (visible) {
|
||||
neo.bindAsActiveContext();
|
||||
int ev = neoui_poll_event(0);
|
||||
while (ev != NEO_EV_NONE) {
|
||||
if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) {
|
||||
render();
|
||||
} else if (ev == NEO_EV_CLOSE_REQ) {
|
||||
closeWindow();
|
||||
break;
|
||||
} else if (ev == NEO_EV_SOFTKEY_LEFT) {
|
||||
if (addModalOpen) {
|
||||
std::string rawId = trimStr(neoui_input_get_text());
|
||||
uint8_t addrBytes[TOX_ADDRESS_SIZE] = {0};
|
||||
if (hexToBytes(rawId, addrBytes, TOX_ADDRESS_SIZE)) {
|
||||
const char* msg = "Hello from Bananarchy Linux";
|
||||
Tox_Err_Friend_Add addErr;
|
||||
tox_friend_add(tox, addrBytes,
|
||||
reinterpret_cast<const uint8_t*>(msg),
|
||||
std::strlen(msg), &addErr);
|
||||
saveToxProfile(tox);
|
||||
addModalOpen = false;
|
||||
neoui_show_toast("Friend request sent", 2000);
|
||||
} else {
|
||||
neoui_show_toast("Invalid 76-hex Tox ID", 2000);
|
||||
}
|
||||
render();
|
||||
} else {
|
||||
menuOpen = !menuOpen;
|
||||
menuSel = 0;
|
||||
render();
|
||||
}
|
||||
} else if (ev == NEO_EV_SOFTKEY_RIGHT) {
|
||||
if (addModalOpen) {
|
||||
addModalOpen = false;
|
||||
render();
|
||||
} else if (menuOpen) {
|
||||
menuOpen = false;
|
||||
render();
|
||||
} else if (activeTab != 0) {
|
||||
activeTab = 0;
|
||||
render();
|
||||
} else {
|
||||
closeWindow();
|
||||
break;
|
||||
}
|
||||
} else if (ev == NEO_EV_KEY_PRESS) {
|
||||
int k = neoui_event_key();
|
||||
std::vector<uint32_t> friends = getFriendList();
|
||||
if (menuOpen) {
|
||||
if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5;
|
||||
else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5;
|
||||
else if (k == NEO_KEY_OK) {
|
||||
menuOpen = false;
|
||||
if (menuSel == 0) {
|
||||
addModalOpen = true;
|
||||
neoui_input_reset("");
|
||||
} else if (menuSel == 1 && hasActiveFriend) {
|
||||
startOutgoingToxCall(activeFriendNum);
|
||||
} else if (menuSel == 2) {
|
||||
ensureNetworkStarted();
|
||||
bootstrapToxDht(tox);
|
||||
neoui_show_toast("DHT bootstrap triggered", 1500);
|
||||
} else if (menuSel == 3 && tox) {
|
||||
tox_self_set_nospam(tox, static_cast<uint32_t>(nowMs()));
|
||||
uint8_t addr[TOX_ADDRESS_SIZE] = {0};
|
||||
tox_self_get_address(tox, addr);
|
||||
selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE);
|
||||
saveToxProfile(tox);
|
||||
} else if (menuSel == 4 && activeTab == 0 && !friends.empty()) {
|
||||
int fIdx = selectedRow - static_cast<int>(ctx.pendingReqs.size());
|
||||
if (fIdx >= 0 && fIdx < static_cast<int>(friends.size())) {
|
||||
tox_friend_delete(tox, friends[fIdx], nullptr);
|
||||
saveToxProfile(tox);
|
||||
}
|
||||
}
|
||||
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
|
||||
menuOpen = false;
|
||||
}
|
||||
render();
|
||||
} else if (addModalOpen) {
|
||||
if (k == NEO_KEY_OK) {
|
||||
// Paste from /tmp/tox_add.txt if present
|
||||
std::ifstream pf("/tmp/tox_add.txt");
|
||||
if (pf.is_open()) {
|
||||
std::string line;
|
||||
std::getline(pf, line);
|
||||
neoui_input_set_text(trimStr(line).c_str());
|
||||
}
|
||||
} else if (k == NEO_KEY_STAR) {
|
||||
neoui_input_cycle_mode();
|
||||
} else if (k == NEO_KEY_BACK) {
|
||||
neoui_input_backspace();
|
||||
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
|
||||
neoui_input_feed_key(k);
|
||||
}
|
||||
render();
|
||||
} else {
|
||||
if (k == NEO_KEY_LEFT) {
|
||||
activeTab = (activeTab + 2) % 3;
|
||||
selectedRow = 0;
|
||||
scrollOffset = 0;
|
||||
} else if (k == NEO_KEY_RIGHT) {
|
||||
activeTab = (activeTab + 1) % 3;
|
||||
selectedRow = 0;
|
||||
scrollOffset = 0;
|
||||
} else if (activeTab == 0) {
|
||||
if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow;
|
||||
else if (k == NEO_KEY_DOWN) ++selectedRow;
|
||||
else if (k == NEO_KEY_CALL) {
|
||||
int fIdx = selectedRow - static_cast<int>(ctx.pendingReqs.size());
|
||||
if (fIdx >= 0 && fIdx < static_cast<int>(friends.size())) {
|
||||
startOutgoingToxCall(friends[fIdx]);
|
||||
}
|
||||
} else if (k == NEO_KEY_OK) {
|
||||
if (ctx.pendingReqs.empty() && friends.empty()) {
|
||||
addModalOpen = true;
|
||||
neoui_input_reset("");
|
||||
} else if (selectedRow >= 0 &&
|
||||
selectedRow < static_cast<int>(ctx.pendingReqs.size())) {
|
||||
auto req = ctx.pendingReqs[selectedRow];
|
||||
ctx.pendingReqs.erase(ctx.pendingReqs.begin() + selectedRow);
|
||||
tox_friend_add_norequest(tox, req.pubKey, nullptr);
|
||||
saveToxProfile(tox);
|
||||
neoui_show_toast("Friend request accepted", 1500);
|
||||
} else {
|
||||
int fIdx = selectedRow - static_cast<int>(ctx.pendingReqs.size());
|
||||
if (fIdx >= 0 && fIdx < static_cast<int>(friends.size())) {
|
||||
activeFriendNum = friends[fIdx];
|
||||
hasActiveFriend = true;
|
||||
activeTab = 1;
|
||||
chatScrollBack = 0;
|
||||
neoui_input_reset("");
|
||||
}
|
||||
}
|
||||
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
|
||||
closeWindow();
|
||||
break;
|
||||
}
|
||||
} else if (activeTab == 1) {
|
||||
if (k == NEO_KEY_UP) ++chatScrollBack;
|
||||
else if (k == NEO_KEY_DOWN && chatScrollBack > 0) --chatScrollBack;
|
||||
else if (k == NEO_KEY_CALL && hasActiveFriend) {
|
||||
startOutgoingToxCall(activeFriendNum);
|
||||
} else if (k == NEO_KEY_OK && hasActiveFriend) {
|
||||
std::string txt = trimStr(neoui_input_get_text());
|
||||
if (!txt.empty()) {
|
||||
Tox_Err_Friend_Send_Message sendErr;
|
||||
tox_friend_send_message(tox, activeFriendNum,
|
||||
TOX_MESSAGE_TYPE_NORMAL,
|
||||
reinterpret_cast<const uint8_t*>(txt.data()),
|
||||
txt.size(), &sendErr);
|
||||
if (sendErr == TOX_ERR_FRIEND_SEND_MESSAGE_OK) {
|
||||
appendFriendChat(getFriendPubKeyHex(tox, activeFriendNum),
|
||||
true, txt);
|
||||
neoui_input_reset("");
|
||||
} else {
|
||||
neoui_show_toast("Friend is currently offline", 2000);
|
||||
}
|
||||
}
|
||||
} else if (k == NEO_KEY_STAR) {
|
||||
neoui_input_cycle_mode();
|
||||
} else if (k == NEO_KEY_BACK) {
|
||||
if (!std::string(neoui_input_get_text()).empty()) {
|
||||
neoui_input_backspace();
|
||||
} else {
|
||||
activeTab = 0;
|
||||
}
|
||||
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
|
||||
neoui_input_feed_key(k);
|
||||
}
|
||||
} else if (activeTab == 2) {
|
||||
if (k == NEO_KEY_OK) {
|
||||
addModalOpen = true;
|
||||
neoui_input_reset("");
|
||||
}
|
||||
}
|
||||
render();
|
||||
}
|
||||
}
|
||||
ev = neoui_poll_event(0);
|
||||
}
|
||||
} else {
|
||||
while (XPending(neo.dpy) > 0) {
|
||||
XEvent xev;
|
||||
XNextEvent(neo.dpy, &xev);
|
||||
}
|
||||
}
|
||||
|
||||
struct pollfd pfds[2] {};
|
||||
pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 };
|
||||
pfds[1] = { fifoFd, POLLIN, 0 };
|
||||
int timeoutMs = -1;
|
||||
if (ctx.inCall && ctx.callActive) {
|
||||
timeoutMs = 20;
|
||||
} else if (visible) {
|
||||
timeoutMs = neoui_input_is_tap_active() ? 100 : 200;
|
||||
} else if (shouldIterateTox) {
|
||||
timeoutMs = static_cast<int>(
|
||||
std::clamp<uint32_t>(tox_iteration_interval(tox), 250, 1000));
|
||||
}
|
||||
::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs);
|
||||
}
|
||||
|
||||
stopToxAvAudioPipes(&ctx);
|
||||
if (ctx.toxav) toxav_kill(ctx.toxav);
|
||||
if (tox) {
|
||||
saveToxProfile(tox);
|
||||
tox_kill(tox);
|
||||
}
|
||||
if (fifoFd >= 0) ::close(fifoFd);
|
||||
::unlink(getPluginFifoPath("tox").c_str());
|
||||
::unlink(daemonPidPath.c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int tox_plugin_init(const DwmHostApi* host) {
|
||||
if (host && host->spawn_plugin) {
|
||||
host->spawn_plugin("tox", "--preload");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
|
||||
DWM_PLUGIN_API_VERSION,
|
||||
"tox",
|
||||
"Tox / Trifa P2P messenger and audio call client (c-toxcore)",
|
||||
tox_plugin_init,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
nullptr,
|
||||
tox_run_main
|
||||
};
|
||||
+1
-1
@@ -1659,7 +1659,7 @@ int neoui_hide(void) {
|
||||
XUnmapWindow(ctx->w->dpy, ctx->w->win);
|
||||
ctx->visible = false;
|
||||
ctx->softkeyPending = 0;
|
||||
XFlush(ctx->w->dpy);
|
||||
XSync(ctx->w->dpy, True);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user