diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..32936b5 --- /dev/null +++ b/.clang-format @@ -0,0 +1,150 @@ +--- +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^' + Priority: 2 + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 100 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 2000 +PointerAlignment: Left +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + CanonicalDelimiter: '' + BasedOnStyle: google +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +... + diff --git a/CMakeLists.txt b/CMakeLists.txt index b40c9f1..cac70da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,8 +11,8 @@ add_executable(drogon_website backend/main.cpp backend/Api.cpp) drogon_create_views(drogon_website backend/templates ${CMAKE_CURRENT_BINARY_DIR}/backend) file(COPY drogon_config.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) -target_link_libraries(drogon_website ${DROGON_LIBRARIES}) +target_link_libraries(${PROJECT_NAME} PRIVATE Drogon::Drogon) -install(TARGETS drogon_website) +install(TARGETS drogon_website RUNTIME DESTINATION share/drogon_website/bin) install(DIRECTORY ${CMAKE_SOURCE_DIR}/content DESTINATION share/drogon_website) -install(FILES ${CMAKE_SOURCE_DIR}/drogon_config.json DESTINATION share/drogon_website/) \ No newline at end of file +install(FILES ${CMAKE_SOURCE_DIR}/drogon_config.json DESTINATION share/drogon_website/bin) diff --git a/PKGBUILD b/PKGBUILD index 158b8a2..dd02b3d 100644 --- a/PKGBUILD +++ b/PKGBUILD @@ -30,7 +30,7 @@ build() { package() { cd $srcdir/$pkgname/build make install - sed -i "s|\"document_root\": \".*\"|\"document_root\": \"/usr/share/$pkgname/content\"|" ${pkgdir}/usr/share/$pkg_pathname/drogon_config.json + sed -i "s|\"document_root\": \".*\"|\"document_root\": \"/usr/share/$pkgname/content\"|" ${pkgdir}/usr/share/$pkg_pathname/bin/drogon_config.json # Remove upload folder that may be created during development if [ -d ${pkgdir}/usr/share/$pkgname/content/uploads ]; then diff --git a/backend/Api.cpp b/backend/Api.cpp index 3a1b019..e303d83 100644 --- a/backend/Api.cpp +++ b/backend/Api.cpp @@ -7,44 +7,42 @@ using namespace drogon; namespace api { - class v1 : public HttpController { -public: - v1() : client_(HttpClient::newHttpClient("https://api.github.com")) - { - - } - METHOD_LIST_BEGIN - METHOD_ADD(v1::getContributors, "contributor_avatar_links", {Get}); - METHOD_LIST_END - - HttpClientPtr client_; - - Task<> getContributors(HttpRequestPtr req, std::function callback) - { - req = HttpRequest::newHttpRequest(); - req->setPath("/repos/an-tao/drogon/contributors"); - auto res = co_await client_->sendRequestCoro(req); - if(res->contentType() != CT_APPLICATION_JSON || res->statusCode() != k200OK) - throw std::runtime_error("GitHub contributors API did not respond with expected result"); - - nlohmann::json contributor_info = nlohmann::json::parse(res->body()); - std::vector avatar_links; - for(const auto& elem : contributor_info.items()) - avatar_links.push_back(elem.value()["avatar_url"].get()); - // Only keep at most 50 users - if(avatar_links.size() > 50) - avatar_links.resize(50); - std::string resp_json = nlohmann::json(avatar_links).dump(); - - auto resp = HttpResponse::newHttpResponse(); - resp->setBody(std::move(resp_json)); - resp->setContentTypeCode(CT_APPLICATION_JSON); - // Cache for 6 hours - resp->setExpiredTime(3600*6); - callback(resp); - } + public: + v1() : client_(HttpClient::newHttpClient("https://api.github.com")) + { + } + METHOD_LIST_BEGIN + METHOD_ADD(v1::getContributors, "contributor_avatar_links", {Get}); + METHOD_LIST_END + + HttpClientPtr client_; + + Task<> getContributors(HttpRequestPtr req, std::function callback) + { + req = HttpRequest::newHttpRequest(); + req->setPath("/repos/an-tao/drogon/contributors"); + auto res = co_await client_->sendRequestCoro(req); + if (res->contentType() != CT_APPLICATION_JSON || res->statusCode() != k200OK) + throw std::runtime_error("GitHub contributors API did not respond with expected result"); + + nlohmann::json contributor_info = nlohmann::json::parse(res->body()); + std::vector avatar_links; + for (const auto& elem : contributor_info.items()) + avatar_links.push_back(elem.value()["avatar_url"].get()); + // Only keep at most 50 users + if (avatar_links.size() > 50) + avatar_links.resize(50); + std::string resp_json = nlohmann::json(avatar_links).dump(); + + auto resp = HttpResponse::newHttpResponse(); + resp->setBody(std::move(resp_json)); + resp->setContentTypeCode(CT_APPLICATION_JSON); + // Cache for 6 hours + resp->setExpiredTime(3600 * 6); + callback(resp); + } }; -} \ No newline at end of file +} // namespace api \ No newline at end of file diff --git a/backend/MainPages.cpp b/backend/MainPages.cpp index 82196c3..52d0a7d 100644 --- a/backend/MainPages.cpp +++ b/backend/MainPages.cpp @@ -3,14 +3,14 @@ using namespace drogon; class MainPagesController : public HttpController { -public: - METHOD_LIST_BEGIN - ADD_METHOD_TO(MainPagesController::indexPage, "/", {Get}); - METHOD_LIST_END + public: + METHOD_LIST_BEGIN + ADD_METHOD_TO(MainPagesController::indexPage, "/", {Get}); + METHOD_LIST_END - void indexPage(const HttpRequestPtr& req, std::function&& callback) - { - auto resp = HttpResponse::newHttpViewResponse("IndexPage"); - callback(resp); - } + void indexPage(const HttpRequestPtr& req, std::function&& callback) + { + auto resp = HttpResponse::newHttpViewResponse("IndexPage"); + callback(resp); + } }; \ No newline at end of file diff --git a/backend/main.cpp b/backend/main.cpp index 1bc177f..59d0485 100644 --- a/backend/main.cpp +++ b/backend/main.cpp @@ -4,7 +4,5 @@ using namespace drogon; int main() { - app() - .loadConfigFile("drogon_config.json") - .run(); -} \ No newline at end of file + app().loadConfigFile("drogon_config.json").run(); +} diff --git a/drogon_config.json b/drogon_config.json index 26a474a..efa32d5 100644 --- a/drogon_config.json +++ b/drogon_config.json @@ -1,16 +1,50 @@ { - "log": { - "log_level" : "INFO" - }, - "listeners": [ - { - "address": "0.0.0.0", - "port": 4231, - "https": false - } - ], - "app": { - "document_root": "../content", - "enable_session": false - } -} \ No newline at end of file + "listeners": [ + { + "address": "0.0.0.0", + "port": 8848, + "https": false + } + ], + "app": { + "document_root": "../content", + "enable_session": false, + "log": { + "log_path": "../logs", + "logfile_base_name": "drogon_website", + "log_size_limit": 100000000, + "log_level": "TRACE" + }, + "run_as_daemon": true, + "relaunch_on_error": true, + "file_types": [ + "gif", + "png", + "jpg", + "js", + "css", + "html", + "ico", + "swf", + "xap", + "apk", + "cur", + "xml", + "woff" + ] + }, + "plugins": [ + { + "name": "drogon::plugin::AccessLogger", + "dependencies": [], + "config": { + "log_path": "../logs", + "log_format": "$request_date $method $url [$body_bytes_received] ($remote_addr - $local_addr) $status $body_bytes_sent $processing_time", + "log_file": "access.log", + "log_size_limit": 100000000, + "use_local_time": true, + "log_index": 0 + } + } + ] +} diff --git a/format.sh b/format.sh new file mode 100755 index 0000000..99cea0a --- /dev/null +++ b/format.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +clang-format --version +find backend -name *.h -o -name *.cpp -exec dos2unix {} \; +find backend -name *.h -o -name *.cpp|xargs clang-format -i -style=file diff --git a/systemd/drogon-website.service b/systemd/drogon-website.service index d92685d..dc8f274 100644 --- a/systemd/drogon-website.service +++ b/systemd/drogon-website.service @@ -6,8 +6,8 @@ After=syslog.target network.target User=drogonwebsite AmbientCapabilities=CAP_NET_BIND_SERVICE CapabilityBoundingSet=CAP_NET_BIND_SERVICE -WorkingDirectory=/usr/share/nsysu-ai-website -ExecStart=/usr/bin/nsysu_ai_backend +WorkingDirectory=/usr/share/drogon_website/bin +ExecStart=/usr/share/drogon_website/bin/drogon_website # Hardening PrivateTmp=true @@ -22,4 +22,4 @@ StandardError=syslog Restart=on-failure [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target