We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TMX export incorrectly names files
the tmx files are getting a .zip extension inside the zip archive

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pootle/apps/import_export/utils.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 import logging
10 import os
11 
12 from io import BytesIO
13 from zipfile import ZipFile
14 
15 from translate.storage.factory import getclass
16 from translate.storage import tmx
17 
18 from django.conf import settings
19 from django.utils.functional import cached_property
20 
21 from pootle.core.delegate import revision
22 from pootle.core.url_helpers import urljoin
23 from pootle.i18n.gettext import ugettext_lazy as _
24 from pootle_app.models.permissions import check_user_permission
25 from pootle_statistics.models import SubmissionTypes
26 from pootle_store.constants import TRANSLATED
27 from pootle_store.models import Store
28 
29 from .exceptions import (FileImportError, MissingPootlePathError,
30                          MissingPootleRevError, UnsupportedFiletypeError)
31 
32 
33 logger = logging.getLogger(__name__)
34 
35 
36 def import_file(f, user=None):
37     ttk = getclass(f)(f.read())
38     if not hasattr(ttk, "parseheader"):
39         raise UnsupportedFiletypeError(_("Unsupported filetype '%s', only PO "
40                                          "files are supported at this time\n",
41                                          f.name))
42     header = ttk.parseheader()
43     pootle_path = header.get("X-Pootle-Path")
44     if not pootle_path:
45         raise MissingPootlePathError(_("File '%s' missing X-Pootle-Path "
46                                        "header\n", f.name))
47 
48     rev = header.get("X-Pootle-Revision")
49     if not rev or not rev.isdigit():
50         raise MissingPootleRevError(_("File '%s' missing or invalid "
51                                       "X-Pootle-Revision header\n",
52                                       f.name))
53     rev = int(rev)
54 
55     try:
56         store = Store.objects.get(pootle_path=pootle_path)
57     except Store.DoesNotExist as e:
58         raise FileImportError(_("Could not create '%s'. Missing "
59                                 "Project/Language? (%s)", (f.name, e)))
60 
61     tp = store.translation_project
62     allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'
63                                or tp.is_template_project)
64                               and check_user_permission(user,
65                                                         'administrate',
66                                                         tp.directory))
67     try:
68         store.update(store=ttk, user=user,
69                      submission_type=SubmissionTypes.UPLOAD,
70                      store_revision=rev,
71                      allow_add_and_obsolete=allow_add_and_obsolete)
72     except Exception as e:
73         # This should not happen!
74         logger.error("Error importing file: %s", str(e))
75         raise FileImportError(_("There was an error uploading your file"))
76 
77 
78 class TPTMXExporter(object):
79 
80     def __init__(self, context):
81         self.context = context
82 
83     @property
84     def exported_revision(self):
85         return revision.get(self.context.__class__)(
86             self.context).get(key="pootle.offline.tm")
87 
88     @cached_property
89     def revision(self):
90         return revision.get(self.context.__class__)(
91             self.context.directory).get(key="stats")[:10] or "0"
92 
93     def get_url(self):
94         if self.exported_revision:
95             relative_path = "offline_tm/%s/%s" % (
96                 self.context.language.code,
97                 self.get_filename(self.exported_revision)
98             )
99             return urljoin(settings.MEDIA_URL, relative_path)
100         return None
101 
102     def update_exported_revision(self):
103         if self.has_changes():
104             revision.get(self.context.__class__)(
105                 self.context).set(keys=["pootle.offline.tm"],
106                                   value=self.revision)
107 
108     def has_changes(self):
109         return self.revision != self.exported_revision
110 
111     def file_exists(self):
112         return os.path.exists(self.abs_filepath)
113 
114     @property
115     def last_exported_file_path(self):
116         if not self.exported_revision:
117             return None
118         exported_filename = self.get_filename(self.exported_revision)
119         return os.path.join(self.directory, exported_filename)
120 
121     def exported_file_exists(self):
122         if self.last_exported_file_path is None:
123             return False
124         return os.path.exists(self.last_exported_file_path)
125 
126     @property
127     def directory(self):
128         return os.path.join(settings.MEDIA_ROOT,
129                             'offline_tm',
130                             self.context.language.code)
131 
132     def get_filename(self, revision):
133         return ".".join([self.context.project.code,
134                          self.context.language.code, revision, 'tmx',
135                          'zip'])
136 
137     def check_tp(self, filename):
138         """Check if filename relates to the context TP."""
139 
140         return filename.startswith(".".join([
141             self.context.project.code,
142             self.context.language.code]))
143 
144     @property
145     def filename(self):
146         return self.get_filename(self.revision)
147 
148     @property
149     def abs_filepath(self):
150         return os.path.join(self.directory, self.filename)
151 
152     def export(self, rotate=False):
153         source_language = self.context.project.source_language.code
154         target_language = self.context.language.code
155 
156         if not os.path.exists(self.directory):
157             os.makedirs(self.directory)
158 
159         tmxfile = tmx.tmxfile()
160         for store in self.context.stores.live().iterator():
161             for unit in store.units.filter(state=TRANSLATED):
162                 tmxfile.addtranslation(unit.source, source_language,
163                                        unit.target, target_language,
164                                        unit.developer_comment)
165 
166         bs = BytesIO()
167         tmxfile.serialize(bs)
168         with open(self.abs_filepath, "wb") as f:
169             with ZipFile(f, "w") as zf:
170                 zf.writestr(self.filename, bs.getvalue())
171 
172         last_exported_filepath = self.last_exported_file_path
173         self.update_exported_revision()
174 
175         removed = []
176         if rotate:
177             for fn in os.listdir(self.directory):
178                 # Skip files from other projects.
179                 if not self.check_tp(fn):
180                     continue
181                 filepath = os.path.join(self.directory, fn)
182                 if filepath not in [self.abs_filepath, last_exported_filepath]:
183                     removed.append(filepath)
184                     os.remove(filepath)
185 
186         return self.abs_filepath, removed
187
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pootle/apps/import_export/utils.py b/pootle/apps/import_export/utils.py
--- a/pootle/apps/import_export/utils.py
+++ b/pootle/apps/import_export/utils.py
@@ -167,7 +167,7 @@
         tmxfile.serialize(bs)
         with open(self.abs_filepath, "wb") as f:
             with ZipFile(f, "w") as zf:
