xref: /haiku/src/apps/haikudepot/server/ServerSettings.cpp (revision be622abddb00c474c53631429ad1102d78688d4f)
1 /*
2  * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>.
3  * All rights reserved. Distributed under the terms of the MIT License.
4  */
5 
6 #include "ServerSettings.h"
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 
11 #include <AppFileInfo.h>
12 #include <Application.h>
13 #include <Roster.h>
14 #include <Url.h>
15 
16 
17 #define BASEURL_DEFAULT "https://depot.haiku-os.org"
18 #define USERAGENT_FALLBACK_VERSION "0.0.0"
19 
20 
21 BUrl ServerSettings::sBaseUrl = BUrl(BASEURL_DEFAULT);
22 BString ServerSettings::sUserAgent = BString();
23 pthread_once_t ServerSettings::sUserAgentInitOnce = PTHREAD_ONCE_INIT;
24 
25 
26 status_t
27 ServerSettings::SetBaseUrl(const BUrl& value)
28 {
29 	if (!value.IsValid()) {
30 		fprintf(stderr, "the url is not valid\n");
31 		return B_BAD_VALUE;
32 	}
33 
34 	if (value.Protocol() != "http" && value.Protocol() != "https") {
35 		fprintf(stderr, "the url protocol must be 'http' or 'https'\n");
36 		return B_BAD_VALUE;
37 	}
38 
39 	sBaseUrl = value;
40 
41 	return B_OK;
42 }
43 
44 
45 BUrl
46 ServerSettings::CreateFullUrl(const BString urlPathComponents)
47 {
48 	return BUrl(sBaseUrl, urlPathComponents);
49 }
50 
51 
52 const BString
53 ServerSettings::GetUserAgent()
54 {
55 	if (sUserAgent.IsEmpty())
56 		pthread_once(&sUserAgentInitOnce, &ServerSettings::_InitUserAgent);
57 
58 	return sUserAgent;
59 }
60 
61 
62 void
63 ServerSettings::_InitUserAgent()
64 {
65 	sUserAgent.SetTo("HaikuDepot/");
66 	sUserAgent.Append(_GetUserAgentVersionString());
67 }
68 
69 
70 const BString
71 ServerSettings::_GetUserAgentVersionString()
72 {
73 	app_info info;
74 
75 	if (be_app->GetAppInfo(&info) != B_OK) {
76 		fprintf(stderr, "Unable to get the application info\n");
77 		be_app->Quit();
78 		return BString(USERAGENT_FALLBACK_VERSION);
79 	}
80 
81 	BFile file(&info.ref, B_READ_ONLY);
82 
83 	if (file.InitCheck() != B_OK) {
84 		fprintf(stderr, "Unable to access the application info file\n");
85 		be_app->Quit();
86 		return BString(USERAGENT_FALLBACK_VERSION);
87 	}
88 
89 	BAppFileInfo appFileInfo(&file);
90 	version_info versionInfo;
91 
92 	if (appFileInfo.GetVersionInfo(
93 		&versionInfo, B_APP_VERSION_KIND) != B_OK) {
94 		fprintf(stderr, "Unable to establish the application version\n");
95 		be_app->Quit();
96 		return BString(USERAGENT_FALLBACK_VERSION);
97 	}
98 
99 	BString result;
100 	result.SetToFormat("%" B_PRId32 ".%" B_PRId32 ".%" B_PRId32,
101 		versionInfo.major, versionInfo.middle, versionInfo.minor);
102 	return result;
103 }
104 
105 void
106 ServerSettings::AugmentHeaders(BHttpHeaders& headers)
107 {
108 	headers.AddHeader("User-Agent", GetUserAgent());
109 }
110 
111 
112