Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use api v2 #91

Draft
wants to merge 8 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .clang-tidy
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ Checks: >-
portability-simd-intrinsics,
readability-avoid-const-params-in-decls,
readability-const-return-type,
readability-convert-member-functions-to-static,
readability-delete-null-pointer,
readability-inconsistent-declaration-parameter-name,
readability-make-member-function-const,
Expand Down
2 changes: 1 addition & 1 deletion src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ target_compile_definitions(${PROJECT_NAME}
$<$<CONFIG:Release>:EVENTO_RELEASE>
${PLATFORM}
LOCALE_DIR="${SOURCE_LOCALE_DIR}"
EVENTO_API_V1
# EVENTO_API_V1
)

target_link_libraries(${PROJECT_NAME}
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/Convert.cc
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ slint::SharedString firstUnicode(const std::string& str) {
EventStruct from(const EventEntity& entity) {
boost::algorithm::trim(entity.summary);
return {
.id = entity.id,
.id = slint::SharedString(entity.id),
.summary = slint::SharedString(entity.summary),
.summary_abbr = details::firstUnicode(entity.summary),
.description = slint::SharedString(entity.description),
Expand Down
90 changes: 54 additions & 36 deletions src/Controller/Core/AccountManager.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,12 @@ void AccountManager::performLogin() {

auto data = result.unwrap();

self._userInfo = data.userInfo;
#ifdef EVENTO_API_V1
self.setKeychainAccessToken(data.accessToken);
self._expiredTime = std::chrono::system_clock::now() + std::chrono::days(3);
#else
self.setKeychainRefreshToken(data.refreshToken);
self.scheduleRenewAccessToken();
self.expiredTime = std::chrono::system_clock::now() + std::chrono::days(7);
#endif
self._expiredTime = std::chrono::system_clock::now() + std::chrono::days(7);

self.setNetworkAccessToken(data.accessToken);
self.setLoginState(true);
self.saveConfig();
self.performGetUserInfo();
});
}

Expand Down Expand Up @@ -129,6 +123,7 @@ void AccountManager::performGetUserInfo() {
self._userInfo = result.unwrap();
spdlog::info("get user info success");
self.setLoginState(true);
self.saveConfig();
});
}

Expand All @@ -145,10 +140,10 @@ void AccountManager::requestLogout() {
}
auto& self = *this;
self._userInfo = UserInfoEntity();
#ifndef EVENTO_API_V1

setKeychainRefreshToken("");
renewAccessTokenTimer.cancel();
#endif
_renewAccessTokenTimer.cancel();

setNetworkAccessToken("");

