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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
use language_tags::LanguageTag;
use super::{common_header, Preference, Quality, QualityItem};
use crate::http::header;
common_header! {
/// `Accept-Language` header, defined
/// in [RFC 7231 §5.3.5](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5)
///
/// The `Accept-Language` header field can be used by user agents to indicate the set of natural
/// languages that are preferred in the response.
///
/// The `Accept-Language` header is defined in
/// [RFC 7231 §5.3.5](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5) using language
/// ranges defined in [RFC 4647 §2.1](https://datatracker.ietf.org/doc/html/rfc4647#section-2.1).
///
/// # ABNF
/// ```plain
/// Accept-Language = 1#( language-range [ weight ] )
/// language-range = (1*8ALPHA *("-" 1*8alphanum)) / "*"
/// alphanum = ALPHA / DIGIT
/// weight = OWS ";" OWS "q=" qvalue
/// qvalue = ( "0" [ "." 0*3DIGIT ] )
/// / ( "1" [ "." 0*3("0") ] )
/// ```
///
/// # Example Values
/// - `da, en-gb;q=0.8, en;q=0.7`
/// - `en-us;q=1.0, en;q=0.5, fr`
/// - `fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5`
///
/// # Examples
/// ```
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptLanguage, QualityItem};
///
/// let mut builder = HttpResponse::Ok();
/// builder.insert_header(
/// AcceptLanguage(vec![
/// "en-US".parse().unwrap(),
/// ])
/// );
/// ```
///
/// ```
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptLanguage, QualityItem, q};
///
/// let mut builder = HttpResponse::Ok();
/// builder.insert_header(
/// AcceptLanguage(vec![
/// "da".parse().unwrap(),
/// "en-GB;q=0.8".parse().unwrap(),
/// "en;q=0.7".parse().unwrap(),
/// ])
/// );
/// ```
(AcceptLanguage, header::ACCEPT_LANGUAGE) => (QualityItem<Preference<LanguageTag>>)*
test_parse_and_format {
common_header_test!(no_headers, vec![b""; 0], Some(AcceptLanguage(vec![])));
common_header_test!(empty_header, vec![b""; 1], Some(AcceptLanguage(vec![])));
common_header_test!(
example_from_rfc,
vec![b"da, en-gb;q=0.8, en;q=0.7"]
);
common_header_test!(
not_ordered_by_weight,
vec![b"en-US, en; q=0.5, fr"],
Some(AcceptLanguage(vec![
QualityItem::max("en-US".parse().unwrap()),
QualityItem::new("en".parse().unwrap(), q(0.5)),
QualityItem::max("fr".parse().unwrap()),
]))
);
common_header_test!(
has_wildcard,
vec![b"fr-CH, fr; q=0.9, en; q=0.8, de; q=0.7, *; q=0.5"],
Some(AcceptLanguage(vec![
QualityItem::max("fr-CH".parse().unwrap()),
QualityItem::new("fr".parse().unwrap(), q(0.9)),
QualityItem::new("en".parse().unwrap(), q(0.8)),
QualityItem::new("de".parse().unwrap(), q(0.7)),
QualityItem::new("*".parse().unwrap(), q(0.5)),
]))
);
}
}
impl AcceptLanguage {
/// Extracts the most preferable language, accounting for [q-factor weighting].
///
/// If no q-factors are provided, the first language is chosen. Note that items without
/// q-factors are given the maximum preference value.
///
/// As per the spec, returns [`Preference::Any`] if contained list is empty.
///
/// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
pub fn preference(&self) -> Preference<LanguageTag> {
let mut max_item = None;
let mut max_pref = Quality::ZERO;
// uses manual max lookup loop since we want the first occurrence in the case of same
// preference but `Iterator::max_by_key` would give us the last occurrence
for pref in &self.0 {
// only change if strictly greater
// equal items, even while unsorted, still have higher preference if they appear first
if pref.quality > max_pref {
max_pref = pref.quality;
max_item = Some(pref.item.clone());
}
}
max_item.unwrap_or(Preference::Any)
}
/// Returns a sorted list of languages from highest to lowest precedence, accounting
/// for [q-factor weighting].
///
/// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
pub fn ranked(&self) -> Vec<Preference<LanguageTag>> {
if self.0.is_empty() {
return vec![];
}
let mut types = self.0.clone();
// use stable sort so items with equal q-factor retain listed order
types.sort_by(|a, b| {
// sort by q-factor descending
b.quality.cmp(&a.quality)
});
types.into_iter().map(|qitem| qitem.item).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::header::*;
#[test]
fn ranking_precedence() {
let test = AcceptLanguage(vec![]);
assert!(test.ranked().is_empty());
let test = AcceptLanguage(vec![QualityItem::max("fr-CH".parse().unwrap())]);
assert_eq!(test.ranked(), vec!["fr-CH".parse().unwrap()]);
let test = AcceptLanguage(vec![
QualityItem::new("fr".parse().unwrap(), q(0.900)),
QualityItem::new("fr-CH".parse().unwrap(), q(1.0)),
QualityItem::new("en".parse().unwrap(), q(0.800)),
QualityItem::new("*".parse().unwrap(), q(0.500)),
QualityItem::new("de".parse().unwrap(), q(0.700)),
]);
assert_eq!(
test.ranked(),
vec![
"fr-CH".parse().unwrap(),
"fr".parse().unwrap(),
"en".parse().unwrap(),
"de".parse().unwrap(),
"*".parse().unwrap(),
]
);
let test = AcceptLanguage(vec![
QualityItem::max("fr".parse().unwrap()),
QualityItem::max("fr-CH".parse().unwrap()),
QualityItem::max("en".parse().unwrap()),
QualityItem::max("*".parse().unwrap()),
QualityItem::max("de".parse().unwrap()),
]);
assert_eq!(
test.ranked(),
vec![
"fr".parse().unwrap(),
"fr-CH".parse().unwrap(),
"en".parse().unwrap(),
"*".parse().unwrap(),
"de".parse().unwrap(),
]
);
}
#[test]
fn preference_selection() {
let test = AcceptLanguage(vec![
QualityItem::new("fr".parse().unwrap(), q(0.900)),
QualityItem::new("fr-CH".parse().unwrap(), q(1.0)),
QualityItem::new("en".parse().unwrap(), q(0.800)),
QualityItem::new("*".parse().unwrap(), q(0.500)),
QualityItem::new("de".parse().unwrap(), q(0.700)),
]);
assert_eq!(
test.preference(),
Preference::Specific("fr-CH".parse().unwrap())
);
let test = AcceptLanguage(vec![
QualityItem::max("fr".parse().unwrap()),
QualityItem::max("fr-CH".parse().unwrap()),
QualityItem::max("en".parse().unwrap()),
QualityItem::max("*".parse().unwrap()),
QualityItem::max("de".parse().unwrap()),
]);
assert_eq!(
test.preference(),
Preference::Specific("fr".parse().unwrap())
);
let test = AcceptLanguage(vec![]);
assert_eq!(test.preference(), Preference::Any);
}
}