[tor-commits] [bridgedb/master] Select language and language direction based on order in header

isis at torproject.org isis at torproject.org
Sun Jan 12 06:06:29 UTC 2014


commit 34fa53060d93a4709ba8dfd63194cd798427260e
Author: Matthew Finkel <Matthew.Finkel at gmail.com>
Date:   Sun Jun 30 05:03:08 2013 +0000

    Select language and language direction based on order in header
    
    We guess which language gettext will choose by iterating over
    the languages in the Language header and selecting the first
    one we support. We assume a user will prioritize languages in
    their browser. We then render the page using the selected
    language, or English if it is no available. Bug fix on #9157.
    
    (cherry picked from commit a31c592eadd72a659f22497f66e77fb90c6c207b)
    Signed-off-by: Isis Lovecruft <isis at torproject.org>
    
        Taken from branch 'sysrqb/bug9157_r2_rebased'.
---
 lib/bridgedb/HTTPServer.py               |   65 +++++++++++++++++++++++++++---
 lib/bridgedb/templates/assets/custom.css |   15 ++++++-
 lib/bridgedb/templates/base.html         |   14 +++++++
 lib/bridgedb/templates/bridges.html      |    8 +++-
 lib/bridgedb/templates/index.html        |   41 ++++++++++++-------
 5 files changed, 120 insertions(+), 23 deletions(-)

diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py
index 6b469cc..ea4dea7 100644
--- a/lib/bridgedb/HTTPServer.py
+++ b/lib/bridgedb/HTTPServer.py
@@ -19,6 +19,7 @@ import twisted.web.resource
 from twisted.web.server import Site
 from twisted.web import static
 from twisted.web.util import redirectTo
+from twisted.python import filepath
 
 import bridgedb.Dist
 import bridgedb.I18n as I18n
@@ -38,6 +39,7 @@ from zope.interface import Interface, Attribute, implements
 template_root = os.path.join(os.path.dirname(__file__),'templates')
 lookup = TemplateLookup(directories=[template_root],
                         output_encoding='utf-8')
+rtl_langs = ('ar', 'he', 'fa', 'gu_IN', 'ku')
 
 logging.debug("Set template root to %s" % template_root)
 
@@ -152,7 +154,7 @@ class WebResource(twisted.web.resource.Resource):
             countryCode = geoip.country_code_by_addr(ip)
 
         # set locale
-        setLocaleFromRequestHeader(request)
+        rtl = usingRTLLang(request)
 
         format = request.args.get("format", None)
         if format and len(format): format = format[0] # choose the first arg
@@ -217,13 +219,13 @@ class WebResource(twisted.web.resource.Resource):
             return answer
         else:
             request.setHeader("Content-Type", "text/html; charset=utf-8")
-            return lookup.get_template('bridges.html').render(answer=answer)
+            return lookup.get_template('bridges.html').render(answer=answer, rtl=rtl)
 
 class WebRoot(twisted.web.resource.Resource):
     isLeaf = True
     def render_GET(self, request):