-                zf.writestr(self.filename, bs.getvalue())
+                zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())
 
         last_exported_filepath = self.last_exported_file_path
         self.update_exported_revision()

{"golden_diff": "diff --git a/pootle/apps/import_export/utils.py b/pootle/apps/import_export/utils.py\n--- a/pootle/apps/import_export/utils.py\n+++ b/pootle/apps/import_export/utils.py\n@@ -167,7 +167,7 @@\n         tmxfile.serialize(bs)\n         with open(self.abs_filepath, \"wb\") as f:\n             with ZipFile(f, \"w\") as zf:\n-                zf.writestr(self.filename, bs.getvalue())\n+                zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())\n \n         last_exported_filepath = self.last_exported_file_path\n         self.update_exported_revision()\n", "issue": "TMX export incorrectly names files\nthe tmx files are getting a .zip extension inside the zip archive\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport logging\nimport os\n\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nfrom translate.storage.factory import getclass\nfrom translate.storage import tmx\n\nfrom django.conf import settings\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.delegate import revision\nfrom pootle.core.url_helpers import urljoin\nfrom pootle.i18n.gettext import ugettext_lazy as _\nfrom pootle_app.models.permissions import check_user_permission\nfrom pootle_statistics.models import SubmissionTypes\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Store\n\nfrom .exceptions import (FileImportError, MissingPootlePathError,\n                         MissingPootleRevError, UnsupportedFiletypeError)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_file(f, user=None):\n    ttk = getclass(f)(f.read())\n    if not hasattr(ttk, \"parseheader\"):\n        raise UnsupportedFiletypeError(_(\"Unsupported filetype '%s', only PO \"\n                                         \"files are supported at this time\\n\",\n                                         f.name))\n    header = ttk.parseheader()\n    pootle_path = header.get(\"X-Pootle-Path\")\n    if not pootle_path:\n        raise MissingPootlePathError(_(\"File '%s' missing X-Pootle-Path \"\n                                       \"header\\n\", f.name))\n\n    rev = header.get(\"X-Pootle-Revision\")\n    if not rev or not rev.isdigit():\n        raise MissingPootleRevError(_(\"File '%s' missing or invalid \"\n                                      \"X-Pootle-Revision header\\n\",\n                                      f.name))\n    rev = int(rev)\n\n    try:\n        store = Store.objects.get(pootle_path=pootle_path)\n    except Store.DoesNotExist as e:\n        raise FileImportError(_(\"Could not create '%s'. Missing \"\n                                \"Project/Language? (%s)\", (f.name, e)))\n\n    tp = store.translation_project\n    allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'\n                               or tp.is_template_project)\n                              and check_user_permission(user,\n                                                        'administrate',\n                                                        tp.directory))\n    try:\n        store.update(store=ttk, user=user,\n                     submission_type=SubmissionTypes.UPLOAD,\n                     store_revision=rev,\n                     allow_add_and_obsolete=allow_add_and_obsolete)\n    except Exception as e:\n        # This should not happen!\n        logger.error(\"Error importing file: %s\", str(e))\n        raise FileImportError(_(\"There was an error uploading your file\"))\n\n\nclass TPTMXExporter(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @property\n    def exported_revision(self):\n        return revision.get(self.context.__class__)(\n            self.context).get(key=\"pootle.offline.tm\")\n\n    @cached_property\n    def revision(self):\n        return revision.get(self.context.__class__)(\n            self.context.directory).get(key=\"stats\")[:10] or \"0\"\n\n    def get_url(self):\n        if self.exported_revision:\n            relative_path = \"offline_tm/%s/%s\" % (\n                self.context.language.code,\n                self.get_filename(self.exported_revision)\n            )\n            return urljoin(settings.MEDIA_URL, relative_path)\n        return None\n\n    def update_exported_revision(self):\n        if self.has_changes():\n            revision.get(self.context.__class__)(\n                self.context).set(keys=[\"pootle.offline.tm\"],\n                                  value=self.revision)\n\n    def has_changes(self):\n        return self.revision != self.exported_revision\n\n    def file_exists(self):\n        return os.path.exists(self.abs_filepath)\n\n    @property\n    def last_exported_file_path(self):\n        if not self.exported_revision:\n            return None\n        exported_filename = self.get_filename(self.exported_revision)\n        return os.path.join(self.directory, exported_filename)\n\n    def exported_file_exists(self):\n        if self.last_exported_file_path is None:\n            return False\n        return os.path.exists(self.last_exported_file_path)\n\n    @property\n    def directory(self):\n        return os.path.join(settings.MEDIA_ROOT,\n                            'offline_tm',\n                            self.context.language.code)\n\n    def get_filename(self, revision):\n        return \".\".join([self.context.project.code,\n                         self.context.language.code, revision, 'tmx',\n                         'zip'])\n\n    def check_tp(self, filename):\n        \"\"\"Check if filename relates to the context TP.\"\"\"\n\n        return filename.startswith(\".\".join([\n            self.context.project.code,\n            self.context.language.code]))\n\n    @property\n    def filename(self):\n        return self.get_filename(self.revision)\n\n    @property\n    def abs_filepath(self):\n        return os.path.join(self.directory, self.filename)\n\n    def export(self, rotate=False):\n        source_language = self.context.project.source_language.code\n        target_language = self.context.language.code\n\n        if not os.path.exists(self.directory):\n            os.makedirs(self.directory)\n\n        tmxfile = tmx.tmxfile()\n        for store in self.context.stores.live().iterator():\n            for unit in store.units.filter(state=TRANSLATED):\n                tmxfile.addtranslation(unit.source, source_language,\n                                       unit.target, target_language,\n                                       unit.developer_comment)\n\n        bs = BytesIO()\n        tmxfile.serialize(bs)\n        with open(self.abs_filepath, \"wb\") as f:\n            with ZipFile(f, \"w\") as zf:\n                zf.writestr(self.filename, bs.getvalue())\n\n        last_exported_filepath = self.last_exported_file_path\n        self.update_exported_revision()\n\n        removed = []\n        if rotate:\n            for fn in os.listdir(self.directory):\n                # Skip files from other projects.\n                if not self.check_tp(fn):\n                    continue\n                filepath = os.path.join(self.directory, fn)\n                if filepath not in [self.abs_filepath, last_exported_filepath]:\n                    removed.append(filepath)\n                    os.remove(filepath)\n\n        return self.abs_filepath, removed\n", "path": "pootle/apps/import_export/utils.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport logging\nimport os\n\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nfrom translate.storage.factory import getclass\nfrom translate.storage import tmx\n\nfrom django.conf import settings\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.delegate import revision\nfrom pootle.core.url_helpers import urljoin\nfrom pootle.i18n.gettext import ugettext_lazy as _\nfrom pootle_app.models.permissions import check_user_permission\nfrom pootle_statistics.models import SubmissionTypes\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Store\n\nfrom .exceptions import (FileImportError, MissingPootlePathError,\n                         MissingPootleRevError, UnsupportedFiletypeError)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_file(f, user=None):\n    ttk = getclass(f)(f.read())\n    if not hasattr(ttk, \"parseheader\"):\n        raise UnsupportedFiletypeError(_(\"Unsupported filetype '%s', only PO \"\n                                         \"files are supported at this time\\n\",\n                                         f.name))\n    header = ttk.parseheader()\n    pootle_path = header.get(\"X-Pootle-Path\")\n    if not pootle_path:\n        raise MissingPootlePathError(_(\"File '%s' missing X-Pootle-Path \"\n                                       \"header\\n\", f.name))\n\n    rev = header.get(\"X-Pootle-Revision\")\n    if not rev or not rev.isdigit():\n        raise MissingPootleRevError(_(\"File '%s' missing or invalid \"\n                                      \"X-Pootle-Revision header\\n\",\n                                      f.name))\n    rev = int(rev)\n\n    try:\n        store = Store.objects.get(pootle_path=pootle_path)\n    except Store.DoesNotExist as e:\n        raise FileImportError(_(\"Could not create '%s'. Missing \"\n                                \"Project/Language? (%s)\", (f.name, e)))\n\n    tp = store.translation_project\n    allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'\n                               or tp.is_template_project)\n                              and check_user_permission(user,\n                                                        'administrate',\n                                                        tp.directory))\n    try:\n        store.update(store=ttk, user=user,\n                     submission_type=SubmissionTypes.UPLOAD,\n                     store_revision=rev,\n                     allow_add_and_obsolete=allow_add_and_obsolete)\n    except Exception as e:\n        # This should not happen!\n        logger.error(\"Error importing file: %s\", str(e))\n        raise FileImportError(_(\"There was an error uploading your file\"))\n\n\nclass TPTMXExporter(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @property\n    def exported_revision(self):\n        return revision.get(self.context.__class__)(\n            self.context).get(key=\"pootle.offline.tm\")\n\n    @cached_property\n    def revision(self):\n        return revision.get(self.context.__class__)(\n            self.context.directory).get(key=\"stats\")[:10] or \"0\"\n\n    def get_url(self):\n        if self.exported_revision:\n            relative_path = \"offline_tm/%s/%s\" % (\n                self.context.language.code,\n                self.get_filename(self.exported_revision)\n            )\n            return urljoin(settings.MEDIA_URL, relative_path)\n        return None\n\n    def update_exported_revision(self):\n        if self.has_changes():\n            revision.get(self.context.__class__)(\n                self.context).set(keys=[\"pootle.offline.tm\"],\n                                  value=self.revision)\n\n    def has_changes(self):\n        return self.revision != self.exported_revision\n\n    def file_exists(self):\n        return os.path.exists(self.abs_filepath)\n\n    @property\n    def last_exported_file_path(self):\n        if not self.exported_revision:\n            return None\n        exported_filename = self.get_filename(self.exported_revision)\n        return os.path.join(self.directory, exported_filename)\n\n    def exported_file_exists(self):\n        if self.last_exported_file_path is None:\n            return False\n        return os.path.exists(self.last_exported_file_path)\n\n    @property\n    def directory(self):\n        return os.path.join(settings.MEDIA_ROOT,\n                            'offline_tm',\n                            self.context.language.code)\n\n    def get_filename(self, revision):\n        return \".\".join([self.context.project.code,\n                         self.context.language.code, revision, 'tmx',\n                         'zip'])\n\n    def check_tp(self, filename):\n        \"\"\"Check if filename relates to the context TP.\"\"\"\n\n        return filename.startswith(\".\".join([\n            self.context.project.code,\n            self.context.language.code]))\n\n    @property\n    def filename(self):\n        return self.get_filename(self.revision)\n\n    @property\n    def abs_filepath(self):\n        return os.path.join(self.directory, self.filename)\n\n    def export(self, rotate=False):\n        source_language = self.context.project.source_language.code\n        target_language = self.context.language.code\n\n        if not os.path.exists(self.directory):\n            os.makedirs(self.directory)\n\n        tmxfile = tmx.tmxfile()\n        for store in self.context.stores.live().iterator():\n            for unit in store.units.filter(state=TRANSLATED):\n                tmxfile.addtranslation(unit.source, source_language,\n                                       unit.target, target_language,\n                                       unit.developer_comment)\n\n        bs = BytesIO()\n        tmxfile.serialize(bs)\n        with open(self.abs_filepath, \"wb\") as f:\n            with ZipFile(f, \"w\") as zf:\n                zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())\n\n        last_exported_filepath = self.last_exported_file_path\n        self.update_exported_revision()\n\n        removed = []\n        if rotate:\n            for fn in os.listdir(self.directory):\n                # Skip files from other projects.\n                if not self.check_tp(fn):\n                    continue\n                filepath = os.path.join(self.directory, fn)\n                if filepath not in [self.abs_filepath, last_exported_filepath]:\n                    removed.append(filepath)\n                    os.remove(filepath)\n\n        return self.abs_filepath, removed\n", "path": "pootle/apps/import_export/utils.py"}]}