Skip to content

Commit

Permalink
Modify installation (#15)
Browse files Browse the repository at this point in the history
Co-authored-by: Martin Chang <[email protected]>
  • Loading branch information
an-tao and marty1885 authored Jun 20, 2021
1 parent 51d2025 commit 45b20ef
Show file tree
Hide file tree
Showing 9 changed files with 257 additions and 72 deletions.
150 changes: 150 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -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: '^<ext/.*\.h>'
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
...

6 changes: 3 additions & 3 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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/)
install(FILES ${CMAKE_SOURCE_DIR}/drogon_config.json DESTINATION share/drogon_website/bin)
2 changes: 1 addition & 1 deletion PKGBUILD
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
72 changes: 35 additions & 37 deletions backend/Api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,42 @@ using namespace drogon;

namespace api
{

class v1 : public HttpController<v1>
{
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<void(const HttpResponsePtr &)> 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<std::string> avatar_links;
for(const auto& elem : contributor_info.items())
avatar_links.push_back(elem.value()["avatar_url"].get<std::string>());
// 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<void(const HttpResponsePtr&)> 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<std::string> avatar_links;
for (const auto& elem : contributor_info.items())
avatar_links.push_back(elem.value()["avatar_url"].get<std::string>());
// 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);
}
};

}
} // namespace api
18 changes: 9 additions & 9 deletions backend/MainPages.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
using namespace drogon;
class MainPagesController : public HttpController<MainPagesController>
{
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<void(const HttpResponsePtr &)>&& callback)
{
auto resp = HttpResponse::newHttpViewResponse("IndexPage");
callback(resp);
}
void indexPage(const HttpRequestPtr& req, std::function<void(const HttpResponsePtr&)>&& callback)
{
auto resp = HttpResponse::newHttpViewResponse("IndexPage");
callback(resp);
}
};
6 changes: 2 additions & 4 deletions backend/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,5 @@ using namespace drogon;

int main()
{
app()
.loadConfigFile("drogon_config.json")
.run();
}
app().loadConfigFile("drogon_config.json").run();
}
64 changes: 49 additions & 15 deletions drogon_config.json
Original file line number Diff line number Diff line change
@@ -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
}
}
"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
}
}
]
}
5 changes: 5 additions & 0 deletions format.sh
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions systemd/drogon-website.service
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,4 +22,4 @@ StandardError=syslog
Restart=on-failure

[Install]
WantedBy=multi-user.target
WantedBy=multi-user.target

0 comments on commit 45b20ef

Please sign in to comment.