-        setLocaleFromRequestHeader(request)
-        return lookup.get_template('index.html').render()
+        rtl = usingRTLLang(request)
+        return lookup.get_template('index.html').render(rtl=rtl)
 
 def addWebServer(cfg, dist, sched):
     """Set up a web server.
@@ -277,13 +279,65 @@ def addWebServer(cfg, dist, sched):
 
     return site
 
+def usingRTLLang(request):
+    """
+    Check if we should translate the text into a RTL language
+
+    Retrieve the headers from the request. Obtain the Accept-Language header
+    and decide if we need to translate the text. Install the requisite
+    languages via gettext, if so. Then, manually check which languages we
+    support. Choose the first language from the header that we support and
+    return True if it is a RTL language, else return False.
+
+    :param request twisted.web.server.Request: Incoming request
+    :returns bool: Language is right-to-left
+    """
+    langs = setLocaleFromRequestHeader(request)
+
+    # Grab only the language (first two characters) so we know if the language
+    # is read right-to-left
+    #langs = [ lang[:2] for lang in langs ]
+    lang = getAssumedChosenLang(langs)
+    if lang in rtl_langs:
+        return True
+    return False
+
+def getAssumedChosenLang(langs):
+    """
+    Return the first language in ``langs`` and we supprt
+
+    :param langs list: All requested languages
+    :returns string: Chosen language
+    """
+    i18npath = os.path.join(os.path.dirname(__file__), 'i18n')
+    path = filepath.FilePath(i18npath)
+    assert path.isdir()
+
+    lang = 'en-US'
+    supp_langs = path.listdir() + ['en']
+    for l in langs:
+        if l in supp_langs:
+            lang = l
+            break
+    return lang
+
 def setLocaleFromRequestHeader(request):
+    """
+    Retrieve the languages from the accept-language header and insall
+
+    Parse the languages in the header, if any of them contain locales then
+    add their languages to the list, also. Then install all of them using
+    gettext, it will choose the best one.
+
+    :param request twisted.web.server.Request: Incoming request
+    :returns list: All requested languages
+    """
     langs = request.getHeader('accept-language').split(',')
     logging.debug("Accept-Language: %s" % langs)
     localedir=os.path.join(os.path.dirname(__file__), 'i18n/')
 
     if langs:
-        langs = filter(lambda x: re.match('^[a-z\-]{1,5}$', x), langs)
+        langs = filter(lambda x: re.match('^[a-z\-]{1,5}', x), langs)
         logging.debug("Languages: %s" % langs)
         # add fallback languages
         langs_only = filter(lambda x: '-' in x, langs)
@@ -293,3 +347,4 @@ def setLocaleFromRequestHeader(request):
         lang = gettext.translation("bridgedb", localedir=localedir,
                  languages=langs, fallback=True)
         lang.install(True)
+    return langs
diff --git a/lib/bridgedb/templates/assets/custom.css b/lib/bridgedb/templates/assets/custom.css
index e46ed9b..bc0e2d1 100644
--- a/lib/bridgedb/templates/assets/custom.css
+++ b/lib/bridgedb/templates/assets/custom.css
@@ -88,4 +88,17 @@ font-weight: 100;
     font-size: 18px;
 line-height: 30px;
 margin-top: 2px;
-}
\ No newline at end of file
+}
+.lead_right {
+    margin-bottom: 20px;
+    font-size: 21px;
+    font-weight: 200;
+    line-height: 30px
+}
+[class*="bdb_span"] {
+    min-height: 1px;
+    margin: 0 20px 22px 20px;
+}
+.bdb_span7 {
+    width: 560px
+}
diff --git a/lib/bridgedb/templates/base.html b/lib/bridgedb/templates/base.html
index e9a13b8..629680e 100644
--- a/lib/bridgedb/templates/base.html
+++ b/lib/bridgedb/templates/base.html
@@ -11,6 +11,20 @@
 <!-- Le styles -->
 <link href="/assets/bootstrap.min.css" rel="stylesheet">
 <link href="/assets/custom.css" rel="stylesheet">
+
+% if rtl:
+<style>
+span,p,h3,h4 {
+    text-align: right;
+    direction: rtl;
+}
+
+span {
+    float: right;
+}
+</style>
+%endif
+
 </head>
 <body>
 <div class="container-narrow">
diff --git a/lib/bridgedb/templates/bridges.html b/lib/bridgedb/templates/bridges.html
index 44cd365..7bb0a79 100644
--- a/lib/bridgedb/templates/bridges.html
+++ b/lib/bridgedb/templates/bridges.html
@@ -7,8 +7,12 @@
 <pre>
 ${answer}
 </pre>
-<br />
-<p>${_("""To use the above lines, go to Vidalia's Network settings page, and click "My ISP blocks connections to the Tor network". Then add each bridge address one at a time.""")}
+<br \>
+<p>
+<p>
+${_("""To use the above lines, go to Vidalia's Network settings page, and """ \
+    """click "My ISP blocks connections to the Tor network". Then add """ \
+    """each bridge address one at a time.""")}
 </p>
 % else:
 <h3> ${_("No bridges currently available")} </h3>
diff --git a/lib/bridgedb/templates/index.html b/lib/bridgedb/templates/index.html
index 2839e1a..82522c8 100644
--- a/lib/bridgedb/templates/index.html
+++ b/lib/bridgedb/templates/index.html
@@ -3,23 +3,34 @@
 
 <div class="main-steps">
 <div class="step row">
-  <div class="span1">
-    <p class="lead"><span class="step-title"> ${_("Step 1")} </span></p></div>
-  <div class="span5 step-text">
-    ${_("Get the %s Pluggable Transports Tor Browser Bundle %s") % \
-("""<a href="https://www.torproject.org/projects/obfsproxy.html.en#download">""", "</a>")}</div>
+  <div class="bdb_span7 step-text">
+    <span class="lead">
+      <span class="step-title">
+        ${_("Step 1")}</span>
+        <span style="margin-left: 20px;">
+          ${_("Get the %s Pluggable Transports Tor Browser Bundle %s") % \
+    ("""<a href="https://www.torproject.org/projects/obfsproxy.html.en#download">""", "</a>")}</span>
+    </span></div>
 </div>
+
 <div class="step row">
-  <div class="span1">
-    <p class="lead"><span class="step-title"> ${_("Step 2")} </span></p></div>
-  <div class="span5 step-text">
-    ${_("Get %s bridges %s") % ("""<a href="/bridges">""", "</a>")}</div>
+  <div class="bdb_span7 step-text">
+    <span class="lead">
+      <span class="step-title">
+        ${_("Step 2")} </span>
+      <span style="margin-left: 20px;">
+        ${_("Get %s bridges %s") % ("""<a href="/bridges">""", "</a>")}</span>
+    </span></div>
 </div>
+
 <div class="step row">
-  <div class="span1">
-    <p class="lead"><span class="step-title"> ${_("Step 3")} </span></p></div>
-  <div class="span5 step-text">
-    ${_("Now %s add the bridges to Tor %s") % \
-       ("""<a href="https://www.torproject.org/docs/bridges#UsingBridges">""", "</a>")}
-  </div>
+  <div class="bdb_span7 step-text">
+    <span class="lead">
+      <span class="step-title">
+        ${_("Step 3")}</span>
+      <span style="margin-left: 20px;">
+        ${_("Now %s add the bridges to Tor %s") % \
+       ("""<a href="https://www.torproject.org/docs/bridges#UsingBridges">""", "</a>")}</span>
+</span></div>
 </div>
+





More information about the tor-commits mailing list