mirror of
https://git.neolegacy.dev/neoStudiosLCE/neoLegacy.git
synced 2026-12-02 22:18:09 +01:00
+Discord account connection +Friends List +UPnP Connection +Cosmetics (Iggy menus need to be fixed up a little)
1829 lines
49 KiB
C++
1829 lines
49 KiB
C++
#include "stdafx.h"
|
|
#include "SocialOnlineService.h"
|
|
#include <winhttp.h>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <deque>
|
|
#include <algorithm>
|
|
#include <map>
|
|
#include <set>
|
|
|
|
#pragma comment(lib, "winhttp.lib")
|
|
|
|
namespace
|
|
{
|
|
const wchar_t *kLinkFile = L"online_link.dat";
|
|
const wchar_t *kApiUrlFile = L"social_api_url.txt";
|
|
const wchar_t *kDefaultApiUrl = L"http://23.167.232.23:2053/v1";
|
|
const unsigned long long kPollIntervalMs = 2500ULL;
|
|
const unsigned long long kPollRetryMs = 5000ULL;
|
|
const unsigned long long kSessionRetryMs = 15000ULL;
|
|
const unsigned long long kSessionRenewMarginMs = 60000ULL;
|
|
|
|
struct JsonValue
|
|
{
|
|
enum EType { eNull, eBool, eNumber, eString, eArray, eObject };
|
|
EType type = eNull;
|
|
bool boolean = false;
|
|
double number = 0.0;
|
|
std::string str;
|
|
std::vector<JsonValue> items;
|
|
std::vector<std::string> keys;
|
|
std::vector<JsonValue> values;
|
|
|
|
const JsonValue *get(const char *key) const
|
|
{
|
|
if (type != eObject)
|
|
return nullptr;
|
|
for (size_t i = 0; i < keys.size(); ++i)
|
|
{
|
|
if (keys[i] == key)
|
|
return &values[i];
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
std::string getString(const char *key) const
|
|
{
|
|
const JsonValue *v = get(key);
|
|
return v != nullptr && v->type == eString ? v->str : std::string();
|
|
}
|
|
|
|
double getNumber(const char *key, double fallback) const
|
|
{
|
|
const JsonValue *v = get(key);
|
|
return v != nullptr && v->type == eNumber ? v->number : fallback;
|
|
}
|
|
};
|
|
|
|
void AppendUtf8(std::string &out, unsigned int cp)
|
|
{
|
|
if (cp < 0x80)
|
|
{
|
|
out += static_cast<char>(cp);
|
|
}
|
|
else if (cp < 0x800)
|
|
{
|
|
out += static_cast<char>(0xC0 | (cp >> 6));
|
|
out += static_cast<char>(0x80 | (cp & 0x3F));
|
|
}
|
|
else
|
|
{
|
|
out += static_cast<char>(0xE0 | (cp >> 12));
|
|
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
|
|
out += static_cast<char>(0x80 | (cp & 0x3F));
|
|
}
|
|
}
|
|
|
|
class JsonParser
|
|
{
|
|
public:
|
|
explicit JsonParser(const std::string &source) : m_s(source), m_i(0) {}
|
|
|
|
bool parse(JsonValue &out)
|
|
{
|
|
if (!parseValue(out))
|
|
return false;
|
|
skipWhitespace();
|
|
return m_i == m_s.size();
|
|
}
|
|
|
|
private:
|
|
const std::string &m_s;
|
|
size_t m_i;
|
|
|
|
void skipWhitespace()
|
|
{
|
|
while (m_i < m_s.size() && (m_s[m_i] == ' ' || m_s[m_i] == '\n' || m_s[m_i] == '\r' || m_s[m_i] == '\t'))
|
|
++m_i;
|
|
}
|
|
|
|
bool parseString(std::string &out)
|
|
{
|
|
if (m_i >= m_s.size() || m_s[m_i] != '"')
|
|
return false;
|
|
++m_i;
|
|
while (m_i < m_s.size())
|
|
{
|
|
char c = m_s[m_i++];
|
|
if (c == '"')
|
|
return true;
|
|
if (c != '\\')
|
|
{
|
|
out += c;
|
|
continue;
|
|
}
|
|
if (m_i >= m_s.size())
|
|
return false;
|
|
char e = m_s[m_i++];
|
|
switch (e)
|
|
{
|
|
case '"': out += '"'; break;
|
|
case '\\': out += '\\'; break;
|
|
case '/': out += '/'; break;
|
|
case 'b': out += '\b'; break;
|
|
case 'f': out += '\f'; break;
|
|
case 'n': out += '\n'; break;
|
|
case 'r': out += '\r'; break;
|
|
case 't': out += '\t'; break;
|
|
case 'u':
|
|
{
|
|
if (m_i + 4 > m_s.size())
|
|
return false;
|
|
unsigned int cp = static_cast<unsigned int>(strtoul(m_s.substr(m_i, 4).c_str(), nullptr, 16));
|
|
m_i += 4;
|
|
AppendUtf8(out, cp);
|
|
}
|
|
break;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool parseValue(JsonValue &v)
|
|
{
|
|
skipWhitespace();
|
|
if (m_i >= m_s.size())
|
|
return false;
|
|
char c = m_s[m_i];
|
|
if (c == '{')
|
|
{
|
|
v.type = JsonValue::eObject;
|
|
++m_i;
|
|
skipWhitespace();
|
|
if (m_i < m_s.size() && m_s[m_i] == '}')
|
|
{
|
|
++m_i;
|
|
return true;
|
|
}
|
|
while (true)
|
|
{
|
|
skipWhitespace();
|
|
std::string key;
|
|
if (!parseString(key))
|
|
return false;
|
|
skipWhitespace();
|
|
if (m_i >= m_s.size() || m_s[m_i] != ':')
|
|
return false;
|
|
++m_i;
|
|
JsonValue child;
|
|
if (!parseValue(child))
|
|
return false;
|
|
v.keys.push_back(key);
|
|
v.values.push_back(child);
|
|
skipWhitespace();
|
|
if (m_i < m_s.size() && m_s[m_i] == ',')
|
|
{
|
|
++m_i;
|
|
continue;
|
|
}
|
|
if (m_i < m_s.size() && m_s[m_i] == '}')
|
|
{
|
|
++m_i;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
if (c == '[')
|
|
{
|
|
v.type = JsonValue::eArray;
|
|
++m_i;
|
|
skipWhitespace();
|
|
if (m_i < m_s.size() && m_s[m_i] == ']')
|
|
{
|
|
++m_i;
|
|
return true;
|
|
}
|
|
while (true)
|
|
{
|
|
JsonValue child;
|
|
if (!parseValue(child))
|
|
return false;
|
|
v.items.push_back(child);
|
|
skipWhitespace();
|
|
if (m_i < m_s.size() && m_s[m_i] == ',')
|
|
{
|
|
++m_i;
|
|
continue;
|
|
}
|
|
if (m_i < m_s.size() && m_s[m_i] == ']')
|
|
{
|
|
++m_i;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
if (c == '"')
|
|
{
|
|
v.type = JsonValue::eString;
|
|
return parseString(v.str);
|
|
}
|
|
if (m_s.compare(m_i, 4, "true") == 0)
|
|
{
|
|
v.type = JsonValue::eBool;
|
|
v.boolean = true;
|
|
m_i += 4;
|
|
return true;
|
|
}
|
|
if (m_s.compare(m_i, 5, "false") == 0)
|
|
{
|
|
v.type = JsonValue::eBool;
|
|
v.boolean = false;
|
|
m_i += 5;
|
|
return true;
|
|
}
|
|
if (m_s.compare(m_i, 4, "null") == 0)
|
|
{
|
|
v.type = JsonValue::eNull;
|
|
m_i += 4;
|
|
return true;
|
|
}
|
|
const char *start = m_s.c_str() + m_i;
|
|
char *end = nullptr;
|
|
double number = strtod(start, &end);
|
|
if (end == start)
|
|
return false;
|
|
v.type = JsonValue::eNumber;
|
|
v.number = number;
|
|
m_i += static_cast<size_t>(end - start);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
std::wstring Utf8ToWide(const std::string &text)
|
|
{
|
|
if (text.empty())
|
|
return std::wstring();
|
|
int len = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0);
|
|
std::wstring result(static_cast<size_t>(len), L'\0');
|
|
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), &result[0], len);
|
|
return result;
|
|
}
|
|
|
|
std::string WideToUtf8(const std::wstring &text)
|
|
{
|
|
if (text.empty())
|
|
return std::string();
|
|
int len = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
|
|
std::string result(static_cast<size_t>(len), '\0');
|
|
WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), &result[0], len, nullptr, nullptr);
|
|
return result;
|
|
}
|
|
|
|
std::string JsonString(const std::string &text)
|
|
{
|
|
std::string out = "\"";
|
|
for (char c : text)
|
|
{
|
|
switch (c)
|
|
{
|
|
case '"': out += "\\\""; break;
|
|
case '\\': out += "\\\\"; break;
|
|
case '\n': out += "\\n"; break;
|
|
case '\r': out += "\\r"; break;
|
|
case '\t': out += "\\t"; break;
|
|
default:
|
|
if (static_cast<unsigned char>(c) < 0x20)
|
|
{
|
|
char buffer[8];
|
|
sprintf_s(buffer, "\\u%04x", static_cast<unsigned char>(c));
|
|
out += buffer;
|
|
}
|
|
else
|
|
{
|
|
out += c;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
out += "\"";
|
|
return out;
|
|
}
|
|
|
|
std::wstring ExeDirectory()
|
|
{
|
|
wchar_t exePath[MAX_PATH] = {};
|
|
GetModuleFileNameW(nullptr, exePath, MAX_PATH);
|
|
wchar_t *lastSlash = wcsrchr(exePath, L'\\');
|
|
if (lastSlash)
|
|
*(lastSlash + 1) = L'\0';
|
|
return exePath;
|
|
}
|
|
|
|
std::wstring TrimLine(const std::wstring &line)
|
|
{
|
|
std::wstring value = line;
|
|
while (!value.empty() && (value.back() == L'\n' || value.back() == L'\r' || value.back() == L' ' || value.back() == L'\t'))
|
|
value.pop_back();
|
|
while (!value.empty() && (value.front() == L' ' || value.front() == L'\t' || value.front() == 0xFEFF))
|
|
value.erase(0, 1);
|
|
return value;
|
|
}
|
|
|
|
struct ApiTarget
|
|
{
|
|
std::wstring url;
|
|
std::wstring host;
|
|
std::wstring basePath;
|
|
INTERNET_PORT port = 0;
|
|
bool secure = false;
|
|
bool valid = false;
|
|
};
|
|
|
|
ApiTarget LoadTarget()
|
|
{
|
|
ApiTarget target;
|
|
target.url = kDefaultApiUrl;
|
|
std::wstring path = ExeDirectory() + kApiUrlFile;
|
|
FILE *f = nullptr;
|
|
if (_wfopen_s(&f, path.c_str(), L"r, ccs=UTF-8") == 0 && f)
|
|
{
|
|
wchar_t line[512] = {};
|
|
if (fgetws(line, 512, f) != nullptr)
|
|
{
|
|
std::wstring value = TrimLine(line);
|
|
if (!value.empty())
|
|
target.url = value;
|
|
}
|
|
fclose(f);
|
|
}
|
|
while (!target.url.empty() && target.url.back() == L'/')
|
|
target.url.pop_back();
|
|
|
|
URL_COMPONENTS parts = {};
|
|
parts.dwStructSize = sizeof(parts);
|
|
wchar_t host[256] = {};
|
|
wchar_t urlPath[1024] = {};
|
|
parts.lpszHostName = host;
|
|
parts.dwHostNameLength = 256;
|
|
parts.lpszUrlPath = urlPath;
|
|
parts.dwUrlPathLength = 1024;
|
|
if (WinHttpCrackUrl(target.url.c_str(), 0, 0, &parts))
|
|
{
|
|
target.host = host;
|
|
target.basePath = urlPath;
|
|
target.port = parts.nPort;
|
|
target.secure = parts.nScheme == INTERNET_SCHEME_HTTPS;
|
|
target.valid = !target.host.empty();
|
|
}
|
|
return target;
|
|
}
|
|
|
|
bool HttpPost(HINTERNET session, const ApiTarget &target, const std::string &path, const std::string &body, const std::string &bearer, int &status, std::string &response)
|
|
{
|
|
HINTERNET connection = WinHttpConnect(session, target.host.c_str(), target.port, 0);
|
|
if (connection == nullptr)
|
|
return false;
|
|
std::wstring fullPath = target.basePath + Utf8ToWide(path);
|
|
HINTERNET request = WinHttpOpenRequest(connection, L"POST", fullPath.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, target.secure ? WINHTTP_FLAG_SECURE : 0);
|
|
bool ok = false;
|
|
if (request != nullptr)
|
|
{
|
|
std::wstring headers = L"Content-Type: application/json\r\n";
|
|
if (!bearer.empty())
|
|
headers += L"Authorization: Bearer " + Utf8ToWide(bearer) + L"\r\n";
|
|
DWORD length = static_cast<DWORD>(body.size());
|
|
LPVOID data = length > 0 ? const_cast<char *>(body.data()) : WINHTTP_NO_REQUEST_DATA;
|
|
if (WinHttpSendRequest(request, headers.c_str(), static_cast<DWORD>(-1), data, length, length, 0) && WinHttpReceiveResponse(request, nullptr))
|
|
{
|
|
DWORD code = 0;
|
|
DWORD size = sizeof(code);
|
|
WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &code, &size, WINHTTP_NO_HEADER_INDEX);
|
|
status = static_cast<int>(code);
|
|
while (true)
|
|
{
|
|
DWORD available = 0;
|
|
if (!WinHttpQueryDataAvailable(request, &available) || available == 0)
|
|
break;
|
|
std::string chunk(available, '\0');
|
|
DWORD read = 0;
|
|
if (!WinHttpReadData(request, &chunk[0], available, &read))
|
|
break;
|
|
chunk.resize(read);
|
|
response += chunk;
|
|
}
|
|
ok = true;
|
|
}
|
|
WinHttpCloseHandle(request);
|
|
}
|
|
WinHttpCloseHandle(connection);
|
|
return ok;
|
|
}
|
|
|
|
enum EJob
|
|
{
|
|
eJob_LinkStart,
|
|
eJob_LinkPoll,
|
|
eJob_SessionRefresh,
|
|
eJob_FriendsList,
|
|
eJob_FriendsRequests,
|
|
eJob_FriendRequest,
|
|
eJob_FriendRespond,
|
|
eJob_FriendRemove,
|
|
eJob_Rename,
|
|
eJob_Settings,
|
|
eJob_PresenceHost,
|
|
eJob_PresenceStop,
|
|
eJob_PresenceGames,
|
|
eJob_Heartbeat,
|
|
eJob_Offline,
|
|
eJob_InviteSend,
|
|
eJob_CapeImage,
|
|
eJob_PlayerCosmetics,
|
|
eJob_CosmeticImage,
|
|
eJob_InvitePending,
|
|
};
|
|
|
|
struct Job
|
|
{
|
|
EJob kind;
|
|
std::string path;
|
|
std::string body;
|
|
std::string bearer;
|
|
unsigned int generation;
|
|
};
|
|
|
|
struct JobResult
|
|
{
|
|
Job job;
|
|
bool transportOk;
|
|
int status;
|
|
std::string body;
|
|
};
|
|
|
|
struct Worker
|
|
{
|
|
std::mutex mutex;
|
|
std::condition_variable wake;
|
|
std::deque<Job> jobs;
|
|
std::deque<JobResult> results;
|
|
ApiTarget target;
|
|
};
|
|
|
|
Worker *s_worker = nullptr;
|
|
|
|
void WorkerMain(Worker *worker)
|
|
{
|
|
HINTERNET session = WinHttpOpen(L"neoLegacy/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
|
if (session != nullptr)
|
|
WinHttpSetTimeouts(session, 5000, 5000, 8000, 8000);
|
|
while (true)
|
|
{
|
|
Job job;
|
|
{
|
|
std::unique_lock<std::mutex> lock(worker->mutex);
|
|
worker->wake.wait(lock, [worker]() { return !worker->jobs.empty(); });
|
|
job = worker->jobs.front();
|
|
worker->jobs.pop_front();
|
|
}
|
|
JobResult result;
|
|
result.job = job;
|
|
result.status = 0;
|
|
result.transportOk = session != nullptr && worker->target.valid && HttpPost(session, worker->target, job.path, job.body, job.bearer, result.status, result.body);
|
|
std::lock_guard<std::mutex> lock(worker->mutex);
|
|
worker->results.push_back(result);
|
|
}
|
|
}
|
|
|
|
std::recursive_mutex s_sharedMutex;
|
|
bool s_loaded = false;
|
|
SocialOnlineService::ELinkState s_state = SocialOnlineService::eLink_Unlinked;
|
|
std::string s_refreshToken;
|
|
std::wstring s_linkedName;
|
|
std::wstring s_onlineIdText;
|
|
unsigned long long s_onlineId = 0;
|
|
std::wstring s_linkCode;
|
|
std::string s_pollId;
|
|
unsigned long long s_linkExpiresMs = 0;
|
|
unsigned long long s_nextPollMs = 0;
|
|
bool s_pollInFlight = false;
|
|
unsigned int s_linkGeneration = 0;
|
|
std::string s_sessionToken;
|
|
unsigned long long s_sessionExpiresMs = 0;
|
|
bool s_sessionInFlight = false;
|
|
unsigned long long s_nextSessionAttemptMs = 0;
|
|
unsigned long long s_renameAvailableMs = 0;
|
|
bool s_renameInFlight = false;
|
|
bool s_hasAccountSettings = false;
|
|
bool s_acceptingRequests = true;
|
|
bool s_friendsLoaded = false;
|
|
bool s_requestsLoaded = false;
|
|
std::vector<SocialOnlineService::Person> s_friends;
|
|
std::vector<SocialOnlineService::Person> s_incoming;
|
|
std::deque<SocialOnlineService::Event> s_events;
|
|
bool s_hosting = false;
|
|
bool s_hostPublished = false;
|
|
int s_hostPort = 0;
|
|
std::wstring s_hostWorld;
|
|
int s_hostPlayers = 0;
|
|
int s_hostMaxPlayers = 0;
|
|
std::vector<unsigned long long> s_hostPlayerIds;
|
|
bool s_hostFriendsOfFriends = false;
|
|
bool s_hostDirty = false;
|
|
unsigned long long s_nextHostBeatMs = 0;
|
|
bool s_hostInFlight = false;
|
|
bool s_gamesInFlight = false;
|
|
std::vector<SocialOnlineService::FriendGame> s_friendGames;
|
|
std::deque<SocialOnlineService::GameInvite> s_invites;
|
|
struct CosmeticEntry
|
|
{
|
|
bool known = false;
|
|
unsigned long long fetchedMs = 0;
|
|
std::string capeId;
|
|
unsigned int capeIndex = 0;
|
|
std::string earsId;
|
|
unsigned int earsIndex = 0;
|
|
std::string earsBoxes;
|
|
};
|
|
std::map<unsigned long long, CosmeticEntry> s_cosmetics;
|
|
std::set<unsigned long long> s_cosmeticsWanted;
|
|
std::map<std::string, std::wstring> s_cosmeticDownloads;
|
|
std::set<std::wstring> s_cosmeticFailed;
|
|
bool s_cosmeticsInFlight = false;
|
|
unsigned long long s_nextCosmeticsMs = 0;
|
|
std::string s_capeId;
|
|
unsigned int s_capeIndex = 0;
|
|
unsigned int s_capeReadyIndex = 0;
|
|
bool s_capeInFlight = false;
|
|
unsigned long long s_nextCapeAttemptMs = 0;
|
|
std::vector<std::pair<unsigned long long, unsigned long long>> s_recentInvites;
|
|
bool s_invitePollInFlight = false;
|
|
unsigned long long s_nextInvitePollMs = 0;
|
|
SocialOnlineService::EActivity s_activity = SocialOnlineService::eActivity_Hidden;
|
|
bool s_activityDirty = false;
|
|
bool s_statusPublished = false;
|
|
bool s_heartbeatInFlight = false;
|
|
unsigned long long s_nextHeartbeatMs = 0;
|
|
|
|
unsigned long long NowMs()
|
|
{
|
|
return GetTickCount64();
|
|
}
|
|
|
|
void PushEvent(SocialOnlineService::EEvent type, const std::wstring &status = std::wstring(), const std::wstring &name = std::wstring())
|
|
{
|
|
SocialOnlineService::Event e;
|
|
e.type = type;
|
|
e.status = status;
|
|
e.name = name;
|
|
s_events.push_back(e);
|
|
while (s_events.size() > 32)
|
|
s_events.pop_front();
|
|
}
|
|
|
|
void EnsureWorker()
|
|
{
|
|
if (s_worker != nullptr)
|
|
return;
|
|
s_worker = new Worker();
|
|
s_worker->target = LoadTarget();
|
|
std::thread(WorkerMain, s_worker).detach();
|
|
}
|
|
|
|
void Enqueue(EJob kind, const std::string &path, const std::string &body, bool auth)
|
|
{
|
|
EnsureWorker();
|
|
Job job;
|
|
job.kind = kind;
|
|
job.path = path;
|
|
job.body = body.empty() ? std::string("{}") : body;
|
|
job.bearer = auth ? s_sessionToken : std::string();
|
|
job.generation = s_linkGeneration;
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_worker->mutex);
|
|
s_worker->jobs.push_back(job);
|
|
}
|
|
s_worker->wake.notify_one();
|
|
}
|
|
|
|
std::wstring LinkPath()
|
|
{
|
|
return ExeDirectory() + kLinkFile;
|
|
}
|
|
|
|
void SaveLink()
|
|
{
|
|
FILE *f = nullptr;
|
|
if (_wfopen_s(&f, LinkPath().c_str(), L"w, ccs=UTF-8") != 0 || !f)
|
|
return;
|
|
fwprintf(f, L"%ls\n%ls\n%ls\n", Utf8ToWide(s_refreshToken).c_str(), s_onlineIdText.c_str(), s_linkedName.c_str());
|
|
fclose(f);
|
|
}
|
|
|
|
void SetOwnCape(const std::string &capeId, unsigned int capeIndex)
|
|
{
|
|
if (capeId != s_capeId || capeIndex != s_capeIndex)
|
|
{
|
|
s_capeId = capeId;
|
|
s_capeIndex = capeIndex;
|
|
s_capeReadyIndex = 0;
|
|
s_nextCapeAttemptMs = 0;
|
|
}
|
|
}
|
|
|
|
void RefreshCosmetics()
|
|
{
|
|
for (auto &entry : s_cosmetics)
|
|
{
|
|
entry.second.fetchedMs = 0;
|
|
if (s_cosmeticsWanted.size() < 256)
|
|
s_cosmeticsWanted.insert(entry.first);
|
|
}
|
|
if (s_onlineId != 0)
|
|
s_cosmeticsWanted.insert(s_onlineId);
|
|
s_cosmeticFailed.clear();
|
|
s_nextCosmeticsMs = 0;
|
|
}
|
|
|
|
void ApplyAccount(const JsonValue *account)
|
|
{
|
|
if (account == nullptr)
|
|
return;
|
|
std::string onlineId = account->getString("onlineId");
|
|
std::string username = account->getString("username");
|
|
if (!onlineId.empty())
|
|
{
|
|
s_onlineIdText = Utf8ToWide(onlineId);
|
|
s_onlineId = _wcstoui64(s_onlineIdText.c_str(), nullptr, 16);
|
|
}
|
|
if (!username.empty())
|
|
s_linkedName = Utf8ToWide(username);
|
|
double renameIn = account->getNumber("renameAvailableIn", -1.0);
|
|
if (renameIn >= 0.0)
|
|
s_renameAvailableMs = NowMs() + static_cast<unsigned long long>(renameIn * 1000.0);
|
|
const JsonValue *cape = account->get("cape");
|
|
std::string capeId;
|
|
unsigned int capeIndex = 0;
|
|
if (cape != nullptr && cape->type == JsonValue::eObject)
|
|
{
|
|
capeId = cape->getString("id");
|
|
capeIndex = static_cast<unsigned int>(cape->getNumber("index", 0.0)) & 0x7FFFFFE0u;
|
|
}
|
|
SetOwnCape(capeId, capeIndex);
|
|
const JsonValue *accepting = account->get("acceptingRequests");
|
|
if (accepting != nullptr && accepting->type == JsonValue::eBool)
|
|
{
|
|
s_acceptingRequests = accepting->boolean;
|
|
s_hasAccountSettings = true;
|
|
}
|
|
}
|
|
|
|
std::vector<SocialOnlineService::Person> ParsePeople(const JsonValue *list)
|
|
{
|
|
std::vector<SocialOnlineService::Person> people;
|
|
if (list == nullptr || list->type != JsonValue::eArray)
|
|
return people;
|
|
for (const JsonValue &item : list->items)
|
|
{
|
|
SocialOnlineService::Person person;
|
|
person.onlineId = Utf8ToWide(item.getString("onlineId"));
|
|
person.username = Utf8ToWide(item.getString("username"));
|
|
person.status = Utf8ToWide(item.getString("status"));
|
|
if (!person.onlineId.empty())
|
|
people.push_back(person);
|
|
}
|
|
return people;
|
|
}
|
|
|
|
void ClearSessionData()
|
|
{
|
|
s_sessionToken.clear();
|
|
s_sessionExpiresMs = 0;
|
|
s_friendsLoaded = false;
|
|
s_requestsLoaded = false;
|
|
s_friends.clear();
|
|
s_incoming.clear();
|
|
}
|
|
|
|
void ResetLinkAttempt()
|
|
{
|
|
s_linkCode.clear();
|
|
s_pollId.clear();
|
|
s_pollInFlight = false;
|
|
++s_linkGeneration;
|
|
}
|
|
|
|
void ForgetLink()
|
|
{
|
|
s_capeId.clear();
|
|
s_capeIndex = 0;
|
|
s_capeReadyIndex = 0;
|
|
ResetLinkAttempt();
|
|
ClearSessionData();
|
|
s_state = SocialOnlineService::eLink_Unlinked;
|
|
s_refreshToken.clear();
|
|
s_linkedName.clear();
|
|
s_onlineIdText.clear();
|
|
s_onlineId = 0;
|
|
s_sessionInFlight = false;
|
|
DeleteFileW(LinkPath().c_str());
|
|
}
|
|
|
|
std::wstring ErrorOf(const JobResult &result)
|
|
{
|
|
if (!result.transportOk)
|
|
return L"unreachable";
|
|
JsonValue json;
|
|
JsonParser parser(result.body);
|
|
if (parser.parse(json))
|
|
{
|
|
std::string error = json.getString("error");
|
|
if (error.empty())
|
|
error = json.getString("status");
|
|
if (!error.empty())
|
|
return Utf8ToWide(error);
|
|
}
|
|
return L"http_" + std::to_wstring(result.status);
|
|
}
|
|
|
|
bool HandleAuthFailure(const JobResult &result, bool notify = true)
|
|
{
|
|
if (!result.transportOk)
|
|
{
|
|
if (notify)
|
|
PushEvent(SocialOnlineService::eEvent_ActionFailed, L"unreachable");
|
|
return true;
|
|
}
|
|
if (result.status == 401)
|
|
{
|
|
s_sessionToken.clear();
|
|
s_nextSessionAttemptMs = 0;
|
|
if (notify)
|
|
PushEvent(SocialOnlineService::eEvent_ActionFailed, L"session");
|
|
return true;
|
|
}
|
|
if (result.status == 403)
|
|
{
|
|
ForgetLink();
|
|
PushEvent(SocialOnlineService::eEvent_SessionRevoked, L"banned");
|
|
return true;
|
|
}
|
|
if (result.status != 200)
|
|
{
|
|
if (notify)
|
|
PushEvent(SocialOnlineService::eEvent_ActionFailed, ErrorOf(result));
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void HandleResult(const JobResult &result)
|
|
{
|
|
JsonValue json;
|
|
bool parsed = false;
|
|
if (result.transportOk && !result.body.empty())
|
|
{
|
|
JsonParser parser(result.body);
|
|
parsed = parser.parse(json);
|
|
}
|
|
|
|
switch (result.job.kind)
|
|
{
|
|
case eJob_LinkStart:
|
|
if (result.job.generation != s_linkGeneration || s_state != SocialOnlineService::eLink_Starting)
|
|
return;
|
|
if (result.transportOk && result.status == 200 && parsed && !json.getString("code").empty())
|
|
{
|
|
s_linkCode = Utf8ToWide(json.getString("code"));
|
|
s_pollId = json.getString("pollId");
|
|
s_linkExpiresMs = NowMs() + static_cast<unsigned long long>(json.getNumber("expiresIn", 600.0) * 1000.0);
|
|
s_nextPollMs = NowMs() + kPollIntervalMs;
|
|
s_state = SocialOnlineService::eLink_Pending;
|
|
PushEvent(SocialOnlineService::eEvent_LinkStarted);
|
|
}
|
|
else
|
|
{
|
|
ResetLinkAttempt();
|
|
s_state = SocialOnlineService::eLink_Unlinked;
|
|
PushEvent(SocialOnlineService::eEvent_LinkFailed, ErrorOf(result));
|
|
}
|
|
return;
|
|
|
|
case eJob_LinkPoll:
|
|
if (result.job.generation != s_linkGeneration || s_state != SocialOnlineService::eLink_Pending)
|
|
return;
|
|
s_pollInFlight = false;
|
|
if (!result.transportOk || result.status >= 500 || result.status == 429)
|
|
{
|
|
s_nextPollMs = NowMs() + kPollRetryMs;
|
|
return;
|
|
}
|
|
if (result.status == 200 && parsed)
|
|
{
|
|
std::string status = json.getString("status");
|
|
if (status == "pending")
|
|
{
|
|
s_nextPollMs = NowMs() + kPollIntervalMs;
|
|
return;
|
|
}
|
|
if (status == "linked" && !json.getString("refreshToken").empty())
|
|
{
|
|
s_refreshToken = json.getString("refreshToken");
|
|
ApplyAccount(json.get("account"));
|
|
ResetLinkAttempt();
|
|
s_state = SocialOnlineService::eLink_Linked;
|
|
SaveLink();
|
|
s_nextSessionAttemptMs = 0;
|
|
PushEvent(SocialOnlineService::eEvent_Linked, std::wstring(), s_linkedName);
|
|
return;
|
|
}
|
|
if (status == "expired")
|
|
{
|
|
ResetLinkAttempt();
|
|
s_state = SocialOnlineService::eLink_Unlinked;
|
|
PushEvent(SocialOnlineService::eEvent_LinkExpired);
|
|
return;
|
|
}
|
|
}
|
|
ResetLinkAttempt();
|
|
s_state = SocialOnlineService::eLink_Unlinked;
|
|
PushEvent(SocialOnlineService::eEvent_LinkFailed, ErrorOf(result));
|
|
return;
|
|
|
|
case eJob_SessionRefresh:
|
|
s_sessionInFlight = false;
|
|
if (s_state != SocialOnlineService::eLink_Linked)
|
|
return;
|
|
if (result.transportOk && result.status == 200 && parsed && !json.getString("sessionToken").empty())
|
|
{
|
|
s_sessionToken = json.getString("sessionToken");
|
|
s_sessionExpiresMs = NowMs() + static_cast<unsigned long long>(json.getNumber("expiresIn", 3600.0) * 1000.0);
|
|
std::wstring oldName = s_linkedName;
|
|
ApplyAccount(json.get("account"));
|
|
if (oldName != s_linkedName)
|
|
SaveLink();
|
|
PushEvent(SocialOnlineService::eEvent_SessionReady);
|
|
SocialOnlineService::RefreshFriends();
|
|
return;
|
|
}
|
|
if (result.transportOk && (result.status == 401 || result.status == 403))
|
|
{
|
|
std::wstring reason = result.status == 403 ? L"banned" : L"revoked";
|
|
ForgetLink();
|
|
PushEvent(SocialOnlineService::eEvent_SessionRevoked, reason);
|
|
return;
|
|
}
|
|
s_nextSessionAttemptMs = NowMs() + kSessionRetryMs;
|
|
PushEvent(SocialOnlineService::eEvent_SessionFailed, ErrorOf(result));
|
|
return;
|
|
|
|
case eJob_FriendsList:
|
|
if (HandleAuthFailure(result, false))
|
|
return;
|
|
if (parsed)
|
|
{
|
|
s_friends = ParsePeople(json.get("friends"));
|
|
s_friendsLoaded = true;
|
|
PushEvent(SocialOnlineService::eEvent_FriendsUpdated);
|
|
}
|
|
return;
|
|
|
|
case eJob_FriendsRequests:
|
|
if (HandleAuthFailure(result, false))
|
|
return;
|
|
if (parsed)
|
|
{
|
|
s_incoming = ParsePeople(json.get("incoming"));
|
|
s_requestsLoaded = true;
|
|
PushEvent(SocialOnlineService::eEvent_FriendsUpdated);
|
|
}
|
|
return;
|
|
|
|
case eJob_FriendRequest:
|
|
if (HandleAuthFailure(result))
|
|
return;
|
|
if (parsed)
|
|
{
|
|
std::wstring status = Utf8ToWide(json.getString("status"));
|
|
std::wstring name = Utf8ToWide(json.getString("username"));
|
|
PushEvent(SocialOnlineService::eEvent_FriendRequestResult, status, name);
|
|
if (status == L"accepted")
|
|
SocialOnlineService::RefreshFriends();
|
|
}
|
|
return;
|
|
|
|
case eJob_FriendRespond:
|
|
case eJob_FriendRemove:
|
|
if (HandleAuthFailure(result))
|
|
return;
|
|
SocialOnlineService::RefreshFriends();
|
|
return;
|
|
|
|
case eJob_Settings:
|
|
if (HandleAuthFailure(result))
|
|
return;
|
|
if (parsed)
|
|
ApplyAccount(json.get("account"));
|
|
return;
|
|
|
|
case eJob_Rename:
|
|
s_renameInFlight = false;
|
|
if (result.transportOk && (result.status == 400 || result.status == 429) && parsed)
|
|
{
|
|
double renameIn = json.getNumber("renameAvailableIn", -1.0);
|
|
if (renameIn >= 0.0)
|
|
s_renameAvailableMs = NowMs() + static_cast<unsigned long long>(renameIn * 1000.0);
|
|
PushEvent(SocialOnlineService::eEvent_RenameResult, Utf8ToWide(json.getString("error")));
|
|
return;
|
|
}
|
|
if (HandleAuthFailure(result))
|
|
{
|
|
PushEvent(SocialOnlineService::eEvent_RenameResult, L"failed");
|
|
return;
|
|
}
|
|
if (parsed)
|
|
{
|
|
ApplyAccount(json.get("account"));
|
|
SaveLink();
|
|
PushEvent(SocialOnlineService::eEvent_RenameResult, L"ok", s_linkedName);
|
|
}
|
|
return;
|
|
|
|
case eJob_PresenceHost:
|
|
s_hostInFlight = false;
|
|
if (HandleAuthFailure(result, false))
|
|
{
|
|
s_nextHostBeatMs = NowMs() + 15000;
|
|
return;
|
|
}
|
|
if (result.transportOk && result.status == 200)
|
|
{
|
|
s_hostPublished = true;
|
|
double refreshIn = parsed ? json.getNumber("refreshIn", 30.0) : 30.0;
|
|
s_nextHostBeatMs = NowMs() + static_cast<unsigned long long>(refreshIn * 1000.0);
|
|
}
|
|
else
|
|
{
|
|
s_nextHostBeatMs = NowMs() + 15000;
|
|
}
|
|
return;
|
|
|
|
case eJob_PresenceStop:
|
|
case eJob_Offline:
|
|
return;
|
|
|
|
case eJob_InviteSend:
|
|
if (HandleAuthFailure(result))
|
|
{
|
|
PushEvent(SocialOnlineService::eEvent_InviteResult, L"failed");
|
|
return;
|
|
}
|
|
PushEvent(SocialOnlineService::eEvent_InviteResult, parsed ? Utf8ToWide(json.getString("status")) : std::wstring(L"failed"), parsed ? Utf8ToWide(json.getString("username")) : std::wstring());
|
|
return;
|
|
|
|
case eJob_PlayerCosmetics:
|
|
s_cosmeticsInFlight = false;
|
|
if (result.transportOk && result.status == 200 && parsed)
|
|
{
|
|
const JsonValue *players = json.get("players");
|
|
if (players != nullptr && players->type == JsonValue::eArray)
|
|
{
|
|
for (const JsonValue &item : players->items)
|
|
{
|
|
unsigned long long id = _strtoui64(item.getString("onlineId").c_str(), nullptr, 16);
|
|
if (id == 0)
|
|
continue;
|
|
CosmeticEntry entry;
|
|
entry.known = true;
|
|
entry.fetchedMs = NowMs();
|
|
const JsonValue *cape = item.get("cape");
|
|
if (cape != nullptr && cape->type == JsonValue::eObject)
|
|
{
|
|
entry.capeId = cape->getString("id");
|
|
entry.capeIndex = static_cast<unsigned int>(cape->getNumber("index", 0.0)) & 0x7FFFFFE0u;
|
|
}
|
|
const JsonValue *ears = item.get("ears");
|
|
if (ears != nullptr && ears->type == JsonValue::eObject)
|
|
{
|
|
entry.earsId = ears->getString("id");
|
|
entry.earsIndex = static_cast<unsigned int>(ears->getNumber("index", 0.0)) & 0x7FFFFFE0u;
|
|
entry.earsBoxes = ears->getString("boxes");
|
|
}
|
|
s_cosmetics[id] = entry;
|
|
if (id == s_onlineId && s_state == SocialOnlineService::eLink_Linked)
|
|
SetOwnCape(entry.capeId, entry.capeIndex);
|
|
wchar_t path[64] = {};
|
|
if (!entry.capeId.empty() && entry.capeIndex != 0)
|
|
{
|
|
swprintf(path, 64, L"ugccape%08X.png", entry.capeIndex);
|
|
std::string body = "{\"capeId\":" + JsonString(entry.capeId) + "}";
|
|
if (!app.IsFileInMemoryTextures(path) && s_cosmeticDownloads.find(body) == s_cosmeticDownloads.end() && s_cosmeticFailed.find(path) == s_cosmeticFailed.end())
|
|
{
|
|
s_cosmeticDownloads[body] = path;
|
|
Enqueue(eJob_CosmeticImage, "/capes/image", body, false);
|
|
}
|
|
}
|
|
if (!entry.earsId.empty() && entry.earsIndex != 0)
|
|
{
|
|
swprintf(path, 64, L"ugcears%08X.png", entry.earsIndex);
|
|
std::string body = "{\"earsId\":" + JsonString(entry.earsId) + "}";
|
|
if (!app.IsFileInMemoryTextures(path) && s_cosmeticDownloads.find(body) == s_cosmeticDownloads.end() && s_cosmeticFailed.find(path) == s_cosmeticFailed.end())
|
|
{
|
|
s_cosmeticDownloads[body] = path;
|
|
Enqueue(eJob_CosmeticImage, "/capes/ears-image", body, false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
s_nextCosmeticsMs = NowMs() + 30000;
|
|
}
|
|
return;
|
|
|
|
case eJob_CosmeticImage:
|
|
{
|
|
auto it = s_cosmeticDownloads.find(result.job.body);
|
|
if (it == s_cosmeticDownloads.end())
|
|
return;
|
|
std::wstring path = it->second;
|
|
s_cosmeticDownloads.erase(it);
|
|
if (result.transportOk && result.status == 200 && result.body.size() > 8 && static_cast<unsigned char>(result.body[0]) == 0x89 && result.body.compare(1, 3, "PNG") == 0)
|
|
{
|
|
if (!app.IsFileInMemoryTextures(path))
|
|
{
|
|
PBYTE data = new BYTE[result.body.size()];
|
|
memcpy(data, result.body.data(), result.body.size());
|
|
app.AddMemoryTextureFile(path, data, static_cast<DWORD>(result.body.size()));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
s_cosmeticFailed.insert(path);
|
|
}
|
|
}
|
|
return;
|
|
|
|
case eJob_CapeImage:
|
|
s_capeInFlight = false;
|
|
if (result.job.body.find("\"" + s_capeId + "\"") == std::string::npos)
|
|
return;
|
|
if (result.transportOk && result.status == 200 && result.body.size() > 8 && static_cast<unsigned char>(result.body[0]) == 0x89 && result.body.compare(1, 3, "PNG") == 0)
|
|
{
|
|
wchar_t path[64] = {};
|
|
swprintf(path, 64, L"ugccape%08X.png", s_capeIndex);
|
|
if (!app.IsFileInMemoryTextures(path))
|
|
{
|
|
PBYTE data = new BYTE[result.body.size()];
|
|
memcpy(data, result.body.data(), result.body.size());
|
|
app.AddMemoryTextureFile(path, data, static_cast<DWORD>(result.body.size()));
|
|
}
|
|
s_capeReadyIndex = s_capeIndex;
|
|
}
|
|
else
|
|
{
|
|
s_nextCapeAttemptMs = NowMs() + 60000;
|
|
}
|
|
return;
|
|
|
|
case eJob_InvitePending:
|
|
s_invitePollInFlight = false;
|
|
if (HandleAuthFailure(result, false))
|
|
return;
|
|
if (parsed)
|
|
{
|
|
const JsonValue *list = json.get("invites");
|
|
if (list != nullptr && list->type == JsonValue::eArray)
|
|
{
|
|
for (const JsonValue &item : list->items)
|
|
{
|
|
SocialOnlineService::GameInvite invite;
|
|
invite.fromOnlineId = Utf8ToWide(item.getString("fromOnlineId"));
|
|
invite.fromUsername = Utf8ToWide(item.getString("fromUsername"));
|
|
invite.worldName = Utf8ToWide(item.getString("worldName"));
|
|
if (invite.fromOnlineId.empty())
|
|
continue;
|
|
unsigned long long fromId = _wcstoui64(invite.fromOnlineId.c_str(), nullptr, 16);
|
|
s_recentInvites.push_back(std::make_pair(fromId, NowMs() + 10ULL * 60ULL * 1000ULL));
|
|
s_invites.push_back(invite);
|
|
while (s_invites.size() > 8)
|
|
s_invites.pop_front();
|
|
}
|
|
}
|
|
}
|
|
return;
|
|
|
|
case eJob_Heartbeat:
|
|
s_heartbeatInFlight = false;
|
|
if (HandleAuthFailure(result, false))
|
|
{
|
|
s_nextHeartbeatMs = NowMs() + 30000;
|
|
return;
|
|
}
|
|
if (result.transportOk && result.status == 200)
|
|
{
|
|
double refreshIn = parsed ? json.getNumber("refreshIn", 60.0) : 60.0;
|
|
s_nextHeartbeatMs = NowMs() + static_cast<unsigned long long>(refreshIn * 1000.0);
|
|
}
|
|
else
|
|
{
|
|
s_nextHeartbeatMs = NowMs() + 30000;
|
|
}
|
|
return;
|
|
|
|
case eJob_PresenceGames:
|
|
s_gamesInFlight = false;
|
|
if (HandleAuthFailure(result, false))
|
|
return;
|
|
if (parsed)
|
|
{
|
|
std::vector<SocialOnlineService::FriendGame> games;
|
|
const JsonValue *list = json.get("games");
|
|
if (list != nullptr && list->type == JsonValue::eArray)
|
|
{
|
|
for (const JsonValue &item : list->items)
|
|
{
|
|
SocialOnlineService::FriendGame game;
|
|
game.onlineId = Utf8ToWide(item.getString("onlineId"));
|
|
game.username = Utf8ToWide(item.getString("username"));
|
|
game.worldName = Utf8ToWide(item.getString("worldName"));
|
|
game.playerCount = static_cast<int>(item.getNumber("playerCount", 1.0));
|
|
game.maxPlayers = static_cast<int>(item.getNumber("maxPlayers", 8.0));
|
|
game.viaFriend = Utf8ToWide(item.getString("viaFriend"));
|
|
const JsonValue *blocked = item.get("blockedPlayers");
|
|
if (blocked != nullptr && blocked->type == JsonValue::eArray)
|
|
{
|
|
for (const JsonValue &name : blocked->items)
|
|
{
|
|
if (name.type == JsonValue::eString && !name.str.empty())
|
|
game.blockedPlayers.push_back(Utf8ToWide(name.str));
|
|
}
|
|
}
|
|
if (game.onlineId.size() == 16)
|
|
games.push_back(game);
|
|
}
|
|
}
|
|
s_friendGames.swap(games);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace SocialOnlineService
|
|
{
|
|
void Load()
|
|
{
|
|
if (s_loaded)
|
|
return;
|
|
s_loaded = true;
|
|
FILE *f = nullptr;
|
|
if (_wfopen_s(&f, LinkPath().c_str(), L"r, ccs=UTF-8") != 0 || !f)
|
|
return;
|
|
wchar_t token[256] = {};
|
|
wchar_t id[64] = {};
|
|
wchar_t name[64] = {};
|
|
bool ok = fgetws(token, 256, f) != nullptr && fgetws(id, 64, f) != nullptr && fgetws(name, 64, f) != nullptr;
|
|
fclose(f);
|
|
if (!ok)
|
|
return;
|
|
s_refreshToken = WideToUtf8(TrimLine(token));
|
|
s_onlineIdText = TrimLine(id);
|
|
s_onlineId = _wcstoui64(s_onlineIdText.c_str(), nullptr, 16);
|
|
s_linkedName = TrimLine(name);
|
|
if (s_refreshToken.size() == 64 && s_onlineId != 0)
|
|
s_state = eLink_Linked;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
Load();
|
|
if (s_worker != nullptr)
|
|
{
|
|
std::deque<JobResult> results;
|
|
{
|
|
std::lock_guard<std::mutex> lock(s_worker->mutex);
|
|
results.swap(s_worker->results);
|
|
}
|
|
for (const JobResult &result : results)
|
|
HandleResult(result);
|
|
}
|
|
|
|
unsigned long long now = NowMs();
|
|
if (s_state == eLink_Pending)
|
|
{
|
|
if (now >= s_linkExpiresMs)
|
|
{
|
|
ResetLinkAttempt();
|
|
s_state = eLink_Unlinked;
|
|
PushEvent(eEvent_LinkExpired);
|
|
}
|
|
else if (!s_pollInFlight && now >= s_nextPollMs)
|
|
{
|
|
s_pollInFlight = true;
|
|
Enqueue(eJob_LinkPoll, "/link/poll", "{\"pollId\":" + JsonString(s_pollId) + "}", false);
|
|
}
|
|
}
|
|
|
|
if (s_state == eLink_Linked)
|
|
{
|
|
if (!s_sessionToken.empty() && now + kSessionRenewMarginMs >= s_sessionExpiresMs)
|
|
s_sessionToken.clear();
|
|
if (s_sessionToken.empty() && !s_sessionInFlight && now >= s_nextSessionAttemptMs)
|
|
{
|
|
s_sessionInFlight = true;
|
|
Enqueue(eJob_SessionRefresh, "/session/refresh", "{\"refreshToken\":" + JsonString(s_refreshToken) + "}", false);
|
|
}
|
|
}
|
|
|
|
if (!s_cosmeticsWanted.empty() && !s_cosmeticsInFlight && now >= s_nextCosmeticsMs)
|
|
{
|
|
std::string body = "{\"onlineIds\":[";
|
|
int count = 0;
|
|
while (!s_cosmeticsWanted.empty() && count < 32)
|
|
{
|
|
char idText[17] = {};
|
|
sprintf_s(idText, "%016llX", *s_cosmeticsWanted.begin());
|
|
s_cosmeticsWanted.erase(s_cosmeticsWanted.begin());
|
|
body += (count > 0 ? ",\"" : "\"") + std::string(idText) + "\"";
|
|
++count;
|
|
}
|
|
body += "]}";
|
|
s_cosmeticsInFlight = true;
|
|
s_nextCosmeticsMs = now + 2000;
|
|
Enqueue(eJob_PlayerCosmetics, "/capes/players", body, false);
|
|
}
|
|
|
|
if (s_state == eLink_Linked && !s_capeId.empty() && s_capeIndex != 0 && s_capeReadyIndex != s_capeIndex && !s_capeInFlight && now >= s_nextCapeAttemptMs)
|
|
{
|
|
s_capeInFlight = true;
|
|
Enqueue(eJob_CapeImage, "/capes/image", "{\"capeId\":" + JsonString(s_capeId) + "}", false);
|
|
}
|
|
|
|
if (s_activity != eActivity_Hidden && HasSession() && !s_invitePollInFlight && now >= s_nextInvitePollMs)
|
|
{
|
|
s_invitePollInFlight = true;
|
|
s_nextInvitePollMs = now + 8000;
|
|
Enqueue(eJob_InvitePending, "/invites/pending", "{}", true);
|
|
}
|
|
|
|
if (s_activity == eActivity_Hidden)
|
|
{
|
|
if (s_activityDirty && s_statusPublished && HasSession())
|
|
Enqueue(eJob_Offline, "/presence/offline", "{}", true);
|
|
s_activityDirty = false;
|
|
s_statusPublished = false;
|
|
}
|
|
else if (HasSession() && !s_heartbeatInFlight && (s_activityDirty || now >= s_nextHeartbeatMs))
|
|
{
|
|
s_activityDirty = false;
|
|
s_heartbeatInFlight = true;
|
|
s_statusPublished = true;
|
|
const char *status = s_activity == eActivity_InWorld ? "in_world" : "online";
|
|
Enqueue(eJob_Heartbeat, "/presence/heartbeat", std::string("{\"status\":\"") + status + "\"}", true);
|
|
}
|
|
|
|
if (s_hosting && HasSession() && !s_hostInFlight && (s_hostDirty || now >= s_nextHostBeatMs))
|
|
{
|
|
s_hostDirty = false;
|
|
s_hostInFlight = true;
|
|
std::string body = "{\"port\":" + std::to_string(s_hostPort) +
|
|
",\"worldName\":" + JsonString(WideToUtf8(s_hostWorld)) +
|
|
",\"playerCount\":" + std::to_string(s_hostPlayers) +
|
|
",\"maxPlayers\":" + std::to_string(s_hostMaxPlayers) +
|
|
",\"friendsOfFriends\":" + (s_hostFriendsOfFriends ? "true" : "false") + ",\"players\":[";
|
|
for (size_t i = 0; i < s_hostPlayerIds.size(); ++i)
|
|
{
|
|
char idText[17] = {};
|
|
sprintf_s(idText, "%016llX", s_hostPlayerIds[i]);
|
|
body += (i > 0 ? ",\"" : "\"") + std::string(idText) + "\"";
|
|
}
|
|
body += "]}";
|
|
Enqueue(eJob_PresenceHost, "/presence/host", body, true);
|
|
}
|
|
}
|
|
|
|
void SetActivity(EActivity activity)
|
|
{
|
|
if (activity != s_activity)
|
|
{
|
|
if (activity == eActivity_InWorld)
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
RefreshCosmetics();
|
|
}
|
|
s_activity = activity;
|
|
s_activityDirty = true;
|
|
}
|
|
}
|
|
|
|
void GoOffline()
|
|
{
|
|
std::string sessionToken;
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
if (!s_statusPublished || !HasSession())
|
|
return;
|
|
s_statusPublished = false;
|
|
sessionToken = s_sessionToken;
|
|
}
|
|
ApiTarget target = LoadTarget();
|
|
if (!target.valid)
|
|
return;
|
|
HINTERNET session = WinHttpOpen(L"neoLegacy/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
|
if (session == nullptr)
|
|
return;
|
|
WinHttpSetTimeouts(session, 1500, 1500, 1500, 1500);
|
|
int status = 0;
|
|
std::string body;
|
|
HttpPost(session, target, "/presence/offline", "{}", sessionToken, status, body);
|
|
WinHttpCloseHandle(session);
|
|
}
|
|
|
|
const CosmeticEntry *LookupCosmetics(unsigned long long onlineId)
|
|
{
|
|
if ((onlineId >> 63) == 0)
|
|
return nullptr;
|
|
auto it = s_cosmetics.find(onlineId);
|
|
if (it == s_cosmetics.end() || NowMs() > it->second.fetchedMs + 5ULL * 60ULL * 1000ULL)
|
|
{
|
|
if (s_cosmeticsWanted.size() < 256)
|
|
s_cosmeticsWanted.insert(onlineId);
|
|
if (it == s_cosmetics.end())
|
|
{
|
|
CosmeticEntry placeholder;
|
|
placeholder.fetchedMs = NowMs();
|
|
s_cosmetics[onlineId] = placeholder;
|
|
return nullptr;
|
|
}
|
|
it->second.fetchedMs = NowMs();
|
|
}
|
|
return it->second.known ? &it->second : nullptr;
|
|
}
|
|
|
|
bool GetPlayerEarsTexture(unsigned long long onlineId, std::wstring &outPath)
|
|
{
|
|
const CosmeticEntry *entry = LookupCosmetics(onlineId);
|
|
if (entry == nullptr || entry->earsIndex == 0)
|
|
return false;
|
|
wchar_t path[64] = {};
|
|
swprintf(path, 64, L"ugcears%08X.png", entry->earsIndex);
|
|
if (!app.IsFileInMemoryTextures(path))
|
|
return false;
|
|
outPath = path;
|
|
return true;
|
|
}
|
|
|
|
bool GetPlayer3DCosmetic(unsigned long long onlineId, std::wstring &outTexture, std::string &outBoxes, unsigned int &outIndex)
|
|
{
|
|
if (!GetPlayerEarsTexture(onlineId, outTexture))
|
|
return false;
|
|
const CosmeticEntry *entry = LookupCosmetics(onlineId);
|
|
if (entry == nullptr || entry->earsBoxes.empty())
|
|
return false;
|
|
outBoxes = entry->earsBoxes;
|
|
outIndex = entry->earsIndex;
|
|
return true;
|
|
}
|
|
|
|
bool GetPlayerCapeTexture(unsigned long long onlineId, bool &outKnown, bool &outHasCape, std::wstring &outPath)
|
|
{
|
|
outKnown = false;
|
|
outHasCape = false;
|
|
outPath.clear();
|
|
const CosmeticEntry *entry = LookupCosmetics(onlineId);
|
|
if (entry == nullptr)
|
|
return false;
|
|
outKnown = true;
|
|
if (entry->capeIndex == 0)
|
|
return false;
|
|
outHasCape = true;
|
|
wchar_t path[64] = {};
|
|
swprintf(path, 64, L"ugccape%08X.png", entry->capeIndex);
|
|
if (!app.IsFileInMemoryTextures(path))
|
|
return false;
|
|
outPath = path;
|
|
return true;
|
|
}
|
|
|
|
unsigned int GetCapeOverride()
|
|
{
|
|
if (s_activity == eActivity_Hidden || s_state != eLink_Linked)
|
|
return 0;
|
|
return s_capeReadyIndex;
|
|
}
|
|
|
|
std::wstring GetMyStatus()
|
|
{
|
|
if (s_activity == eActivity_Hidden || !HasSession())
|
|
return L"offline";
|
|
if (s_hosting && s_hostPublished)
|
|
return L"hosting";
|
|
if (s_activity == eActivity_InWorld)
|
|
return L"in_world";
|
|
return L"online";
|
|
}
|
|
|
|
std::wstring StatusLabel(const std::wstring &status)
|
|
{
|
|
if (status == L"hosting")
|
|
return L"Hosting";
|
|
if (status == L"in_world")
|
|
return L"In a world";
|
|
if (status == L"online")
|
|
return L"Online";
|
|
return L"Offline";
|
|
}
|
|
|
|
void SetHosting(int port, const std::wstring &worldName, int playerCount, int maxPlayers, const std::vector<unsigned long long> &players, bool friendsOfFriends)
|
|
{
|
|
std::wstring world = worldName.substr(0, 64);
|
|
std::vector<unsigned long long> ids;
|
|
for (unsigned long long id : players)
|
|
{
|
|
if ((id >> 63) != 0 && std::find(ids.begin(), ids.end(), id) == ids.end() && ids.size() < 256)
|
|
ids.push_back(id);
|
|
}
|
|
std::sort(ids.begin(), ids.end());
|
|
if (!s_hosting || port != s_hostPort || world != s_hostWorld || playerCount != s_hostPlayers || maxPlayers != s_hostMaxPlayers || ids != s_hostPlayerIds || friendsOfFriends != s_hostFriendsOfFriends)
|
|
s_hostDirty = true;
|
|
s_hosting = true;
|
|
s_hostPort = port;
|
|
s_hostWorld = world;
|
|
s_hostPlayers = playerCount;
|
|
s_hostMaxPlayers = maxPlayers;
|
|
s_hostPlayerIds = ids;
|
|
s_hostFriendsOfFriends = friendsOfFriends;
|
|
}
|
|
|
|
const FriendGame *FindFriendGame(unsigned long long onlineId)
|
|
{
|
|
for (const FriendGame &game : s_friendGames)
|
|
{
|
|
if (_wcstoui64(game.onlineId.c_str(), nullptr, 16) == onlineId)
|
|
return &game;
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
void StopHosting()
|
|
{
|
|
if (!s_hosting)
|
|
return;
|
|
s_hosting = false;
|
|
s_hostDirty = false;
|
|
if (s_hostPublished && HasSession())
|
|
Enqueue(eJob_PresenceStop, "/presence/stop", "{}", true);
|
|
s_hostPublished = false;
|
|
}
|
|
|
|
void SendInvite(const std::wstring &onlineId)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_InviteResult, L"session");
|
|
return;
|
|
}
|
|
Enqueue(eJob_InviteSend, "/invites/send", "{\"onlineId\":" + JsonString(WideToUtf8(onlineId)) + "}", true);
|
|
}
|
|
|
|
bool PopInvite(GameInvite &out)
|
|
{
|
|
if (s_invites.empty())
|
|
return false;
|
|
out = s_invites.front();
|
|
s_invites.pop_front();
|
|
return true;
|
|
}
|
|
|
|
bool HasRecentInviteFrom(unsigned long long onlineId)
|
|
{
|
|
unsigned long long now = NowMs();
|
|
s_recentInvites.erase(std::remove_if(s_recentInvites.begin(), s_recentInvites.end(), [now](const std::pair<unsigned long long, unsigned long long> &entry) { return entry.second < now; }), s_recentInvites.end());
|
|
for (const auto &entry : s_recentInvites)
|
|
{
|
|
if (entry.first == onlineId)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void RefreshFriendGames()
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
s_friendGames.clear();
|
|
return;
|
|
}
|
|
if (s_gamesInFlight)
|
|
return;
|
|
s_gamesInFlight = true;
|
|
Enqueue(eJob_PresenceGames, "/presence/games", "{}", true);
|
|
}
|
|
|
|
const std::vector<FriendGame> &GetFriendGames()
|
|
{
|
|
return s_friendGames;
|
|
}
|
|
|
|
bool ResolveFriendGame(unsigned long long onlineId, std::string &outIp, int &outPort)
|
|
{
|
|
outIp.clear();
|
|
outPort = 0;
|
|
std::string sessionToken;
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
if (!HasSession())
|
|
return false;
|
|
sessionToken = s_sessionToken;
|
|
}
|
|
char idText[17] = {};
|
|
sprintf_s(idText, "%016llX", onlineId);
|
|
ApiTarget target = LoadTarget();
|
|
if (!target.valid)
|
|
return false;
|
|
HINTERNET session = WinHttpOpen(L"neoLegacy/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
|
if (session == nullptr)
|
|
return false;
|
|
WinHttpSetTimeouts(session, 3000, 3000, 4000, 4000);
|
|
int status = 0;
|
|
std::string body;
|
|
bool ok = false;
|
|
if (HttpPost(session, target, "/presence/resolve", "{\"onlineId\":" + JsonString(idText) + "}", sessionToken, status, body) && status == 200)
|
|
{
|
|
JsonValue json;
|
|
JsonParser parser(body);
|
|
if (parser.parse(json))
|
|
{
|
|
outIp = json.getString("ip");
|
|
outPort = static_cast<int>(json.getNumber("port", 0.0));
|
|
ok = !outIp.empty() && outPort > 0 && outPort < 65536;
|
|
}
|
|
}
|
|
WinHttpCloseHandle(session);
|
|
return ok;
|
|
}
|
|
|
|
unsigned long long GetJoinOnlineId()
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
Load();
|
|
return s_state == eLink_Linked ? s_onlineId : 0;
|
|
}
|
|
|
|
bool RequestJoinToken(const std::string &serverAddress, std::wstring &outToken)
|
|
{
|
|
outToken.clear();
|
|
std::string refreshToken;
|
|
std::string sessionToken;
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
Load();
|
|
if (s_state != eLink_Linked)
|
|
return false;
|
|
refreshToken = s_refreshToken;
|
|
if (!s_sessionToken.empty() && NowMs() + kSessionRenewMarginMs < s_sessionExpiresMs)
|
|
sessionToken = s_sessionToken;
|
|
}
|
|
|
|
ApiTarget target = LoadTarget();
|
|
if (!target.valid)
|
|
return false;
|
|
HINTERNET session = WinHttpOpen(L"neoLegacy/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
|
if (session == nullptr)
|
|
return false;
|
|
WinHttpSetTimeouts(session, 3000, 3000, 4000, 4000);
|
|
|
|
bool ok = false;
|
|
if (sessionToken.empty())
|
|
{
|
|
int status = 0;
|
|
std::string body;
|
|
if (HttpPost(session, target, "/session/refresh", "{\"refreshToken\":" + JsonString(refreshToken) + "}", std::string(), status, body) && status == 200)
|
|
{
|
|
JsonValue json;
|
|
JsonParser parser(body);
|
|
if (parser.parse(json))
|
|
{
|
|
sessionToken = json.getString("sessionToken");
|
|
if (!sessionToken.empty())
|
|
{
|
|
std::lock_guard<std::recursive_mutex> shared(s_sharedMutex);
|
|
s_sessionToken = sessionToken;
|
|
s_sessionExpiresMs = NowMs() + static_cast<unsigned long long>(json.getNumber("expiresIn", 3600.0) * 1000.0);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!sessionToken.empty())
|
|
{
|
|
int status = 0;
|
|
std::string body;
|
|
if (HttpPost(session, target, "/session/join", "{\"serverAddress\":" + JsonString(serverAddress) + "}", sessionToken, status, body) && status == 200)
|
|
{
|
|
JsonValue json;
|
|
JsonParser parser(body);
|
|
if (parser.parse(json))
|
|
{
|
|
std::string token = json.getString("joinToken");
|
|
if (token.size() == 64)
|
|
{
|
|
outToken = Utf8ToWide(token);
|
|
ok = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
WinHttpCloseHandle(session);
|
|
return ok;
|
|
}
|
|
|
|
bool PopEvent(Event &out)
|
|
{
|
|
if (s_events.empty())
|
|
return false;
|
|
out = s_events.front();
|
|
s_events.pop_front();
|
|
return true;
|
|
}
|
|
|
|
ELinkState GetLinkState()
|
|
{
|
|
Load();
|
|
return s_state;
|
|
}
|
|
|
|
bool IsLinked()
|
|
{
|
|
return GetLinkState() == eLink_Linked;
|
|
}
|
|
|
|
bool HasSession()
|
|
{
|
|
return IsLinked() && !s_sessionToken.empty();
|
|
}
|
|
|
|
bool IsConnecting()
|
|
{
|
|
return IsLinked() && s_sessionToken.empty() && s_sessionInFlight;
|
|
}
|
|
|
|
std::wstring GetLinkedName()
|
|
{
|
|
Load();
|
|
return s_linkedName;
|
|
}
|
|
|
|
unsigned long long GetOnlineId()
|
|
{
|
|
Load();
|
|
return s_onlineId;
|
|
}
|
|
|
|
std::wstring GetApiUrl()
|
|
{
|
|
EnsureWorker();
|
|
return s_worker->target.url;
|
|
}
|
|
|
|
bool StartLink()
|
|
{
|
|
Load();
|
|
if (s_state != eLink_Unlinked)
|
|
return false;
|
|
ResetLinkAttempt();
|
|
s_state = eLink_Starting;
|
|
Enqueue(eJob_LinkStart, "/link/start", "{}", false);
|
|
return true;
|
|
}
|
|
|
|
void CancelLink()
|
|
{
|
|
if (s_state != eLink_Starting && s_state != eLink_Pending)
|
|
return;
|
|
ResetLinkAttempt();
|
|
s_state = eLink_Unlinked;
|
|
}
|
|
|
|
std::wstring GetLinkCode()
|
|
{
|
|
return s_linkCode;
|
|
}
|
|
|
|
int GetLinkSecondsLeft()
|
|
{
|
|
if (s_state != eLink_Pending)
|
|
return 0;
|
|
unsigned long long now = NowMs();
|
|
if (now >= s_linkExpiresMs)
|
|
return 0;
|
|
return static_cast<int>((s_linkExpiresMs - now) / 1000ULL);
|
|
}
|
|
|
|
void Unlink()
|
|
{
|
|
Load();
|
|
ForgetLink();
|
|
}
|
|
|
|
void RefreshFriends()
|
|
{
|
|
if (!HasSession())
|
|
return;
|
|
Enqueue(eJob_FriendsList, "/friends/list", "{}", true);
|
|
Enqueue(eJob_FriendsRequests, "/friends/requests", "{}", true);
|
|
}
|
|
|
|
bool HasFriendsData()
|
|
{
|
|
return HasSession() && s_friendsLoaded && s_requestsLoaded;
|
|
}
|
|
|
|
const std::vector<Person> &GetFriends()
|
|
{
|
|
return s_friends;
|
|
}
|
|
|
|
const std::vector<Person> &GetIncomingRequests()
|
|
{
|
|
return s_incoming;
|
|
}
|
|
|
|
void SendFriendRequest(const std::wstring &username)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_ActionFailed, L"session");
|
|
return;
|
|
}
|
|
Enqueue(eJob_FriendRequest, "/friends/request", "{\"username\":" + JsonString(WideToUtf8(username)) + "}", true);
|
|
}
|
|
|
|
void RespondToRequest(const std::wstring &onlineId, bool accept)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_ActionFailed, L"session");
|
|
return;
|
|
}
|
|
Enqueue(eJob_FriendRespond, "/friends/respond", "{\"onlineId\":" + JsonString(WideToUtf8(onlineId)) + ",\"accept\":" + (accept ? "true" : "false") + "}", true);
|
|
}
|
|
|
|
bool HasAccountSettings()
|
|
{
|
|
return HasSession() && s_hasAccountSettings;
|
|
}
|
|
|
|
bool IsAcceptingRequests()
|
|
{
|
|
return s_acceptingRequests;
|
|
}
|
|
|
|
void SetAcceptingRequests(bool accepting)
|
|
{
|
|
s_acceptingRequests = accepting;
|
|
if (!HasSession())
|
|
return;
|
|
Enqueue(eJob_Settings, "/account/settings", std::string("{\"acceptingRequests\":") + (accepting ? "true" : "false") + "}", true);
|
|
}
|
|
|
|
int GetRenameSecondsLeft()
|
|
{
|
|
unsigned long long now = NowMs();
|
|
if (now >= s_renameAvailableMs)
|
|
return 0;
|
|
return static_cast<int>((s_renameAvailableMs - now + 999ULL) / 1000ULL);
|
|
}
|
|
|
|
void RenameAccount(const std::wstring &username)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_RenameResult, L"session");
|
|
return;
|
|
}
|
|
if (s_renameInFlight)
|
|
return;
|
|
s_renameInFlight = true;
|
|
Enqueue(eJob_Rename, "/account/rename", "{\"username\":" + JsonString(WideToUtf8(username)) + "}", true);
|
|
}
|
|
|
|
void RemoveFriend(const std::wstring &onlineId)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_ActionFailed, L"session");
|
|
return;
|
|
}
|
|
Enqueue(eJob_FriendRemove, "/friends/remove", "{\"onlineId\":" + JsonString(WideToUtf8(onlineId)) + "}", true);
|
|
}
|
|
|
|
void BlockUser(const std::wstring &onlineId)
|
|
{
|
|
if (!HasSession())
|
|
{
|
|
PushEvent(eEvent_ActionFailed, L"session");
|
|
return;
|
|
}
|
|
Enqueue(eJob_FriendRemove, "/friends/block", "{\"onlineId\":" + JsonString(WideToUtf8(onlineId)) + "}", true);
|
|
}
|
|
}
|