weblate: check a language exists before pushing to it

Julien LepillerSat Aug 28 19:56:26+0200 2021

1fc8510

weblate: check a language exists before pushing to it

offlate/systems/weblate.py

141141
            callback.reportProgress(100.0 * i / len(self.files))
142142
            print('{} => {}'.format(slug['slug'], slug['file_format']))
143143
            filename = self.filename(slug['slug'], False)
144-
            ans = requests.post(
144+
145+
            # First, check the file has some translations
146+
            has_translations = False
147+
            for c in self.content()[slug['slug']]:
148+
                if c.isTranslated() or c.isFuzzy():
149+
                    has_translations = True
150+
                    break
151+
152+
            if not has_translations:
153+
                continue
154+
155+
            # First check the component exists, and create it otherwise
156+
            ans = requests.get(
145157
                self.data['instance'] + '/api/translations/' +
146-
                    self.data['project'] + '/' + slug['slug'] + '/' +
147-
                    self.lang + '/file/',
148-
                    files={'file': (os.path.basename(filename), open(filename, 'rb'))},
158+
                self.data['project'] + '/' + slug['slug'] + '/' +
159+
                self.lang + '/')
160+
            if ans.status_code == 404:
161+
                ans = request.post(
162+
                    self.data['instance'] + '/api/components/' +
163+
                    self.data['project'] + '/' + slug['slug'] + '/translations/',
164+
                    data = {'language_code': self.lang},
149165
                    headers={"user-agent": "offlate", "Accept": "application/json",
150-
                        "Authorization": 'Token '+self.conf['token']},
151-
                    data={'conflicts': 'replace-translated',
152-
                        'method': 'translate'})
153-
                    #auth=HTTPBasicAuth('Token', self.conf['token']))
166+
                        "Authorization": 'Token '+self.conf['token']})
167+
            
168+
            if ans.status_code == 200: 
169+
                ans = requests.post(
170+
                    self.data['instance'] + '/api/translations/' +
171+
                        self.data['project'] + '/' + slug['slug'] + '/' +
172+
                        self.lang + '/file/',
173+
                        files={'file': (os.path.basename(filename), open(filename, 'rb'))},
174+
                        headers={"user-agent": "offlate", "Accept": "application/json",
175+
                            "Authorization": 'Token '+self.conf['token']},
176+
                        data={'conflicts': 'replace-translated',
177+
                            'method': 'translate'})
154178
            print(ans)
155179
            print(ans.text)
156180
            i += 1