This repository has been archived by the owner on Apr 30, 2020. It is now read-only.
forked from gigablast/open-source-search-engine
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCountryLanguage.cpp
91 lines (77 loc) · 2.39 KB
/
CountryLanguage.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// Copyright (C) 2018 Privacore ApS - https://www.privacore.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// License TL;DR: If you change this file, you must publish your changes.
//
#include "CountryLanguage.h"
#include "GbUtil.h"
#include "CountryCode.h"
#include "Lang.h"
#include <fstream>
#include <sys/stat.h>
#include <sstream>
#include <map>
static std::map<uint8_t, std::string> s_country_accept_languages;
static bool initCountryAcceptLanguages() {
static const char *s_filename = "countryacceptlanguages.txt";
struct stat st;
if (stat(s_filename, &st) != 0) {
return false;
}
std::ifstream file(s_filename);
std::string line;
while (std::getline(file, line)) {
// ignore comments & empty lines
if (line.length() == 0 || line[0] == '#') {
continue;
}
auto tokens = split(line, '|');
if (tokens.size() != 2) {
// invalid format
continue;
}
uint8_t country_id = getCountryId(tokens[0].c_str());
if (country_id == 0 && tokens[0].compare("zz") != 0) {
continue;
}
s_country_accept_languages[country_id] = tokens[1];
}
return true;
}
bool CountryLanguage::init() {
return initCountryAcceptLanguages();
}
std::string CountryLanguage::getHttpAcceptLanguageStr(const char *host, int32_t hostLen) {
uint8_t country_id = 0;
std::string hostStr(host, hostLen);
auto pos = hostStr.find_last_of('.');
if (pos != std::string::npos) {
std::string tld = hostStr.substr(pos + 1);
country_id = getCountryId(tld.c_str());
}
auto it = s_country_accept_languages.find(country_id);
if (it == s_country_accept_languages.end()) {
// try to get default
if (country_id != 0) {
it = s_country_accept_languages.find(0);
}
if (it == s_country_accept_languages.end()) {
// nothing is found (use en as default)
return "en";
}
}
return it->second;
}