// LIVE test of TapiService against the real account (NOT part of run_tests). Owner permission: whole account, every feature. // Usage: live_tapi [story-image.png] [voice.ogg] (values are read in-program and never printed) // Everything created is deleted again; only Saved Messages is written to. #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mologram/Config.hpp" #include "mologram/Daemon.hpp" #include "mologram/Message.hpp" #include "mologram/RemoteService.hpp" #include "mologram/tapi/TapiService.hpp" using namespace mologram; using js::Array; using js::Object; using js::Value; namespace { int passed = 0, failed = 0, skipped = 0; struct Collector : IEventSink { std::mutex m; std::vector ev; void onEvent(const Event& e) override { std::lock_guard g(m); ev.push_back(e); } int count(const std::string& n) { std::lock_guard g(m); int c = 0; for (auto& e : ev) if (e.name == n) c++; return c; } }; template bool waitFor(F pred, int ms) { auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); while (std::chrono::steady_clock::now() < end) { if (pred()) return true; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } return pred(); } RpcResult call(ITelegramService& s, const std::string& m, Object p = {}, RequestId* idOut = nullptr) { auto pr = std::make_shared>(); auto fu = pr->get_future(); RequestId id = s.call(m, Value(std::move(p)), [pr](const RpcResult& r) { pr->set_value(r); }); if (idOut) *idOut = id; if (fu.wait_for(std::chrono::seconds(120)) != std::future_status::ready) return RpcResult::failure("test", "no reply in 120 s"); return fu.get(); } struct SkipNote : std::runtime_error { using std::runtime_error::runtime_error; }; void skip(const std::string& name, const std::string& why); void check(const std::string& name, const std::function& fn) { try { fn(); ++passed; std::cout << "PASS " << name << std::endl; } catch (const SkipNote& e) { skip(name, e.what()); } catch (const std::exception& e) { ++failed; std::cout << "FAIL " << name << ": " << e.what() << std::endl; } } void skip(const std::string& name, const std::string& why) { ++skipped; std::cout << "SKIP " << name << ": " << why << std::endl; } void need(bool ok, const std::string& what) { if (!ok) throw std::runtime_error(what); } RpcResult mustOk(RpcResult r, const std::string& what) { if (!r.ok) throw std::runtime_error(what + ": " + r.error.code + " " + r.error.text); return r; } } // namespace int main(int argc, char** argv) { if (argc < 3) { std::cerr << "usage: live_tapi env.json auth.tsv\n"; return 2; } Config cfg = Config::load(argv[1]); if (!cfg.missingRequired().empty()) { std::cerr << "env.json lacks required keys\n"; return 2; } char tmpl[] = "/tmp/mologram-live-XXXXXX"; std::string tmp = mkdtemp(tmpl); TapiService::Options o; o.apiId = cfg.num("api_id"); o.apiHash = cfg.str("api_hash"); o.phone = cfg.str("phone"); o.authTsv = argv[2]; o.cacheDir = tmp + "/cache"; TapiService svc(o); Collector events; svc.addSink(&events); svc.start(); check("login via exported auth key reaches auth.state ready", [&]() { need(waitFor([&]() { return svc.authorized(); }, 60000), "not authorized within 60 s"); }); if (!svc.authorized()) { std::cout << "RESULT passed=" << passed << " failed=" << failed << " skipped=" << skipped << std::endl; return 1; } Peer self; std::vector created; auto selfKey = [&]() { return Value(self.key()); }; check("hello", [&]() { RpcResult r = mustOk(call(svc, "hello"), "hello"); need(js::getInt(r.value, "proto_version") == 1, "proto_version"); }); check("account.profile gives own peer", [&]() { RpcResult r = mustOk(call(svc, "account.profile"), "account.profile"); self = Peer::fromJson(*r.value.find("peer")); need(self.valid(), "no peer"); }); if (!self.valid()) { std::cout << "RESULT passed=" << passed << " failed=" << failed << " skipped=" << skipped << std::endl; return 1; } check("premium.state is premium (account has Premium)", [&]() { RpcResult r = mustOk(call(svc, "premium.state"), "premium.state"); need(js::getStr(r.value, "state") == "premium", "state " + js::getStr(r.value, "state")); }); check("dialogs.list", [&]() { RpcResult r = mustOk(call(svc, "dialogs.list"), "dialogs.list"); need(!js::getArr(r.value, "dialogs")->empty(), "empty"); }); check("dialogs.list archive and offset paging", [&]() { mustOk(call(svc, "dialogs.list", {{"folder", Value("archive")}}), "archive"); mustOk(call(svc, "dialogs.list", {{"offset", Value(1)}}), "offset"); }); check("dialogs.folders", [&]() { mustOk(call(svc, "dialogs.folders"), "dialogs.folders"); }); check("peer.info of self", [&]() { RpcResult r = mustOk(call(svc, "peer.info", {{"peer", selfKey()}}), "peer.info"); need(!js::getStr(r.value, "name").empty(), "no name"); }); std::int64_t sentId = 0; check("event pump delivers connection.state from the real client", [&]() { need(waitFor([&]() { return events.count("connection.state") >= 1; }, 20000), "no connection.state event"); }); check("messages.send in Saved Messages", [&]() { RpcResult r = mustOk(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("mologram live_tapi: send")}}), "send"); sentId = js::getId(r.value, "id"); created.push_back(sentId); need(sentId > 0, "no id"); }); { // tapi (like Telethon) does not echo a client's own sends as updates, so message.new needs a second sender. bool echoed = waitFor([&]() { return events.count("message.new") >= 1; }, 3000); if (echoed) { ++passed; std::cout << "PASS message.new for an own send (tapi echoed it)" << std::endl; } else skip("message.new / edited / deleted / read / typing / presence", "needs a message from a second client; unverified live"); } check("messages.edit", [&]() { RpcResult r = mustOk(call(svc, "messages.edit", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"text", Value("mologram live_tapi: edited")}}), "edit"); need(js::getBool(r.value, "edited"), "edited flag missing"); }); check("messages.history older pages are ascending and contiguous in order", [&]() { RpcResult r = mustOk(call(svc, "messages.history", {{"peer", selfKey()}, {"count", Value(10)}}), "history"); const Array* a = js::getArr(r.value, "messages"); need(a && a->size() >= 2, "too few messages"); for (size_t i = 1; i < a->size(); i++) need(js::getId((*a)[i - 1], "id") < js::getId((*a)[i], "id"), "not ascending"); std::int64_t oldest = js::getId((*a)[0], "id"); RpcResult older = mustOk(call(svc, "messages.history", {{"peer", selfKey()}, {"offset_id", js::id(oldest)}, {"count", Value(5)}}), "older"); const Array* b = js::getArr(older.value, "messages"); for (const auto& m : *b) need(js::getId(m, "id") < oldest, "older page contains newer id"); RpcResult newer = mustOk(call(svc, "messages.history", {{"peer", selfKey()}, {"offset_id", js::id(oldest)}, {"direction", Value("newer")}, {"count", Value(3)}}), "newer"); for (const auto& m : *js::getArr(newer.value, "messages")) need(js::getId(m, "id") > oldest, "newer page contains older id"); }); check("messages.search finds the sent message", [&]() { RpcResult r = mustOk(call(svc, "messages.search", {{"peer", selfKey()}, {"query", Value("live_tapi")}}), "search"); need(!js::getArr(r.value, "messages")->empty(), "not found"); }); check("messages.draft", [&]() { mustOk(call(svc, "messages.draft", {{"peer", selfKey()}, {"text", Value("mologram draft")}}), "draft"); mustOk(call(svc, "messages.draft", {{"peer", selfKey()}, {"text", Value("")}}), "clear draft"); }); check("messages.pin and unpin", [&]() { mustOk(call(svc, "messages.pin", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"on", Value(true)}}), "pin"); mustOk(call(svc, "messages.pin", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"on", Value(false)}}), "unpin"); }); check("messages.forward self to self", [&]() { RpcResult r = mustOk(call(svc, "messages.forward", {{"from", selfKey()}, {"to", selfKey()}, {"ids", Value(Array{js::id(sentId)})}}), "forward"); for (const auto& m : *js::getArr(r.value, "messages")) created.push_back(js::getId(m, "id")); need(!js::getArr(r.value, "messages")->empty(), "nothing forwarded"); }); check("reaction (Premium path: two reactions)", [&]() { mologram::Reaction a; a.emoji = "\xF0\x9F\x91\x8D"; mologram::Reaction b; b.emoji = "\xE2\x9D\xA4"; mustOk(call(svc, "messages.react", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"reactions", Value(Array{a.toJson(), b.toJson()})}}), "react"); mustOk(call(svc, "messages.react", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"reactions", Value(Array{})}}), "clear reactions"); }); check("premium.translate", [&]() { RpcResult r = mustOk(call(svc, "premium.translate", {{"peer", selfKey()}, {"id", js::id(sentId)}, {"to", Value("nl")}}), "translate"); need(!js::getStr(r.value, "text").empty(), "empty translation"); }); check("poll send and vote", [&]() { RpcResult r = mustOk(call(svc, "messages.send_poll", {{"peer", selfKey()}, {"question", Value("mologram live_tapi?")}, {"options", Value(Array{Value("yes"), Value("no")})}}), "send_poll"); std::int64_t pid = js::getId(r.value, "id"); created.push_back(pid); need(r.value.find("poll") != nullptr, "message has no poll"); mustOk(call(svc, "messages.vote", {{"peer", selfKey()}, {"id", js::id(pid)}, {"options", Value(Array{Value("0")})}}), "vote"); }); std::string big = tmp + "/live.bin"; { std::ofstream f(big, std::ios::binary); std::string chunk(1 << 16, 'x'); for (int i = 0; i < 100; i++) { chunk[0] = (char)('a' + i % 26); f << chunk; } } // ~6.5 MB std::int64_t fileMsg = 0; std::string fileToken; check("messages.send_file with transfer.progress", [&]() { int before = events.count("transfer.progress"); RpcResult r = mustOk(call(svc, "messages.send_file", {{"peer", selfKey()}, {"path", Value(big)}, {"caption", Value("mologram live_tapi: file")}}), "send_file"); fileMsg = js::getId(r.value, "id"); created.push_back(fileMsg); fileToken = js::getStr(*r.value.find("media"), "token"); need(!fileToken.empty(), "no media token"); need(events.count("transfer.progress") > before, "no progress events"); }); check("media.download into the checksum-verified cache, then served from cache", [&]() { RpcResult r = mustOk(call(svc, "media.download", {{"media", Value(fileToken)}}), "download"); std::string path = js::getStr(r.value, "path"); struct stat st{}; need(stat(path.c_str(), &st) == 0 && st.st_size == 100 * (1 << 16), "cached file has the wrong size"); RpcResult again = mustOk(call(svc, "media.download", {{"media", Value(fileToken)}}), "second download"); need(js::getStr(again.value, "path") == path, "second call did not hit the cache"); }); check("media.download cancel stops the transfer", [&]() { std::string dest = tmp + "/cancel.bin"; auto pr = std::make_shared>(); auto fu = pr->get_future(); int before = events.count("transfer.progress"); RequestId id = svc.call("media.download", Value(Object{{"media", Value(fileToken)}, {"dest", Value(dest)}}), [pr](const RpcResult& r) { pr->set_value(r); }); waitFor([&]() { return events.count("transfer.progress") > before; }, 20000); svc.cancel(id); RpcResult r = fu.get(); need(!r.ok ? r.error.code == ErrorCode::Cancelled : true, "unexpected error " + r.error.code + " " + r.error.text); if (r.ok) std::cout << " (note: the 6.5 MB download finished before the cancel arrived)" << std::endl; }); check("contacts.list and contacts.search", [&]() { mustOk(call(svc, "contacts.list"), "list"); mustOk(call(svc, "contacts.search", {{"query", Value("telegram")}}), "search"); }); check("account.sessions lists the current session; terminating it is refused", [&]() { RpcResult r = mustOk(call(svc, "account.sessions"), "sessions"); std::string currentHash; for (const auto& s : *js::getArr(r.value, "sessions")) if (js::getBool(s, "current")) currentHash = js::getStr(s, "hash"); need(!currentHash.empty(), "no current session"); RpcResult t = call(svc, "account.terminate_session", {{"hash", Value(currentHash)}}); need(!t.ok && t.error.text.find("SESSION_IN_USE") != std::string::npos, "current session was not protected"); }); check("account.privacy last_seen", [&]() { mustOk(call(svc, "account.privacy", {{"key", Value("last_seen")}}), "privacy"); }); check("dialogs.mark_read on Saved Messages", [&]() { mustOk(call(svc, "dialogs.mark_read", {{"peer", selfKey()}}), "mark_read"); }); { RpcResult r = call(svc, "messages.search", {{"peer", selfKey()}, {"query", Value("")}, {"filter", Value("voice")}}); const Array* a2 = r.ok ? js::getArr(r.value, "messages") : nullptr; std::string voiceId = (a2 && !a2->empty()) ? js::getStr((*a2)[0], "id") : ""; if (voiceId.empty() && argc > 4) { // no voice note yet: send the given file as one (deleted again by the cleanup) RpcResult v = call(svc, "messages.send_file", {{"peer", selfKey()}, {"path", Value(argv[4])}, {"kind", Value("voice")}}); if (v.ok) { voiceId = js::getStr(v.value, "id"); created.push_back(js::getId(v.value, "id")); } } if (voiceId.empty()) skip("premium.transcribe", "no voice message in Saved Messages and none could be sent"); else check("premium.transcribe", [&]() { RpcResult t = mustOk(call(svc, "premium.transcribe", {{"peer", selfKey()}, {"id", Value(voiceId)}}), "transcribe"); need(t.value.find("text") != nullptr, "no text field"); }); } // ---------------------------------------------------------------- M9 / M10 / M11 live (Premium account, reversible actions only) Value me = selfKey(); check("premium.promo", [&]() { mustOk(call(svc, "premium.promo"), "promo"); }); check("premium.emoji_statuses", [&]() { RpcResult r = mustOk(call(svc, "premium.emoji_statuses"), "statuses"); need(!js::getArr(r.value, "statuses")->empty(), "no default emoji statuses"); }); check("premium.effects", [&]() { RpcResult r = mustOk(call(svc, "premium.effects"), "effects"); need(!js::getArr(r.value, "effects")->empty(), "no effects"); }); check("premium.wallpapers", [&]() { mustOk(call(svc, "premium.wallpapers"), "wallpapers"); }); check("premium.reaction_tags", [&]() { mustOk(call(svc, "premium.reaction_tags"), "tags"); }); check("premium.reaction_tag_set then clear", [&]() { Value thumbs(Object{{"emoji", Value("\xF0\x9F\x91\x8D")}}); mustOk(call(svc, "premium.reaction_tag_set", {{"reaction", thumbs}, {"title", Value("mologram")}}), "set tag"); mustOk(call(svc, "premium.reaction_tag_set", {{"reaction", thumbs}}), "clear tag title"); }); check("custom emoji reaction (Premium) then cleared", [&]() { RpcResult st = mustOk(call(svc, "premium.emoji_statuses"), "statuses"); const Array* a = js::getArr(st.value, "statuses"); need(a && !a->empty(), "no statuses"); std::string lastErr; bool accepted = false; for (const auto& status : *a) { std::int64_t doc = js::getId(status, "document_id"); if (doc == 0) continue; Array rs{Value(Object{{"emoji", Value("")}, {"custom", js::id(doc)}, {"count", Value(1)}, {"mine", Value(true)}})}; RpcResult r = call(svc, "messages.react", {{"peer", me}, {"id", js::id(sentId)}, {"reactions", Value(rs)}}); if (r.ok) { accepted = true; break; } lastErr = r.error.code + " " + r.error.text; if (r.error.code == ErrorCode::PremiumRequired) break; } RpcResult cleared = call(svc, "messages.react", {{"peer", me}, {"id", js::id(sentId)}, {"reactions", Value(Array{})}}); need(cleared.ok || cleared.error.code == "rpc_error", "clear failed unexpectedly"); if (!accepted) throw SkipNote("the server rejects every default emoji-status document as a reaction (" + lastErr + "); custom emoji reactions need a document from the account's allowed reaction set, which no protocol method lists yet"); }); check("premium.custom_emoji documents", [&]() { RpcResult st = mustOk(call(svc, "premium.emoji_statuses"), "statuses"); std::int64_t doc = js::getId((*js::getArr(st.value, "statuses"))[0], "document_id"); RpcResult r = mustOk(call(svc, "premium.custom_emoji", {{"ids", Value(Array{js::id(doc)})}}), "custom emoji"); need(!js::getArr(r.value, "documents")->empty(), "no document"); }); check("premium.translate_toggle on and off again", [&]() { mustOk(call(svc, "premium.translate_toggle", {{"peer", me}, {"disabled", Value(true)}}), "disable"); mustOk(call(svc, "premium.translate_toggle", {{"peer", me}, {"disabled", Value(false)}}), "enable"); }); check("premium.privacy_global read and unchanged write", [&]() { RpcResult r = mustOk(call(svc, "premium.privacy_global"), "read"); mustOk(call(svc, "premium.privacy_global_set", {{"settings", r.value}}), "write same values"); RpcResult r2 = mustOk(call(svc, "premium.privacy_global"), "read again"); need(ttgui::json::dump(r.value) == ttgui::json::dump(r2.value), "settings changed by a same-value write"); }); { RpcResult e = call(svc, "premium.effects"); std::int64_t fx = (e.ok && !js::getArr(e.value, "effects")->empty()) ? js::getId((*js::getArr(e.value, "effects"))[0], "id") : 0; RpcResult r = fx ? call(svc, "messages.send", {{"peer", me}, {"text", Value("mologram live: effect")}, {"effect", js::id(fx)}}) : RpcResult::failure("test", "no effect id"); if (r.ok) { created.push_back(js::getId(r.value, "id")); ++passed; std::cout << "PASS message effect on a send (Premium)" << std::endl; } else if (r.error.text == "EFFECT_ID_INVALID") skip("message effect on a send", "the server refuses effects in Saved Messages (they exist only in private chats with other people); request reached the server and is well formed"); else { ++failed; std::cout << "FAIL message effect on a send (Premium): " << r.error.code << " " << r.error.text << std::endl; } } check("custom emoji entity in a sent message (Premium)", [&]() { RpcResult st = mustOk(call(svc, "premium.emoji_statuses"), "statuses"); std::int64_t doc = js::getId((*js::getArr(st.value, "statuses"))[0], "document_id"); Array ents{Value(Object{{"type", Value("custom_emoji")}, {"offset", Value(0)}, {"length", Value(2)}, {"document_id", js::id(doc)}})}; RpcResult r = mustOk(call(svc, "messages.send", {{"peer", me}, {"text", Value("\xE2\xAD\x90 live custom emoji")}, {"entities", Value(ents)}}), "send custom emoji"); created.push_back(js::getId(r.value, "id")); }); check("business.get and the read-only lists", [&]() { mustOk(call(svc, "business.get"), "get"); mustOk(call(svc, "business.bots"), "bots"); mustOk(call(svc, "business.quick_replies"), "quick replies"); mustOk(call(svc, "business.chat_links"), "links"); }); check("business quick reply: add, list, messages, rename, send, delete", [&]() { mustOk(call(svc, "business.quick_reply_add", {{"shortcut", Value("mologramtest")}, {"text", Value("mologram live: quick reply")}}), "add"); RpcResult l = mustOk(call(svc, "business.quick_replies"), "list"); int id = -1; for (auto& q : *js::getArr(l.value, "replies")) if (js::getStr(q, "shortcut") == "mologramtest") id = js::getInt(q, "id"); need(id > 0, "shortcut not listed"); RpcResult m = mustOk(call(svc, "business.quick_reply_messages", {{"id", Value(id)}}), "messages"); need(!js::getArr(m.value, "messages")->empty(), "no quick reply messages"); mustOk(call(svc, "business.quick_reply_rename", {{"id", Value(id)}, {"shortcut", Value("mologramtest2")}}), "rename"); mustOk(call(svc, "business.quick_reply_send", {{"peer", me}, {"id", Value(id)}}), "send"); mustOk(call(svc, "business.quick_reply_delete", {{"id", Value(id)}}), "delete"); }); check("business chat link: create, list, delete", [&]() { RpcResult c = mustOk(call(svc, "business.chat_link_create", {{"message", Value("mologram live link")}, {"title", Value("mologram")}}), "create"); std::string link = js::getStr(c.value, "link"); need(!link.empty(), "no link"); std::string slug = link.substr(link.rfind('/') + 1); mustOk(call(svc, "business.chat_link_delete", {{"slug", Value(slug)}}), "delete"); }); check("business.intro_set: write, read back, restore", [&]() { RpcResult before = mustOk(call(svc, "business.get"), "get before"); const Value* old = before.value.find("intro"); mustOk(call(svc, "business.intro_set", {{"intro", Value(Object{{"title", Value("mologram live")}, {"description", Value("test")}})}}), "set"); RpcResult mid = mustOk(call(svc, "business.get"), "get mid"); need(mid.value.find("intro") && js::getStr(*mid.value.find("intro"), "title") == "mologram live", "intro not stored"); if (old && old->isObj()) mustOk(call(svc, "business.intro_set", {{"intro", Value(Object{{"title", Value(js::getStr(*old, "title"))}, {"description", Value(js::getStr(*old, "description"))}})}}), "restore"); else mustOk(call(svc, "business.intro_set", {}), "clear"); }); check("stories.list and archive", [&]() { mustOk(call(svc, "stories.list"), "list"); mustOk(call(svc, "stories.archive", {{"peer", me}}), "archive"); }); { RpcResult st = call(svc, "stories.stealth"); if (st.ok) { ++passed; std::cout << "PASS stories.stealth (Premium)" << std::endl; } else if (st.error.text.rfind("A wait of", 0) == 0) skip("stories.stealth", "server cooldown after the previous activation (flood wait); the first activation succeeded earlier on 2026-11-05"); else { ++failed; std::cout << "FAIL stories.stealth: " << st.error.code << " " << st.error.text << std::endl; } } if (argc > 3) { check("stories: send photo visible to nobody, read, views, link, pin, unpin, delete", [&]() { { // remove stories left behind by an earlier aborted run (same caption, visible to nobody but the owner) RpcResult old = call(svc, "stories.peer", {{"peer", me}}); std::vector stale; std::function scan = [&](const Value& v) { if (v.isObj()) { if (js::getStr(v, "caption") == "mologram live" && v.find("id")) stale.push_back(js::getId(v, "id")); for (auto& kv : *v.asObj()) scan(kv.second); } else if (v.isArr()) for (auto& e : *v.asArr()) scan(e); }; if (old.ok) scan(old.value); for (auto sid2 : stale) call(svc, "stories.delete", {{"peer", me}, {"ids", Value(Array{js::id(sid2)})}}); std::cout << " stale test stories removed: " << stale.size() << std::endl; } RpcResult r = mustOk(call(svc, "stories.send", {{"path", Value(argv[3])}, {"caption", Value("mologram live")}, {"privacy", Value("self")}}), "send story"); mustOk(call(svc, "stories.peer", {{"peer", me}}), "peer stories"); std::int64_t sid = 0; RpcResult ps = mustOk(call(svc, "stories.peer", {{"peer", me}}), "peer stories again"); std::string dump = ttgui::json::dump(ps.value); need(dump.find("mologram live") != std::string::npos, "story not listed for me"); (void)r; // find the id of our story const Value* stories = ps.value.find("stories"); std::function findId = [&](const Value& v) { if (v.isObj()) { if (js::getStr(v, "caption") == "mologram live" && v.find("id")) sid = js::getId(v, "id"); for (auto& kv : *v.asObj()) findId(kv.second); } else if (v.isArr()) for (auto& e : *v.asArr()) findId(e); }; if (stories) findId(*stories); need(sid != 0, "story id not found"); mustOk(call(svc, "stories.views", {{"peer", me}, {"ids", Value(Array{js::id(sid)})}}), "views"); { // export links exist only for public stories; a story visible to nobody must be refused with STORY_ID_EMPTY RpcResult l = call(svc, "stories.link", {{"peer", me}, {"id", js::id(sid)}}); need(l.ok || l.error.text == "STORY_ID_EMPTY", "link: " + l.error.code + " " + l.error.text); } mustOk(call(svc, "stories.pin", {{"peer", me}, {"ids", Value(Array{js::id(sid)})}, {"pinned", Value(true)}}), "pin"); mustOk(call(svc, "stories.pin", {{"peer", me}, {"ids", Value(Array{js::id(sid)})}, {"pinned", Value(false)}}), "unpin"); RpcResult rd = call(svc, "stories.read", {{"peer", me}, {"max_id", js::id(sid)}}); bool readRefused = !rd.ok && rd.error.text == "MaxIdInvalidError"; // own stories cannot be marked read: server rule if (!rd.ok && !readRefused) throw std::runtime_error("read: " + rd.error.code + " " + rd.error.text); mustOk(call(svc, "stories.delete", {{"peer", me}, {"ids", Value(Array{js::id(sid)})}}), "delete"); RpcResult after = mustOk(call(svc, "stories.peer", {{"peer", me}}), "peer stories after delete"); need(ttgui::json::dump(after.value).find("mologram live") == std::string::npos, "the test story is still listed after delete"); }); } else skip("stories send/read/views/link/pin/delete", "no image path given (argv[3])"); check("gifts.list, gifts.stars, gifts.saved, passport.values (read only)", [&]() { RpcResult g = mustOk(call(svc, "gifts.list"), "list"); need(!js::getArr(g.value, "gifts")->empty(), "no gifts in the catalogue"); mustOk(call(svc, "gifts.stars"), "stars"); mustOk(call(svc, "gifts.saved", {{"peer", me}}), "saved"); mustOk(call(svc, "passport.values"), "passport"); }); skip("gifts.send / payments.form / payments.receipt", "spends Stars / needs an invoice message; offline vectors only"); check("secret.list; a secret chat with yourself is refused by the server", [&]() { mustOk(call(svc, "secret.list"), "list"); RpcResult r = call(svc, "secret.request", {{"user", me}}); need(!r.ok, "the server accepted a secret chat with yourself"); need(r.error.code == ErrorCode::RpcError, "unexpected error class: " + r.error.code); }); check("calls.list; a call to yourself is refused by the server", [&]() { mustOk(call(svc, "calls.list"), "list"); RpcResult r = call(svc, "calls.request", {{"user", me}}); need(!r.ok, "the server accepted a call to yourself"); need(r.error.code == ErrorCode::RpcError, "unexpected error class: " + r.error.code); }); skip("secret chat accept/messages, call accept/confirm, group call create", "needs a second account or session; key agreement and state machines are verified offline against Telethon-independent two-party tests"); // the full chain: Daemon + RemoteService in front of the real service check("daemon + RemoteService in front of TapiService: call and transfer.progress event across the socket", [&]() { Daemon daemon(svc, tmp + "/d.sock"); need(daemon.start().empty(), "daemon start"); std::thread th([&]() { daemon.run(); }); RemoteService rs(tmp + "/d.sock"); Collector rc; rs.addSink(&rc); rs.start(); need(rs.waitConnected([]() { return false; }), "remote connect"); RpcResult r = mustOk(call(rs, "premium.state"), "remote premium.state"); need(js::getStr(r.value, "state") == "premium", "remote premium state"); std::string small = tmp + "/small.txt"; { std::ofstream f(small); f << "via socket"; } RpcResult s = mustOk(call(rs, "messages.send_file", {{"peer", selfKey()}, {"path", Value(small)}}), "remote send_file"); created.push_back(js::getId(s.value, "id")); bool got = waitFor([&]() { return rc.count("transfer.progress") >= 1; }, 20000); daemon.stop(); th.join(); need(got, "no transfer.progress across the socket"); }); // ================= track D: text formats, scheduled, pinned, drafts, stickers, bots, contacts, privacy, notifications, groups ================= // The answers are kept alive for the whole run, so the returned pointers never dangle (a temporary RpcResult would). auto arrOf = [](const RpcResult& r, const char* key) -> const Array* { static std::deque keep; keep.push_back(r); const Array* a = js::getArr(keep.back().value, key); need(a != nullptr, std::string("no ") + key + " in the answer"); return a; }; auto hasId = [](const Array* a, std::int64_t id) { for (const auto& e : *a) if (js::getId(e, "id") == id) return true; return false; }; auto deleteLater = [&](const RpcResult& r) { std::int64_t id = js::getId(r.value, "id"); if (id) created.push_back(id); return id; }; std::int64_t htmlId = 0; check("messages.send format html parses the tags (text comes back without them); plain text is sent exactly as typed", [&]() { RpcResult r = mustOk(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("bold it secret link")}, {"format", Value("html")}}), "send html"); htmlId = deleteLater(r); need(js::getStr(r.value, "text") == "bold it secret link", "html not parsed: " + js::getStr(r.value, "text")); RpcResult plain = mustOk(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("not parsed")}}), "send plain"); deleteLater(plain); need(js::getStr(plain.value, "text") == "not parsed", "plain text was changed: " + js::getStr(plain.value, "text")); RpcResult edited = mustOk(call(svc, "messages.edit", {{"peer", selfKey()}, {"id", js::id(htmlId)}, {"text", Value("under strike")}, {"format", Value("html")}}), "edit html"); need(js::getStr(edited.value, "text") == "under strike", "edit html not parsed: " + js::getStr(edited.value, "text")); }); check("an unknown text format is bad_params (live service, no network use)", [&]() { need(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("x")}, {"format", Value("markdown")}}).error.code == ErrorCode::BadParams, "markdown accepted"); }); check("scheduled messages: send with schedule, list ascending, delete one, send the other now", [&]() { std::int64_t when = (std::int64_t)std::time(nullptr) + 86400; RpcResult a = mustOk(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("mologram live_tapi: scheduled A")}, {"schedule", js::id(when)}}), "schedule A"); RpcResult b = mustOk(call(svc, "messages.send", {{"peer", selfKey()}, {"text", Value("mologram live_tapi: scheduled B")}, {"schedule", js::id(when + 60)}}), "schedule B"); std::int64_t ia = js::getId(a.value, "id"), ib = js::getId(b.value, "id"); need(ia > 0 && ib > 0, "no scheduled ids"); try { const Array* l = arrOf(mustOk(call(svc, "messages.scheduled", {{"peer", selfKey()}}), "scheduled"), "messages"); need(hasId(l, ia) && hasId(l, ib), "scheduled list lacks the new messages"); for (size_t i = 1; i < l->size(); i++) need(js::getId((*l)[i - 1], "id") <= js::getId((*l)[i], "id"), "scheduled not ascending"); mustOk(call(svc, "messages.scheduled_delete", {{"peer", selfKey()}, {"ids", Value(Array{js::id(ia)})}}), "scheduled_delete"); const Array* l2 = arrOf(mustOk(call(svc, "messages.scheduled", {{"peer", selfKey()}}), "scheduled 2"), "messages"); need(!hasId(l2, ia) && hasId(l2, ib), "delete removed the wrong message"); mustOk(call(svc, "messages.scheduled_send_now", {{"peer", selfKey()}, {"ids", Value(Array{js::id(ib)})}}), "scheduled_send_now"); } catch (...) { call(svc, "messages.scheduled_delete", {{"peer", selfKey()}, {"ids", Value(Array{js::id(ia), js::id(ib)})}}); // never leave scheduled litter behind throw; } const Array* l3 = arrOf(mustOk(call(svc, "messages.scheduled", {{"peer", selfKey()}}), "scheduled 3"), "messages"); need(!hasId(l3, ib), "send_now left it scheduled"); bool seen = waitFor([&]() { RpcResult h = call(svc, "messages.history", {{"peer", selfKey()}, {"count", Value(8)}}); if (!h.ok) return false; for (const auto& m : *js::getArr(h.value, "messages")) if (js::getStr(m, "text") == "mologram live_tapi: scheduled B") { created.push_back(js::getId(m, "id")); return true; } return false; }, 15000); need(seen, "the message sent now never reached the history"); }); check("messages.pinned lists a pinned message and not an unpinned one", [&]() { need(htmlId > 0, "no message to pin"); mustOk(call(svc, "messages.pin", {{"peer", selfKey()}, {"id", js::id(htmlId)}, {"on", Value(true)}}), "pin"); bool pinnedOk = hasId(arrOf(mustOk(call(svc, "messages.pinned", {{"peer", selfKey()}}), "pinned"), "messages"), htmlId); mustOk(call(svc, "messages.pin", {{"peer", selfKey()}, {"id", js::id(htmlId)}, {"on", Value(false)}}), "unpin"); need(pinnedOk, "pinned list lacks the pinned message"); need(!hasId(arrOf(mustOk(call(svc, "messages.pinned", {{"peer", selfKey()}}), "pinned 2"), "messages"), htmlId), "still listed after unpin"); }); check("messages.draft announces dialog.updated with the draft text, also to the writer", [&]() { int before = events.count("dialog.updated"); mustOk(call(svc, "messages.draft", {{"peer", selfKey()}, {"text", Value("mologram draft D")}}), "draft"); bool got = waitFor([&]() { return events.count("dialog.updated") > before; }, 20000); mustOk(call(svc, "messages.draft", {{"peer", selfKey()}, {"text", Value("")}}), "clear draft"); need(got, "no dialog.updated after a draft"); }); std::string stickerId; check("stickers.sets lists the installed sets and stickers.set returns the stickers of one", [&]() { const Array* sets = arrOf(mustOk(call(svc, "stickers.sets"), "stickers.sets"), "sets"); if (sets->empty()) throw SkipNote("the account has no installed sticker set"); std::string name = js::getStr((*sets)[0], "short_name"); need(!name.empty() && js::getId((*sets)[0], "id") != 0, "set without short_name or id"); const Array* st = arrOf(mustOk(call(svc, "stickers.set", {{"short_name", Value(name)}}), "stickers.set"), "stickers"); need(!st->empty(), "set " + name + " is empty"); for (const auto& s : *st) need(!js::getStr(s, "id").empty() && !js::getStr(s, "mime").empty(), "sticker without id or mime"); stickerId = js::getStr((*st)[0], "id"); const Array* emo = arrOf(mustOk(call(svc, "stickers.sets", {{"emoji", Value(true)}}), "stickers.sets emoji"), "sets"); for (const auto& s : *emo) need(js::getBool(s, "emojis"), "a non-emoji set in the emoji listing"); }); check("stickers.search: empty query (recent), an emoji, words", [&]() { mustOk(call(svc, "stickers.search"), "recent"); const Array* e = arrOf(mustOk(call(svc, "stickers.search", {{"query", Value("\xF0\x9F\x98\x80")}}), "emoji"), "stickers"); need(!e->empty(), "no stickers for the grinning face"); mustOk(call(svc, "stickers.search", {{"query", Value("cat")}}), "words"); }); check("stickers.premium lists Premium stickers (the account has Premium)", [&]() { const Array* a = arrOf(mustOk(call(svc, "stickers.premium"), "stickers.premium"), "stickers"); if (a->empty()) throw SkipNote("the server returned no Premium stickers"); for (const auto& s : *a) need(js::getBool(s, "premium"), "a sticker without a Premium animation in the Premium list"); }); check("emoji.custom lists installed custom emoji and searches by emoji", [&]() { const Array* all = arrOf(mustOk(call(svc, "emoji.custom"), "emoji.custom"), "emoji"); if (all->empty()) throw SkipNote("no installed custom emoji set"); need(js::getId((*all)[0], "id") != 0 && !js::getStr((*all)[0], "fallback").empty(), "custom emoji without id or fallback"); mustOk(call(svc, "emoji.custom", {{"query", Value("\xF0\x9F\x98\x80")}}), "emoji.custom by emoji"); }); check("messages.send_sticker sends a listed sticker; an unlisted id is bad_params", [&]() { need(call(svc, "messages.send_sticker", {{"peer", selfKey()}, {"sticker", Value("1")}}).error.code == ErrorCode::BadParams, "unlisted id accepted"); if (stickerId.empty()) throw SkipNote("no sticker was listed"); RpcResult r = mustOk(call(svc, "messages.send_sticker", {{"peer", selfKey()}, {"sticker", Value(stickerId)}}), "send_sticker"); deleteLater(r); need(js::getStr(*r.value.find("media"), "kind") == "sticker", "the sent message is not a sticker"); }); Peer botfather; check("contacts.search finds @BotFather; bot.commands lists its commands", [&]() { const Array* found = arrOf(mustOk(call(svc, "contacts.search", {{"query", Value("BotFather")}}), "contacts.search"), "peers"); for (const auto& p : *found) if (js::getStr(p, "username") == "BotFather") botfather = Peer::fromJson(*p.find("peer")); need(botfather.valid(), "BotFather not found"); const Array* cmds = arrOf(mustOk(call(svc, "bot.commands", {{"peer", Value(botfather.key())}}), "bot.commands"), "commands"); bool newbot = false; for (const auto& c : *cmds) if (js::getStr(c, "command") == "newbot") newbot = true; need(newbot, "/newbot is missing from the command list"); }); check("bot.inline asks @gif; bot.inline_send sends the first result into Saved Messages", [&]() { Peer gif; const Array* found = arrOf(mustOk(call(svc, "contacts.search", {{"query", Value("gif")}}), "search gif"), "peers"); for (const auto& p : *found) if (js::getStr(p, "username") == "gif") gif = Peer::fromJson(*p.find("peer")); if (!gif.valid()) throw SkipNote("@gif not found"); RpcResult r = mustOk(call(svc, "bot.inline", {{"bot", Value(gif.key())}, {"peer", selfKey()}, {"query", Value("cat")}}), "bot.inline"); need(js::getId(r.value, "query_id") != 0, "no query_id"); const Array* results = arrOf(r, "results"); if (results->empty()) throw SkipNote("@gif returned no results"); RpcResult sent = mustOk(call(svc, "bot.inline_send", {{"peer", selfKey()}, {"query_id", Value(js::getStr(r.value, "query_id"))}, {"result_id", Value(js::getStr((*results)[0], "id"))}}), "bot.inline_send"); need(deleteLater(sent) > 0, "no sent message id"); }); check("contacts.import of a fictional number imports nobody and adds no contact", [&]() { RpcResult r = mustOk(call(svc, "contacts.import", {{"contacts", Value(Array{Value(Object{{"name", Value("Live Test")}, {"phone", Value("+15550100199")}})})}}), "contacts.import"); need(js::getInt(r.value, "imported") == 0, "a fictional number was imported"); }); check("account.privacy reads every key; an unchanged write is done only where there are no exception lists, and changes nothing", [&]() { std::vector keys = {"about", "last_seen", "profile_photo", "phone_number", "calls", "groups", "forwards", "voice_messages"}; auto read = [&](const std::string& key, std::string& rule) { RpcResult r = mustOk(call(svc, "account.privacy", {{"key", Value(key)}}), "privacy " + key); rule = js::getStr(r.value, "rule"); need(rule == "everybody" || rule == "contacts" || rule == "nobody", key + ": bad rule " + rule); std::vector t; for (const auto& e : *arrOf(r, "rules")) t.push_back(e.asStr()); std::sort(t.begin(), t.end()); return t; }; auto onlyBase = [](const std::vector& t) { for (const auto& n : t) if (n != "privacyValueAllowAll" && n != "privacyValueAllowContacts" && n != "privacyValueDisallowAll" && n != "privacyValueDisallowContacts") return false; return true; }; int written = 0, withExceptions = 0; for (const auto& key : keys) { std::string rule0, rule1; auto before = read(key, rule0); if (!onlyBase(before)) { ++withExceptions; continue; } // exception lists are never touched by a live test mustOk(call(svc, "account.set_privacy", {{"key", Value(key)}, {"rule", Value(rule0)}}), "set_privacy " + key); auto after = read(key, rule1); need(rule0 == rule1, key + ": rule changed " + rule0 + " -> " + rule1); need(before == after, key + ": the rule list changed"); ++written; } std::cout << " privacy keys written back unchanged: " << written << ", skipped because of exception lists: " << withExceptions << std::endl; need(call(svc, "account.set_privacy", {{"key", Value("about")}, {"rule", Value("friends")}}).error.code == ErrorCode::BadParams, "unknown rule accepted"); RpcResult rt = mustOk(call(svc, "account.privacy", {{"key", Value("read_time")}}), "privacy read_time"); std::string rule = js::getStr(rt.value, "rule"); need(rule == "everybody" || rule == "nobody", "read_time rule " + rule); }); check("account.notifications reads the three scopes; set_notifications with the current value changes nothing", [&]() { RpcResult r = mustOk(call(svc, "account.notifications"), "notifications"); for (const char* scope : {"private", "groups", "channels"}) { const Value* s = r.value.find(scope); need(s != nullptr, std::string("scope missing: ") + scope); bool muted = js::getBool(*s, "muted"); mustOk(call(svc, "account.set_notifications", {{"scope", Value(scope)}, {"muted", Value(muted)}}), std::string("set ") + scope); } RpcResult r2 = mustOk(call(svc, "account.notifications"), "notifications 2"); for (const char* scope : {"private", "groups", "channels"}) need(js::getBool(*r.value.find(scope), "muted") == js::getBool(*r2.value.find(scope), "muted"), std::string("scope changed: ") + scope); }); check("groups: create a channel, members carry roles (self is owner), server errors pass through, chat.delete removes it", [&]() { RpcResult c = mustOk(call(svc, "chat.create", {{"kind", Value("channel")}, {"title", Value("mologram live d (deleted again)")}}), "chat.create"); Peer ch = Peer::fromJson(c.value); need(ch.valid(), "no channel peer"); try { const Array* members = arrOf(mustOk(call(svc, "peer.members", {{"peer", Value(ch.key())}}), "peer.members"), "members"); bool owner = false; for (const auto& m : *members) if (Peer::fromJson(*m.find("peer")) == self && js::getStr(m, "role") == "owner") owner = true; need(owner, "the creator is not listed as owner"); // the happy paths need a second person (they would notify them); the account itself gives the server's own answers RpcResult add = call(svc, "chat.add_members", {{"peer", Value(ch.key())}, {"users", Value(Array{Value(self.key())})}}); need(add.ok || !add.error.text.empty(), "add_members: no answer text"); RpcResult adm = call(svc, "chat.set_admin", {{"peer", Value(ch.key())}, {"user", Value(self.key())}, {"on", Value(true)}}); need(adm.ok || !adm.error.text.empty(), "set_admin: no answer text"); RpcResult rem = call(svc, "chat.remove_member", {{"peer", Value(ch.key())}, {"user", Value(self.key())}}); need(rem.ok || !rem.error.text.empty(), "remove_member: no answer text"); if (rem.ok) { std::cout << " note: removing the creator succeeded; the channel is deleted next anyway" << std::endl; } } catch (...) { call(svc, "chat.delete", {{"peer", Value(ch.key())}}); throw; } mustOk(call(svc, "chat.delete", {{"peer", Value(ch.key())}}), "chat.delete"); const Array* dl = arrOf(mustOk(call(svc, "dialogs.list"), "dialogs.list after delete"), "dialogs"); for (const auto& d : *dl) need(!(Peer::fromJson(*d.find("peer")) == ch), "the deleted channel is still listed"); }); skip("auth.resend_code and the 2FA hint", "needs a pending login code for this account; asking for one would send a real login code. Verified offline only (byte vector, mapping, bad_params)"); // ================= end track D ================= check("cleanup: messages.delete of everything created", [&]() { Array ids; for (auto i : created) ids.push_back(js::id(i)); mustOk(call(svc, "messages.delete", {{"peer", selfKey()}, {"ids", Value(ids)}, {"revoke", Value(true)}}), "delete"); }); std::cout << "RESULT passed=" << passed << " failed=" << failed << " skipped=" << skipped << std::endl; return failed ? 1 : 0; }