setLoginState(false);
Expand All @@ -167,19 +162,10 @@ void AccountManager::tryLoginDirectly() {
spdlog::info("Try login directly, expired time: {}", _expiredTime.time_since_epoch().count());
self->set_loading(true);

#ifdef EVENTO_API_V1
if (auto token = getKeychainAccessToken()) {
spdlog::info("Token is found. Login directly!");
setNetworkAccessToken(*token);
performGetUserInfo();
}
#else
// If the token is not expired after 15min, we don't need to login again
if (getKeychainRefreshToken()) {
performRefreshToken();
}
#endif
else {
} else {
self->set_loading(false);
self.bridge.getMessageManager().showMessage("登录过期,请重新登录", MessageType::Info);
}
Expand All @@ -193,24 +179,56 @@ void AccountManager::loadConfig() {
setLoginState(false);
auto [year, month, day] = evento::account.expire.date;
auto [hour, minute, second, _] = evento::account.expire.time;
std::tm t = {year, month, day, hour, minute, second};
spdlog::info("Loading config with date: {}-{}-{} and time: {}:{}:{}",
year,
month,
day,
hour,
minute,
second);

if (year < 1900 || month < 1 || month > 12 || day < 1 || day > 31 || hour < 0 || hour > 23
|| minute < 0 || minute > 59 || second < 0 || second > 60) {
spdlog::error("Invalid date or time values");
return;
}
std::tm t = {};
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = day;
t.tm_hour = hour;
t.tm_min = minute;
t.tm_sec = second;
t.tm_isdst = -1;

time_t time = std::mktime(&t);
if (time == -1) {
spdlog::error("Failed to convert time to time_t");
return;
}

_expiredTime = std::chrono::system_clock::from_time_t(std::mktime(&t));
_userInfo.id = evento::account.userId;
_expiredTime = std::chrono::system_clock::from_time_t(time);
_userInfo.linkId = evento::account.userId;
}

void AccountManager::saveConfig() {
auto expire = std::chrono::system_clock::to_time_t(_expiredTime);
auto expireTm = *std::localtime(&expire);
evento::account.expire
= toml::date_time{toml::date{expireTm.tm_year + 1900, expireTm.tm_mon + 1, expireTm.tm_mday},
toml::time{expireTm.tm_hour, expireTm.tm_min, expireTm.tm_sec}};
evento::account.userId = _userInfo.id;
if (auto expireTm = std::localtime(&expire)) {
evento::account.expire = toml::date_time{toml::date{expireTm->tm_year + 1900,
expireTm->tm_mon + 1,
expireTm->tm_mday},
toml::time{expireTm->tm_hour,
expireTm->tm_min,
expireTm->tm_sec}};
evento::account.userId = _userInfo.linkId;
} else {
spdlog::error("Failed to convert time to time_t");
}
}

void AccountManager::setKeychainRefreshToken(const std::string& refreshToken) const {
keychain::Error err;
keychain::setPassword(package, service, _userInfo.id, refreshToken, err);
keychain::setPassword(package, service, _userInfo.linkId, refreshToken, err);

if (err.type != keychain::ErrorType::NoError) {
spdlog::error("Failed to save refresh token: {}", err.message);
Expand All @@ -221,7 +239,7 @@ void AccountManager::setKeychainRefreshToken(const std::string& refreshToken) co

std::optional<std::string> AccountManager::getKeychainRefreshToken() const {
keychain::Error err;
auto refreshToken = keychain::getPassword(package, service, _userInfo.id, err);
auto refreshToken = keychain::getPassword(package, service, _userInfo.linkId, err);

if (err.type != keychain::ErrorType::NoError) {
spdlog::error("Failed to get refresh token: {}", err.message);
Expand Down Expand Up @@ -251,14 +269,14 @@ void AccountManager::setNetworkAccessToken(std::string accessToken) {
evento::networkClient()->tokenBytes = accessToken;
}

#ifdef EVENTO_API_V1
// #ifdef EVENTO_API_V1
std::optional<std::string> AccountManager::getKeychainAccessToken() const {
if (!settings.autoLogin) {
return std::nullopt;
}

keychain::Error err;
auto accessToken = keychain::getPassword(package, service, _userInfo.id, err);
auto accessToken = keychain::getPassword(package, service, _userInfo.linkId, err);

if (err.type != keychain::ErrorType::NoError) {
debug(), (int) err.type;
Expand All @@ -278,7 +296,7 @@ void AccountManager::setKeychainAccessToken(const std::string& accessToken) cons
return;
}
keychain::Error err;
keychain::setPassword(package, service, _userInfo.id, accessToken, err);
keychain::setPassword(package, service, _userInfo.linkId, accessToken, err);

if (err.type != keychain::ErrorType::NoError) {
debug(), (int) err.type;
Expand All @@ -287,7 +305,7 @@ void AccountManager::setKeychainAccessToken(const std::string& accessToken) cons
}
spdlog::info("Save access token success");
}
#endif
// #endif

void AccountManager::setLoginState(bool newState) {
auto& self = *this;
Expand Down
12 changes: 6 additions & 6 deletions src/Controller/Core/AccountManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ class AccountManager : private GlobalAgent<AccountManagerBridge>,

static const inline std::string package = "org.sast.evento";
static const inline std::string service =
#ifdef EVENTO_API_V1
// #ifdef EVENTO_API_V1
"access-token";
#else
"refresh-token";
#endif
// #else
// "refresh-token";
// #endif

public:
AccountManager(slint::ComponentHandle<UiEntryName> uiEntry, UiBridge& bridge);
Expand All @@ -50,10 +50,10 @@ class AccountManager : private GlobalAgent<AccountManagerBridge>,

static void setNetworkAccessToken(std::string accessToken);

#ifdef EVENTO_API_V1
// #ifdef EVENTO_API_V1
[[nodiscard]] std::optional<std::string> getKeychainAccessToken() const;
void setKeychainAccessToken(const std::string& accessToken) const;
#endif
// #endif

void setLoginState(bool newState);
void onStateChanged();
Expand Down
24 changes: 12 additions & 12 deletions src/Controller/View/DetailPage.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#include "app.h"
#include <Controller/AsyncExecutor.hh>
#include <Controller/Convert.h>
#include <Controller/UiBridge.h>
Expand All @@ -19,13 +18,14 @@ void DetailPage::onCreate() {
self->on_load_feedback([&self = *this]() { self.loadFeedback(); });
self->on_load_event([&self = *this]() { self.loadEvent(); });
self->on_feedback([&self = *this](int rate, slint::SharedString content) {
self.feedbackEvent(self->get_event_model().id, rate, content.data());
self.feedbackEvent(self->get_event_model().id.data(), rate, content.data());
});
self->on_check_in([&self = *this](slint::SharedString checkInCode) {
self.checkIn(self->get_event_model().id, checkInCode.data());
self.checkIn(self->get_event_model().id.data(), checkInCode.data());
});
self->on_subscribe([&self = *this](bool subscribe) {
self.subscribe(self->get_event_model().id.data(), subscribe);
});
self->on_subscribe(
[&self = *this](bool subscribe) { self.subscribe(self->get_event_model().id, subscribe); });
}

void DetailPage::onShow() {
Expand All @@ -39,7 +39,7 @@ void DetailPage::onShow() {

void DetailPage::loadEvent() {
auto& self = *this;
executor()->asyncExecute(networkClient()->getEventById(self->get_event_model().id),
executor()->asyncExecute(networkClient()->getEventById(self->get_event_model().id.data()),
[&self = *this](Result<EventQueryRes> result) {
if (result.isErr()) {
self.bridge.getMessageManager()
Expand All @@ -61,7 +61,7 @@ void DetailPage::loadEvent() {
void DetailPage::loadFeedback() {
auto& self = *this;
self->set_state(PageState::Loading);
executor()->asyncExecute(networkClient()->getUserFeedback(self->get_event_model().id),
executor()->asyncExecute(networkClient()->getUserFeedback(self->get_event_model().id.data()),
[&self = *this](Result<std::optional<FeedbackEntity>> result) {
if (result.isErr()) {
self->set_state(PageState::Error);
Expand All @@ -75,7 +75,7 @@ void DetailPage::loadFeedback() {
});
}

void DetailPage::checkIn(int eventId, std::string checkInCode) {
void DetailPage::checkIn(eventId_t eventId, std::string checkInCode) {
auto& self = *this;
executor()->asyncExecute(
networkClient()->checkInEvent(eventId, checkInCode), [&self = *this](Result<bool> result) {
Expand Down Expand Up @@ -103,9 +103,9 @@ void DetailPage::checkIn(int eventId, std::string checkInCode) {
});
}

void DetailPage::subscribe(int eventId, bool subscribe) {
void DetailPage::subscribe(std::string eventId_t, bool subscribe) {
auto& self = *this;
executor()->asyncExecute(networkClient()->subscribeEvent(eventId, subscribe),
executor()->asyncExecute(networkClient()->subscribeEvent(eventId_t, subscribe),
[&self = *this, subscribe](Result<bool> result) {
if (result.isErr()) {
self.bridge.getMessageManager()
Expand All @@ -130,10 +130,10 @@ void DetailPage::subscribe(int eventId, bool subscribe) {
});
}

void DetailPage::feedbackEvent(int eventId, int rate, std::string content) {
void DetailPage::feedbackEvent(std::string eventId_t, int rate, std::string content) {
auto& self = *this;
executor()
->asyncExecute(networkClient()->addUserFeedback(eventId, rate, content),
->asyncExecute(networkClient()->addUserFeedback(eventId_t, rate, content),
[&self = *this, rate, content](Result<bool> result) {
if (result.isErr()) {
self.bridge.getMessageManager().showMessage(result.unwrapErr().what(),
Expand Down
6 changes: 3 additions & 3 deletions src/Controller/View/DetailPage.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class DetailPage : public BasicView, private GlobalAgent<DetailPageBridge> {

void loadEvent();
void loadFeedback();
void checkIn(int eventId, std::string checkInCode);
void subscribe(int eventId, bool subscribe);
void feedbackEvent(int eventId, int rate, std::string content);
void checkIn(eventId_t eventId, std::string checkInCode);
void subscribe(eventId_t eventId, bool subscribe);
void feedbackEvent(eventId_t eventId, int rate, std::string content);
};

EVENTO_UI_END
6 changes: 3 additions & 3 deletions src/Controller/View/HistoryPage.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#include "app.h"

Check failure on line 1 in src/Controller/View/HistoryPage.cc

View workflow job for this annotation

GitHub Actions / review

'app.h' file not found [clang-diagnostic-error]
#include <Controller/AsyncExecutor.hh>
#include <Controller/Convert.h>
#include <Controller/UiBridge.h>
Expand All @@ -19,8 +19,8 @@

self->on_load_events(
[this](int pageIndex, int size) { loadHistoryEvents(pageIndex + 1, size); });
self->on_comment([this](int eventId, int rating, slint::SharedString content) {
feedbackEvent(eventId, rating, content.data());
self->on_comment([this](slint::SharedString eventId, int rating, slint::SharedString content) {
feedbackEvent(eventId.data(), rating, content.data());
});
self->on_navigate_to_detail([this](EventStruct eventStruct) {
spdlog::debug("navigate to DetailPage, current event is {}", eventStruct.summary.data());
Expand Down Expand Up @@ -79,7 +79,7 @@
co_return res;
}

void HistoryPage::feedbackEvent(int eventId, int rating, std::string content) {
void HistoryPage::feedbackEvent(eventId_t eventId, int rating, std::string content) {
auto& self = *this;
auto trans = [](const auto& e) { return e.id; };
executor()
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/View/HistoryPage.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class HistoryPage : public BasicView, private GlobalAgent<HistoryPageBridge> {

Task<Result<std::vector<EventFeedbackStruct>>> loadHistoryEventsTask(int page, int size);

void feedbackEvent(int eventId, int rating, std::string content);
void feedbackEvent(eventId_t eventId, int rating, std::string content);

std::vector<EventFeedbackStruct> eventFeedbacks;
};
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/View/MenuOverlay.cc
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ void MenuOverlay::refreshUserInfo(UserInfoEntity const& userInfo) {
auto& self = *this;
self->set_user_name(slint::SharedString(userInfo.nickname));
self->set_user_signature(
slint::SharedString(userInfo.biography.value_or("这个人很神秘,什么也没留下 ")));
slint::SharedString(userInfo.bio.value_or("这个人很神秘,什么也没留下 ")));
if (userInfo.avatar.has_value())
executor()->asyncExecute(networkClient()->getFile(*userInfo.avatar),
[&self = *this](Result<std::filesystem::path> result) {
Expand Down
6 changes: 3 additions & 3 deletions src/Controller/View/MyEventPage.cc
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ void MyEventPage::refreshUiModel(Result<EventQueryRes> result) {
if (evento::settings.noticeBegin)
for (auto const& entity : models[(int) EventState::SigningUp]) {
auto time = parseIso8601Utc(entity.start.c_str());
ipc()->showOrUpdateMessage(entity.id,
ipc()->showOrUpdateMessage(entity.id.data(),
std::format("活动 {} 还有 15 分钟就要开始了,记得参加哦",
entity.summary),
std::chrono::system_clock::from_time_t(time) - 15min);
Expand All @@ -88,14 +88,14 @@ void MyEventPage::refreshUiModel(Result<EventQueryRes> result) {
if (evento::settings.noticeEnd)
for (auto const& entity : models[(int) EventState::Active]) {
auto time = parseIso8601Utc(entity.end.c_str());
ipc()->showOrUpdateMessage(entity.id,
ipc()->showOrUpdateMessage(entity.id.data(),
std::format("活动 {} 结束了,记得反馈哦", entity.summary),
std::chrono::system_clock::from_time_t(time));
}

for (auto const& entity : models[(int) EventState::Cancelled]) {
auto time = parseIso8601Utc(entity.start.c_str());
ipc()->cancelMessage(entity.id);
ipc()->cancelMessage(entity.id.data());
}

self->set_not_started_model(convert::from(models[(int) EventState::SigningUp]));
Expand Down
Loading
Loading